Questions from Beginners MQL5 MT5 MetaTrader 5 - page 81

 
oldiol: I write in the code: if(!m_Trade.PositionClose(_Symbol,100))//--- we close the position by the current symbol. The result is that the position is reversed! I would be very grateful for hints on how to close the position.
The position is reversed because the program sends two identical requests to the server. The program sends two identical requests to the server, because its code does not check for the presence of an earlier sent request (and does not check the result of processing this request on the server).
 
Yedelkin:
The position is reversed because the program sends two identical requests to the server. The program sends two identical requests to the server because its code doesn't check for an earlier sent request (and doesn't check for the result of processing this request on the server).
Please fix my code to the correct one...
 

Yedelkin writes: its code doesn't check for a previously sent request. Can you tell me which function does this check?

 
oldiol: Please correct my code to the right one...

Everyone has a different understanding of the right code. So you have to write the "correct" code in the end. And as another tip - try to see if this code works in the right way (schematic use of sentRequest flag):

bool sentRequest=false;  //задать на уровне глобальных переменных программы
...

   if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
     {
      if(!sentRequest)
        {                           
         if(p_close1<buy_stop_level)
           {
            if(!m_Trade.PositionClose(_Symbol,100))
              Print("Метод PositionClose() потерпел неудачу. Код возврата=",m_Trade.ResultRetcode(),". Описание кода: ",m_Trade.ResultRetcodeDescription());
            else
               {
                Print("Метод PositionClose() выполнен успешно. Код возврата=",m_Trade.ResultRetcode()," (",m_Trade.ResultRetcodeDescription(),")");       
                sentRequest=true;
               }
            }  
         }
       else Print("Блок закрытия позиции: имеется POSITION_TYPE_BUY и ранее отосланный запрос на закрытие позиции");        
       }
    else 
      if(sentRequest) sentRequest=false;
 
Yedelkin:

Everyone has a different understanding of the right code. So you have to write the "correct" code in the end. And as another tip - try to see if this code works in the right key (schematic use of sentRequest flag):

Thank you very much! Trying it out...

 

The result is as follows: the code properly closes a long position and does not open a short one... When re-opening a long position, the EA does not close it according to the condition. There are messages in the EA window all the time:

How can I use this code in the Expert Advisor body, if it only works once)?

 

oldiol: При повторном открытии лонга, эксперт не закрывает больше позу по условию. В окне эксперта всё время идут сообщения:    Как же использовать этот код в теле эксперта, если он работает только 1 раз)?

It should be quite simple in this matter. In the schematic code the sentRequest flag should be set to zero if the open position is not a Buy position (last line of code). See why this flag is not set to zero in your code when either there is no open position or the open position is not a Buy position.

 

Hooray! It worked)))) Removed if(sentRequest) sentRequest=false; And wrote before the block if(PositionsTotal()==0) sentRequest=false; Thanks a lot to Yedelkin for his help, GOOD Luck!

 
oldiol Removed if(sentRequest) sentRequest=false; And wrote before the block if(PositionsTotal()==0) sentRequest=false;
So there was no position check in the main code? Then I would add that the position for a particular symbol is selected using the PositionGetSymbol or PositionSelect functions.
 

oldiol : When reopening a long, EA does not close the position by condition anymore. There are messages in EA window all the time: How can I use this code in EA body, if it works only 1 time)? Sorry, my mistake... There is one more condition in the code

if(PositionSelect(_Symbol)==true) // there is an open position
{

POSITION CLOSE BLOCK

} // ... therefore

if(sentRequest) sentRequest=false;// placed it behind the next bracket and everything works perfectly. Yedelkin THANK YOU!

Reason: