Useful features from KimIV - page 18

 
rid писал (а):
MA. I'll keep the post for 24 hours - then I'll delete it!

You don't have to delete it! Let it stay...

 

Igor, first of all thank you for your functions and for this branch, they help many non-professional programmers. But I'd like to ask you a question about the NumberOfOrders() function. I can't get it to work. I put it into a standard MACD Expert Advisor to give an example of how I use it. I am pasting the code:

To describe it briefly, it's changed there:

// в стандартной версии  
total=OrdersTotal();
   if(total<1) 
     {
// бла бла бла ...
// в моей версии эксперта
   total=OrdersTotal(); // total я оставил т.к. он используется дальше
   if(NumberOfOrders(NULL,-1,-1)<1) 
     {
// бла бла бла ... ну и плюс сама функция NumberOfOrders() ниже
Naturally, it doesn't work. Could you please explain what's wrong? Thanks in advance.
Files:
 
seifer писал (а):
Could you explain what's wrong? Thanks in advance.

Two comments:

1. I would do it like this:

total=NumberOfOrders(NULL);
if (total<1) {
  ...
}
2. Function NumberOfOrders() returns the number of orders - trades of BuyLimit, BuyStop, SellLimit and SellStop types. The Expert Advisor that you have modified does not work with orders. It opens positions at market prices, i.e. performs Buy and Sell trades. You need to use the NumberOfPositions() function, which I will post in the next post.
 

The NumberOfPositions() function.

This function returns the number of positions currently open. A more accurate selection of counted positions is specified 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   - любой магик)                    |
//+----------------------------------------------------------------------------+
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);
}
Attached is a script to test NumberOfPositions() function.
 

Wow! I thought it was a design:

      ...
      ot=OrderType();
      if (ot>1 && ot<6) {
      ...
would go through all positions (including OP_SELL and OP_BUY). Everything is working now. Thanks again!
 

GetProfitFromDateInCurrency() function.

This function returns the total profit in the currency of the positions closed since a certain date. More accurate selection of positions to be taken into account is specified using external parameters:

  • sy - Name of market instrument. If you specify this parameter, the function will consider only positions of this 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.
  • dt - Date and time in seconds since 1970. Default value - 0 means all positions available in history are taken into account.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Возвращает суммарный профит в валюте депозита                  |
//|             закрытых с определённой даты позиций                           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента             (""   - любой символ,         |
//|                                               NULL - текущий символ)       |
//|    op - операция                             (-1   - любая позиция)        |
//|    mn - MagicNumber                          (-1   - любой магик)          |
//|    dt - Дата и время в секундах с 1970 года  ( 0   - с начала истории)     |
//+----------------------------------------------------------------------------+
double GetProfitFromDateInCurrency(string sy="", int op=-1, int mn=-1, datetime dt=0)
{
  double p=0;
  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=="") && (op<0 || OrderType()==op)) {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (mn<0 || OrderMagicNumber()==mn) {
            if (dt<OrderCloseTime()) {
              p+=OrderProfit()+OrderCommission()+OrderSwap();
            }
          }
        }
      }
    }
  }
  return(p);
}

HH. Attached is a script to test function GetProfitFromDateInCurrency().

The i-Profit indicator, which shows absolute and percentage profit values for different time periods, is a more practical example of how to learn how to use this function.

 

Hello Igor.

I would like to say thank you for the correlation fic. I had some options, I just wanted to clarify them)

I also have such a question. I very often encounter error 130 - wrong stop during testing of Expert Advisor in the real time mode. I do not analyze it, I do not understand why it occurs in one situation or another. I have started to use this construction

   double md = MarketInfo(Symbol(), MODE_TICKSIZE);
   return(NormalizeDouble(Value/md, 0) * md);

I've started to use this construct to normalize stop and TP, but it didn't solve the situation. Maybe you've faced similar situations, tell me how to deal with it and what's the best way to analyze it.

To clarify: This happens very often when I try to set a stop at +1 p from the open price

 
scorpionk писал (а):
encounter error 131 - Incorrect stop.

131 - Incorrect volume, error in volume granulation. This is the size of the lot being traded.

 
KimIV:
scorpionk wrote (a):
I encounter error 131 - Wrong stop.

131 - Incorrect volume, an error in volume granulation. This is the size of the lot being traded.

Wrong code, not 131 but 130

 
scorpionk:

Wrong code, it's not 131, it's 130.

I see...

Try normalising as follows:

int dg=MarketInfo(Symbol(), MODE_DIGITS);
return(NormalizeDouble(Value, dg));
I do so and I don't encounter error 130.
Reason: