StdDev Volatility
Download scriptThe StdDev Volatility indicator is designed to help traders visualize market price fluctuations and identify specific areas of high or low volatility. By mapping out the "normal" range of price movements, it provides a framework for recognizing when the market is behaving exceptionally, which can signal potential entry or exit opportunities.
Core Logic and Mechanics
The indicator functions by calculating a baseline of average price action and then constructing multiple boundaries (bands) around that baseline. Here is the step-by-step logic used to generate these visuals:
1. Establishing the Baseline (Moving Average) The script first calculates a Moving Average of the price. This represents the "center" or the prevailing trend of the market over a specific number of past bars. Users can choose different smoothing methods—such as Exponential, Smoothed, Linear Weighted, or Simple moving averages—to determine how quickly the baseline reacts to new price data.
2. Measuring Volatility (Standard Deviation) To understand how much the price is "swinging" away from the baseline, the script calculates the Standard Deviation. In simple terms, this measures the mathematical spread of prices. If the price stays very close to the moving average, the volatility is low; if the price makes large, erratic jumps, the volatility is high.
3. Creating the Dynamic Bands Using the results from the Moving Average and the Standard Deviation, the script projects four distinct boundary lines on your chart:
- Outer Bands (Upper and Lower): These are calculated by taking the baseline and adding/subtracting a user-defined number of standard deviations. These bands represent the outer limits of "normal" market behavior. When prices push toward or pierce these bands, it often indicates extreme price movement.
- Middle Bands (Upper Middle and Lower Middle): The script also calculates a secondary, narrower set of bands. These are based on a smaller fraction (specifically 25%) of the standard deviation. These act as intermediate zones to help traders identify tightening volatility or early signs of a trend shift.
Practical Application
For a trader, this logic translates into a visual "channel" on the chart:
- Volatility Identification: The wider the gap between the bands, the more volatile the market is currently behaving.
- Price Extremes: When the price reaches the outer bands, it suggests the market may be overextended in that direction.
- Trend Analysis: The narrowing of the bands can signal a period of consolidation (low volatility), while a sudden expansion suggests the start of a new, more aggressive price move.
//+------------------------------------------------------------------+
//| StdDev Volatility.mq5 |
//| Copyright 2023, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#property description "The StdDev Volatility indicator is used to identify high and low volatility, identify potential entry and exit points for trades."
#property description "It uses standard deviation and moving average to create bands and traders can use this information to make buy or sell decisions."
#property strict
#include <MovingAverages.mqh>
#property indicator_chart_window
#property indicator_buffers 6
#property indicator_plots 4
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDarkSlateGray
#property indicator_style1 STYLE_SOLID
#property indicator_width1 2
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrDarkSlateGray
#property indicator_style2 STYLE_SOLID
#property indicator_width2 2
#property indicator_type3 DRAW_FILLING
#property indicator_color3 C'30,49,49'//clrDarkSlateGray
#property indicator_style3 STYLE_SOLID
#property indicator_type4 DRAW_LINE
#property indicator_color4 C'30,49,49'//clrDarkSlateGray
#property indicator_style4 STYLE_SOLID
//--- input parametrs
input int InpStdDevPeriod=20; // Period
input int InpStdDevShift=0; // Shift
input double InpStdDeviations=2.0; // Deviations
input ENUM_MA_METHOD InpMAMethod=MODE_SMMA; // Method
//--- indicator buffers
double ExtStdDevBuffer[];
double ExtMABuffer[];
//---
double ExtUpperBand[];
double ExtLowerBand[];
double ExtUpperMiddleBand[];
double ExtLowerMiddleBand[];
//--- defines the variables for storing the calculated period, shift, and number of deviations
int ExtStdDevPeriod,ExtStdDevShift;
double ExtStdDeviations,Ext4thStdDev;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- check for input values
if(InpStdDevPeriod<=1)
{
ExtStdDevPeriod=14;
PrintFormat("Incorrect value for input variable StdDevVolatilityPeriod=%d. Indicator will use value %d for calculations.",
InpStdDevPeriod,ExtStdDevPeriod);
}
else
ExtStdDevPeriod=InpStdDevPeriod;
if(InpStdDevShift<0)
{
ExtStdDevShift=0;
PrintFormat("Incorrect value for input variable InpStdDevVolatilityShift=%d. Indicator will use value %d for calculations.",
InpStdDevShift,ExtStdDevShift);
}
else
ExtStdDevShift=InpStdDevShift;
if(InpStdDeviations<1)
{
ExtStdDeviations=2;
PrintFormat("Incorrect value for input variable InpStdDevVolatilityDeviations=%d. Indicator will use value %d for calculations.",
InpStdDevShift,ExtStdDeviations);
}
else
ExtStdDeviations=InpStdDeviations;
//--- calculates a value for the 4th standard deviation
Ext4thStdDev=ExtStdDeviations*0.25;
//--- define indicator buffers as indexes
SetIndexBuffer(0,ExtUpperBand);
SetIndexBuffer(1,ExtLowerBand);
SetIndexBuffer(2,ExtUpperMiddleBand);
SetIndexBuffer(3,ExtLowerMiddleBand);
SetIndexBuffer(4,ExtStdDevBuffer,INDICATOR_CALCULATIONS);
SetIndexBuffer(5,ExtMABuffer,INDICATOR_CALCULATIONS);
//--- set indicator short name
string short_name=StringFormat("StdDev Volatility (%d): %s",ExtStdDevPeriod,EnumToString(InpMAMethod));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
PlotIndexSetString(0,PLOT_LABEL,"StdDevVolatilityUpperBand");
PlotIndexSetString(1,PLOT_LABEL,"StdDevVolatilityLowerBand");
PlotIndexSetString(2,PLOT_LABEL,"StdDevVolatilityUpperMiddleBand");
PlotIndexSetString(3,PLOT_LABEL,"StdDevVolatilityLowerMiddleBand");
//--- set index shift
PlotIndexSetInteger(0,PLOT_SHIFT,ExtStdDevShift);
PlotIndexSetInteger(1,PLOT_SHIFT,ExtStdDevShift);
PlotIndexSetInteger(2,PLOT_SHIFT,ExtStdDevShift);
PlotIndexSetInteger(3,PLOT_SHIFT,ExtStdDevShift);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,const int prev_calculated,const int begin,const double &price[])
{
if(rates_total<ExtStdDevPeriod)
return(0);
//--- starting work
int start=prev_calculated-1;
//--- correct position for first iteration
if(start<ExtStdDevPeriod)
{
start=ExtStdDevPeriod-1;
ArrayInitialize(ExtStdDevBuffer,0.0);
ArrayInitialize(ExtMABuffer,0.0);
ArrayInitialize(ExtUpperBand,0.0);
ArrayInitialize(ExtLowerBand,0.0);
ArrayInitialize(ExtUpperMiddleBand,0.0);
ArrayInitialize(ExtLowerMiddleBand,0.0);
PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,ExtStdDevPeriod-1+begin);
}
//--- main cycle
switch(InpMAMethod)
{
case MODE_EMA :
for(int i=start; i<rates_total && !IsStopped(); i++)
{
if(i==ExtStdDevPeriod-1)
ExtMABuffer[i]=SimpleMA(i,ExtStdDevPeriod,price);
else
ExtMABuffer[i]=ExponentialMA(i,ExtStdDevPeriod,ExtMABuffer[i-1],price);
//--- Calculate StdDev
ExtStdDevBuffer[i]=StdDevFunc(price,ExtMABuffer,i);
//--- Calculate StdDev Bands
ExtUpperBand[i]=ExtMABuffer[i]+(ExtStdDeviations*ExtStdDevBuffer[i]);
ExtLowerBand[i]=ExtMABuffer[i]-(ExtStdDeviations*ExtStdDevBuffer[i]);
ExtUpperMiddleBand[i]=ExtMABuffer[i]+ExtStdDevBuffer[i]*Ext4thStdDev;
ExtLowerMiddleBand[i]=ExtMABuffer[i]-ExtStdDevBuffer[i]*Ext4thStdDev;
}
break;
case MODE_SMMA :
for(int i=start; i<rates_total && !IsStopped(); i++)
{
if(i==ExtStdDevPeriod-1)
ExtMABuffer[i]=SimpleMA(i,ExtStdDevPeriod,price);
else
ExtMABuffer[i]=SmoothedMA(i,ExtStdDevPeriod,ExtMABuffer[i-1],price);
//--- Calculate StdDev
ExtStdDevBuffer[i]=StdDevFunc(price,ExtMABuffer,i);
//--- Calculate StdDev Bands
ExtUpperBand[i]=ExtMABuffer[i]+(ExtStdDeviations*ExtStdDevBuffer[i]);
ExtLowerBand[i]=ExtMABuffer[i]-(ExtStdDeviations*ExtStdDevBuffer[i]);
ExtUpperMiddleBand[i]=ExtMABuffer[i]+ExtStdDevBuffer[i]*Ext4thStdDev;
ExtLowerMiddleBand[i]=ExtMABuffer[i]-ExtStdDevBuffer[i]*Ext4thStdDev;
}
break;
case MODE_LWMA :
for(int i=start; i<rates_total && !IsStopped(); i++)
{
ExtMABuffer[i]=LinearWeightedMA(i,ExtStdDevPeriod,price);
ExtStdDevBuffer[i]=StdDevFunc(price,ExtMABuffer,i);
//--- Calculate StdDev Bands
ExtUpperBand[i]=ExtMABuffer[i]+(ExtStdDeviations*ExtStdDevBuffer[i]);
ExtLowerBand[i]=ExtMABuffer[i]-(ExtStdDeviations*ExtStdDevBuffer[i]);
ExtUpperMiddleBand[i]=ExtMABuffer[i]+ExtStdDevBuffer[i]*Ext4thStdDev;
ExtLowerMiddleBand[i]=ExtMABuffer[i]-ExtStdDevBuffer[i]*Ext4thStdDev;
}
break;
default :
for(int i=start; i<rates_total && !IsStopped(); i++)
{
ExtMABuffer[i]=SimpleMA(i,ExtStdDevPeriod,price);
//--- Calculate StdDev
ExtStdDevBuffer[i]=StdDevFunc(price,ExtMABuffer,i);
//--- Calculate StdDev Bands
ExtUpperBand[i]=ExtMABuffer[i]+(ExtStdDeviations*ExtStdDevBuffer[i]);
ExtLowerBand[i]=ExtMABuffer[i]-(ExtStdDeviations*ExtStdDevBuffer[i]);
ExtUpperMiddleBand[i]=ExtMABuffer[i]+ExtStdDevBuffer[i]*Ext4thStdDev;
ExtLowerMiddleBand[i]=ExtMABuffer[i]-ExtStdDevBuffer[i]*Ext4thStdDev;
}
}
//--- OnCalculate done. Return new prev_calculated.
return(rates_total);
}
//+------------------------------------------------------------------+
//| Calculate Standard Deviation |
//+------------------------------------------------------------------+
double StdDevFunc(const double &price[],const double &ma_price[],const int position)
{
double dev=0.0;
for(int i=0; i<ExtStdDevPeriod; i++)
dev+=MathPow(price[position-i]-ma_price[position],2.0);
dev=MathSqrt(dev/ExtStdDevPeriod);
return(dev);
}
//+------------------------------------------------------------------+
Comments