Discussion of article "Trade Operations in MQL5 - It's Easy" - page 3

 

Can you tell me if it is possible to implement this construction from MQL4 using m_Trade.PositionModify (m_Trade is a member of CTrade class)?

...
if(TrendUp==true) 
   for(int i=0; i<10; i++)
      {
        ticket = OrderSend(Symbol(),OP_BUY,Lots,Ask,30,0,0);
        if(ticket>0 && i<9) OrderModify(ticket,0,0,Ask+SPS*take_koef[i],0);
      };
...

The point of the script is to open a buy on the market with a given number of lots, and then set a take profit in 10 parts. I got stuck in the fact that without setting a stop loss PositionModify gives error 10016(Incorrect stops in the request). And there is no task to set a stop :). In the help it says that it is possible not to specify a value:

Параметры

symbol

[in]  Наименование торгового инструмента, по которому предполагается модифицировать позицию.

sl

[in]  Новая цена, по которой сработает Stop Loss (либо, если изменение не нужно, предыдущее значение).

tp

[in]  Новая цена, по которой сработает Take Profit (либо, если изменение не нужно, предыдущее значение).

I tried to pass the value obtained from the previous purchase request (there is zero of course), well, the same rake only in profile. Here is my code:

...
         m_Trade.Buy(Lots);// buy the entire volume at the market
         if(m_Trade.ResultRetcode()==10008)//if the purchase is successful, change the position by setting the take-outs
           {
            S="Application fulfilled. Order number: "+IntegerToString(m_Trade.RequestOrder());
            Comment(S);
            sl=m_Trade.RequestSL();// get stop loss from the last request
            for(int i=0;i<=10;i++)
              {
               if(m_Trade.PositionModify(symbol,sl,Ask+SPS*take_koef[i]))
                 {
                  S+="Snap Take: "+IntegerToString(i);
                  Comment(S);
                 }
               else
                 {
                  S+="SnPosition change error with code: "+IntegerToString(m_Trade.ResultRetcode());
                  Comment(S);
                  return(4);
                 };
              };
...

Thank you in advance for your help.

[Deleted]  
This is YUGE help to jump start your EA programming.
 

Good Introduction to Object Oriented Programming in MQL5. 

With MT5 build 1347 the first code example fails to compile with error "illegal switch expression type".

I had to add casting to int in switch statements in AccountInfo.mqh to make it work, like:

switch((int)MarginMode())

 
Николай Осипов:

Hello,
When using BuyStop function in the code to trade RTS-3.13 (RIH3) futures, an error keeps occurring :
10022 TRADE_RETCODE_INVALID_EXPIRATION - Invalid order expiry date


Nicholas, greetings. Have you by any chance solved this problem? I experience the same difficulties on RTS-6.17, I don't understand how to solve it.
 
Rashid Zeynalov:
Similar problem on RTS-3.13 Opening-demo, tried everything (while limit orders are set to ORDER_TIME_SPECIFIED_DAY as written in the symbol profile) !!!!. While buy-stop order is perfectly open in the market manually. This is a terminal glitch, you should write to the developers
Rashid, hello. Have you by any chance solved this problem? I am experiencing the same difficulties on the real Open on RTS-6.17.

 
sgtkachev:
Rashid, hello. Have you by any chance solved this problem? I am experiencing the same difficulties on the real Open on RTS-6.17.

Sorry, did not notice the question. Try to replace this file and report the result, please.
Files:
Trade.mqh  68 kb
 

Hello

On some brokers (FoxPro for example) when trying to open a position error 10030. Code description: invalid fill. On other brokers (for example Alpari) works without these lines

In the block of initialisation of the Expert Advisor wrote different values in the code:

trade.SetTypeFilling(SYMBOL_FILLING_FOK);

или
trade.SetTypeFilling(SYMBOL_FILLING_IOC);

или

trade.SetTypeFilling(ORDER_FILLING_RETURN);

Does not help. How to solve the problem? Or is this CTrade class outdated and does not correspond to the latest terminal updates and I need to write trade operations according to the standard scheme through the structure?


UPD: Rashid posted a library file above, it solved my problem. It's sad that the standard library has an error. I will now study the comparison to see if it is possible to make some changes directly in the EA without replacing the library so that everything works

Автоматическое обновление - Для продвинутых пользователей - Начало работы - Справка по MetaTrader 5
Автоматическое обновление - Для продвинутых пользователей - Начало работы - Справка по MetaTrader 5
  • www.metatrader5.com
В платформу встроена система автоматического обновления. Она позволяет своевременно получать и устанавливать новые версии программы. Эту систему...
 
Good
 
makk:

Good Introduction to Object Oriented Programming in MQL5. 

With MT5 build 1347 the first code example fails to compile with error "illegal switch expression type".

I had to add casting to int in switch statements in AccountInfo.mqh to make it work, like:

switch((int)MarginMode())

 

Hi, Thanks for this very helpful post and please help me resolve this. I am new to MT5 and am learning to create EAs so I copied sample code to execute Ctrade.Buy but the backtest failed. Here's more info:


1) Account: Its a live account with base currency as NZD

2) MetaEditor settings for backtest:

Options


3) Code: Copied from https://www.mql5.com/en/articles/481:


//+------------------------------------------------------------------+

//|                                                         demo.mq5 |

//|                        Copyright 2017, MetaQuotes Software Corp. |

//|                                             https://www.mql5.com |

//+------------------------------------------------------------------+

#property copyright "Copyright 2017, MetaQuotes Software Corp."

#property link      "https://www.mql5.com"

#property version   "1.00"

#include<Trade\Trade.mqh>


//--- object for performing trade operations

CTrade  trade;

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

int OnInit()

  {

   //--- set MagicNumber for your orders identification

   int MagicNumber=123456;

   trade.SetExpertMagicNumber(MagicNumber);

   //--- set available slippage in points when buying/selling

   int deviation=10;

   trade.SetDeviationInPoints(deviation);

   //--- order execution mode

   trade.SetTypeFilling(ORDER_FILLING_RETURN);

   //--- logging mode: it would be better not to declare this method at all, the class will set the best mode on its own

   trade.LogLevel(1);

   //--- what function is to be used for trading: true - OrderSendAsync(), false - OrderSend()

   trade.SetAsyncMode(true);

   //---

   return(0);

  }

//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

  {

//---

   

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void OnTick()

  {

   BuySample1();

  }


//--- Buy sample  

//+------------------------------------------------------------------+

//|  Buying a specified volume at the current symbol                 |

//+------------------------------------------------------------------+

void BuySample1()

  {

//--- 1. example of buying at the current symbol

   if(!trade.Buy(0.1))

     {

      //--- failure message

      Print("Buy() method failed. Return code=",trade.ResultRetcode(),

            ". Code description: ",trade.ResultRetcodeDescription());

     }

   else

     {

      Print("Buy() method executed successfully. Return code=",trade.ResultRetcode(),

            " (",trade.ResultRetcodeDescription(),")");

     }

//---

  }

4) Error log (Please note that I am testing only on EUR/USD):

GJ 0 19:36:44.410 127.0.0.1 login (build 1730)

HH 0 19:36:44.420 Network 38520 bytes of account info loaded

JO 0 19:36:44.420 Network 1482 bytes of tester parameters loaded

QE 0 19:36:44.420 Network 188 bytes of input parameters loaded

FR 0 19:36:44.421 Network 443 bytes of symbols list loaded

IF 0 19:36:44.421 Tester expert file added: Experts\demo.ex5. 46684 bytes loaded

QH 0 19:36:44.433 Tester initial deposit 10000.00 NZD, leverage 1:100

JN 0 19:36:44.437 Tester successfully initialized

ES 0 19:36:44.437 Network 46 Kb of total initialization data received

PP 0 19:36:44.437 Tester Intel Core i7-4510U  @ 2.00GHz, 8103 MB

RJ 0 19:36:44.799 Symbols EURUSD: symbol to be synchronized

HR 0 19:36:44.800 Symbols EURUSD: symbol synchronized, 3624 bytes of symbol info received

NJ 0 19:36:44.800 History EURUSD: history synchronization started

GO 0 19:36:44.856 History EURUSD: load 27 bytes of history data to synchronize in 0:00:00.000

RQ 0 19:36:44.856 History EURUSD: history synchronized from 2012.01.01 to 2017.11.15

EF 0 19:36:44.993 History EURUSD,Daily: history cache allocated for 1010 bars and contains 312 bars from 2014.01.01 00:00 to 2014.12.31 00:00

ND 0 19:36:44.993 History EURUSD,Daily: history begins from 2014.01.01 00:00

OL 0 19:36:44.996 Tester EURUSD,Daily (HalifaxPlus-Live): every tick generating

GN 0 19:36:44.996 Tester EURUSD,Daily: testing of Experts\demo.ex5 from 2015.01.01 00:00 to 2017.11.15 00:00 started

CK 0 19:36:56.288 Symbols NZDUSD: symbol to be synchronized

IS 0 19:36:56.288 Symbols NZDUSD: symbol synchronized, 3624 bytes of symbol info received

JL 0 19:36:56.288 History NZDUSD: history synchronization started

HJ 0 19:36:56.575 History NZDUSD: load 14 Kb of history data to synchronize in 0:00:00.078

LS 0 19:36:56.575 History NZDUSD: history synchronized from 2013.01.01 to 2017.11.15

CO 0 19:36:56.579 Symbols EURNZD: symbol to be synchronized

OJ 0 19:36:56.580 Symbols EURNZD: symbol synchronized, 3624 bytes of symbol info received

DL 0 19:36:56.580 History EURNZD: history synchronization started

MK 0 19:36:56.656 History EURNZD: load 27 bytes of history data to synchronize in 0:00:00.000

OD 0 19:36:56.656 History EURNZD: history synchronized from 2013.01.01 to 2017.11.15

IN 0 19:36:56.665 Trade 2015.01.02 03:00:00   market buy 0.10 EURUSD (1.20538 / 1.20549 / 1.20538)

PE 0 19:36:56.665 Trades 2015.01.02 03:00:00   deal #2 buy 0.10 EURUSD at 1.20549 done (based on order #2)

FH 0 19:36:56.666 Trade 2015.01.02 03:00:00   deal performed [#2 buy 0.10 EURUSD at 1.20549]

OG 0 19:36:56.666 Trade 2015.01.02 03:00:00   order performed buy 0.10 at 1.20549 [#2 buy 0.10 EURUSD at 1.20549]

FO 0 19:36:56.670 demo (EURUSD,D1) 2015.01.02 03:00:00   Buy() method executed successfully. Return code=10009 (done at 1.20549)

NM 2 19:37:15.823 History NZDUSD 2016.09.21 23:01:00: corrupted history detected (s:-73370, o:73433, h:+48, l:-123, c:-117 -- tv:63, rv:11250111)

JF 2 19:37:15.823 History NZDUSD 2016.09.21, bad container found, must be resynchronized

LQ 2 19:37:16.106 Tester history error 9 in undefined function

OH 2 19:37:16.106 Tester stopped on 0% of testing interval with error '20 NZDUSD'


Please tell me whats wrong and how do I resolve this?