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

 
Vyacheslav Kornev:

Thanks for the help, but in real trading it makes no difference how to take the price? After all, you will have to put both indicator and EA on the chart?

In real trading you will be able to get the data. As long as you don't accidentally delete the indicator lines...

 
Artyom Trishkin:

With a real one you will be able to receive data. If you don't accidentally remove the indicator lines...


So, I have one more question. this is an awesome EA. But it needs to do this: when it crosses a line, an additional order is opened in this direction, and then it closes on profit... How to make so that after closing on profit, the additional order is not opened again? Until the indicator line is updated?

//==================Setting an additional order ============
double Lots2;
if((PriceHigh>PriceLow && Ask>PriceHigh && LBUY<LSELL)|| (PriceLow>PriceHigh && Ask>PriceLow && LBUY<LSELL) )
 

Good afternoon! Need a little help with the code which:

opens BUY if file 11112222.txt contains 1;

opens SELL if file 11112222.txt contains -1;

closes all orders if file 11112222.txt contains 0;


Given file 11112222.txt, there can be only three entries: 1, -1 or 0


I don't understand what is wrong with this code; for some reason, if I see 0 in file 11112222.txt, it opens BUY order, instead of closed order code, I just don't know what is wrong.

Ay, there is also a problem, when EA is running, it's almost always impossible to open 11112222.txt, it says the file is busy with another application, so to fix this problem I put FileClose(handle2); // Close text file; but it doesn't help and I need the EA to check file 11112222.txt for 1, -1 or 0 after it was opened and then close it, because the file is periodically used by another program to add 1, -1 or 0.

//=================================BUY=========================================
    int handle2 = FileOpen("11112222.txt", FILE_CSV|FILE_READ, ";");//код открывает файл для чтения
  if(handle2>0) // если в файле больше 0, то есть 1, то открывать BUY
   {
    
       Print(FileReadString(handle2));
       FileClose(handle2); // закрытие текстового файла

                    //ОТКРЫТИЕ ОРДЕРА НА ПОКУПКУ      
                    if(OrdersTotal() == 0) // если нет открытых ордеров то открывать ордер на покупку
                     {
                        OrderSend(Symbol(), OP_BUY, 0.01, Ask, 3, 0, 0); // первым указывается ЛОСЬ, вторым ПРОФИТ
                        FileClose(handle2); // закрытие текстового файла
                     }
                    else
                      Print("NE USPESHNO!!!");
                      FileClose(handle2); // закрытие текстового файла

   }
//=================================конец кода BUY=========================================
      
      
      
      
      
      
      
      
//=================================SELL=========================================
    int handle3 = FileOpen("11112222.txt", FILE_CSV|FILE_READ, ";");//код открывает файл для чтения
  if(handle3<0)//если в текстовом файле меньше 0, то есть -1, то открывать SELL
   {
    
       Print(FileReadString(handle3));
       FileClose(handle3); // закрытие текстового файла

                    if(OrdersTotal() == 0) // если нет открытых ордеров то открывать ордер на продажу
                        {
                           OrderSend(Symbol(), OP_SELL, 0.01, Bid, 3, 0, 0); // первым указывается ЛОСЬ, вторым ПРОФИТ
                           FileClose(handle3); // закрытие текстового файла
                        }
                       else
                       Print("NE USPESHNO!!!");
                       FileClose(handle3); // закрытие текстового файла

   }
//=================================конец кода SELL=========================================
      
      
      
      
      
//=================================ЗАКРЫТИЕ ВСЕХ ОРДЕРОВ=========================================
    int handle4 = FileOpen("11112222.txt", FILE_CSV|FILE_READ, ";");//код открывает файл для чтения
  if(handle4=0)//если в текстовом файле равно 0, то закрыть все ордера
   {
      
       Print(FileReadString(handle4));
       FileClose(handle4); // закрытие текстового файла
//-----------------код закрывает все ордера--------------------
   bool   result;
   int    error;

 while (OrdersTotal()>0)
 {
   if(OrderSelect(0,SELECT_BY_POS,MODE_TRADES))
     {   if(OrderType()==OP_BUY)  result=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(OrderSymbol(),MODE_BID),MarketInfo(OrderSymbol(),MODE_DIGITS)),3,CLR_NONE);
          if(OrderType()==OP_SELL) result=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(OrderSymbol(),MODE_ASK),MarketInfo(OrderSymbol(),MODE_DIGITS)),3,CLR_NONE);
          if (OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP || OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP)
           OrderDelete(OrderTicket());
          
           if(result!=TRUE) { error=GetLastError();
              Print("LastError = ",error, " ",Symbol()); }
           else error=0; }
   else Print( "Error when order select ", GetLastError());
         
         FileClose(handle4); // закрытие текстового файла
  }
//------------конец кода закрывающего ордера------------------
 

         FileClose(handle4); // закрытие текстового файла
      
      
   }
//=================================конец кода ЗАКРЫТИЕ ВСЕХ ОРДЕРОВ=========================================


 
Санек:

Good afternoon! Need a little help with the code which:

opens BUY if file 11112222.txt contains 1;

opens SELL if file 11112222.txt contains -1;

closes all orders if file 11112222.txt contains 0;


The file 11112222.txt is given and it may have only three entries: 1, -1 or 0.


For some reason, when 0 is in file 11112222.txt, it opens a BUY order, while a close order code should be triggered; I don't understand what the error is.

So, there is also a problem, when the EA is running, it's almost always impossible to open 11112222.txt, because it says the file is busy with another application. To fix it, I put FileClose(handle2); // Close text file; but it doesn't work and I need the EA to check the file 11112222.txt for 1, -1 or 0 and close it, because every second another program uses this file to put 1, -1 or 0 in it.

Because the file handle is not the file contents.

You have to read the contents of the file first, and only then set the condition. It's the other way around, you have a condition by handle, then read the file and close it.

 
Alexey Viktorov:

Because the handle of the file is not the contents of the file.

You have to read the contents of the file first, and only then put the condition. In your case it's vice versa, condition by handle, then read file and close it.

1) - This part opens file 11112222.txt to read data from it:

//=================================BUY=========================================
    int handle2 = FileOpen("11112222.txt", FILE_CSV|FILE_READ, ";");//код открывает файл для чтения

2) - Next comes the condition if handle2>0


  if(handle2>0) // если в файле больше 0, то есть 1, то открывать BUY
   {

3) - This is the part I don't understand:


       Print(FileReadString(handle2));

4) - This part closes the file:


       FileClose(handle2); // закрытие текстового файла

5) - Since the handle2>0 condition is met, i.e. file 11112222.txt contains 1, it opens a buy order:

  //ОТКРЫТИЕ ОРДЕРА НА ПОКУПКУ      
                    if(OrdersTotal() == 0) // если нет открытых ордеров то открывать ордер на покупку
                     {
                        OrderSend(Symbol(), OP_BUY, 0.01, Ask, 3, 0, 0); // первым указывается ЛОСЬ, вторым ПРОФИТ
                        FileClose(handle2); // закрытие текстового файла
                     }
                    else
                      Print("NE USPESHNO!!!");
                      FileClose(handle2); // закрытие текстового файла

   }
//=================================конец кода BUY=========================================

Which parts have I mixed up?
 

Greetings trying to write a script to close orders.

#property copyright "Copyright 2017, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
{  
   bool reasult;
   for (int i = OrdersTotal()-1; i >= 0; i--)
   {
      if (OrderSelect(i, SELECT_BY_POS)>0)
      {
         if (OrderSymbol() != Symbol())
            continue;
         
         switch (OrderType())
         {
            case OP_BUY  :
               reasult = OrderClose(OrderTicket(), OrderLots(), Bid, 50, Red);
               if (!reasult) Print ("Ошибка закрытия ордера на покупку", GetLastError());
               break;
            case OP_SELL :
               reasult = OrderClose(OrderTicket(), OrderLots(), Ask, 50, Blue);
               if (!reasult) Print ("Ошибка закрытия ордера на продажу", GetLastError());
               break;
         }   
         
      }
   }
}

If I open several sell and buy orders alternately and try to close them with this order, only a few are closed, the rest get error 129 (Incorrect price).

I tried to make a script which for example makes 10 attempts * on the number of orders, with pause in case of error.

#property copyright "Copyright 2017, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict


//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
{ 
   int c=CountTrades()*10;
   
   for ( int a=1 ; a<=c; a++)
   {
   if (CountTrades()==0) { Print ("Orders are successfully closed! Break."); break;}
    Print("Try ", a, " out of ", c);
      
      bool reasult;
      for (int i = OrdersTotal()-1; i >= 0; i--)
      {
         if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         {
            if (OrderSymbol() == Symbol()) 
            
            {      
            
            if (OrderType() == OP_BUY)  {
                  reasult = OrderClose(OrderTicket(), OrderLots(), Bid, 50, Red);
                  if (!reasult) {Print ("ERROR ", GetLastError());} 
                  }
            if (OrderType() == OP_SELL)  {
                  reasult = OrderClose(OrderTicket(), OrderLots(), Ask, 50, Blue);
                  if (!reasult) {Print ("ERROR ", GetLastError());}  
                  }              
            }   
            
         }
      }Sleep(1000);
   }   
}
//+------------------------------------------------------------------+
int CountTrades()
{
    int count=0;
    for (int i=OrdersTotal()-1; i>=0; i--)
    {
        if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
           if (OrderSymbol() == Symbol())
               if (OrderType() == OP_BUY || OrderType() == OP_SELL)
                 count++;
        }
    }
    
    return(count);
}

It usually copes with its task after quite a number of attempts, at which the same 129 error is issued. But while it tries, with many attempts, to close orders out can be closed manually, and this does not cause errors, they close.

What am I doing wrong?

 
Andrey Sokolov:

Greetings trying to write a script to close orders.

If I open several sell and buy orders alternately and try to close them with this order, only a few are closed, the rest get error 129 (Incorrect price).

I tried to make a script which for example makes 10 attempts * on the number of orders, with pause in case of error.

It usually copes with its task after quite a number of attempts, at which the same 129 error is issued. But while it tries, with many attempts, to close orders out can be closed manually, and this does not cause errors, they close.

What am I doing wrong?

            RefreshRates(); // Попробуйте добавить
            if (OrderType() == OP_BUY)  {
                  reasult = OrderClose(OrderTicket(), OrderLots(), Bid, 50, Red);
                  if (!reasult) {Print ("ERROR ", GetLastError());} 
                  }
            if (OrderType() == OP_SELL)  {
                  reasult = OrderClose(OrderTicket(), OrderLots(), Ask, 50, Blue);
                  if (!reasult) {Print ("ERROR ", GetLastError());}  
                  }  

In general, what you write is not allowed to trade on a real account, it is only for a tester

 
Vitaly Muzichenko:

In general, what you write should not be allowed to trade in a real account, it is only for the tester

            RefreshRates(); // Попробуйте добавить

It helps, thank you.

 
Vitaly Muzichenko:

In general, what you write is not allowed to trade on a real account, it's only for a tester


Can you elaborate on why "not allowed to trade..."?

 
Andrey Sokolov:

Can you elaborate on why "not allowed to trade"?

There is no check for errors, and if the server closes and generates a critical error, the Expert Advisor will still continue to pound the server, and this smells like a ban for further auto-trading.

Reason: