Indicators: Variation Index

 

Variation Index:

The indicator displays what dominates in a time series: the trend or the flat component or the series acts randomly.

Author: Ильнур Иксанов

 

Hi!

I have optimized a bit the speed of the indicator (mainly by removing/replacing excess calculations). And I would also have a request: could you please translate the comments to english?

Thanks.

//+------------------------------------------------------------------+
//|                                                         iVAR.mq4 |
//|                                        (C)opyright © 2008, Ilnur |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
 
//   Индикатор отображает индекс вариации ценового ряда, вычисленного
// на минимальном предшествующем интервале длины 2^n. Индекс вариации
// показывает, что преобладает во временном ряду – трендовая или флетовая
// составляющая, или же ряд ведет себя случайно.
 
// М.М. Дубовиков и др. - Размерность минимального покрытия и локальный
// анализ фрактальных временных рядов.
 
#property copyright "(C)opyright © 2008, Ilnur"
#property link      "http://www.metaquotes.net"
//---- настройки индикатора
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Red
#property indicator_level1 0.5
//---- входные параметры
extern int n = 5;
extern int nBars = 1000;
//---- буфер индикатора
double ibuffer[];
#define LOG_2_0 0.69314718055994530941723212145818 //MathLog(2.0);
//+------------------------------------------------------------------+
//| Функция инициализации индикатора                                 |
//+------------------------------------------------------------------+
int init()
{
//---- настройка параметров отрисовки
   SetIndexBuffer(0,ibuffer);
   SetIndexStyle(0,DRAW_LINE);
   SetIndexDrawBegin(0,Bars-nBars);
   SetIndexLabel(0,"iVAR");
//---- "короткое имя" отображаемое в окне индикатора
   IndicatorShortName("iVAR("+n+")");
   return(0);
}
//+------------------------------------------------------------------+
//| Основная функция индикатора                                      |
//+------------------------------------------------------------------+
int start()
{
   int i, j, k, kCount, nTotal, nCountedBars = IndicatorCounted();
   int ihigh, ilow, nInterval, nIntervalStart;
   double Delta, Xc, Yc, Sx, Sy, Sxx, Sxy;
//---- последний посчитанный бар будет пересчитан
   if(nCountedBars==0) nTotal = nBars;
   if(nCountedBars>0) nTotal = Bars-nCountedBars-1;
//---- основной цикл индикатора
   for(j=nTotal; j>=0; j--)
   {22
      Sx = 0; Sy = 0; Sxx = 0; Sxy = 0;
      for(i=0; i<=n; i++)
      {
         nInterval = 1 << (n-i); //MathPow(2,n-i);
         kCount = 1 << i; //MathPow(2,i);
      //---- суммируем разницы максимальной и минимальной цен на интервале
         for(Delta=0, k=0; k<kCount; k++)
         {
            nIntervalStart = nInterval*k+j;
            ihigh = iHighest(Symbol(),0,MODE_HIGH,nInterval,nIntervalStart);
            ilow = iLowest(Symbol(),0,MODE_LOW,nInterval,nIntervalStart);
            Delta += High[ihigh]-Low[ilow];
         }
      //---- вычисляем координаты вариации в двойном логарифмическом масштабе
         Xc = (n-i)*LOG_2_0; //MathLog(2.0);
         Yc = MathLog(Delta);
      //---- накапливаем данные для нахождения коэффициентов линии регрессии с помощью МНК
         Sx += Xc; 
         Sy += Yc;
         Sxx += Xc*Xc; 
         Sxy += Xc*Yc;
      }
   //---- вычисляем индекс вариации (коэффициент наклона линии регрессии)
      ibuffer[j] = -(Sx*Sy-(n+1)*Sxy)/(Sx*Sx-(n+1)*Sxx);
   }
   return(0);
}
 

the "22" is not needed:

//---- основной цикл индикатора
   for(j=nTotal; j>=0; j--)
   {
      Sx = 0; Sy = 0; Sxx = 0; Sxy = 0;
 
lesliel:

I have optimized a bit the speed of the indicator (mainly by removing/replacing excess calculations). 

Thanks.

lesliel wrote:

And I would also have a request: could you please translate the comments to english?

I speak in English badly. However I will try to translate:

//+------------------------------------------------------------------+
//|                                                         iVAR.mq4 |
//|                                        (C)opyright © 2008, Ilnur |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
//The indicator displays a variation index of the price series,
//calculated on a previous interval which is 2^n long. The variation index
//shows what dominates in a time series - the trend or the flat component 
//or the series acts randomly.
 
// M.M.Dubovikov, A.V.Kryanev, N.V.Starchenko 
// Dimension of the Minimal Cover and Local Analysis of Fractal Time Series.
 
#property copyright "(C)opyright © 2008, Ilnur"
#property link      "http://www.metaquotes.net"
//---- indicator options
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Red
#property indicator_level1 0.5
//---- input parameters
extern int n = 5;
extern int nBars = 1000;
//---- indicator buffers
double ibuffer[];
#define LOG_2_0 0.69314718055994530941723212145818 //MathLog(2.0);
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
{
//---- drawing settings
   SetIndexBuffer(0,ibuffer);
   SetIndexStyle(0,DRAW_LINE);
   SetIndexDrawBegin(0,Bars-nBars);
   SetIndexLabel(0,"iVAR");
//---- name for DataWindow and indicator subwindow label
   IndicatorShortName("iVAR("+n+")");
   return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
{
   int i, j, k, kCount, nTotal, nCountedBars = IndicatorCounted();
   int ihigh, ilow, nInterval, nIntervalStart;
   double Delta, Xc, Yc, Sx, Sy, Sxx, Sxy;
//---- last counted bar will be recounted
   if(nCountedBars==0) nTotal = nBars;
   if(nCountedBars>0) nTotal = Bars-nCountedBars-1;
//---- main loop
   for(j=nTotal; j>=0; j--)
   {
      Sx = 0; Sy = 0; Sxx = 0; Sxy = 0;
      for(i=0; i<=n; i++)
      {
         nInterval = 1 << (n-i); //MathPow(2,n-i);
         kCount = 1 << i; //MathPow(2,i);
      //---- summarise differences of the maximum and minimum prices on an interval
         for(Delta=0, k=0; k<kCount; k++)
         {
            nIntervalStart = nInterval*k+j;
            ihigh = iHighest(Symbol(),0,MODE_HIGH,nInterval,nIntervalStart);
            ilow = iLowest(Symbol(),0,MODE_LOW,nInterval,nIntervalStart);
            Delta += High[ihigh]-Low[ilow];
         }
      //---- compute coordinate of variation [Xc,Yc] in double logarithmic scale
         Xc = (n-i)*LOG_2_0; //MathLog(2.0);
         Yc = MathLog(Delta);
      //---- accumulate data for finding of factors of line of regress by means of LMS (least mean squares)
         Sx += Xc; 
         Sy += Yc;
         Sxx += Xc*Xc; 
         Sxy += Xc*Yc;
      }
   //---- compute variation index (slope of the line of regress)
      ibuffer[j] = -(Sx*Sy-(n+1)*Sxy)/(Sx*Sx-(n+1)*Sxx);
   }
   return(0);
}


 

optimized version/get sometimes  some errors,  not described in stderror.mqh

google says that is def/C+ errors.

 

*When you use some (not price array) calc with VARiation

 

to example

 

 

//+------------------------------------------------------------------+
double getFV(double in_h[],double in_l[],int n,int j)
{
//----
#define LOG 0.69314718055994530941723212145818

double Delta, Xс, Yс, Sx, Sy, Sxx, Sxy;
   int ihigh, ilow, nInterval;
   int k;
   
   for(int i=0; i<=n; i++)
      {
 
      nInterval = 1 << (n-i);
      
      int K = 1 << i;
 
      //---- суммируем разницы максимальной и минимальной цен на интервале
      for(Delta=0, k=0; k<K; k++)
         {
         ihigh = ArrayMaximum(in_h, nInterval, nInterval*k+j );
         ilow  = ArrayMinimum(in_l, nInterval, nInterval*k+j );
 
         Delta += in_h[ihigh] - in_l[ilow];
         }
      //---- вычисляем координаты вариации в двойном логарифмическом масштабе
      Xс = (n-i)*LOG;
      Yс = MathLog(Delta);
      //---- накапливаем данные для нахождения коэффициентов линии регрессии с помощью МНК
      Sx += Xс; 
      Sy += Yс;
      Sxx += Xс*Xс; 
      Sxy += Xс*Yс;
      }   
double answer = -(Sx*Sy-(n+1)*Sxy)/(Sx*Sx-(n+1)*Sxx); 
//----     
return(answer);      
} 
//+------------------------------------------------------------------+