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

 
Artyom Trishkin:
I recently posted a cross-platform indicator template here. Check it out.
IndicatorBuffers()

you need to blog and post answers to the same questions there.... I wish I had that kind of patience!

here's https://www.mql5.com/ru/forum/160683/page670#comment_9054670

Любые вопросы новичков по MQL4, помощь и обсуждение по алгоритмам и кодам
Любые вопросы новичков по MQL4, помощь и обсуждение по алгоритмам и кодам
  • 2018.10.18
  • www.mql5.com
В этой ветке я хочу начать свою помощь тем, кто действительно хочет разобраться и научиться программированию на новом MQL4 и желает легко перейти н...
 
Igor Makanu:

you should blog and post answers to the same questions there.... I wish I had that kind of patience!

Maybe you should. I don't have the time. And the questions will always be the same +/-

 
The problem is solved by assigning the auxiliary variables to the last buffer order numbers, but without prescribing the display settings. Before this, unnecessary buffers were in the middle of the list.
 

Help.

I want to place pending orders on positions that have been closed for the day.

The function puts the order at the price of the last closed position.

What should I do to put pending orders on the price of all the positions closed during the day?

oid PriceTimePos(string sy="",int op=-1,int mn=-1) 
  {
   datetime t;
   bool daa;
   int d,k_=OrdersTotal(),typ_;
   double   r=0;
   int      i,k=OrdersHistoryTotal();

   if(sy=="0") sy=Symbol();
   for(i=0; i<k; i++) 
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) 
        {
         if(OrderSymbol()==Symbol()) 
           {
            if(OrderType()==OP_BUY || OrderType()==OP_SELL) 
              {
               if(op<0 ||OrderType()==op) 
                 {
                  if(mn<0 || OrderMagicNumber()==mn) 
                    {
                     if(OrderCloseTime()>=TimeCurrent()-1440*60)
                       {
                        t=OrderCloseTime();
                        r=OrderOpenPrice();
                        sl=OrderStopLoss();
                        tp=OrderTakeProfit();
                        lot=OrderLots();
                        typ_=OrderType();
                        //Print("OpenPrice",r);
                       }
                    }
                 }
              }
           }
        }
     }
// ЕСТЬ ОРДЕР ПО ЦЕНЕ ЗАКРЫТОЙ ПОЗИЦИИ?
   daa=false;
   for(i=0; i<k; i++) 
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) 
        {
         if((OrderSymbol()==sy || sy=="") && (op<0 || OrderType()==op)) 
           {
            if(OrderType()>1 && OrderType()<6) 
              {
               d=MarketInfo(OrderSymbol(), MODE_DIGITS);
               r=NormalizeDouble(r, d);
               if(r==NormalizeDouble(OrderOpenPrice(),d)) {daa=true;}
              }
           }
        }
     }
   if(daa==false)//ЕСЛИ НЕТ ОРДЕРА ПО ЦЕНЕ, СТАВЛЮ
     {
      double opprord=0;
      for(i=0; i<k_; i++) 
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) 
           {
            if((OrderSymbol()==sy || sy=="") && (op<0 || OrderType()==op)) 
              {
               if(OrderType()>1 && OrderType()<6) 
                 {
                  d=MarketInfo(OrderSymbol(),MODE_DIGITS);
                  opprord=OrderOpenPrice();
                  // r=NormalizeDouble(r, d);
                  if(r!=NormalizeDouble(opprord,d))
                    {
                     if(r>Ask)
                       {
                        if(typ_==OP_BUY)
                          {
                           Print("OP_BUYSTOP",r);
                           SetOrder(Symbol(),OP_BUYSTOP,lot,r,sl,tp,_MagicNumber,0,"bs");
                          }
                        if(typ_==OP_SELL)
                          {
                           Print("OP_SELLLIMIT",r);
                           SetOrder(Symbol(),OP_SELLLIMIT,lot,r,sl,tp,_MagicNumber,0,"sl");
                          }
                       }

                     //
                     if(Bid>r)
                       {
                        if(typ_==OP_BUY)
                          {
                           Print("OP_BUYLIMIT",r);
                           SetOrder(Symbol(),OP_BUYLIMIT,lot,r,sl,tp,_MagicNumber,0,"bl");
                          }
                        if(typ_==OP_SELL)
                          {
                           Print("OP_SELLSTOP",r);
                           SetOrder(Symbol(),OP_SELLSTOP,lot,r,sl,tp,_MagicNumber,0,"bs");
                          }
                       }
                    }
                 }
              }
           }
        }
     }
//return(r);
  }
 
PolarSeaman:

Help.

I want to place pending orders on positions that have been closed for the day.

The function puts the order at the price of the last closed position.

What should I do to put pending orders on prices of all the positions closed within one day?

  1. Go through the list of closed positions in the loop, choosing those that close time is greater than the time of start of the required day (and less than the time of start of the next day, if it was the day before yesterday for example).
  2. Add all close prices (open prices - do not know what exactly you want to set them to) of all found positions to a simple array or an array of structures.
  3. Go through the created array in the loop and place pending orders at the array prices (by checking if an order exists at this price - you do not need to place several orders at the same price)
  4. You can also delete the prices of already placed orders from the array in the meantime, but it's a bit tricky...
 

I started to study MQL4 by S. Kovalev's book. Kovalev, there are some inconsistencies in the code, as the book was written for old builds of MT4.


Please advise how to process this code to avoid errors.

#property strict

int Count=0;
int init()      
{
   Alert ("Сработала ф-ия init() при запуске");   // Сообщение
   return;                                                                     // Выход из init()
   }   
//--------------------------------------------------------------------
int start()                                                                           // Спец. ф-ия start()
   {
   double Price = Bid;                                                      // Локальная перемен.
   Count++;                                                                      // Счётчик тиков
   Alert("Новый тик ",Count," Цена = ",Price);       // Сообщение
   return;                                                                        // Выход из start()
   }
int deinit()                                                                              // Спец. ф-ия deinit()
   {
   Alert ("Сработала ф-ия deinit() при выгрузке");         // Сообщение
   return;                                                                                 // Выход из deinit()
   }

error

'return' - the function must return a value

1. Is it correct to do so?

#property strict

int Count=0;
int init()      
{
   Alert ("Сработала ф-ия init() при запуске");   // Сообщение
   return(0);                                                                     // Выход из init()
   }   
//--------------------------------------------------------------------
int start()                                                                           // Спец. ф-ия start()
   {
   double Price = Bid;                                                      // Локальная перемен.
   Count++;                                                                      // Счётчик тиков
   Alert("Новый тик ",Count," Цена = ",Price);       // Сообщение
   return(0);                                                                        // Выход из start()
   }
int deinit()                                                                              // Спец. ф-ия deinit()
   {
   Alert ("Сработала ф-ия deinit() при выгрузке");         // Сообщение
   return(0);                                                                                 // Выход из deinit()
   }


2. Question, how problematic is it to write code for new builds using the knowledge given in the tutorial (I mean the age factor of the information)?



Files:
 
Sergey Branin:

I started to study MQL4 by S. Kovalev's book. Kovalev, there are some inconsistencies in the code, as the book was written for old builds of MT4.


Please advise how to process this code to avoid errors.

error

'return' - the function must return a value

1. Is it correct to do so?


2. Question, how much of a problem is it to write code for new builds using the knowledge given in the tutorial (I mean the information ageing factor)?



Use OnInit(), OnDeinit(), OnTick(), and others from the list:

Документация по MQL5: Обработка событий
Документация по MQL5: Обработка событий
  • www.mql5.com
В языке MQL5 предусмотрена обработка некоторых предопределенных событий. Функции для обработки этих событий должны быть определены в программе MQL5: имя функции, тип возвращаемого значения, состав параметров (если они есть) и их типы должны строго соответствовать описанию функции-обработчика события. Именно по типу возвращаемого значения и по...
 
Sergey Branin:

I started to study MQL4 by S. Kovalev's book. Kovalev, there are some inconsistencies in the code, as the book was written for old builds of MT4.


Please advise how to process this code to avoid errors.

error

'return' - the function must return a value

1. Is it correct to do so?


2. Question, how much of a problem to write code for new builds using knowledge from the tutorial (I mean the age factor of the information)?



  1. You are right to return values from non- void functions, but it's better to switch to new builds - there is nothing complicated there.
  2. Write, do not forget to insert #property strict directive at the beginning of the code - where all directives are written, read error codes - their descriptions are in the documentation, and everything will be fine and not complicated.
 
Artyom Trishkin:
  1. Cycle through the list of closed positions, selecting those with a closing time greater than the start time of the day you want

Thank you, I find open prices of closed positions at the required time in the first cycle. They all appear on the printer and I need to place orders on them.

The array is a bit of a jigsaw for me, please advise me how to insert the cycles to check and set them to the opening price into the first cycle of searching for these prices.

So, puts on the price of the oldest one I need, how do I go to the next price found?
void PriceTimePos(string sy="",int op=-1,int mn=-1)
  {
   datetime t;
   bool daa;
   int d,k_=OrdersTotal(),typ_;
   double   r=0;
   int      i,k=OrdersHistoryTotal();

   if(sy=="0") sy=Symbol();
   for(i=0; i<k; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))
        {
         if(OrderSymbol()==Symbol())
           {
            if(OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               if(op<0 || OrderType()==op)
                 {
                  if(mn<0 || OrderMagicNumber()==mn)
                    {
                     if(OrderCloseTime()>=TimeCurrent()-1440*60)
                       {
                        t=OrderCloseTime();
                        r=OrderOpenPrice();
                        sl=OrderStopLoss();
                        tp=OrderTakeProfit();
                        lot=OrderLots();
                        typ_=OrderType();
                        //Print("OpenPrice",r);

                        // ЕСТЬ ОРДЕР ПО ЦЕНЕ ЗАКРЫТОЙ ПОЗИЦИИ?
                        daa=false;
                        for(i=0; i<k; i++)
                          {
                           if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
                             {
                              if((OrderSymbol()==sy || sy=="") && (op<0 || OrderType()==op))
                                {
                                 if(OrderType()>1 && OrderType()<6)
                                   {
                                    d=MarketInfo(OrderSymbol(), MODE_DIGITS);
                                    r=NormalizeDouble(r, d);
                                    if(r==NormalizeDouble(OrderOpenPrice(),d)) daa=true; //else continue;
                                   }
                                }
                             }
                          }
                        if(daa==false)//ЕСЛИ НЕТ ОРДЕРА ПО ЦЕНЕ, СТАВЛЮ
                          {

                           if(r>Ask)
                             {
                              if(typ_==OP_BUY)
                                {
                                 Print("OP_BUYSTOP",r);
                                 SetOrder(Symbol(),OP_BUYSTOP,lot,r,sl,tp,_MagicNumber,0,"bs");
                                }
                              if(typ_==OP_SELL)
                                {
                                 Print("OP_SELLLIMIT",r);
                                 SetOrder(Symbol(),OP_SELLLIMIT,lot,r,sl,tp,_MagicNumber,0,"sl");
                                }
                             }

                           //
                           if(Bid>r)
                             {
                              if(typ_==OP_BUY)
                                {
                                 Print("OP_BUYLIMIT",r);
                                 SetOrder(Symbol(),OP_BUYLIMIT,lot,r,sl,tp,_MagicNumber,0,"bl");
                                }
                              if(typ_==OP_SELL)
                                {
                                 Print("OP_SELLSTOP",r);
                                 SetOrder(Symbol(),OP_SELLSTOP,lot,r,sl,tp,_MagicNumber,0,"bs");
                                }
                             }

                          }
                        //return(r);
                       }
                    }
                 }
              }
           }
        }
     }
//
  }
 
PolarSeaman:

Thank you, I find the opening prices of closed positions at the right time in the first cycle. They all show up on the printer and I need to place orders on them.

The array is a maze for me, tell me how to put the cycles to check and set to the opening price into the first loop to find these prices.

It's faster to understand and understand what arrays are, than to correct what you have done.

Especially since arrays are not simple, but very simple.

AK magazine holds 30 cartridges - it's an array of size 30. And the cartridges are the data stored in the array.

Admittedly this is not a good example - you can't get the third one unless you get 0, 1 and 2.

Well imagine a spreadsheet:

Index 0
Index 1
Index 2
Index 3
Index 4
Index5.Index6.Index 7
Index 8
Index 9
Value 1
Index value 2
Value 3
Value 4
Value 5
Value 6
Value 7
Value 8
Value 9
Value 10

Here's a simple one-dimensional array of size 10.

Value 1 is stored in cell with index 0, value 2 is stored in cell with index 1, value 3 is stored in cell with index 2, ...
...
Value 8 is stored in index cell 7, value 9 is stored in index cell 8, value 10 is stored in index cell 9

It is as simple as that. To get value 3, you need to refer to the array - its cell 2: Value3=Array[2];

Reason: