[WARNING CLOSED!] Any newbie question, so as not to clutter up the forum. Professionals, don't go by. Can't go anywhere without you. - page 276

 
rid >> :

When using (calling) functions from these files (already implemented in mt4), in case of incorrect work of the EA we can see in the log the number of the error made by us in the code.

For example, we call the GetLastError() function :

In this case, if we made an error in the code or set incorrect external parameters, we will see the number of this error in the log.

For example, 130.

And the decoding of the number can be found on the page -https://book.mql4.com/ru/appendix/errors

And we won't have to search through all code, because we already know by this number - where exactly mistake is made !

Let me correct a bit: the GetLastError function can be called without the header file but to get the error description without navigating the sites you should link the library:

#include <stderr.mqh>
#include <stdlib.mqh>

...
Print("Ошибка открытия ордера BUY #", ErrorDescription(GetLastError()));
...
 
rid писал(а) >>

You have not called the function correctly.

Your function is called like this: if (NumberOfPositions(NULL,Magic)> 1)

It should look like this:


Feel the difference (you missed the "-1") ! and CHANGE YOUR CODE.

To control it, you can print a comment on the chart. For example, like this (at the beginning of the START function).

As for your second condition, I would ("without thinking cleverly") set a different magician and separate function Open_Buy_2() to open positions by the second condition !

The code of the second condition would look like this

rid,

I also understand why the second condition does not work, maybe I explained the problem incorrectly:

I want my EA to be able to check if the orders were opened by it or not, even if they were closed a long time ago. NumberOfPositions works, but it only counts the number of open positions. (that's why it doesn't work)

In the code of my EA, there is a script which opens every next position taking into account the data of the previous position and if there was no previous position, the first order should be opened without this condition (otherwise, the EA will not start). Therefore, there should be a function that understands if at least one order of this EA has been opened or not (even if the order was then closed). If there have not been any orders yet (the beginning of work), then the first order is opened without considering the second condition, and all subsequent orders are opened considering the second condition, i.e. using the data from previous orders.

Is it possible to modify the function in this way?

 

Please tell me what the iTime function shows.

What is that gibberish of 10 digits? Seconds?

How would it translate to year-month-day-hour-minute?

 

I see. To determine if there were positions on the history, you can do this:

  for (int i=0; i< OrdersTotal(); i++)                          {
    if (!(OrderSelect( i, SELECT_BY_POS, MODE_HISTORY ))) continue;
//выбираем из истории счета
    if (OrderSymbol() != Symbol()) continue;    
     if ( OrderMagicNumber()== Magic)                            {
              позиции = true;
                                                             }}
                  



But then your code will only work in tester. Because otherwise you will have to change the magik every time you turn on the EA online.

Apparently, you need to set the time for which the account history is taken.

I.e. when was the last trade with the given magik opened/closed? Was it six months ago or 24 hours ago?

There are functions that return the bar number (counting from the current bar to the back of the history) of the last trade opened or closed.


//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru/                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Возвращает номер бара открытия последней позиции или -1.       |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   ("" или NULL - текущий символ)          |
//|    tf - таймфрейм                  (    0       - текущий таймфрейм)       |
//|    op - операция                   (   -1       - любая позиция)           |
//|    mn - MagicNumber                (   -1       - любой магик)             |
//+----------------------------------------------------------------------------+
int NumberOfBarOpenLastPos(string sy="0", int tf=0, int op=-1, int mn=-1) {
  datetime t;
  int      i, k=OrdersTotal();

  if ( sy=="" || sy=="0") sy=Symbol();
  for ( i=0; i< k; i++) {
    if (OrderSelect( i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()== sy) {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if ( op<0 || OrderType()== op) {
            if ( mn<0 || OrderMagicNumber()== mn) {
              if ( t<OrderOpenTime()) t=OrderOpenTime();
            }}}}} }  return(iBarShift( sy, tf, t, True));}

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru/                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Возвращает номер бара закрытия последней позиции или -1.       |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   ("" или NULL - текущий символ)          |
//|    tf - таймфрейм                  (    0       - текущий таймфрейм)       |
//|    op - операция                   (   -1       - любая позиция)           |
//|    mn - MagicNumber                (   -1       - любой магик)             |
//+----------------------------------------------------------------------------+
int NumberOfBarCloseLastPos(string sy="0", int tf=0, int op=-1, int mn=-1) {
  datetime t;
  int      i, k=OrdersHistoryTotal();

  if ( sy=="" || sy=="0") sy=Symbol();
  for ( i=0; i< k; i++) {
    if (OrderSelect( i, SELECT_BY_POS, MODE_HISTORY)) {
      if (OrderSymbol()== sy) {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if ( op<0 || OrderType()== op) {
            if ( mn<0 || OrderMagicNumber()== mn) {
              if ( t<OrderCloseTime()) t=OrderCloseTime();
            } } }} }  }  return(iBarShift( sy, tf, t, True));}

To give you an example. I have used these functions in my code like this:
//======================================================================
// запретить торговлю - в день , если с начала текущих суток
//уже были открыты или закрыты позиции с заданным магиком
if ( NumberOfBarOpenLastPos(NULL, 1440,-1, Magic)==0 
     ||  NumberOfBarCloseLastPos(NULL, 1440,-1, Magic)==0 )
    Trade=false;       else Trade=true;
//================================================================

Or like this:
//======================================================================
// запрет торговли  , если за последние 85 баров графика Н1
//т.е. за посл.85 часов)уже были открыты   позиции  или
// закрыты позиции с заданным магиком
if ( NumberOfBarOpenLastPos(NULL, 60,-1, Magic)<=85 
     ||  NumberOfBarCloseLastPos(NULL,60,-1, Magic)<=85 )
    Trade=false;       else Trade=true;
 
Gentlemen! Help! How to write the code correctly to display a message that the closed last candle is white (up) or black (down). I know it doesn't make sense, but still .....

 

Hmm.struggling with the same simple problem...opens a sea of positions but needs only 1 at the most and when buy closes and a signal comes to open sell... Big request hint and correct what's wrong.in the code below... Where do I need to prescribe a magik? If you don't mind, make a dumb example, when buy cross upwards (not more than 1 order) and sell downwards also not more than 1. I think this will immediately solve the questions of many newbies. Thank you in advance.

//---- input parameters
extern int       Ema1=14;
extern int       Ema2=48;
double Ema_1;
double Ema_2;

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
   int Orders = OrdersTotal(); 
   Ema_1 =iMA(NULL, 0, Ema1, 0,MODE_SMMA, PRICE_MEDIAN, 0);
   Ema_2 =iMA(NULL, 0, Ema2, 0,MODE_SMMA, PRICE_MEDIAN, 0);
   
   int ticket;
  if ( NumberOfPositions(NULL,OP_BUY)< 1 && Ema_1> Ema_2) 
    {
      ticket=OrderSend(Symbol(),OP_BUY,0.5,Ask,10,Ask-850*Point,Ask+550*Point,"kupil",16384,0,Green);
    } 
   if ( NumberOfPositions(NULL,OP_BUY)< 1 && Ema_1< Ema_2) 
    {
      ticket=OrderSend(Symbol(),OP_SELL,0.5,Bid,10,Ask+850*Point,Bid-550*Point,"kupil",16384,0,Green);
    } 
   return(0);
  }

int NumberOfPositions(string sy="", int op=-1, int mn=-1) {
  int i, k=OrdersTotal(), kp=0;

  if ( sy=="0") sy=Symbol();
  for ( i=0; i< k; i++)                                    {
    if (OrderSelect( i, SELECT_BY_POS, MODE_TRADES))      {
      if (OrderSymbol()== sy || sy=="")                   {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if ( op<0 || OrderType()== op)                   {
            if ( mn<0 || OrderMagicNumber()== mn) kp++;
          }}}}}
  return( kp);
}
 

Another stupid question:

- How to declare an array whose number of elements is given by an external variable.

 
chaynik_1 >> :
Gentlemen! Help! How to write the code correctly to display a message that the last closed candle is white (up) or black (down). I know it doesn't make sense, but still .....

It's like this.

if ((Open[1]-Close[1])<0  ) Comment ("1 свеча =  бычья");
 
alderru >> :

Another stupid question:

- How to declare an array whose number of elements is given by an external variable.

https://docs.mql4.com/ru/array/ArrayResize

 
morok >> :

Hmm.struggling with the same simple problem...opens a sea of positions but needs only 1 at the most and when buy closes and a signal to open sell comes... Big request hint and correct what's wrong.in the code below... Where do I need to prescribe a magik? If you don't mind, make a dumb example, when buy cross upwards (not more than 1 order) and sell downwards also not more than 1. I think this will immediately solve the questions of many newbies. Thanks in advance.

Try it like this:

(you have to be more attentive with NumberOfPositions(), it's written in the header for a reason:

/| Description : | Description : Returns the number of positions.
//| Parameters : |
//| sy - instrument name ("" or NULL - current symbol) |
|| op - operation ( -1 - any position) |
//| mn - MagicNumber ( -1 - any magic number) |
//+----------------------------------------------------------------------------+

extern int       Magic=5675;
extern int       Ema1=14;
extern int       Ema2=48;
double Ema_1;
double Ema_2;

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
   //int Orders = OrdersTotal(); 
   Ema_1 =iMA(NULL, 0, Ema1, 0,MODE_SMMA, PRICE_MEDIAN, 0);
   Ema_2 =iMA(NULL, 0, Ema2, 0,MODE_SMMA, PRICE_MEDIAN, 0);   
   int ticket;
//------------------------------------------------
 if ( NumberOfPositions(NULL,OP_BUY, Magic)< 1 && Ema_1> Ema_2) 
    {
      ticket=OrderSend(Symbol(),OP_BUY,0.5,Ask,10,Ask-850*Point,Ask+550*Point,"kupil",16384,0,Green);
    } 
//------------------------------------------------------
   if ( NumberOfPositions(NULL,OP_SELL, Magic)< 1 && Ema_1< Ema_2) 
    {
      ticket=OrderSend(Symbol(),OP_SELL,0.5,Bid,10,Ask+850*Point,Bid-550*Point,"kupil",16384,0,Green);
    } 
//------------------------------------------------------
   return(0);
  }

//жжжжжжжжж Пользовательские функции жжжжжжж

int NumberOfPositions(string sy="", int op=-1, int mn=-1) {
  int i, k=OrdersTotal(), kp=0;

  if ( sy=="0") sy=Symbol();
  for ( i=0; i< k; i++)                                    {
    if (OrderSelect( i, SELECT_BY_POS, MODE_TRADES))      {
      if (OrderSymbol()== sy || sy=="")                   {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if ( op<0 || OrderType()== op)                   {
            if ( mn<0 || OrderMagicNumber()== mn) kp++;
          }}}}}
  return( kp);
}