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

Nadaraya-Watson Envelope NR

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

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

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

О программе

Индикатор Nadaraya-Watson Envelope NR предназначен для платформы MetaTrader 5 и реализует оценку конечной точки с использованием гауссовых весов. Он строит верхнюю и нижнюю границы огибающей на основе средней абсолютной ошибки и отображает сигналы пересечения ценой этих границ в виде стрелок на графике.

Индикатор поддерживает выбор типа цены для расчётов (Close, Open, High, Low, Median, Typical, Weighted), а также настраивает цвет верхней и нижней линий и сигналов. Пересчёт выполняется инкрементально — для текущего и последнего закрытого бара, что позволяет сохранять исторические значения без повторного полного пересчёта.

В качестве входных параметров доступны ширина ядра и множитель огибающей. Индикатор работает на стандартном графике MetaTrader 5 и использует четыре отрисовки: две линии огибающей и два набора стрелок-сигналов.

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

НастройкаОписание
InpBandwidth Параметр ширины ядра (bandwidth), определяющий скорость убывания гауссовых весов при удалении от текущего бара.
InpMult Множитель, используемый для масштабирования средней абсолютной ошибки при построении верхней и нижней границ огибающей.
InpSource Тип цены, используемой для расчётов: Close, Open, High, Low, Median, Typical или Weighted.
InpUpColor Цвет верхней линии огибающей и стрелок сигнала роста.
InpDownColor Цвет нижней линии огибающей и стрелок сигнала падения.
Получить полный код

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

#property version   "1.00"

#property description "Nadaraya-Watson Envelope NR"
#property description "Non-repainting Gaussian endpoint envelope with upper and lower bands."
#property description "Displays crossover signals when price crosses the envelope."
#property description "Developed by Derrick Njagi - Forexis.net"

#property strict
#property indicator_chart_window
#property indicator_plots   4
#property indicator_buffers 7

#property indicator_label1  "Upper"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrBlue
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1

#property indicator_label2  "Lower"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrRed
#property indicator_style2  STYLE_SOLID
#property indicator_width2  1

#property indicator_label3  "Crossunder"
#property indicator_type3   DRAW_ARROW
#property indicator_color3  clrBlue
#property indicator_width3  1

#property indicator_label4  "Crossover"
#property indicator_type4   DRAW_ARROW
#property indicator_color4  clrRed
#property indicator_width4  1

input group "Settings"
input double             InpBandwidth = 8.0;          // Bandwidth
input double             InpMult      = 3.0;          // Envelope multiplier
input ENUM_APPLIED_PRICE InpSource    = PRICE_CLOSE;  // Applied price

input group "Style"
input color              InpUpColor   = clrBlue;      // Upper line and upward signal color
input color              InpDownColor = clrRed;       // Lower line and downward signal color

double UpperBuffer[];
double LowerBuffer[];
double UpArrowBuffer[];
double DownArrowBuffer[];

double SourceBuffer[];
double OutBuffer[];
double ResidualBuffer[];

double g_gauss[500];
double g_den=0.0;

/*
   Calculate the Gaussian weight used by the endpoint estimator.
   The weight becomes smaller as the distance from the current
   price bar increases.
*/
double Gauss(const int x,const double h)
  {
   if(h<=0.0)
      return (x==0 ? 1.0 : 0.0);

   const double xd=(double)x;
   return MathExp(-(xd*xd)/(h*h*2.0));
  }

/*
   Return the price value selected by the user.

   This allows the envelope to work with Close, Open, High, Low,
   Median, Typical or Weighted price without changing the main
   calculation routine.
*/
double AppliedPriceAt(const int i,
                      const double &open[],
                      const double &high[],
                      const double &low[],
                      const double &close[])
  {
   switch(InpSource)
     {
      case PRICE_OPEN:
         return open[i];

      case PRICE_HIGH:
         return high[i];

      case PRICE_LOW:
         return low[i];

      case PRICE_MEDIAN:
         return (high[i]+low[i])*0.5;

      case PRICE_TYPICAL:
         return (high[i]+low[i]+close[i])/3.0;

      case PRICE_WEIGHTED:
         return (high[i]+low[i]+close[i]+close[i])*0.25;

      case PRICE_CLOSE:
      default:
         return close[i];
     }
  }

/*
   Perform a complete historical calculation.

   The first stage calculates the Gaussian endpoint value for every
   available bar. The absolute difference between price and the
   estimated value is stored for the envelope calculation.

   The second stage calculates the mean absolute error and builds
   the upper and lower bands.

   Signal arrows are generated when the closing price crosses the
   corresponding envelope boundary.
*/
void CalculateEndpointFull(const int rates_total,
                           const double &close[],
                           const double &high[],
                           const double &low[])
  {
   ArrayInitialize(UpperBuffer,EMPTY_VALUE);
   ArrayInitialize(LowerBuffer,EMPTY_VALUE);
   ArrayInitialize(UpArrowBuffer,EMPTY_VALUE);
   ArrayInitialize(DownArrowBuffer,EMPTY_VALUE);
   ArrayInitialize(OutBuffer,EMPTY_VALUE);
   ArrayInitialize(ResidualBuffer,EMPTY_VALUE);

   const int maxOut=rates_total-500;

   if(maxOut<0 || g_den==0.0)
      return;

   for(int i=maxOut;i>=0;i--)
     {
      double out=0.0;

      for(int k=0;k<500;k++)
         out+=SourceBuffer[i+k]*g_gauss[k];

      out/=g_den;

      OutBuffer[i]=out;
      ResidualBuffer[i]=MathAbs(SourceBuffer[i]-out);
     }

   const int maxMae=maxOut-498;

   if(maxMae<0)
      return;

   double residualSum=0.0;

   for(int k=0;k<499;k++)
      residualSum+=ResidualBuffer[maxMae+k];

   for(int i=maxMae;i>=0;i--)
     {
      if(i<maxMae)
        {
         residualSum+=ResidualBuffer[i];
         residualSum-=ResidualBuffer[i+499];
        }

      const double mae=(residualSum/499.0)*InpMult;

      UpperBuffer[i]=OutBuffer[i]+mae;
      LowerBuffer[i]=OutBuffer[i]-mae;

      if(i+1<rates_total && LowerBuffer[i+1]!=EMPTY_VALUE)
        {
         if(close[i]<LowerBuffer[i] &&
            close[i+1]>=LowerBuffer[i+1])
           {
            UpArrowBuffer[i]=low[i];
           }
        }

      if(i+1<rates_total && UpperBuffer[i+1]!=EMPTY_VALUE)
        {
         if(close[i]>UpperBuffer[i] &&
            close[i+1]<=UpperBuffer[i+1])
           {
            DownArrowBuffer[i]=high[i];
           }
        }
     }
  }

/*
   Recalculate a single recent endpoint bar.

   Only the current and most recently closed bars need to be refreshed
   during normal operation. Older endpoint values remain unchanged,
   which preserves historical indicator values and signals.
*/
void CalculateEndpo

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

Открыть по тарифу

Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.

Разовая покупка файла

На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.

Чтобы оформить заказ, введите email и перейдите к оплате.

Стоимость полного кода
762,60₽ ≈ $9.32