Любые вопросы новичков по MQL4 и MQL5, помощь и обсуждение по алгоритмам и кодам - страница 2646

 

коллеги - может у кого будет время помочь вот индикатор МА кривую рисует не правильно - отображаю по аналогии с этой статьей - нужно правильная кривая SMA

не правильно отображает кривую SMA


//+------------------------------------------------------------------+
//|                                                   SpreadSMA.mq5  |
//|                        Copyright 2025, Roman Shiredchenko        |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, Roman Shiredchenko"
#property version   "1.4"
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots   2
//--- plot Spread
#property indicator_label1  "Spread"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrGold
#property indicator_style1  STYLE_SOLID
#property indicator_width1  2
//--- plot SMA
#property indicator_label2  "SMA"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrRed
#property indicator_style2  STYLE_SOLID
#property indicator_width2  2

//--- input parameters
input double Weighting_coefficients1 = 1;          // proportionality factor (position volume) of the first spread symbol
input int Coefficient_to_an_integer1 = 100000;     // number of quotation marks Sym 1
input string Symbol2 = "EURUSD";                   // second spread symbol
input bool Reverse = true;                         // inverse correlation
input double Weighting_coefficients2 = 1;          // proportionality factor (position volume) of the first spread symbol
input int Coefficient_to_an_integer2 = 100000;     // number of quotation marks Sym 2
input int MAPeriod = 14;                           // SMA period

//--- indicator buffers
double SpreadBuffer[];
double SMABuffer[];

//--- global variables
int priv = 0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
{
   // Check symbol availability
   if(!SymbolSelect(Symbol2, true))
      return INIT_FAILED;
      
   // Set indicator buffers
   SetIndexBuffer(0, SpreadBuffer, INDICATOR_DATA);
   SetIndexBuffer(1, SMABuffer, INDICATOR_DATA);
   
   // Set indicator properties
   ArraySetAsSeries(SpreadBuffer, true);
   ArraySetAsSeries(SMABuffer, true);
   
   // Set plot properties
   PlotIndexSetString(0, PLOT_LABEL, "Spread");
   PlotIndexSetString(1, PLOT_LABEL, "SMA("+IntegerToString(MAPeriod)+")");
   IndicatorSetInteger(INDICATOR_DIGITS, 0);
   PlotIndexSetInteger(0, PLOT_SHIFT, 0);
   
   // Set timer for auto-refresh
   EventSetTimer(1);
   
   return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
//| Calculate SMA function                                           |
//+------------------------------------------------------------------+
void CalculateSMA(double &price[], double &maBuffer[], int maPeriod, int rates_total, int prev_calculated)
{
   if (rates_total < maPeriod - 1)
      return;
    
   int first, bar, iii;
   double Sum, SMA;
   
   if (prev_calculated == 0)
      first = maPeriod - 1;
   else 
      first = prev_calculated - 1;

   for(bar = first; bar < rates_total; bar++)
   {
      Sum = 0.0;
      for(iii = 0; iii < maPeriod; iii++)
         Sum += price[bar - iii];
     
      SMA = Sum / maPeriod;
      maBuffer[bar] = SMA;
   }
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
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[])
{
   int limit = 0, corr = 0;
   if(prev_calculated <= 0)
   {
      limit = rates_total - 1;
      priv = 0;
   }

   ArraySetAsSeries(time, true);
   ArraySetAsSeries(open, true);
   
   if(Bars(Symbol2, PERIOD_CURRENT) == 0)
      return 0;
   
   // Calculate spread values
   for(int i = limit; i >= 0; i--)
   {
      datetime time2 = iTime(Symbol2, PERIOD_CURRENT, i - corr);
      if(time2 > time[i]) // if there is no such bar on the current instrument
      {
         corr++;
         continue;
      }
      
      double open2 = iOpen(Symbol2, PERIOD_CURRENT, i);
      if(open2 != 0)
      {
         if(!Reverse)
            SpreadBuffer[i] = NormalizeDouble(
               Coefficient_to_an_integer1 * Weighting_coefficients1 * open[i] - 
               Coefficient_to_an_integer2 * Weighting_coefficients2 * open2, 0);
         else
            SpreadBuffer[i] = NormalizeDouble(
               Coefficient_to_an_integer1 * Weighting_coefficients1 * open[i] + 
               Coefficient_to_an_integer2 * Weighting_coefficients2 * open2, 0);
      }     
   }
   
   // Calculate SMA of spread
   CalculateSMA(SpreadBuffer, SMABuffer, MAPeriod, rates_total, prev_calculated);
   
   priv = rates_total;
   return rates_total;
}
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
{
   if(priv <= 0) // if it's a weekend and there are no new ticks
      ChartSetSymbolPeriod(0, _Symbol, PERIOD_CURRENT);
   else
      ChartRedraw();
}
//+------------------------------------------------------------------+
//| Deinitialization function                                        |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   EventKillTimer();
}
//+------------------------------------------------------------------+
Пользовательские индикаторы в MQL5 для начинающих
Пользовательские индикаторы в MQL5 для начинающих
  • 2010.03.03
  • www.mql5.com
Любой новый предмет для новичка с первого взгляда кажется сложным для понимания. Нам кажется простым и ясным то, что мы уже знаем. Но мы просто не помним, что всем нам когда-то приходилось изучать с нуля, даже родной язык, на котором мы разговариваем. Так и язык MQL5, таящий в себе огромные возможности для написания торговых стратегий, можно начать изучать с базовых понятий и примеров. В этой статье на примере пользовательского индикатора SMA рассматривается взаимодействие технического индикатора с клиентским терминалом MetaTrader 5.
Файлы:
SpreadsSMA.mq5  12 kb
[Удален]  
Aleksandr Slavskii #:

Новый компилятор выдаёт предупреждение на такой код

то есть на глобале объявлена структура

Теперь обычную структуру нужно копировать как-то по-другому.

Вопрос как?

Поэлементно?

Или есть какой то более красивый способ, а то ведь в структурах бывает и поболее чем два элемента.

struct CPoint
{
   int x;
   int y;
   
   CPoint() : x( 0 ), y( 0 ){}
   CPoint( const CPoint& point ) : x( point.x ), y( point.y ){}
};
 
Koldun Zloy #:

Большое спасибо!

 
Roman Shiredchenko #:

коллеги - может у кого будет время помочь вот индикатор МА кривую рисует не правильно - отображаю по аналогии с этой статьей - нужно правильная кривая SMA

не правильно отображает кривую SMA


Тут нет вопроса как такового. Могу продать свое время для решения. Или же можете сделать сами используя отладчик.

 
Andrei Sokolov #:

Тут нет вопроса как такового. Могу продать свое время для решения. Или же можете сделать сами используя отладчик.

игнорьте мои запросы они не для вас

 
Roman Shiredchenko #:

коллеги - может у кого будет время помочь вот индикатор МА кривую рисует не правильно - отображаю по аналогии с этой статьей - нужно правильная кривая SMA

не правильно отображает кривую SMA

Файлы:
Indi1.mq5  6 kb
 
Roman Shiredchenko #:

игнорьте мои запросы они не для вас

Агенты по недвижимости подъехали) 
 
Roman Shiredchenko #:

коллеги - может у кого будет время помочь вот индикатор МА кривую рисует не правильно - отображаю по аналогии с этой статьей - нужно правильная кривая SMA

не правильно отображает кривую SMA


   

Файлы:
SpreadsSMA.mq5  11 kb
 
Tretyakov Rostyslav #:

   

Сенкс! О! Великий программист! )Ростислав!

я не шучу. Спсб! Разберу по косточкам код и сделаю тоже самое для свечного спреда!!! 

Тут то работа то одно то другое - не мог сам докрутить...

казалось бы да - вот всё элементарно - спсб! 

щас еще раз все перекурю и в индик спреда по свечам сам правки внесу!!!

   // Calculate SMA of spread
      double Sum = 0.0;
      for(int j = i; j < i+MAPeriod; j++) Sum += SpreadBuffer[j];
      SMABuffer[i] = Sum / MAPeriod;
 
Vitaly Muzichenko #:

Виталий - спасибо большое взял в работу!

тоже все ок работает 

функцию изучу: 

//+------------------------------------------------------------------+
//| Calculate SMA function                                           |
//+------------------------------------------------------------------+
double SMA(const int rates_total,const double &array_src[],const int period,const int shift)
{
  if(period<1 || shift>rates_total-period-1)
    return array_src[shift];
  double sum=0;
  for(int i=0; i<period; i++)
    sum+=array_src[shift+i];
  return(sum/period);
}


  for(int i = limit; i >= 0; i--)
    SMABuffer[i] = SMA(rates_total,SpreadBuffer,MAPeriod,i);