Смотри, как бесплатно скачать роботов
Ищи нас в Twitter!
Ставь лайки и следи за новостями
Интересный скрипт?
Поставь на него ссылку - пусть другие тоже оценят
Понравился скрипт?
Оцени его работу в терминале MetaTrader 5
Просмотров:
348
Рейтинг:
(6)
Опубликован:
MQL5 Фриланс Нужен робот или индикатор на основе этого кода? Закажите его на бирже фрилансеров Перейти на биржу

Я разработал этот индикатор, чтобы предоставить альтернативу стандартным методам скользящей средней в индикаторе MetaTrader 5 Bollinger Bands, которые предлагают только "простой" метод. С моим индикатором у пользователей есть возможность выбрать один из дополнительных методов, включая Exponential, Smoothed и LinearWeighted.

Чтобы использовать этот индикатор, вам нужно поместить его в каталог (в Windows) по следующему пути:

C:\Users\lucas\AppData\Roaming\MetaQuotes\Terminal\Indicators\Examples

Добавлены функции:

один


По умолчанию он равен нулю:

два


Пример выполнения выбора среднего значения LinearWeighted:


дерево четыре


CODE:

//+------------------------------------------------------------------+
//|BBPersonalizada.mq5 |
//|Лукас Видал |
//|https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright   "Lucas Vidal"
#property link        "https://www.mql5.com/ru/users/lucasmoura00"
#property description "Bollinger Bands Personalizada"
#include <MovingAverages.mqh>
//---
#property indicator_chart_window
#property indicator_buffers 4
#property indicator_plots   3
#property indicator_type1   DRAW_LINE
#property indicator_color1  LightSeaGreen
#property indicator_type2   DRAW_LINE
#property indicator_color2  LightSeaGreen
#property indicator_type3   DRAW_LINE
#property indicator_color3  LightSeaGreen
#property indicator_label1  "Bands middle"
#property indicator_label2  "Bands upper"
#property indicator_label3  "Bands lower"
//--- входные параметры
enum MovingAverageMethod {
    Simple,    // 0
    Exponential,  // 1
    Smoothed,     // 2
    LinearWeighted  // 3
};
input MovingAverageMethod InpMaMethod = Simple; // Método da Média Móvel
input int     InpBandsPeriod=20;       // Период
input int     InpBandsShift=0;         // Смена
input double  InpBandsDeviations=2.0;  // Отклонение
//--- глобальные переменные
int           ExtBandsPeriod,ExtBandsShift;
double        ExtBandsDeviations;
int           ExtPlotBegin=0;
//--- индикаторный буфер
double        ExtMLBuffer[];
double        ExtTLBuffer[];
double        ExtBLBuffer[];
double        ExtStdDevBuffer[];
//+------------------------------------------------------------------+
//| Пользовательская функция инициализации индикатора |
//+------------------------------------------------------------------+
void OnInit()
  {
//--- проверка входных значений
   if(InpBandsPeriod<2)
     {
      ExtBandsPeriod=20;
      PrintFormat("Incorrect value for input variable InpBandsPeriod=%d. Indicator will use value=%d for calculations.",InpBandsPeriod,ExtBandsPeriod);
     }
   else
      ExtBandsPeriod=InpBandsPeriod;
   if(InpBandsShift<0)
     {
      ExtBandsShift=0;
      PrintFormat("Incorrect value for input variable InpBandsShift=%d. Indicator will use value=%d for calculations.",InpBandsShift,ExtBandsShift);
     }
   else
      ExtBandsShift=InpBandsShift;
   if(InpBandsDeviations==0.0)
     {
      ExtBandsDeviations=2.0;
      PrintFormat("Incorrect value for input variable InpBandsDeviations=%f. Indicator will use value=%f for calculations.",InpBandsDeviations,ExtBandsDeviations);
     }
   else
      ExtBandsDeviations=InpBandsDeviations;
//--- определите буферы
   SetIndexBuffer(0,ExtMLBuffer);
   SetIndexBuffer(1,ExtTLBuffer);
   SetIndexBuffer(2,ExtBLBuffer);
   SetIndexBuffer(3,ExtStdDevBuffer,INDICATOR_CALCULATIONS);
//--- установите метки индексов
   PlotIndexSetString(0,PLOT_LABEL,"Bands("+string(ExtBandsPeriod)+") Middle");
   PlotIndexSetString(1,PLOT_LABEL,"Bands("+string(ExtBandsPeriod)+") Upper");
   PlotIndexSetString(2,PLOT_LABEL,"Bands("+string(ExtBandsPeriod)+") Lower");
//--- название индикатора
   IndicatorSetString(INDICATOR_SHORTNAME,"Bollinger Bands");
//--- индексы рисуют начальные настройки
   ExtPlotBegin=ExtBandsPeriod-1;
   PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,ExtBandsPeriod);
   PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,ExtBandsPeriod);
   PlotIndexSetInteger(2,PLOT_DRAW_BEGIN,ExtBandsPeriod);
//--- индексы настройки сдвига
   PlotIndexSetInteger(0,PLOT_SHIFT,ExtBandsShift);
   PlotIndexSetInteger(1,PLOT_SHIFT,ExtBandsShift);
   PlotIndexSetInteger(2,PLOT_SHIFT,ExtBandsShift);
//--- количество цифр значения индикатора
   IndicatorSetInteger(INDICATOR_DIGITS,_Digits+1);
  }
//+------------------------------------------------------------------+
//| Рассчитать скользящее среднее|
//+------------------------------------------------------------------+
double CalculateMovingAverage(int position, int period, const double &price[]) {
    switch(InpMaMethod) {
        case Simple:
            return SimpleMA(position, period, price);
        case Exponential:
            // Исправление чамады функции iMA с помощью корректных параметров
            return iMA(NULL, 0, period, 0, MODE_EMA, PRICE_CLOSE);
        case Smoothed:
            // Implemente sua função SMMA aqui
            break;
        case LinearWeighted:
            return LinearWeightedMA(position, period, price);
    }
    return 0; // Восстановление падрана в случае неопределенного метода
}

//+------------------------------------------------------------------+
//| Полосы Боллинджера|
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const int begin,
                const double &price[])
  {
   if(rates_total<ExtPlotBegin)
      return(0);
//--- индексы рисуют настройки begin, когда мы получили предыдущие begin
   if(ExtPlotBegin!=ExtBandsPeriod+begin)
     {
      ExtPlotBegin=ExtBandsPeriod+begin;
      PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,ExtPlotBegin);
      PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,ExtPlotBegin);
      PlotIndexSetInteger(2,PLOT_DRAW_BEGIN,ExtPlotBegin);
     }
//--- начальный расчет
   int pos;
   if(prev_calculated>1)
      pos=prev_calculated-1;
   else
      pos=0;
//--- основной цикл
   for(int i=pos; i<rates_total && !IsStopped(); i++)
     {
      //--- средняя линия
      ExtMLBuffer[i]=CalculateMovingAverage(i, ExtBandsPeriod, price);
      //--- вычислите и запишите StdDev
      ExtStdDevBuffer[i]=StdDev_Func(i,price,ExtMLBuffer,ExtBandsPeriod);
      //--- верхняя строка
      ExtTLBuffer[i]=ExtMLBuffer[i]+ExtBandsDeviations*ExtStdDevBuffer[i];
      //--- нижняя строка
      ExtBLBuffer[i]=ExtMLBuffer[i]-ExtBandsDeviations*ExtStdDevBuffer[i];
     }
//--- OnCalculate done. Возвращаем новый prev_calculated.
   return(rates_total);
  }
//+------------------------------------------------------------------+
//| Вычислите стандартное отклонение|
//+------------------------------------------------------------------+
double StdDev_Func(const int position,const double &price[],const double &ma_price[],const int period)
  {
   double std_dev=0.0;
//--- calcualte StdDev
   if(position>=period)
     {
      for(int i=0; i<period; i++)
         std_dev+=MathPow(price[position-i]-ma_price[position],2.0);
      std_dev=MathSqrt(std_dev/period);
     }
//--- верните вычисленное значение
   return(std_dev);
  }
//+------------------------------------------------------------------+




Перевод с английского произведен MetaQuotes Ltd.
Оригинальная публикация: https://www.mql5.com/en/code/49464

Geometric Moving Average Geometric Moving Average

MQL5-версия геометрической скользящей средней.

Get Nth Active Trade from the end in MT5 Get Nth Active Trade from the end in MT5

Этот советник просканирует все открытые сделки, а затем выведет n-ую сделку с конца

OHLC Candles with Ask and Bid OHLC Candles with Ask and Bid

Свечной график, который соединяет цену спроса и цену предложения с максимумом и минимумом свечи

MathTicker - генератор тиков в математическом режиме MathTicker - генератор тиков в математическом режиме

Записывает тики в режиме по реальным тикам и считывает их в математическом вызывая вашу стратегию с каждым тиком.