My code is wrong or tester doesn't work.

 

Hello.

I was building my first EA and I have problem with opening a trade. Even when I write such simple code like this one :           Trade doesn't open.

#include<Trade\Trade.mqh>
CTrade trade;

void OnTick()
  {
   double Ask=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);  
   if(PositionsTotal() == 0)
     trade.Buy(0.1,NULL,Ask,(Ask-500*_Point),(Ask+500*_Point),NULL); // also tierd  trade.Buy(0.1,NULL,Ask,0,0,NULL); and many other 
} 

I was trying to build EA with creator based on stoch and still trade didn't open.

Is my MT5 client wrong or Am I missing sth-ing ?

 
Trade-Server, Tester Interval, Symbol, Tester PriceType?
 

Trade-Server - XMUK-MT5 (demo)

Tester Interval - H1, 2016.01.01 - 2016.12.31 data 

Symbol - EUR/USD

Tester PriceType - not sure where is this setting in tester but I guess it's close_price 


All auto traiding settings are enabled. Maybe the case is that this XM brooker doesn't allow auto traiding on demo? 

Logs here:                            I don't see anything wrong. 

 

LK      0       17:08:59.162    Core 1  agent process started
NO      0       17:08:59.663    Core 1  connecting to 127.0.0.1:3000
GG      0       17:09:03.127    Core 1  connected
JQ      0       17:09:03.130    Core 1  authorized (agent build 1596)
QS      0       17:09:03.134    Tester  EURUSD,H1 (XMUK-MT5): testing of Experts\robot.ex5 from 2016.01.01 00:00 to 2016.12.31 00:00
JL      0       17:09:03.145    Core 1  common synchronization completed
NG      0       17:09:03.442    Tester  quality of analyzed history is 99%
DR      0       17:09:09.269    Core 1  1482 bytes of tester parameters loaded
MF      0       17:09:09.269    Core 1  188 bytes of input parameters loaded
NL      0       17:09:09.269    Core 1  1998 bytes of symbols list loaded
FJ      0       17:09:09.269    Core 1  expert file added: Experts\robot.ex5. 43249 bytes loaded
MQ      0       17:09:09.269    Core 1  initial deposit 100000.00 USD, leverage 1:100
DO      0       17:09:09.269    Core 1  successfully initialized
EQ      0       17:09:09.269    Core 1  45 Kb of total initialization data received
ME      0       17:09:09.269    Core 1  Intel Core i7-6700HQ  @ 2.60GHz, 16328 MB
GN      0       17:09:09.269    Core 1  EURUSD: symbol to be synchronized
JJ      0       17:09:09.269    Core 1  EURUSD: symbol synchronized, 3384 bytes of symbol info received
MG      0       17:09:09.269    Core 1  EURUSD: load 27 bytes of history data to synchronize in 0:00:00.016
RP      0       17:09:09.269    Core 1  EURUSD: history synchronized from 2015.01.02 to 2017.05.02
NP      0       17:09:09.269    Core 1  EURUSD,H1: history cache allocated for 12514 bars and contains 6200 bars from 2015.01.02 08:00 to 2015.12.31 19:00
IP      0       17:09:09.269    Core 1  EURUSD,H1: history begins from 2015.01.02 08:00
KH      0       17:09:09.269    Core 1  EURUSD,H1 (XMUK-MT5): every tick generating
CN      0       17:09:09.269    Core 1  EURUSD,H1: testing of Experts\robot.ex5 from 2016.01.01 00:00 to 2016.12.31 00:00 started
OL      0       17:12:26.153    Core 1  final balance 100000.00 USD
FD      0       17:12:26.153    Core 1  EURUSD,H1: 26445034 ticks, 6228 bars generated. Environment synchronized in 0:00:00.032. Test passed in 0:03:22.984 (including ticks preprocessing 0:00:02.718).
IS      0       17:12:26.153    Core 1  EURUSD,H1: total time from login to stop testing 0:03:23.016 (including 0:00:00.032 for history data synchronization)
FQ      0       17:12:26.153    Core 1  519 Mb memory used including 0.94 Mb of history data, 320 Mb of cached tick data (total memory for tick data 511 Mb)
DP      0       17:12:26.153    Core 1  log file "C:\Users\Timi\AppData\Roaming\MetaQuotes\Tester\D0E8209F77C8CF37AD8BF550E51FF075\Agent-127.0.0.1-3000\logs\20170613.log" written
EH      0       17:12:26.167    Core 1  connection closed
 
TimiTim:

Logs here:                            I don't see anything wrong.

What does the tester show when running this code?
#include <MT4Orders2.mqh> // the attached file

#define Ask SymbolInfoDouble(_Symbol, SYMBOL_ASK)

void OnTick()
{
  if ((OrdersTotal() == 0) && (OrderSend(NULL, OP_BUY, 0.1, Ask, 0, Ask - 500 * _Point, Ask + 500 * _Point, NULL, 0, 0, INT_MIN) == -1))
  {
    Print(ToString(MT4ORDERS::LastTradeRequest) + ToString(MT4ORDERS::LastTradeResult) + ToString(MT4ORDERS::LastTradeCheckResult));
    
    ExpertRemove();    
  }
}

#define TOSTRING(A)  #A + " = " + (string)(A) + "\n"
#define TOSTRING2(A) #A + " = " + EnumToString(A) + " (" + (string)(A) + ")\n"

string ToString( const MqlTradeRequest &Request )
{
  return(TOSTRING2(Request.action) + TOSTRING(Request.magic) + TOSTRING(Request.order) +
         TOSTRING(Request.symbol) + TOSTRING(Request.volume) + TOSTRING(Request.price) + 
         TOSTRING(Request.stoplimit) + TOSTRING(Request.sl) +  TOSTRING(Request.tp) + 
         TOSTRING(Request.deviation) + TOSTRING2(Request.type) + TOSTRING2(Request.type_filling) +
         TOSTRING2(Request.type_time) + TOSTRING(Request.expiration) + TOSTRING(Request.comment) +
         TOSTRING(Request.position) + TOSTRING(Request.position_by));
}

string ToString( const MqlTradeResult &Result )
{
  return(TOSTRING(Result.retcode) + TOSTRING(Result.deal) + TOSTRING(Result.order) +
         TOSTRING(Result.volume) + TOSTRING(Result.price) + TOSTRING(Result.bid) +  
         TOSTRING(Result.ask) + TOSTRING(Result.comment) + TOSTRING(Result.request_id) +  
         TOSTRING(Result.retcode_external));
}

string ToString( const MqlTradeCheckResult &CheckResult )
{
  return(TOSTRING(CheckResult.retcode) + TOSTRING(CheckResult.balance) + TOSTRING(CheckResult.equity) +
         TOSTRING(CheckResult.profit) + TOSTRING(CheckResult.margin_free) + TOSTRING(CheckResult.margin_level) +
         TOSTRING(CheckResult.comment));
}
 
Well this EA works. Opening and closing trades without any problems, so what maybe the case ? this MT4Orders2 file is needed ?  and do you want me to copy logs? There's a lot of them.
 
TimiTim :

Hello.

I was building my first EA and I have problem with opening a trade. Even when I write such simple code like this one :           Trade doesn't open.

I was trying to build EA with creator based on stoch and still trade didn't open.

Is my MT5 client wrong or Am I missing sth-ing ?


Try this code - Byu On Every Tick:

//+------------------------------------------------------------------+
//|                                               ByuOnEveryTick.mq5 |
//|                              Copyright © 2017, Vladimir Karputov |
//|                                           http://wmua.ru/slesar/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2017, Vladimir Karputov"
#property link      "http://wmua.ru/slesar/"
#property version   "1.000"
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>  
CPositionInfo  m_position;                   // trade position object
CTrade         m_trade;                      // trading object
CSymbolInfo    m_symbol;                     // symbol info object
//---
double m_volume=0;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   m_symbol.Name(Symbol());                  // sets symbol name
   RefreshRates();
   m_symbol.Refresh();

   m_volume=m_symbol.LotsMin();
   if(m_volume<=0.0)
     {
      Print("Error Lots Min!");
      return(INIT_FAILED);
     }
//---
   if(IsFillingTypeAllowed(Symbol(),SYMBOL_FILLING_FOK))
      m_trade.SetTypeFilling(ORDER_FILLING_FOK);
   else if(IsFillingTypeAllowed(Symbol(),SYMBOL_FILLING_IOC))
      m_trade.SetTypeFilling(ORDER_FILLING_IOC);
   else
      m_trade.SetTypeFilling(ORDER_FILLING_RETURN);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   if(!RefreshRates())
      return;
   OpenBuy(0.0,0.0,m_volume);
//---
   return;
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
      return(false);
//--- protection against the return value of "zero"
   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)
      return(false);
//---
   return(true);
  }
//+------------------------------------------------------------------+ 
//| Checks if the specified filling mode is allowed                  | 
//+------------------------------------------------------------------+ 
bool IsFillingTypeAllowed(string symbol,int fill_type)
  {
//--- Obtain the value of the property that describes allowed filling modes 
   int filling=(int)SymbolInfoInteger(symbol,SYMBOL_FILLING_MODE);
//--- Return true, if mode fill_type is allowed 
   return((filling & fill_type)==fill_type);
  }
//+------------------------------------------------------------------+
//| Open Buy position                                                |
//+------------------------------------------------------------------+
void OpenBuy(double sl,double tp,double volume)
  {
   sl=m_symbol.NormalizePrice(sl);
   tp=m_symbol.NormalizePrice(tp);

//--- check volume before OrderSend to avoid "not enough money" error (CTrade)
   double check_volume_lot=m_trade.CheckVolume(m_symbol.Name(),volume,m_symbol.Ask(),ORDER_TYPE_BUY);

   if(check_volume_lot!=0.0)
      if(check_volume_lot>=volume)
        {
         if(m_trade.Buy(volume,NULL,m_symbol.Ask(),sl,tp))
           {
            if(m_trade.ResultDeal()==0)
              {
               Print("Buy -> false. Result Retcode: ",m_trade.ResultRetcode(),
                     ", description of result: ",m_trade.ResultRetcodeDescription());
              }
            else
              {
               Print("Buy -> true. Result Retcode: ",m_trade.ResultRetcode(),
                     ", description of result: ",m_trade.ResultRetcodeDescription());
              }
           }
         else
           {
            Print("Buy -> false. Result Retcode: ",m_trade.ResultRetcode(),
                  ", description of result: ",m_trade.ResultRetcodeDescription());
           }
        }
//---
  }
//+------------------------------------------------------------------+

df

Files:
 
TimiTim:
Well this EA works. Opening and closing trades without any problems, so what maybe the case ?

You can use one of the following options

#include<Trade\Trade.mqh>

#define Ask SymbolInfoDouble(_Symbol, SYMBOL_ASK)

ENUM_ORDER_TYPE_FILLING GetFilling( const string Symb, const uint Type = ORDER_FILLING_FOK )
{
  static ENUM_ORDER_TYPE_FILLING Res = ORDER_FILLING_FOK;
  static string LastSymb = NULL;
  static uint LastType = ORDER_FILLING_FOK;

  if ((LastType != Type) || (LastSymb != Symb))
  {
    LastType = Type;
    LastSymb = Symb;

    const ENUM_SYMBOL_TRADE_EXECUTION ExeMode = (ENUM_SYMBOL_TRADE_EXECUTION)::SymbolInfoInteger(Symb, SYMBOL_TRADE_EXEMODE);
    const int FillingMode = (int)::SymbolInfoInteger(Symb, SYMBOL_FILLING_MODE);

    Res = (FillingMode == 0 || (Type >= ORDER_FILLING_RETURN) || ((FillingMode & (Type + 1)) != Type + 1)) ?
          (((ExeMode == SYMBOL_TRADE_EXECUTION_EXCHANGE) || (ExeMode == SYMBOL_TRADE_EXECUTION_INSTANT)) ?
           ORDER_FILLING_RETURN : ((FillingMode == SYMBOL_FILLING_IOC) ? ORDER_FILLING_IOC : ORDER_FILLING_FOK)) :
          (ENUM_ORDER_TYPE_FILLING)Type;
  }

  return(Res);
}

CTrade Trade;
  
void OnTick()
{
  if (PositionsTotal() == 0)
  {
    Trade.SetTypeFilling(GetFilling(_Symbol));
    
    Trade.Buy(0.1, NULL, Ask, Ask - 500 * _Point, Ask + 500 * _Point);
  }
}

#include <MT4Orders.mqh> // https://www.mql5.com/en/code/16006

#define Ask SymbolInfoDouble(_Symbol, SYMBOL_ASK)

void OnTick()
{
  if (OrdersTotal() == 0)
    OrderSend(NULL, OP_BUY, 0.1, Ask, 0, Ask - 500 * _Point, Ask + 500 * _Point);
}

  • All variants at the same time.
Trade Functions - MQL4 Reference
Trade Functions - MQL4 Reference
  • docs.mql4.com
Trade Functions - MQL4 Reference
 
Thank you very much for your help and time.  
 

@fxsaber: Thanks for your awesome MT4-MT5 trade module - it's made MT5 infinitely more appealing to MT4 users!

Unfortunately, it seems that the order history functionality of MT4Orders is broken :(

I've been running various EAs under the 13.11.2016 version for a while, but only just needed to check order history in a new EA, and it returned incorrect information in the tester. 

I used this example code in the OnTick function of the parent .mq5 file to track what was happening:

Comment("Open trades: ", OrdersTotal(), OrdersToString(), "\n", "Closed trades: ", OrdersHistoryTotal(), OrdersToString(MODE_HISTORY));

After opening a trade, the chart shows this:



...but when the trade closes-out, this is displayed, so it's seeing the correct number of history entries, but only retrieving / duplicating details of the 1st (balance) entry:


I saw that the latest (14.06.2017) version of MT4Orders was available and gave that a try, but a similar problem exists - when the trade closes-out, the chart shows:


...so it's now showing an incorrect history count too

However, if I open 2 orders then the chart shows this (the history count is wrong and the balance entry is no longer displayed):


...and when both trades close, they report correctly in the history, but the balance entry is still missing and the history count is still wrong:

I'm hoping that there's a quick fix for this as I've tried checking the code and can't see what's causing it.

 
SysFX:

I'm hoping that there's a quick fix for this as I've tried checking the code and can't see what's causing it.

Try MT5_b1616. MT5_b1606-1607 had the bug.


#include <MT4Orders.mqh>

void OrdersToLog( const int Pool = MODE_TRADES )
{
  const int Total = ((Pool == MODE_TRADES) ? OrdersTotal() : OrdersHistoryTotal());

  for (int i = 0; i < Total; i++)
    if (OrderSelect(i, SELECT_BY_POS, Pool))
      OrderPrint();
}

void PrintAll()
{
  Print("Trades = " + (string)OrdersTotal());
  OrdersToLog();
  
  Print("History = " + (string)OrdersHistoryTotal());
  OrdersToLog(MODE_HISTORY);  
  
  Print("----------");
}

void CloseAll()
{
  for (int i = OrdersTotal() - 1; i >= 0; i--)
    if (OrderSelect(i, SELECT_BY_POS))
      OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 0);  
}

#define Ask SymbolInfoDouble(_Symbol, SYMBOL_ASK)

void OnTick()
{
  PrintAll();
  
  OrderSend(_Symbol, OP_BUY, 0.1, Ask, 0, 0, 0);
  OrderSend(_Symbol, OP_BUY, 0.2, Ask, 0, 0, 0);
  PrintAll();

  CloseAll();
  PrintAll();
  
  ExpertRemove();  
}


MT5_b1616 result:

2017.07.02 15:10:39.406 2017.06.30 00:04:42   Trades = 0
2017.07.02 15:10:39.406 2017.06.30 00:04:42   History = 1
2017.07.02 15:10:39.406 2017.06.30 00:04:42   #1 2017.06.30 00:00:00 balance 0.00  0 0 0 2017.06.30 00:00:00 0 0.00 0.00 10000000.00 0
2017.07.02 15:10:39.406 2017.06.30 00:04:42   ----------
2017.07.02 15:10:39.406 2017.06.30 00:04:42   instant buy 0.10 EURUSD at 1.14405 (1.14396 / 1.14405)
2017.07.02 15:10:39.406 2017.06.30 00:04:42   deal #2 buy 0.10 EURUSD at 1.14405 done (based on order #2)
2017.07.02 15:10:39.406 2017.06.30 00:04:42   deal performed [#2 buy 0.10 EURUSD at 1.14405]
2017.07.02 15:10:39.406 2017.06.30 00:04:42   order performed buy 0.10 at 1.14405 [#2 buy 0.10 EURUSD at 1.14405]
2017.07.02 15:10:39.406 2017.06.30 00:04:42   instant buy 0.20 EURUSD at 1.14405 (1.14396 / 1.14405)
2017.07.02 15:10:39.406 2017.06.30 00:04:42   deal #3 buy 0.20 EURUSD at 1.14405 done (based on order #3)
2017.07.02 15:10:39.406 2017.06.30 00:04:42   deal performed [#3 buy 0.20 EURUSD at 1.14405]
2017.07.02 15:10:39.406 2017.06.30 00:04:42   order performed buy 0.20 at 1.14405 [#3 buy 0.20 EURUSD at 1.14405]
2017.07.02 15:10:39.406 2017.06.30 00:04:42   Trades = 2
2017.07.02 15:10:39.406 2017.06.30 00:04:42   #2 2017.06.30 00:04:42 buy 0.10 EURUSD 1.14405 0.00000 0.00000 1.14396 0.00 0.00 -0.90 0
2017.07.02 15:10:39.406 2017.06.30 00:04:42   #3 2017.06.30 00:04:42 buy 0.20 EURUSD 1.14405 0.00000 0.00000 1.14396 0.00 0.00 -1.80 0
2017.07.02 15:10:39.406 2017.06.30 00:04:42   History = 1
2017.07.02 15:10:39.406 2017.06.30 00:04:42   #1 2017.06.30 00:00:00 balance 0.00  0 0 0 2017.06.30 00:00:00 0 0.00 0.00 10000000.00 0
2017.07.02 15:10:39.406 2017.06.30 00:04:42   ----------
2017.07.02 15:10:39.406 2017.06.30 00:04:42   instant sell 0.20 EURUSD at 1.14396, close #3 (1.14396 / 1.14405)
2017.07.02 15:10:39.406 2017.06.30 00:04:42   deal #4 sell 0.20 EURUSD at 1.14396 done (based on order #4)
2017.07.02 15:10:39.406 2017.06.30 00:04:42   deal performed [#4 sell 0.20 EURUSD at 1.14396]
2017.07.02 15:10:39.406 2017.06.30 00:04:42   order performed sell 0.20 at 1.14396 [#4 sell 0.20 EURUSD at 1.14396]
2017.07.02 15:10:39.406 2017.06.30 00:04:42   instant sell 0.10 EURUSD at 1.14396, close #2 (1.14396 / 1.14405)
2017.07.02 15:10:39.406 2017.06.30 00:04:42   deal #5 sell 0.10 EURUSD at 1.14396 done (based on order #5)
2017.07.02 15:10:39.406 2017.06.30 00:04:42   deal performed [#5 sell 0.10 EURUSD at 1.14396]
2017.07.02 15:10:39.406 2017.06.30 00:04:42   order performed sell 0.10 at 1.14396 [#5 sell 0.10 EURUSD at 1.14396]
2017.07.02 15:10:39.406 2017.06.30 00:04:42   Trades = 0
2017.07.02 15:10:39.406 2017.06.30 00:04:42   History = 3
2017.07.02 15:10:39.406 2017.06.30 00:04:42   #1 2017.06.30 00:00:00 balance 0.00  0 0 0 2017.06.30 00:00:00 0 0.00 0.00 10000000.00 0
2017.07.02 15:10:39.406 2017.06.30 00:04:42   #4 2017.06.30 00:04:42 buy 0.20 EURUSD 1.14405 0.00000 0.00000 2017.06.30 00:04:42 1.14396 0.00 0.00 -1.80 0
2017.07.02 15:10:39.406 2017.06.30 00:04:42   #5 2017.06.30 00:04:42 buy 0.10 EURUSD 1.14405 0.00000 0.00000 2017.06.30 00:04:42 1.14396 0.00 0.00 -0.90 0
2017.07.02 15:10:39.406 2017.06.30 00:04:42   ----------