← К каталогу
Исходный код · ID 4936

RVOL

rvol.mq5
Вы автор или правообладатель?

Сообщите нам, если считаете, что материал размещён без разрешения.

Краткий обзор

О программе

RVOL — это пользовательский индикатор для MetaTrader 5, который рассчитывает относительный объём (Relative Volume): отношение объёма текущей свечи к среднему объёму. Индикатор отображает результат в виде цветной гистограммы в отдельном подокне и помогает визуально оценить, насколько текущий объём отличается от типичного.

Средний объём может рассчитываться двумя способами: за предыдущие N свечей или за то же время суток на предыдущие N торговых дней (только для внутридневных таймфреймов). Пользователь задаёт период усреднения, тип объёма (тиковый или реальный), а также пороговые уровни для выделения повышенного и экстремального объёма.

Гистограмма окрашивается в разные цвета в зависимости от превышения уровней. По желанию отображается текстовая метка с значениями RVOL закрытой и формирующейся свечей. Индикатор включает три горизонтальных уровня: базовый (1.0), повышенный и экстремальный.

Настройки программы

НастройкаОписание
InpMode Режим расчёта среднего объёма: за предыдущие N свечей или за то же время суток на предыдущие N дней
InpPeriod Количество свечей (или дней), используемых для расчёта среднего объёма
InpVolumeType Тип объёма для расчёта: тиковый или реальный (при нулевом реальном объёме используется тиковый)
InpHighLevel Уровень RVOL, обозначающий повышенный объём
InpExtremeLevel Уровень RVOL, обозначающий экстремальный объём
InpColorNormal Цвет гистограммы при RVOL ниже повышенного уровня
InpColorHigh Цвет гистограммы при RVOL на или выше повышенного уровня
InpColorExtreme Цвет гистограммы при RVOL на или выше экстремального уровня
InpShowLabel Отображать ли текстовую метку с последними значениями RVOL
InpLabelColor Цвет текстовой метки с последними значениями RVOL

Поиск по коду файла

#property version   "1.00"
#property description "Relative Volume (RVOL) = volume of a bar / average volume."
#property description "The average is taken over the previous N bars, or over the same"
#property description "time of day on the previous N days (intraday timeframes)."

#property indicator_separate_window
#property indicator_buffers 3
#property indicator_plots   1
#property indicator_minimum 0.0

#property indicator_label1  "RVOL"
#property indicator_type1   DRAW_COLOR_HISTOGRAM
#property indicator_color1  clrGray,clrDodgerBlue,clrOrangeRed
#property indicator_style1  STYLE_SOLID
#property indicator_width1  3

#property indicator_level1  1.0
#property indicator_level2  1.5
#property indicator_level3  3.0
#property indicator_levelcolor clrDimGray
#property indicator_levelstyle STYLE_DOT
#property indicator_levelwidth 1

enum ENUM_RVOL_MODE
  {
   RVOL_MODE_BARS,         // Previous N bars
   RVOL_MODE_SAME_TIME     // Same time of day, previous N days (intraday only)
  };

enum ENUM_RVOL_VOLUME
  {
   RVOL_VOL_TICK,          // Tick volume
   RVOL_VOL_REAL           // Real volume (falls back to tick volume if 0)
  };

input group "Baseline"
input ENUM_RVOL_MODE   InpMode         = RVOL_MODE_BARS;       // Average volume mode
input int              InpPeriod       = 20;                   // N: number of bars (or days) in the average
input ENUM_RVOL_VOLUME InpVolumeType   = RVOL_VOL_TICK;        // Volume type

input group "Levels"
input double           InpHighLevel    = 1.5;                  // RVOL level marking elevated volume
input double           InpExtremeLevel = 3.0;                  // RVOL level marking extreme volume

input group "Colors and label"
input color            InpColorNormal  = clrGray;              // Histogram color: RVOL below the high level
input color            InpColorHigh    = clrDodgerBlue;        // Histogram color: RVOL at or above the high level
input color            InpColorExtreme = clrOrangeRed;         // Histogram color: RVOL at or above the extreme level
input bool             InpShowLabel    = true;                 // Show the text label with the latest values
input color            InpLabelColor   = clrGray;              // Text label color

double BufRvol[];          // 0: RVOL values (histogram)
double BufColor[];         // 1: color index of each histogram bar
double BufVol[];           // 2: volume of each bar as double (calculation buffer)

ENUM_RVOL_MODE g_mode;        // effective mode (may differ from the input on D1 and above)
string         g_shortName;   // indicator short name
string         g_labelName;   // name of the text label object
string         g_lastText;    // last text written to the label (avoids needless updates)
int            g_minDays;     // minimum number of days required in the same-time mode

int ColorIndexOf(const double rvol)
  {
   if(rvol >= InpExtremeLevel)
      return(2);
   if(rvol >= InpHighLevel)
      return(1);
   return(0);
  }

string FormatValue(const double rvol)
  {
   if(rvol == EMPTY_VALUE)
      return("n/a");
   return(DoubleToString(rvol, 2) + "x");
  }

int FindExactBar(const datetime &time[], const int last, const datetime t)
  {
   int lo = 0;
   int hi = last;                          // search in [lo, hi)
   while(lo < hi)
     {
      int mid = (lo + hi) >> 1;
      if(time[mid] < t)
         lo = mid + 1;
      else
         hi = mid;
     }
   if(lo < last && time[lo] == t)
      return(lo);
   return(-1);
  }

int AverageOfPreviousBars(const int i, double &average)
  {
   average = 0.0;
   if(i < InpPeriod)
      return(0);                           // the full window is required

   double sum = 0.0;
   for(int k = 1; k <= InpPeriod; k++)
      sum += BufVol[i - k];
   average = sum / InpPeriod;
   return(InpPeriod);
  }

int AverageOfSameTime(const datetime &time[], const int i, double &average)
  {
   average = 0.0;
   int      found    = 0;
   double   sum      = 0.0;
   int      max_days = InpPeriod * 2 + 5;  // calendar days to look back
   datetime t        = time[i];

   for(int d = 1; d <= max_days && found < InpPeriod; d++)
     {
      t -= 86400;                          // same time, one day earlier
      if(t < time[0])
         break;
      int idx = FindExactBar(time, i, t);
      if(idx >= 0)
        {
         sum += BufVol[idx];
         found++;
        }
     }

   if(found < g_minDays)
      return(0);
   average = sum / found;
   return(found);
  }

void UpdateLabel(const int rates_total)
  {
   if(!InpShowLabel)
      return;

   int sub = ChartWindowFind();             // subwindow where this indicator runs
   if(sub < 0)
      return;

   int found_in = Ob

Показано первые 50% кода (символов: 6742)