Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 483

 
2047728:
Hello, I have started to study MQL4 using video tutorials from 2013. I am rewriting the code exactly from the video, adding some minor changes from another video, as the result I have 25 errors. I have tried to look for solution to these errors, but since build of terminal has changed and some changes in coding have occurred. I will be grateful if someone can help me to edit the code or at least give some useful advice, thanks in advance.

And how does that help you? Next time, go straight to Freelance.

//+------------------------------------------------------------------+
//|                                                           ea.mq4 |
//|                                                             mql4 |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Intruder"
#property link      ""
#property version   "1.00"
#property strict

extern double Lots         = 0.1;
extern int    TakeProfit   = 50;
extern int    Step         = 50;
extern double Multiplier   = 2;
extern int    Slippage     = 5;
extern int    Magic        = 123;

extern int    MA_1_Period  = 21;
extern int    MA_1_Shift   = 0;

extern int    MA_2_Period  = 3;
extern int    MA_2_Shift   = 0;


int ticket;
double price,TP,lastlot;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int Init()
  {
   if(Digits==3 || Digits==5)
     {
      TakeProfit *= 10;
      Step       *= 10;
      Slippage   *= 10;
     }
   return(0);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Expert start function                                             |
//+------------------------------------------------------------------+
int start()
  {
   bool check;
   if(CountTrades()==0)
     {
      double ima_1 = iMA(Symbol(), PERIOD_CURRENT, MA_1_Period, MA_1_Shift, MODE_SMA, PRICE_CLOSE, 1);
      double ima_2 = iMA(Symbol(), PERIOD_CURRENT, MA_2_Period, MA_2_Shift, MODE_SMA, PRICE_CLOSE, 1);

      if(ima_1>ima_2)
        {
         ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,0,0,"",Magic,0,Blue);
         if(ticket>0)
           {
            TP=NormalizeDouble(Ask+TakeProfit*Point,Digits);
            check=OrderModify(ticket,OrderOpenPrice(),0,TP,0);
           }
        }
      else if(ima_1<ima_2)
        {
         ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,0,0,"",Magic,0,Red);
         if(ticket>0)
           {
            TP=NormalizeDouble(Bid-TakeProfit*Point,Digits);
            check=OrderModify(ticket,OrderOpenPrice(),0,TP,0);
           }
        }

     }
   else
     {
      int order_type= FindLastOrderType();
      if(order_type == OP_BUY)
        {
         price=FindLastOrderPrice(OP_BUY);
         if(Ask<=price-Step*Point)
           {
            lastlot = FindLastLots (OP_BUY);
            lastlot = NormalizeDouble(lastlot * Multiplier, 2);
            ticket=OrderSend(Symbol(),OP_BUY,lastlot,Ask,Slippage,0,0,"",Magic,0,Blue);
            if(ticket>0)
               ModifiOrders(OP_BUY);
           }
        }
      else if(order_type==OP_SELL)
        {
         price = FindLastOrderPrice(OP_SELL);
         if(Bid<= price + Step * Point)
           {
            lastlot = FindLastLots (OP_SELL);
            lastlot = NormalizeDouble(lastlot * Multiplier, 2);
            ticket=OrderSend(Symbol(),OP_BUY,lastlot,Bid,Slippage,0,0,"",Magic,0,Red);
            if(ticket>0)
               ModifiOrders(OP_SELL);
           }
        }
     }

   return(0);
  }
//+------------------------------------------------------------------+
void ModifiOrders(int otype)
  {
   double avgprice=0,
   order_lots=0;
   bool check;
   price=0;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==otype)
           {
            price+=OrderOpenPrice()*OrderLots();
            order_lots+=OrderLots();
           }
        }
     }
   avgprice=NormalizeDouble(price/order_lots,Digits);

   if(otype == OP_BUY) TP = NormalizeDouble(avgprice + TakeProfit*Point, Digits);
   if(otype == OP_SELL) TP = NormalizeDouble(avgprice - TakeProfit*Point, Digits);

   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==otype)
            check=OrderModify(OrderTicket(),OrderOpenPrice(),0,TP,0);
        }
     }
  }
//+------------------------------------------------------------------+
double FindLastLots(int otype)
  {
   double oldlots=0;
   int oldticket=0;

   ticket=0;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==otype)
           {
            oldticket=OrderTicket();
            if(oldticket>ticket)
              {
               oldlots= OrderLots();
               ticket = oldticket;
              }
           }
        }
     }
   return(oldlots);
  }
//+------------------------------------------------------------------+
double FindLastOrderPrice(int otype)
  {
   double oldopenprice=-1;
   int    oldticket=0;

   ticket=0;

   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==otype)
           {
            oldticket=OrderTicket();
            if(oldticket>ticket)
              {
               oldopenprice=OrderOpenPrice();
               ticket=oldticket;
              }
           }
        }
     }
   return(oldopenprice);
  }
//+------------------------------------------------------------------+
int FindLastOrderType()
  {
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
            return(OrderType());
        }
     }
   return(-1);
  }
//+------------------------------------------------------------------+
int CountTrades()
  {
   int count= 0;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic) count++;
        }
     }
   return(count);
  }
//-------------------------------------------------------------------+
 
2047728:

Hello, I have started to study MQL4 using the 2013 video tutorials, I have been rewriting the code exactly from the video, adding some minor changes from another one, as I need them. As a result I get 25 errors. I have tried to look for solution to these errors, but since build of terminal has changed and some changes in coding have occurred. I will be grateful if someone can help me to edit the code or at least give me some useful advice, thanks in advance.

Add changes one by one and fix bugs - you will learn step by step. Want to learn the language - start with simple examples

 

Good afternoon! Please help me understand the indicator code. There is a zero level, based on it, you need to fill the first level. What I don't do, what doesn't work. Here is the indicator code:

 //+---------------------------------------------------------------------------------------------------------+
//|                                                                                        Trend Levels.mq5 |
//|                                                                                                   Serzh |
//+---------------------------------------------------------------------------------------------------------+
#property copyright "Serzh"
#property version    "1.00"

//--------------------------------Входные параметры----------------------------------------------------------

#property indicator_chart_window                  // Индикатор отображается в окне графика
#property indicator_buffers 4                      // К-во индикаторных буферов
#property indicator_plots    2                      // К-во графических серий

//--------------------------------Инициализация графических серий--------------------------------------------

#property indicator_label1    "Максимумы 1-го ровня"          // Название индикаторной серии
#property indicator_type1    DRAW_ARROW                      // Тип линии индикатора
#property indicator_color1    clrDarkGreen                    // Цвет линии индикатора
#property indicator_width1    2                                // Толщина линии индикатора

#property indicator_label2    "Минимумы 1-го ровня"            // Название индикаторной серии
#property indicator_type2    DRAW_ARROW                      // Тип линии индикатора
#property indicator_color2    clrCrimson                      // Цвет линии индикатора
#property indicator_width2    2                                // Толщина линии индикатора

//--------------------------------Инициализация индикаторных массивов----------------------------------------

 double Max_1[],Min_1[];                                             // Индикаторные массивы
 double Max_0[],Min_0[];                                             // Вспомогательные массивы
   
//+---------------------------------------------------------------------------------------------------------+
//|                               Функция обработки события OnInit                                          |
//+---------------------------------------------------------------------------------------------------------+
int OnInit ()

  {
  
   EventSetTimer ( _Period );                                 // Установка Таймера

//-----------------------------------------------------------------------------------------------------------
   
   SetIndexBuffer ( 0 ,Max_1, INDICATOR_DATA );                 // Присвоение индикаторного массива буферу
   SetIndexBuffer ( 1 ,Min_1, INDICATOR_DATA );                 // Присвоение индикаторного массива буферу
   
   PlotIndexSetInteger ( 0 , PLOT_ARROW , 159 );                   // Установка кода символа для PLOT_ARROW
   PlotIndexSetInteger ( 1 , PLOT_ARROW , 159 );                   // Установка кода символа для PLOT_ARROW
   
   PlotIndexSetInteger ( 0 , PLOT_ARROW_SHIFT ,- 10 );             // Установка сдвига символа в пикселях
   PlotIndexSetInteger ( 1 , PLOT_ARROW_SHIFT , 10 );             // Установка сдвига символа в пикселях
    
   PlotIndexSetDouble ( 0 , PLOT_EMPTY_VALUE , 0 );               // Установка пустого значения
   PlotIndexSetDouble ( 1 , PLOT_EMPTY_VALUE , 0 );               // Установка пустого значения

//----------------------------------------------------------------------------------------------------------- 

   SetIndexBuffer ( 2 ,Max_0, INDICATOR_CALCULATIONS );                   // Присвоение индикаторного массива буферу
   SetIndexBuffer ( 3 ,Min_0, INDICATOR_CALCULATIONS );                   // Присвоение индикаторного массива буферу
   
   ArraySetAsSeries (Max_0, true );                                     // Установка индексаци массива как в таймсерии
   ArraySetAsSeries (Min_0, true );                                     // Установка индексаци массива как в таймсерии
   
//--------------------------------Инициализация массивов-----------------------------------------------------
   
   return ( INIT_SUCCEEDED );

  }
//+---------------------------------------------------------------------------------------------------------+
//|                               Функция обработки события OnCalculate                                     |
//+---------------------------------------------------------------------------------------------------------+
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 i0, i_1max, i_1min, i_1maxH= 0 , i_1minH= 0 ;                                 // Индексы
 
 int Max_1Index= 0 , Min_1Index= 0 ;                                               // Индексы максимальных и минимальных баров

 int Step_0, Step_1max, Step_1min;                                             // Шаги циклов
 
 int Start_1max, Start_1min;                                                   // Стартовая позиция
 
 int Stop_1maxA= 0 , Stop_1minA= 0 , Stop_1maxB= 0 , Stop_1minB= 0 ;                   // Ограничитель дальнейших действий
 
 int Shift_max1= 0 , Shift_min1= 0 ;                                               // Шифты
 
 int TotalMax_0= 0 , TotalMin_0= 0 ;                                               // Всего баров в нулевых массивах
 int TotalMax_1= 0 , TotalMin_1= 0 ;                                               // Всего баров в массивах 1-го уровня
 
 int imax_0= 0 , imin_0= 0 , imax_1= 0 , imin_1= 0 ;                                   // Инициализаторы массивов

 
//--------------------------------Расчет 0-го уровня индикатора----------------------------------------------

   if (prev_calculated< 4 ) Step_0= 1 ;                                               // Если расчетов еще небыло Step_0=1
   else Step_0=rates_total- 3 ;                                                   // Если расчеты уже были Step_0=rates_total-3
  
   for (i0=Step_0;i0<rates_total- 2 ;i0++)                                         // Цикл для расчетов
    {
     if (high[i0+ 1 ]<high[i0] && high[i0]>=high[i0- 1 ]) Max_0[i0]=high[i0];       // Присвоение значения массиву Max_0
     else Max_0[i0]= 0 ;                                                         // Присвоение 0 значения массиву
     TotalMax_0= ArrayRange (Max_0,imax_0);                                       // Всего баров в массиве Max_0
         
     if (low[i0+ 1 ]>low[i0] && low[i0]<=low[i0- 1 ])     Min_0[i0]=low[i0];       // Присвоение значения массиву Min_0
     else Min_0[i0]= 0 ;                                                         // Присвоение 0 значения массиву
     TotalMin_0= ArrayRange (Min_0,imin_0);                                       // Всего баров в массиве Min_0
    }

//--------------------------------Расчет максимума 1-го уровня индикатора------------------------------------

   if (TotalMax_1< 2 ) Step_1max= 1 ;                                               // Если расчетов еще небыло Step_1max=1
   else Step_1max=TotalMax_0- 1 ;                                                 // Если расчеты уже были Step_1max=TotalMax_0-1
  
   for (i_1max=Step_1max;i_1max<TotalMax_0- 1 ;i_1max++)                           // Главный цикл для заполнения массива Max_1
      {
       if (Max_0[i_1max]>Min_0[i_1max] && Stop_1maxA< 1 )                         // Нахождение ситуации когда Max_0 больше Min_0
          {
           Start_1max=i_1max;                                                   // Определение стартовой позиции
           Stop_1maxA= 1 ;                                                       // Задается значение пераметру Stop_1maxA
           Stop_1minA= 0 ;                                                       // Задается значение пераметру Stop_1minA
           
           for (i_1maxH=i_1max;Max_0[i_1maxH]>=Min_0[i_1maxH];i_1maxH++)       // Цикл для подсчета к-ва баров
           {Shift_max1++;}                                                     // Подсчет к-ва баров для расчета максимального индекса
           Max_1Index= ArrayMaximum (Max_0,Start_1max,Shift_max1);               // Вычисление максимального индекса
          }
       if (i_1max==Max_1Index) Max_1[i_1max]=Max_0[i_1max];                     // Присвоение значения массиву Max_1
       else Max_1[i_1max]= 0 ;                                                   // Присвоение 0 значения массиву Max_1
       TotalMax_1= ArrayRange (Max_1,imax_1);                                     // Всего баров в массиве Max_1
       
       if (Max_0[i_1max]<Min_0[i_1max] && Stop_1minA< 1 )                         // Нахождение ситуации когда Max_0 меньше Min_0
          {
           Stop_1maxA= 0 ;                                                       // Изменение параметра Stop_1maxA
           Stop_1minA= 1 ;                                                       // Изменение параметра Stop_1minA
          }
      }

//--------------------------------Расчет минимума 1-го уровня индикатора-------------------------------------

   if (TotalMin_1< 2 ) Step_1min= 1 ;                                               // Если расчетов еще небыло Step_1min=1
   else Step_1min=TotalMin_0- 1 ;                                                 // Если расчеты уже были Step_1min=TotalMin_0-1
  
   for (i_1min=Step_1min;i_1min<TotalMin_0- 1 ;i_1min++)                           // Главный цикл для заполнения массива Min_1
      {
       if (Min_0[i_1min]>Max_0[i_1min] && Stop_1minB< 1 )                         // Нахождение ситуации когда Min_0 больше Max_0
          {
           Start_1min=i_1min;                                                   // Определение стартовой позиции
           Stop_1minB= 1 ;                                                       // Задается значение пераметру Stop_1minB
           Stop_1maxB= 0 ;                                                       // Задается значение пераметру Stop_1maxB
           
           for (i_1minH=i_1min;Min_0[i_1minH]>=Max_0[i_1minH];i_1minH++)       // Цикл для подсчета к-ва баров
           {Shift_min1++;}                                                     // Подсчет к-ва баров для расчета минимального индекса
           Min_1Index= ArrayMinimum (Min_0,Start_1min,Shift_min1);               // Вычисление максимального индекса
          }
       if (i_1min==Min_1Index) Min_1[i_1min]=Min_0[i_1min];                     // Присвоение значения массиву Min_1
       else Min_1[i_1min]= 0 ;                                                   // Присвоение 0 значения массиву Min_1
       TotalMin_1= ArrayRange (Min_1,imin_1);                                     // Всего баров в массиве Min_1
       
       if (Min_0[i_1min]<Max_0[i_1min] && Stop_1maxB< 1 )                         // Нахождение ситуации когда Min_0 меньше Max_0
          {
           Stop_1minB= 0 ;                                                       // Изменение параметра Stop_1minB
           Stop_1maxB= 1 ;                                                       // Изменение параметра Stop_1maxB
          }
      }

//--------------------------------------------------------------   
   return (rates_total);
  }
//+---------------------------------------------------------------------------------------------------------+
//|                               Функция обработки события Таймер                                          |
//+---------------------------------------------------------------------------------------------------------+
   void OnTimer (){}
//+---------------------------------------------------------------------------------------------------------+

//+---------------------------------------------------------------------------------------------------------+
//|                               Функция обработки события OnDeinit                                        |
//+---------------------------------------------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
   EventKillTimer ();                                                 // Удаление Таймера
   Print ( __FUNCTION__ , "_Код причины деинициализации = " ,reason);     // Причина деинициализации
  }
 

Please help.

I can't seem to create a script on this topic, here's the page https://www.mql5.com/ru/articles/1368

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

We write a script to save chart data to *.csv file (application s_ExportChartToCSV_v1.mq4 file):

int start(){
   int h=FileOpen(Symbol()+Period()+".csv",FILE_WRITE|FILE_CSV,",");
      for(int i=Bars-1;i>=0;i--){
         FileWrite(h,TimeToStr(Time[i],TIME_DATE),TimeToStr(Time[i],TIME_MINUTES),Open[i],High[i],Low[i],Close[i],Volume[i]);
      }
   FileClose(i);
   return(0);
}

Execute the script on non-standard timeframes charts. As a result of the script running, we receive standard *.csv files with non-standard timeframe data in the directory experts/filies.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Если можно сделаете скрипт

thanks in advance

Тестирование экспертов на нестандартных таймфреймах
Тестирование экспертов на нестандартных таймфреймах
  • 2009.05.18
  • Dmitry Fedoseev
  • www.mql5.com
Цена на рынке меняется с достаточно большой частотой, чтобы для технического анализа было удобно пользоваться графиком непосредственного изменения цены, так называемого тикового графика. Для упрощения восприятия изменений цены и обеспечения возможности использования в анализе большие интервалы времени используется отображение графиков в виде...
 

since when did the strategy tester start charging swap?

or haven't I noticed?

why not include it in the HTML version of the report?

 
Vladislav Andruschenko:

since when did the strategy tester start charging swap?

or haven't I noticed?

why not include it in the HTML version of the report?

It has always been like that.

That is why test results with the same settings might be slightly different due to swap changes. Or the results in optimization and tests differ, if the optimization was long and swap has changed during this time.

 
Sergey Basov:

This has always been the case.

That is why test results with the same settings may be slightly different because of swap changes. Or the results are different in optimization and tests, if the optimization was long and swap has changed during this time.


I never noticed that! I thought there was no swap in mt4 in the strategy tester.

 
Guys, please advise. I can't find ADX indicator signals in MQL5 for EA generation
 

Good evening everyone!

In the Strategy Tester the order is modified without any problems, but on a demo account this modification does not work.

Stop Loss is modified. In the tester stoploss can be only 1 pip away from the current price but in demo accounts even if we set stoploss at a distance of spread + 6-8 pips more.

MODE_STOPLEVEL=0, MODE_FREEZELEVEL=0.

Please advise why and how to do correct modification.

 
Valerius:

Good evening everyone!

In the Strategy Tester the order is modified without any problems, but on a demo account this modification does not work.

Stop Loss is modified. In the tester stoploss can be only 1 pip away from the current price but in demo accounts even if we set stoploss at a distance of spread + 6-8 pips more.

MODE_STOPLEVEL=0, MODE_FREEZELEVEL=0.

Please advise why and how to do correct modification.

0 means a floating stop. In the tester, the spread is fixed. If you set 1, then 1 will always be there. But in real life it floats.
Reason: