Useful features from KimIV - page 21

 

The isCloseLastPosByStop() function.

This function returns a flag to close the last position by stop. Flag is up - True - StopLoss has triggered. Flag lowered - False - position has been closed for another reason. More accurate selection of positions to be taken into account is set using external parameters:

  • sy - Name of market instrument. If this parameter is set, the function will consider only positions of the specified instrument. The default value "" means any market instrument. NULL means the current instrument.
  • op - Trade operation, position type. Valid values: OP_BUY, OP_SELL or -1. The default value -1 means any position.
  • mn - Position identifier, MagicNumber. Default value -1 means any identifier.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.05.2008                                                     |
//|  Описание : Возвращает флаг закрытия последней позиции по стопу.           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
bool isCloseLastPosByStop(string sy="", int op=-1, int mn=-1) {
  datetime t;
  double   ocp, osl;
  int      dg, i, j=-1, k=OrdersHistoryTotal();

  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
      if (OrderSymbol()==sy || sy=="") {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (op<0 || OrderType()==op) {
            if (mn<0 || OrderMagicNumber()==mn) {
              if (t<OrderCloseTime()) {
                t=OrderCloseTime();
                j=i;
              }
            }
          }
        }
      }
    }
  }
  if (OrderSelect(j, SELECT_BY_POS, MODE_HISTORY)) {
    dg=MarketInfo(sy, MODE_DIGITS);
    if (dg==0) if (StringFind(OrderSymbol(), "JPY")<0) dg=4; else dg=2;
    ocp=NormalizeDouble(OrderClosePrice(), dg);
    osl=NormalizeDouble(OrderStopLoss(), dg);
    if (ocp==osl) return(True);
  }
  return(False);
}
P.S. Attached is a script to test isCloseLastPosByStop() function.
 
Lukyanov:
KimIV:

OpenPosition() function for online.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 21.03.2008                                                     |
//|  Описание : Открывает позицию и возвращает её тикет.                       |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (NULL или "" - текущий символ)          |
//|    op - операция                                                           |
//|    ll - лот                                                                |
//|    sl - уровень стоп                                                       |
//|    tp - уровень тейк                                                       |
//|    mn - MagicNumber                                                        |
//+----------------------------------------------------------------------------+
int OpenPosition(string sy, int op, double ll, double sl=0, double tp=0, int mn=0) {
//-- skip --
  string   lsComm=WindowExpertName()+" "+GetNameTF(Period());
//-- skip -- 
Plugged OpenPosition() function in EA on real, error 4059, changed NULL to Symbol(), disappeared, then message appeared
2008.05.20 04:47:41 !OBLD_EUR_S EURUSD,M30: expert stopped
2008.05.20 04:47:41 !OBLD_EUR_S EURUSD,M30: expert function calls are not allowed; 'stdlib'-'ErrorDescription'
Back to baseline, everything works... (stdlib.mqh && stderror.mqh are in the include folder from the base MT delivery)
 
teraptor2 писал (а):
I have connected the OpenPosition() function in my Expert Advisor on the real, the error 4059

Error 4059 means that the function is not available in test mode. The error identifier is ERR_FUNCTION_NOT_ALLOWED_IN_TESTING_MODE. The following functions generate the error: MarketInfo, MessageBox, SendFTP, SendMail, WindowIsVisible, WindowFind, WindowHandle.

teraptor2 wrote (a):
changed NULL to Symbol(), it disappeared, then a message appeared
2008.05.20 04:47:41 !OBLD_EUR_S EURUSD,M30: expert stopped
2008.05.20 04:47:41 !OBLD_EUR_S EURUSD,M30: expert function calls are not allowed; 'stdlib'-'ErrorDescription'
 

The isCloseLastPosByTake() function.

This function returns a flag to close the last position at Take Profit. Flag is up - True - TakeProfit has triggered. Flag lowered - False - position was closed due to another reason. More accurate selection of positions to be considered is done using external parameters:

  • sy - Name of market instrument. If this parameter is set, the function will consider only positions of the specified instrument. The default value "" means any market instrument. NULL means the current instrument.
  • op - Trade operation, position type. Valid values: OP_BUY, OP_SELL or -1. The default value -1 means any position.
  • mn - Position identifier, MagicNumber. Default value -1 means any identifier.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.05.2008                                                     |
//|  Описание : Возвращает флаг закрытия последней позиции по тейку.           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
bool isCloseLastPosByTake(string sy="", int op=-1, int mn=-1) {
  datetime t;
  double   ocp, otp;
  int      dg, i, j=-1, k=OrdersHistoryTotal();

  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
      if (OrderSymbol()==sy || sy=="") {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (op<0 || OrderType()==op) {
            if (mn<0 || OrderMagicNumber()==mn) {
              if (t<OrderCloseTime()) {
                t=OrderCloseTime();
                j=i;
              }
            }
          }
        }
      }
    }
  }
  if (OrderSelect(j, SELECT_BY_POS, MODE_HISTORY)) {
    dg=MarketInfo(sy, MODE_DIGITS);
    if (dg==0) if (StringFind(OrderSymbol(), "JPY")<0) dg=4; else dg=2;
    ocp=NormalizeDouble(OrderClosePrice(), dg);
    otp=NormalizeDouble(OrderTakeProfit(), dg);
    if (ocp==otp) return(True);
  }
  return(False);
}
HH. Attached is a script to test the isCloseLastPosByTake() function.
 

The isLossLastPos() function.

This function returns the loss flag of the last closed position. Flag up - True - last position was closed with a loss. Flags down - False - the last position was closed either at zero, or at a profit. This function doesn't consider swaps and commissions. Selection of positions is defined by external parameters:

  • sy - Name of market instrument. If you specify this parameter, the function will only consider positions of the specified instrument. The default value "" means any market instrument. NULL means the current instrument.
  • op - Trade operation, position type. Valid values: OP_BUY, OP_SELL or -1. The default value -1 means any position.
  • mn - Position identifier, MagicNumber. Default value -1 means any identifier.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Возвращает флаг убыточности последней позиции.                 |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
bool isLossLastPos(string sy="", int op=-1, int mn=-1) {
  datetime t;
  int      i, j=-1, k=OrdersHistoryTotal();

  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
      if (OrderSymbol()==sy || sy=="") {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (op<0 || OrderType()==op) {
            if (mn<0 || OrderMagicNumber()==mn) {
              if (t<OrderCloseTime()) {
                t=OrderCloseTime();
                j=i;
              }
            }
          }
        }
      }
    }
  }
  if (OrderSelect(j, SELECT_BY_POS, MODE_HISTORY)) {
    if (OrderProfit()<0) return(True);
  }
  return(False);
}
P.S. Attached is a script to test isLossLastPos() function.
Files:
 

The isTradeToDay() function.

This function returns the trade flag for today. Flag is up - True - there were open positions today. Flag down - False - no positions opened today. The selection of positions to be taken into account is set by external parameters:

  • sy - Name of market instrument. If this parameter is set, the function will consider only positions of the specified instrument. The default value "" means any market instrument. NULL means the current instrument.
  • op - Trade operation, position type. Valid values: OP_BUY, OP_SELL or -1. The default value -1 means any position.
  • mn - Position identifier, MagicNumber. Default value -1 means any identifier.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Возвращает флаг торгов сегодня.                                |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
bool isTradeToDay(string sy="", int op=-1, int mn=-1) {
  int i, k=OrdersHistoryTotal();

  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
      if (OrderSymbol()==sy || sy=="") {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (op<0 || OrderType()==op) {
            if (mn<0 || OrderMagicNumber()==mn) {
              if (TimeDay  (OrderOpenTime())==Day()
              &&  TimeMonth(OrderOpenTime())==Month()
              &&  TimeYear (OrderOpenTime())==Year()) return(True);
            }
          }
        }
      }
    }
  }
  k=OrdersTotal();
  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) {
              if (TimeDay  (OrderOpenTime())==Day()
              &&  TimeMonth(OrderOpenTime())==Month()
              &&  TimeYear (OrderOpenTime())==Year()) return(True);
            }
          }
        }
      }
    }
  }
  return(False);
}
ZZY. Attached is a script to test isTradeToDay() function.
Files:
 
KimIV:

The isCloseLastPosByStop() function.

This function returns a flag to close the last position by stop. Flag is up - True - StopLoss has triggered. Flag lowered - False - position has been closed for another reason. More accurate selection of positions to be considered is set using external parameters:

().

Afternoon . When implementing the code with this function, some confusion has appeared. I have applied this function like this:

if (isCloseLastPosByStop(NULL,OP_BUY, MagicLong1))               {
//если одна из открытых позиций BUY вдруг закрылась по стоплосу   
  for ( int rb_ = OrdersTotal() - 1; rb_ >= 0; rb_ -- )                {       
      if (OrderSelect(rb_, SELECT_BY_POS, MODE_TRADES))                 { 
      //выбираем среди открытых и отложенных ордеров          
      if( (OrderSymbol()==Symbol()) && (OrderMagicNumber()==MagicLong1))  {
         //закрываем все остальные позиции BUY
        OrderClose(OrderTicket(),OrderLots(),Bid,ОтклонениеЦены,Black );
       OrderDelete(OrderTicket());// и удаляем BUY-отложки   
        //  return(0); // выходим     
        }}}}

Up to this point everything works fine! All BUY-positions are closed and BUY-positions are deleted, as I've defined it! But then the Expert Advisor re-sets the pending orders according to its signals for entry. As expected.

But those orders are instantly deleted! Apparently, the flag still hangs there. But why is it hanging? The last positions have not been closed by a Stop Loss but by force!

How should I deal with this situation? How can I get my Expert Advisor to display its next orders normally after the command to close this algorithm is executed?

 
rid писал (а):
What should I do in this situation? So that the EA will be able to place its next orders normally after the command to close them?

This question needs to be addressed in the context of the whole task, because it is not just a single action, but an interaction, and in a certain order. Therefore, describe the task in full. You don't need a code. Just describe the task in words.

Warm-up question. Why do you need to delete orders and put them back? I think it is preferable to modify.

 

My orders and positions are grouped into arrays according to profits, losses, stop and limit orders, and other reasons.

In this particular case, I'm closing the array of BUY positions which have been opened using stop orders and have accumulated a specified profit. And I delete all other stop orders which have not worked.

//---------------------------------------------------------------------------------------------

 

Now I've put up a comment function - Comment (isCloseLastPosByStop());

Looking at. Initially, the function =0. After the first closing of a Stop Loss Comment (isCloseLastPosByStop()); changes to one, and then - after forced closing of other positions, it does not return to zero, but continues to be one!

Reason: