Useful features from KimIV - page 62

 

Thanks for the reply, Igor, I've figured it out. I use your functions separately as well, but I wanted to take advantage of the library at the stage of EA development.

I looked how komposter' s trade_lib&info_lib library is made and made some changes in yours for my own use.

1. I have removed in all libraries #property library and #include library cross-links, renamed libraries not to be confused.

2. I have made a block of direct calls of all the libraries.

#include <b-Positions#.mqh>        // Библиотека функций для работы с позициями 
#include <b-KimIV#.mqh>            // Библиотека дополнительных функций
#include <b-Orders#.mqh>           // Библиотека функций для работы с ордерами
#include <stdlib.mqh>              // Стандартная библиотека
#include <WinUser32.mqh>           // Стандартная библиотека  

Now all functions of all the libraries are available, there are no errors and criminal messages during compilation, except for normal "is not referenced...".

All extern EAs are available, no problems.

Write more, we will connect and use. First of all I would like to see trailing function by total profit.

 

The WeekOfMonth() function.

This function returns the week of the month by date. Accepts only one optional parameter:

  • dt - Date, time. Default value - 0 - current date and time of trade server.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 12.08.2008                                                     |
//|  Описание : Возвращает номер недели месяца по дате                         |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    dt - дата, время           (0 - сейчас по времени торгового сервера)    |
//+----------------------------------------------------------------------------+
int WeekOfMonth(datetime dt=0) {
  if ( dt<=0) dt=TimeCurrent();
  datetime d;
  int      i, kd=TimeDay( dt), nn=1;

  for ( i=2; i<= kd; i++) {
    d=StrToTime(TimeYear( dt)+"."+TimeMonth( dt)+"."+ i);
    if (TimeDayOfWeek( d)==1) nn++;
  }
  return( nn);
}

SZY. Attached is a script to test WeekOfMonth() function.

Files:
 
Igor, isn't there a function that would close all positions starting from those with a larger lot?
 

Hello, Igor! Thank you very much for your useful features! I'm using them as much as I can! I've only recently got into this myself, so a question for you... I've been using them for a long time now, so I've been using them for a long time now. I'm using your function OpenPosition, maybe it`s reacting to an error or something? Here's the log from yesterday, everything was fine before that! can't find error 220........ anywhere

07:47:28 MetaTrader 4.00 build 220 started (MetaQuotes Software Corp.)
07:47:28 Expert open prob USDJPY EURUSD,M1: loaded successfully
07:47:32 '1262868': login
07:47:44 '1262868': login
07:49:40 '1262868': login
07:49:46 '1262868': login
07:54:44 '1262868': connect failed [No connection]
11:38:16 Expert open prob USDJPY EURUSD,M1: removed
11:38:18 MetaTrader 4.00 build 220 stopped
14:05:05 MetaTrader 4.00 build 220 started (MetaQuotes Software Corp.)
14:05:05 Expert open prob USDJPY EURUSD,M1: loaded successfully
14:05:10 '1262868': login
14:05:31 '1262868': login
14:06:39 '1262868': login
14:06:46 '1262868': login
15:57:06 '1262868': connect failed [No connection]
18:30:46 Expert open prob USDJPY EURUSD,M5: removed
18:30:49 Main pumping: timeout on stop
18:30:52 Main pumping: timeout on stop
18:30:55 Main pumping: timeout on stop
18:30:58 Main pumping: timeout on stop
18:31:01 Main pumping: timeout on stop
18:31:01 Main pumping: terminated
18:31:02 MetaTrader 4.00 build 220 stopped
18:31:02 MetaTrader 4.00 build 220 stopped because system shutdown
18:47:57 MetaTrader 4.00 build 220 started (MetaQuotes Software Corp.)
18:47:58 Expert open prob USDJPY EURUSD,M5: loaded successfully
18:48:01 '1262868': connect failed [No connection]
18:48:10 '1262868': login
18:48:20 '1262868': login
20:19:00 '1262868': login
20:19:07 '1262868': login
20:20:05 '1262868': login
20:20:13 '1262868': login
20:59:29 '1262868': login
20:59:39 '1262868': login
21:02:16 '1262868': login
21:02:41 '1262868': DataCenter connecting failed [6]
22:08:40 '1262868': ping failed
22:08:43 '1262868': login
22:08:49 '1262868': DataCenter connecting failed [6]
22:1001 '1262868': login
22:10:05 '1262868': DataCenter connecting failed [6]
22:14:59 '1262868': login
22:15:13 '1262868': login
22:15:22 '1262868': DataCenter connecting failed [6]
22:37:16 '1262868': login
22:37:27 '1262868': DataCenter connecting failed [6]
22:4051 '1262868': login
22:41:04 '1262868': DataCenter connecting failed [6]
23:17:14 Expert open prob USDJPY EURUSD,M5: removed
23:17:16 Expert open prob USDJPY EURUSD,M5: loaded successfully
23:25:52 Expert open prob USDJPY EURUSD,M5: removed
23:25:55 MetaTrader 4.00 build 220 stopped
23:25:59 MetaTrader 4.00 build 220 started (MetaQuotes Software Corp.)
23:26:05 '1262868': login
23:26:05 Expert open prob USDJPY EURUSD,M5: loaded successfully
23:26:15 '1262868': login
23:27:19 '1262868': login
23:27:34 '1262868': login
23:28:20 Expert open prob USDJPY EURUSD,M5: removed
23:28:25 Expert open prob USDJPY USDCHF,H4: loaded successfully
23:28:33 Expert open prob USDJPY USDCHF,H4: removed

Thanks a lot in advance!

 
khorosh писал(а) >>
Igor, is there no function that would close all positions starting from those that have a larger lot?

wasn't... wrote...

The ClosePosBySortLots() function.

This function closes positions in order of sorting by lot size. That is, using this function, you can close positions in ascending or descending order of lots sizes. Function ClosePosBySortLots() accepts the following optional parameters:

  • sy - Name of the trading instrument. "" - any instrument, NULL - current instrument. Default value is "".
  • op - Type of trade operation. Valid values -1 - any position, OP_BUY - buy, OP_SELL - sell. The default value is -1.
  • mn - MagicNumber, unique identifier of trade operation. Default value -1 - any magic number.
  • sd - Lot size sorting direction. Valid values MODE_ASCEND - ascending, MODE_DESCEND - descending. Default value is MODE_DESCEND.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 11.12.2008                                                     |
//|  Описание : Закрытие позиций в порядке сортировки по размерам лотов.       |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента        (    ""       - любой символ,      |
//|                                             NULL      - текущий символ)    |
//|    op - операция                        (    -1       - любая позиция)     |
//|    mn - MagicNumber                     (    -1       - любой магик)       |
//|    sd - Направление сортировки лотов    (MODE_ASCEND  - возрастание,       |
//|                                          MODE_DESCEND - убывание)          |
//+----------------------------------------------------------------------------+
void ClosePosBySortLots(string sy="", int op=-1, int mn=-1, int sd= MODE_DESCEND) {
  double a[][2];                  // Массив лотов и тикетов
  int    i, k=OrdersTotal();      // Счётчик и количество ордеров
  int    p=0;                     // Количество позиций

  if ( sy=="0") sy=Symbol();
  for ( i=0; i< k; i++) {
    if (OrderSelect( i, SELECT_BY_POS, MODE_TRADES)) {
      if ((OrderSymbol()== sy || sy=="") && ( op<0 || OrderType()== op)) {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if ( mn<0 || OrderMagicNumber()== mn) {
            p++;
            ArrayResize( a, p);
            a[ p-1][0]=OrderLots();
            a[ p-1][1]=OrderTicket();
          }
        }
      }
    }
  }

  // вдруг позиций нету, тогда и закрывать нечего
  if ( p>0) {
    ArraySort( a, WHOLE_ARRAY, 0, sd);
    for ( i=0; i< p; i++) {
      if (OrderSelect( a[ i][1], SELECT_BY_TICKET)) {
        // проверим незакрытость на всякий случай,
        // может какая-то позиция уже закрылась по стопу/тейку
        if (OrderCloseTime()==0) ClosePosBySelect();
      }
    }
  }
}

SZY. Attached is a script to test ClosePosBySortLots() function.

 

The AddLeadingZero() function.

This function adds as many leading (left) zeros "0" to the string so that the string length becomes equal to some given value. The AddLeadingZero() function takes the following mandatory parameters:

  • s - The string to which the leading zeros are to be added.
  • k - The length of the resulting string S.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Добавляет к строке S столько лидирующих нулей "0",             |
//|           : чтобы длина строки S стала равна K.                            |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    s - строка                                                              |
//|    k - длина строки S                                                      |
//+----------------------------------------------------------------------------+
string AddLeadingZero(string s, int k) {
  while(StringLen( s)< k) s=StringConcatenate("0", s);
  return( s);
}

SZU. Attached is a script to test AddLeadingZero() function.

Files:
 

The toTime() function.

This function converts two/three integers into a string in time format. If two numbers are passed into the function, the first will be used as hours and the second as minutes. The format string returned will be "HH:MM". If there are three numbers, the third will be replaced by the seconds and the function will return the "HH:MM:SS" string. The toTime() function accepts the following optional parameters:

  • h - Clock. Default value is 0.
  • m - Minutes. Default value is 0.
  • s - Seconds. 0 - Do not use. Default value 0.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Преобразует два/три целых числа в строку в формате времени     |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    h - часы                                                                |
//|    m - минуты                                                              |
//|    s - секунды           (0 - не использовать)                             |
//+----------------------------------------------------------------------------+
string toTime(int h=0, int m=0, int s=0) {
  string st="";

  if ( h==0) st="00:";
  else      st=StringConcatenate( AddLeadingZero( h, 2), ":");

  if ( m==0) st=StringConcatenate( st, "00");
  else      st=StringConcatenate( st, AddLeadingZero( m, 2));

  if ( s!=0) st=StringConcatenate( st, ":", AddLeadingZero( s, 2));

  return( st);
}

ZS. Attached is a script to test toTime() function.

Files:
 

Igor, could you suggest a function that would give a corresponding signal when the price matches one of the variables, say b=1.2400, s=1.2300;

If b=price sig=1, if s=price sig=-1.

I apologise for the sloppiness).

 
Prival >> :
Sorry, I'm not Igor. But maybe this will help.

I apologise too. >> it's more accurate.

//+------------------------------------------------------------------+
//| Функция                                                          |
//+------------------------------------------------------------------+
int Sign(double b, double s)
   {
   double var, e; var=Close[0]; e=0.000001;
   if( var< b+ e && var> b- e) return( 1);
   if( var< s+ e && var> s- e) return(-1); 
   return(0);
   }
 
Prival >> :

..I'll be deleting my posts by tonight so as not to clutter up the thread...

No need. It will be useful to have a look, it will wake you up to the idea that the exact price value is not consistently caught.