Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1540

 
maxvoronin74 #:
If the average volatility is given by the ATR indicator, is there any way to represent or modernise ATR so that the period is arbitrary? After all, MT5 does not have periods shorter than a minute.

Make a tick ATR

 
Artyom Trishkin #:

Make a tick ATR

Thank you. But I want to see periods of time, not ticks.

And do I understand correctly that iATR(Symbol, Period, 0) gives the volatility of the current candle, i.e. the current volatility?

 
maxvoronin74 #:

Thank you. But I would like to see periods of time, not ticks.

And do I understand correctly that iATR(Symbol, Period, 0) gives the volatility of the current candle, i.e. the current volatility?

1. From ticks you can make any periods of time.

2. Open the ATR code and look at its calculation.

After all, everything is within the reach of an outstretched hand.

 
maxvoronin74 #:
What formula is used to calculate SYMBOL_PRICE_VOLATILITY?

If this doesn't help you either, then I don't know how else to help you (I found it on the MQL5 website):

Коэффициент волатильности определяется, как истинный диапазон (True Range) текущего дня поделенный на истинный диапазон (True Range)
за определенное количество дней (т.е. N периодов).

Для расчета коэффициента волатильности используется следующая формула:
Коэффициент волатильности (VR) = True Range за текущий день/True Range за N дней

Истинный диапазон True Range для текущего дня рассчитывается по следующей формуле:
True Range текущего дня = MAX (сегодняшний максимум, вчерашнее закрытие) - MIN (сегодняшний минимум, вчерашнее закрытие)

Истинный диапазон True Range за N дней рассчитывается по следующей формуле:
True Range за N дней = MAX (максимум дня 1, максимум дня 2, ...максимум дня N, закрытие дня 0) - MIN (минимум дня 1, минимум дня 2, ...минимум дня N, закрытие дня 0)

Например, коэффициент волатильности акции с истинным диапазоном true range = 1.5 и true range за последние 10 дней = 3.5 будет равен 1.5/3.5 = 0.428.
Это значимый коэффициент волатильности. Обычно коэффициент волатильности выше 0,5 означает возможность разворота.

Regards, Vladimir.

 
Artyom Trishkin #:

1. from ticks you can make any time periods.

2. open the ATR code and look at its calculation.

It's all within the reach of an outstretched hand.

Here I can find how ATR is calculated: https://www.mql5.com/ru/articles/10748.

There's an algorithm:

"First we need to calculate the true range, which will be the largest value of the following:

  • The difference of the current High and the current Low;
  • The difference of the current High and the previous Close (absolute value);
  • The difference of the current Low and the previous Close (absolute value).

It turns out that to calculate the indicator we need data on the highs, lows and closing prices. After that, the average true range itself is calculated."

It does not say how the indicator behaves if the number of periods is equal to zero. Is it written somewhere else? Show it, if possible.

More. There is a line in the ATR code: "CopyBuffer(ATRDef,0,0,3,PriceArray)". Taken from the same place: https://www.mql5.com/ru/articles/10748. Can I ask why only 3 items are copied? How to determine the size of the indicator buffer and copy not three, but all elements? Or is it not necessary?


Разработка торговой системы на основе индикатора ATR
Разработка торговой системы на основе индикатора ATR
  • www.mql5.com
В этой статье мы изучим новый технический инструмент, который можно использовать в торговле. Это продолжение серии, в которой мы учимся проектировать простые торговые системы. В этот раз мы будем работать с еще одним популярным техническим индикатором — Средний истинный диапазон (Average True Range, ATR).
 
maxvoronin74 #:

Here's how ATR is calculated: https://www.mql5.com/ru/articles/10748

There's an algorithm:

"First we need to calculate the true range, which will be the largest value of the following:

  • The difference of the current High and the current Low;
  • The difference of the current High and the previous Close (absolute value);
  • The difference of the current Low and the previous Close (absolute value).

It turns out that to calculate the indicator you need data about the highs, lows and closing prices. After that, the average true range itself is calculated."

It does not say how the indicator behaves if the number of periods is equal to zero. Is it written somewhere else? Show me, if possible.

More. There is a line in the ATR code: "CopyBuffer(ATRDef,0,0,3,PriceArray)". Taken from the same place: https://www.mql5.com/ru/articles/10748. Can I ask why only 3 items are copied? How to determine the size of the indicator buffer and copy not three, but all elements? Or is it not necessary?


Open the editor.

Open the file at the path \MQL5\Indicators\Examples\ATR.mq5. There are examples for all indicators there. And it has been like this since the time of creation...

Study:

//+------------------------------------------------------------------+
//|                                                          ATR.mq5 |
//|                             Copyright 2000-2024, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright   "Copyright 2000-2024, MetaQuotes Ltd."
#property link        "https://www.mql5.com"
#property description "Average True Range"
//--- indicator settings
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_color1  DodgerBlue
#property indicator_label1  "ATR"
//--- input parameters
input int InpAtrPeriod=14;  // ATR period
//--- indicator buffers
double    ExtATRBuffer[];
double    ExtTRBuffer[];

int       ExtPeriodATR;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
void OnInit()
  {
//--- check for input value
   if(InpAtrPeriod<=0)
     {
      ExtPeriodATR=14;
      PrintFormat("Incorrect input parameter InpAtrPeriod = %d. Indicator will use value %d for calculations.",InpAtrPeriod,ExtPeriodATR);
     }
   else
      ExtPeriodATR=InpAtrPeriod;
//--- indicator buffers mapping
   SetIndexBuffer(0,ExtATRBuffer,INDICATOR_DATA);
   SetIndexBuffer(1,ExtTRBuffer,INDICATOR_CALCULATIONS);
//---
   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
//--- sets first bar from what index will be drawn
   PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,InpAtrPeriod);
//--- name for DataWindow and indicator subwindow label
   string short_name=StringFormat("ATR(%d)",ExtPeriodATR);
   IndicatorSetString(INDICATOR_SHORTNAME,short_name);
   PlotIndexSetString(0,PLOT_LABEL,short_name);
  }
//+------------------------------------------------------------------+
//| Average True Range                                               |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
   if(rates_total<=ExtPeriodATR)
      return(0);

   int i,start;
//--- preliminary calculations
   if(prev_calculated==0)
     {
      ExtTRBuffer[0]=0.0;
      ExtATRBuffer[0]=0.0;
      //--- filling out the array of True Range values for each period
      for(i=1; i<rates_total && !IsStopped(); i++)
         ExtTRBuffer[i]=MathMax(high[i],close[i-1])-MathMin(low[i],close[i-1]);
      //--- first AtrPeriod values of the indicator are not calculated
      double firstValue=0.0;
      for(i=1; i<=ExtPeriodATR; i++)
        {
         ExtATRBuffer[i]=0.0;
         firstValue+=ExtTRBuffer[i];
        }
      //--- calculating the first value of the indicator
      firstValue/=ExtPeriodATR;
      ExtATRBuffer[ExtPeriodATR]=firstValue;
      start=ExtPeriodATR+1;
     }
   else
      start=prev_calculated-1;
//--- the main loop of calculations
   for(i=start; i<rates_total && !IsStopped(); i++)
     {
      ExtTRBuffer[i]=MathMax(high[i],close[i-1])-MathMin(low[i],close[i-1]);
      ExtATRBuffer[i]=ExtATRBuffer[i-1]+(ExtTRBuffer[i]-ExtTRBuffer[i-ExtPeriodATR])/ExtPeriodATR;
     }
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
 
maxvoronin74 #:

Here's how ATR is calculated: https://www.mql5.com/ru/articles/10748

There's an algorithm:

"First we need to calculate the true range, which will be the largest value of the following:

  • The difference of the current High and the current Low;
  • The difference of the current High and the previous Close (absolute value);
  • The difference of the current Low and the previous Close (absolute value).

It turns out that to calculate the indicator you need data about the highs, lows and closing prices. After that, the average true range itself is calculated."

It does not say how the indicator behaves if the number of periods is equal to zero. Is it written somewhere else? Show me, if possible.

More. There is a line in the ATR code: "CopyBuffer(ATRDef,0,0,3,PriceArray)". Taken from the same place: https://www.mql5.com/ru/articles/10748. Can I ask why only 3 items are copied? How to determine the size of the indicator buffer and copy not three, but all elements? Or is it not necessary?

That's it! Don't suffer. Here is the code to get the ATR indicator values:

//+------------------------------------------------------------------+
//| Input variables                                                  |
//+------------------------------------------------------------------+
input ushort Averaging_Period=14; // Период усреднения индикатора ATR

int Handle_ATR;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   Handle_ATR=iATR(_Symbol, PERIOD_CURRENT, Averaging_Period); // получим хэндл индикатора ATR
   if(Handle_ATR==INVALID_HANDLE)
     {
      Print("Некорректный хэндл индикатора ATR!");
      return(INIT_FAILED);
     }
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   IndicatorRelease(Handle_ATR);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   double atr_array_value[]; // создадим массив для значений индикатора ATR
   ArraySetAsSeries(atr_array_value, true); // зададим индексацию элементов массива, как в таймсериях
   int copy_buffer = CopyBuffer(Handle_ATR, 0, 0, 3, atr_array_value); // копируем в массив данные указанного буфера индикатора ATR
   if(copy_buffer > 0) // если скопированные данные больше нуля
      Print("Значение ATR = ", atr_array_value[0]); // выведем на печать
  }
//+------------------------------------------------------------------+

Further, be kind enough to do it yourself.

Regards, Vladimir.

 
MrBrooklin #:

That's it! Don't bother. Here is the code to get the ATR indicator values:

You'll have to do it yourself.

Regards, Vladimir

It is not correct.

You check the handle in OnInit() and exit the handler if the handle is not valid (and it is null at best. In the worst case - there is rubbish there, because Handle_ATR is not initialised). You create an indicator with assigning a valid value to the handle only in OnTick() - what's the point? In OnInit() create an indicator and get its handle. In OnTick(), use the handle to get indicator data.

 
Artyom Trishkin #:

Wrong.

You check the handle in OnInit() and exit the handler if the handle is not valid (and it is null at best. In the worst case - there is rubbish there, because Handle_ATR is not initialised). You create an indicator with assigning a valid value to the handle only in OnTick() - what's the point? In OnInit() create an indicator and get its handle. In OnTick(), use the handle to get indicator data.

Thank you, Artem. I'm not fully awake yet. )) I'll fix it now.

Regards, Vladimir.

P.S. Fixed the code.
 
MrBrooklin #:
double atr_value=NormalizeDouble(atr_array_value[0], 5); // normalise ATR indicator values
Why? What is the point?
Reason: