in strategy tester good but in real bad

 

Hello professional coders
I have an expert that I ran on VPS and below you can see my codes
The logic of the code is that if the price hits the moving average, it will take a buy position, and to prevent requotation and slippage, I put it in a loop, but as you can see the result in the photo, instead of 1 buy position, it takes 5 . (by the way in strategy tester i do not have this problem)
And one more thing
If the EA can not take buy position it must print the last error but as you can see in expert tab it does not did it   
What happened ?!!!
Thank you for guiding me

codes

result

 
masoodbabagoli:

Hello professional coders
I have an expert that I ran on VPS and below you can see my codes
The logic of the code is that if the price hits the moving average, it will take a buy position, and to prevent requotation and slippage, I put it in a loop, but as you can see the result in the photo, instead of 1 buy position, it takes 5 . (by the way in strategy tester i do not have this problem)
And one more thing
If the EA can not take buy position it must print the last error but as you can see in expert tab it does not did it   
What happened ?!!!
Thank you for guiding me


but yesterday in real (not backtest) it worked fine and today suddenly it took 5 position !!!

look at the yesterday history it worked fine

yesterday


and look at the today history, crashes (5 entries !!!)

today

 
masoodbabagoli #:

but yesterday in real (not backtest) it worked fine and today suddenly it took 5 position !!!

look at the yesterday history it worked fine


and look at the today history, crashes (5 entries !!!)

if(iOpen(_Symbol,PERIOD_M5,0)>movingaverage[0]
   && iClose(_Symbol,PERIOD_M5,0)<=movingaverage[0]
   && iClose(_Symbol,PERIOD_M5,1)>movingaverage[0]
   && tradenumber==0)
  {
   int pass=0;
   while(!trade.Buy(0.02) && pass<100)
     {
      Print("LINE = ",__LINE__," | ","TICKET = ",trade.RequestPosition()," | ","GET BUY POSITION FAILED ",GetLastError());
      pass++;
      Sleep(100);
     }
   if(pass<100)
     {
      tradenumber++;
      Print("key_level = ",key_level);
      Print("LINE = ",__LINE__," | ","TICKET = ",trade.ResultOrder()," | ","POSITION GET SUCCESSFULLY");
     }

 
  1. Don't post pictures of code, they are generally too hard to read.

    Please edit your (original) post and use the CODE button (or Alt+S)! (For large amounts of code, attach it.)
          General rules and best pratices of the Forum. - General - MQL5 programming forum #25 (2019)
              Messages Editor
          Forum rules and recommendations - General - MQL5 programming forum (2023)

  2. masoodbabagoli: What happened ?!!!

    Your “if(pass<100)” is not part of your loop.

 
William Roeder #:
  1. Don't post pictures of code, they are generally too hard to read.

    Please edit your (original) post and use the CODE button (or Alt+S)! (For large amounts of code, attach it.)
          General rules and best pratices of the Forum. - General - MQL5 programming forum #25 (2019)
              Messages Editor
          Forum rules and recommendations - General - MQL5 programming forum (2023)

  2. Your “if(pass<100)” is not part of your loop.

i attached the codes, sorry for picturing it

yes i mean if the trade order success (below than 100 time try) , so it comes out from loop and the pass is lower than 100 so it increase tradenumber variable by one

 
masoodbabagoli #:

i attached the codes, sorry for picturing it

yes i mean if the trade order success (below than 100 time try) , so it comes out from loop and the pass is lower than 100 so it increase tradenumber variable by one

You did not show how you initialize tradenumber. Most likely your problem is related to the fact that the library does not do exactly what you expect - the method PositionOpen (inside Buy) does actually call OrderSend function, which is asynchronous - it returns true as indication that the order is sent successfully, but it does not mean that the position is already open. If you check positions on a next event, and don't yet see new position, you probably assign 0 to tradenumber, then your code will issue another order for opening position. Hence, the code can produce different results if orders are processed faster or slower on broker server (which is often changing in real trading environments).

 
Stanislav Korotky #:
You did not show how you initialize tradenumber. Most likely your problem is related to the fact that the library does not do exactly what you expect - the method PositionOpen (inside Buy) does actually call OrderSend function, which is asynchronous - it returns true as indication that the order is sent successfully, but it does not mean that the position is already open. If you check positions on a next event, and don't yet see new position, you probably assign 0 to tradenumber, then your code will issue another order for opening position. Hence, the code can produce different results if orders are processed faster or slower on broker server (which is often changing in real trading environments).

The tradenumber variable is a global variable that has a default value of zero, and what I mean by creating it is that after taking the position, the variable will increase by one, so the "if" condition is violated and does not take any other position. Actually, my codes require me to make sure that the position is taken 100%,

then rest of the codes to be read


What is your solution? Many thanks

 
Stanislav Korotky #:

You did not show how you initialize tradenumber. Most likely your problem is related to the fact that the library does not do exactly what you expect - the method PositionOpen (inside Buy) does actually call OrderSend function, which is asynchronous - it returns true as indication that the order is sent successfully, but it does not mean that the position is already open. If you check positions on a next event, and don't yet see new position, you probably assign 0 to tradenumber, then your code will issue another order for opening position. Hence, the code can produce different results if orders are processed faster or slower on broker server (which is often changing in real trading environments).

yes almost you understand what i mean
 

i believe what @Stanislav Korotky is meaning:

your code is attempting to open as many trades as it can during the current event or tick. So -- opening 5 trades is exactly what you have told your ea to do. 

 
masoodbabagoli #:

The tradenumber variable is a global variable that has a default value of zero, and what I mean by creating it is that after taking the position, the variable will increase by one, so the "if" condition is violated and does not take any other position.

Actually, my codes require me to make sure that the position is taken 100%, then rest of the codes to be read.

What is your solution?

Well, if tradenumber variable is properly used for guarding against multiple positions (and orders!), then I don't understand how you got it.

As for the rest, you could check/wait for new position - either using the library you use (I'm not familiar with the standard library, so someone else might be able to help) or directly via MQL5 API. There is another solution available in the algotrading book -  MqlTradeRequestSync, but it's a separate approach, which can't be used along with the standard library, so you'll need to learn these classes and refactor your code.

"In order to simplify the coding of trading operations, not only buying and selling but also all others, we will start from this section by developing classes, or rather structures that provide automatic and correct filling of fields for trade requests, as well as a truly synchronous waiting for the result. The latter is especially important, given that the OrderSend and OrderSendAsync functions return control to the calling code before the trading action is completed in full. In particular, for market buy and sell, the algorithm usually needs to know not the ticket number of the order created on the server, but whether the position is open or not. Depending on this, it can, for example, modify the position by setting Stop Loss and Take Profit if it has opened or repeat attempts to open it if the order was rejected."

MQL5 Book: Trading automation / Creating Expert Advisors / Buying and selling operations
MQL5 Book: Trading automation / Creating Expert Advisors / Buying and selling operations
  • www.mql5.com
In this section, we finally begin to study the application of MQL5 functions for specific trading tasks. The purpose of these functions is to fill...
 
Stanislav Korotky #:

Well, if tradenumber variable is properly used for guarding against multiple positions (and orders!), then I don't understand how you got it.

As for the rest, you could check/wait for new position - either using the library you use (I'm not familiar with the standard library, so someone else might be able to help) or directly via MQL5 API. There is another solution available in the algotrading book -  MqlTradeRequestSync, but it's a separate approach, which can't be used along with the standard library, so you'll need to learn these classes and refactor your code.

To make sure that every order request is converted into a position, is the following solution appropriate?

void OnTick()
  {

   if(PositionsTotal()==0)
     {
      int pass=0;
      bool orderplaced=false;

      while(!orderplaced && pass<100)
        {
         orderplaced=trade.Buy(0.01);

         if(!orderplaced)
           {
            Print("LINE = ", __LINE__, " | ", "GET BUY POSITION FAILED. Error: ", GetLastError());
            pass++;
           }
         else
           {
            break;
           }
        }
      while(PositionsTotal()==0)
        {
         Sleep(100);
        }
     }
  }