Closing an open trade in the Strategy Tester in MT5

 

Hi

A simple question - can you close an open trade when using the Strategy Tester within MetaTrader 5?

See the code below -  when this runs it fails to close out the open position. No error is given.

I have included the results from the Journal below as well so you can follow the path it takes via print statements from the code ...

After a lot of testing I found that my code was not working - I then replaced it with  code listed in the documentation for TRADE_ACTION_CLOSE_BY

Still cannot get it to close an open trade within the Strategy Tester.

Magic Number for the  EA  (EA_Magic) was set to 22222.


void positionClose()
{
//+------------------------------------------------------------------+
//| Close a position by opposite positions                           |
//+------------------------------------------------------------------+

   int total=PositionsTotal(); // number of open positions   
//--- iterate over all open positions
   for(int i=total-1; i>=0; i--)
     {
      //--- parameters of the order
      ulong  position_ticket=PositionGetTicket(i);                                    // ticket of the position
      string position_symbol=PositionGetString(POSITION_SYMBOL);                      // symbol 
      int    digits=(int)SymbolInfoInteger(position_symbol,SYMBOL_DIGITS);            // ticket of the position
      ulong  magic=PositionGetInteger(POSITION_MAGIC);                                // MagicNumber of the position
      double volume=PositionGetDouble(POSITION_VOLUME);                               // volume of the position
      double sl=PositionGetDouble(POSITION_SL);                                       // Stop Loss of the position
      double tp=PositionGetDouble(POSITION_TP);                                       // Take Profit of the position
      ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);  // type of the position
      //--- output information about the position
      Print("Checking all open tickets ...");
      PrintFormat("#%I64u %s  %s  %.2f  %s  sl: %s  tp: %s  magic: [%I64d]",
                  position_ticket,
                  position_symbol,
                  EnumToString(type),
                  volume,
                  DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN),digits),
                  DoubleToString(sl,digits),
                  DoubleToString(tp,digits),
                  magic);
       PrintFormat("The current magic number of the ticket we are looking at is %I64d",magic);
       PrintFormat("The  magic number of our EA EURUSD is %I64d",EA_Magic);
                  
      //--- if the Magic Number matches
      if(magic==EA_Magic)
        {
         for(int j=0; j<i; j++)
           {
           Print("Closing the ticket that matches the magic number for EURUSD ...");
            string symbol=PositionGetSymbol(j); // symbol of the opposite position
            //--- if the symbols of the opposite and initial positions match
            if(symbol==position_symbol && PositionGetInteger(POSITION_MAGIC)==EA_Magic)
              {
               //--- set the type of the opposite position
               ENUM_POSITION_TYPE type_by=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
               //--- leave, if the types of the initial and opposite positions match
               if(type==type_by)
                  continue;
               //--- zeroing the request and result values
               ZeroMemory(mrequest);
               ZeroMemory(mresult);
               //--- setting the operation parameters
               mrequest.action=TRADE_ACTION_CLOSE_BY;                         // type of trade operation
               mrequest.position=position_ticket;                             // ticket of the position
               mrequest.position_by=PositionGetInteger(POSITION_TICKET);      // ticket of the opposite position
               //request.symbol     =position_symbol;
               mrequest.magic=EA_Magic;                                   // MagicNumber of the position
               //--- output information about the closure by opposite position
               PrintFormat("Close #%I64d %s %s by #%I64d",position_ticket,position_symbol,EnumToString(type),mrequest.position_by);
               //--- send the request
               if(OrderSend(mrequest,mresult))
                  {
                  //--- information about the successful close order operation   
                  PrintFormat("retcode=%u  deal=%I64u  order=%I64u",mresult.retcode,mresult.deal,mresult.order);
                  Print("Order close for EURUSD was successful");
                  }
                  else
                  {
                  PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, output the error code
                  Print("Order close for EURUSD was NOT successful");
                  }
               
              }
           }
        }
     }

}


Results from the Journal under MetaTrader 5.00 build 2981


We have been running to long - closing the trade for EURUSD

**Start of positionClose() **

Checking all open tickets ...

#14 EURUSD  POSITION_TYPE_SELL  6.00  1.09988  sl: 1.12976  tp: 1.09905  magic: [22222]

The current magic number of the ticket we are looking at is 22222

The  magic number of our EA EURUSD is 22222


That's all that happens in the logs - it just repeats over and over from there.


From my testing it never seems to pass the if statement - because none of my print statements appear in the logs ...

if(magic==EA_Magic)


Lastly - my test code I have previously been working with did work but all it did was put on a trade in the opposite direction and was fairly primitive and I was only ever putting on one trade at a time. In the live code I cannot do this as I will have multiple trades open and also the server does not follow FIFO Compliants. If I put on an opposite trade on the live server - it will just open a new position in the opposite direction - not close the existing trade.

Any help would be appreciated.

Thanks

Matt

 
You have opened a position online - that is, you have opened a position on your (demo or real) account. And now you want to close this position by running the Expert Advisor in the Strategy Tester? No, this is not possible - the strategy tester does not see your account and your positions.
 
Vladimir Karputov #:
You have opened a position online - that is, you have opened a position on your (demo or real) account. And now you want to close this position by running the Expert Advisor in the Strategy Tester? No, this is not possible - the strategy tester does not see your account and your positions.

Thanks for your response Vladimir but just to be clear on what I am doing ...

I have developed a working EA - I'm now testing that through the Strategy Tester (backtesting) and MetaTrader 5 is connected to a demo account with my broker.

Running the EA - and testing it through Jan 2020 to Dec 2020 -  it is able to open the trade - but it fails to close an open trade. I have some test code I have previously been working which did work but all it did was put on a trade in the opposite direction and was fairly primitive.

The more elaborate code I developed to search through open trades and find the magic number and close it - seems to not be working.


If this is correct - it would be nice to see the documentation updated to say that closing a trade using TRADE_ACTION_CLOSE_BY will not work within the Strategy Tester and save someone several weeks of trying to troubleshoot the issue.

Thanks

Matt

 
ComputerSange # :

Thanks for your response Vladimir but just to be clear on what I am doing ...

I have developed a working EA - I'm now testing that through the Strategy Tester (backtesting) and MetaTrader 5 is connected to a demo account with my broker.

Running the EA - and testing it through Jan 2020 to Dec 2020 -  it is able to open the trade - but it fails to close an open trade. I have some test code I have previously been working which did work but all it did was put on a trade in the opposite direction and was fairly primitive.

The more elaborate code I developed to search through open trades and find the magic number and close it - seems to not be working.


If this is correct - it would be nice to see the documentation updated to say that closing a trade using TRADE_ACTION_CLOSE_BY will not work within the  Strategy Tester and save someone several weeks of trying to troubleshoot the issue.

Thanks

Matt

I repeat once again: the strategy tester DOES NOT SEE the positions that are open on your account.

 

OK - I have been doing some more testing ....

I setup my EA onto a server I have running with the latest version of MT5 and connected it to a Demo account held at FX Choice.

The code ran OK - it put on a trade and I set it up to automatically close the trade in one hour. In one hour it triggered and tried to close the trade. It did not give an error trying to closing the trade - but - it did not close the trade.

I had to manually close the trade. I cannot get MT5 to close an open trade. Does anyone have a code example that works for them that closes an open trade in MT5.

Any ideas?

Thanks

Matt

 

For anyone who comes across this thread - I have a solution.

If your like me and find the documentation for MT5 to be terrible - and you have spent a lot of time trying to work out the example they list to close a trade and getting frustrated that it does not work.

The answer is -  don't use the TRADE_ACTION_CLOSE_BY and setup a bunch of code to try and close a trade by closing a position with an opposite position. Clearly that does not work.

The solution is to abandon all that and use CTrade.

#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
CPositionInfo  m_position;                   // trade position object
CTrade         m_trade;                      // trading object
#property script_show_inputs
string         m_name="EURUSD";              // symbol
ulong          m_magic=15489;                // magic number
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of current positions
      if(m_position.SelectByIndex(i))     // selects the position by index for further access to its properties
         if(m_position.Symbol()==m_name && m_position.Magic()==m_magic)
            m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
  }


The added advantage of using CTrade within your EA code to close out the trade is it works within Strategy Tester (backtesting) and also on a Demo account with your broker.

 
How to start with MQL5
How to start with MQL5
  • 2021.09.26
  • www.mql5.com
This thread discusses MQL5 code examples. There will be examples of how to get data from indicators, how to program advisors...
Reason: