Questions from Beginners MQL5 MT5 MetaTrader 5 - page 421

 

Made the calculation only at bar change - my method :) If you have any ideas for optimisation - I will listen!

//+------------------------------------------------------------------+
//|                                                       Target.mq4 |
//|                      Copyright © 2008, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2008, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict


double CC;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---

//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   if (Close[1]-CC!=0)
   {
   CC=Close[1]; 
 
   double MAT=NormalizeDouble(iMA(Symbol(),0,100,0,0,0,0),Digits);
   double S=11*Point;
   double Target;
   int Buy=1;
   int Sell=1;
   if(Open[0]-MAT>S || MAT-Open[0]<S) //Условие убытка - надо искать новый TP
     {
      if(Buy==1) //Если условно ордеров на покупку больше, чем ордеров на продажу (проверять лучше по объему позиции)
        {
         double TargetMassiv[5];        //Создаем массив
         double TargetMassivOk[5];      //Создаем массив
         int N=0;                       //Переменная для изменения размера массива
         int X=0;                       //Переменная для получение информации о номере индекса массива, наиболее соответствующему усредненному значению массива
 
         int Max=0;
         int Min=0;
         int MaxBuy=0;
         int MinBuy=0;
         double sr_Target=0;

         ArrayFree  (TargetMassiv);         //Очищаем массив
         ArrayFree  (TargetMassivOk);       //Очищаем массив
         ArrayResize(TargetMassiv,5,0);     //Восстанавливаем размер массива
         ArrayResize(TargetMassivOk,5,0);   //Восстанавливаем размер массива

         TargetMassiv[0]=NormalizeDouble (iMA(Symbol(),0,100,0,0,0,100),Digits);
         TargetMassiv[1]=NormalizeDouble (iMA(Symbol(),0,100,0,1,0,0),Digits);
         TargetMassiv[2]=NormalizeDouble (iMA(Symbol(),0,55,0,2,0,0),Digits);
         TargetMassiv[3]=NormalizeDouble (iMA(Symbol(),0,88,0,3,0,0),Digits);
         TargetMassiv[4]=NormalizeDouble (iMA(Symbol(),0,12,0,0,0,0),Digits);

         for(int i=0;i<5;i++) //Записываем значение в новый массив по условию
           {
            if(TargetMassiv[i]>MAT && TargetMassiv[i]!=0)
              {
               TargetMassivOk[i]=TargetMassiv[i];
               N++;

              }

           }

         ArraySort(TargetMassivOk,WHOLE_ARRAY,0,MODE_DESCEND);    //Сортировка массива
         if(N!=0)

           {
            ArrayResize(TargetMassivOk,N,0);

            Max=ArrayMaximum(TargetMassiv,WHOLE_ARRAY,0);
            Min=ArrayMinimum(TargetMassiv,WHOLE_ARRAY,0);
            MaxBuy=ArrayMaximum(TargetMassivOk,WHOLE_ARRAY,0);
            MinBuy=ArrayMinimum(TargetMassivOk,WHOLE_ARRAY,0);
            sr_Target=NormalizeDouble(iMAOnArray(TargetMassivOk,0,N,0,0,0),Digits);

            if(N==0)
              {X=N;}

            else

              {
               for(int i=0;i<N-1;i++)
                 {
                  if(sr_Target<=TargetMassivOk[i] && sr_Target>TargetMassivOk[i+1]) X=i;  //Берем большее значение т.к. для ордеров на покупку
                 }
              }

            Target=TargetMassivOk[X];
           }

         else

           {
            Max=0;
            Min=0;
            MaxBuy=0;
            MinBuy=0;
            sr_Target=0;
            Target=-1;
           }

         Print("Покупка");
         Print("Значения последних 5 элементов массива");
         for(int i=0;i<5;i++) printf("TargetMassiv[%d] = %G",i,TargetMassiv[i]);
         for(int i=0;i<N;i++) printf("TargetMassivOk[%d] = %G",i,TargetMassivOk[i]);

         Print("MAT= ",MAT);
         Print("Max= ",TargetMassiv[Max],"Min=",TargetMassiv[Min],"MaxBuy=",TargetMassivOk[MaxBuy],"MinBuy=",TargetMassivOk[MinBuy]);
         Print("Среднее значение массива TargetMassivOk= ",sr_Target);
         Print("Среднее значение массива TargetMassivOk наиболее соответствует индексу= ",X);
         Print("Target= ",Target);
        }

      /////////////////////////////////////////////////////////////////////////////

      if(Sell==1) //Если условно ордеров на продажу больше, чем ордеров на продажу (проверять лучше по объему позиции)     
        {
         double TargetMassiv[5];        //Создаем массив
         double TargetMassivOk[5];      //Создаем массив
         int N=0;                       //Переменная для изменения размера массива
         int X=0;                       //Переменная для получение информации о номере индекса массива, наиболее соответствующему усредненному значению массива
 
         int Max=0;
         int Min=0;
         int MaxSell=0;
         int MinSell=0;
         double sr_Target=0;


         ArrayFree  (TargetMassiv);         //Очищаем массив
         ArrayFree  (TargetMassivOk);       //Очищаем массив
         ArrayResize(TargetMassiv,5,0);     //Восстанавливаем размер массива
         ArrayResize(TargetMassivOk,5,0);   //Восстанавливаем размер массива

         TargetMassiv[0]=NormalizeDouble (iMA(Symbol(),0,100,0,0,0,100),Digits);
         TargetMassiv[1]=NormalizeDouble (iMA(Symbol(),0,100,0,1,0,0),Digits);
         TargetMassiv[2]=NormalizeDouble (iMA(Symbol(),0,55,0,2,0,0),Digits);
         TargetMassiv[3]=NormalizeDouble (iMA(Symbol(),0,88,0,3,0,0),Digits);
         TargetMassiv[4]=NormalizeDouble (iMA(Symbol(),0,12,0,0,0,0),Digits);

       // for(int i=0;i<5;i++)
         for(int i=4; i>=0; i--)
           {
            if(TargetMassiv[i]<MAT && TargetMassiv[i]!=0) //Записываем значение в новый массив по условию
              {
               TargetMassivOk[i]=TargetMassiv[i];
               N++;
              }

           }
         Print("N=",N);
         for(int i=0;i<N;i++) printf("До обработки TargetMassivOk[%d] = %G",i,TargetMassivOk[i]);
         ArraySort(TargetMassivOk,WHOLE_ARRAY,0,MODE_DESCEND);
        // ArraySort(TargetMassivOk,N,0,MODE_ASCEND);                //Сортировка массива
         if(N!=0)
           {
            ArrayResize(TargetMassivOk,N,0);
      //      ArraySort(TargetMassivOk,WHOLE_ARRAY,0,MODE_DESCEND);          //Дополнительная сортировка
            Max=ArrayMaximum(TargetMassiv,WHOLE_ARRAY,0);
            Min=ArrayMinimum(TargetMassiv,WHOLE_ARRAY,0);
            MaxSell=ArrayMaximum(TargetMassivOk,WHOLE_ARRAY,0);
            MinSell=ArrayMinimum(TargetMassivOk,WHOLE_ARRAY,0);
            sr_Target=NormalizeDouble(iMAOnArray(TargetMassivOk,0,N,0,0,0),Digits);

            for(int i=0;i<N-1;i++)
              {
               if(sr_Target<=TargetMassivOk[i] && sr_Target>TargetMassivOk[i+1]) X=i;
               //              if (X=!0) X=X-1;
              }
            Target=TargetMassivOk[X];
           }


         else

           {
            Max=0;
            Min=0;
            MaxSell=0;
            MinSell=0;
            sr_Target=0;
            Target=-1;
           }

         Print("Продажа");
         Print("Значения последних 5 элементов массива");
         for(int i=0;i<5;i++) printf("TargetMassiv[%d] = %G",i,TargetMassiv[i]);
         for(int i=0;i<N;i++) printf("TargetMassivOk[%d] = %G",i,TargetMassivOk[i]);

         Print("MAT=",MAT);
         Print("Max=",TargetMassiv[Max],"Min=",TargetMassiv[Min],"MaxSell=",TargetMassivOk[MaxSell],"MaxSell=",TargetMassivOk[MinSell]);
         Print("Среднее значение массива TargetMassivOk= ",sr_Target);
         Print("Среднее значение массива TargetMassivOk наиболее соответствует индексу= ",X);
         Print("Target= ",Target);
        }

     }
  }
}
//+------------------------------------------------------------------+

Автоматический трейдинг и тестирование торговых стратегий
Автоматический трейдинг и тестирование торговых стратегий
  • www.mql5.com
MQL5: язык торговых стратегий для MetaTrader 5, позволяет писать собственные торговые роботы, технические индикаторы, скрипты и библиотеки функций
 
-Aleks-:
Wrong - the enumeration works as it is, if the index value exceeded the array size, it would get cursed, and it doesn't. There is a value with zeros, and N can be non-zero! It turns out that the check also happens, then it turns out that the array doesn't write data.
I wasn't guessing, I was pointing out the incorrectness of the proposed loop. Think yourself from-where and to-where with an array size equal to five you need to make a loop...
 
Artyom Trishkin:
I wasn't guessing, I was pointing out the incorrectness of the proposed loop. Just think for yourself from-where and to-where with an array size equal to five, you need to make a loop...
In both my and your variants there are five values, please explain the difference.
 
-Aleks-:
Both mine and yours have five values, what is the difference - please explain.

The size of the array is five. If you index the array from 4 to 0, including zero, the loop will go through all the array values. If you try to index from five, the array is out of range. If you index from 4 to zero, not including zero, the loop will not go through the whole array - the zero cell of the array will not be read.

I.e. this is correct:

for(int i=4; i>=0; i--) {}

or

for(int i=0; i<5; i++) {}

The index of the array (i)
4
3
2
1
0
Array cell number
5
4
3
2
1
 
Artyom Trishkin:

The size of the array is five. If you index the array from 4 to 0, including zero, the loop will go through all the array values. If you try to index from five, the array is out of range. If you index from 4 to zero, not including zero, the loop will not go through the whole array - the zero cell of the array will not be read.

I.e. this is correct:

for(int i=4; i>=0; i--) {}

or

for(int i=0; i<5; i++) {}

The index of the array (i)
4
3
2
1
0
Array cell number
5
4
3
2
1
So you wrote in the example what I had written in the code. I don't understand what the difference is here...
 
Leanid Aladzyeu:

do a brute force attack from the end ( as the brute force attack may first lose data if the list is changed)


 

Leanid Aladzyeu:


Leanid Aladzyeu:

Do the re-build from the end ( as the re-build may first lose data if the list is changed)


It never ceases to amaze me... Why instead of learning how to use the rear-view mirrors, people just learn one traffic rule and turn the corner without looking and just go ahead...?

Why once you have read that when closing several orders from a list of open ones you have to go from the biggest to the smallest index and even advise others to go in this direction everywhere...

 
Alexey Viktorov:

It never ceases to amaze me... Why is it that instead of learning how to use rear-view mirrors, people just learn one point of the traffic rules and turn the corner without looking and go straight ahead?

Why once read that if we close several orders from a list of open ones we should try to go from a larger to a smaller index, and advise others to do this everywhere...?

The search possibilities may be whatever you want, it bothered me when I was closing from the last to the first one, it should have been vice versa. And I did, only there are nuances, not only the counter to rotate.
 
Alexey Viktorov:

It never ceases to amaze me... Why is it that instead of learning how to use rear-view mirrors, people just learn one point of the traffic rules and turn the corner without looking and go straight ahead???

Why once read that if you close several orders from a list of open ones you must go from a larger to a smaller index and advise others to always go in this direction...?

This is true for everything that is deleted in the loop (orders, graphical objects, etc.), because the deletion fills the previous cells of the "object array" with the subsequent "objects". In general, of course, we have to consider the situation. For example, when you draw indicators, it's silly, to put it mildly, to start drawing from the last element (rates_total-1).
 
Vladimir Zubov:
Duck, you can do it any way you like, I was straining to close from last to first, I should have done it the other way round. And I did, only there are nuances, not only the counter to turn.
Tapochun:
This is true for everything that is deleted in the loop (orders, graph objects, etc.) because deletion fills the previous cells of the "object array" with subsequent "objects". In general, of course, we have to consider the situation. For example, when you write indicators, it's silly, to put it mildly, to start drawing from the last element (rates_total-1).

Are you trying to explain me how to do it correctly? Or maybe I misunderstood something?

Actually, if I'm driving on a deserted road and don't see a single car or tractor around, I don't turn.

Reason: