Only "Useful features from KimIV". - page 9

 

The StringLower() function.

This function converts a string to lower case. All SIGNIFICANT (large) characters become lowercase (small). The StringLower() function accepts only one mandatory parameter, which is the incoming string.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Возвращает строку в нижнем регистре                            |
//+----------------------------------------------------------------------------+
string StringLower(string s) {
  int c, i, k=StringLen(s), n;
  for (i=0; i<k; i++) {
    n=0;
    c=StringGetChar(s, i);
    if (c>64 && c<91) n=c+32;     // A-Z -> a-z
    if (c>191 && c<224) n=c+32;   // А-Я -> а-я
    if (c==168) n=184;            //  Ё  ->  ё
    if (n>0) s=StringSetChar(s, i, n);
  }
  return(s);
}
 

The StringUpper() function.

This function converts the string to Uppercase. All lowercase (small) characters become Uppercase (large). The StringUpper() function accepts only one mandatory parameter, which is the input string.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Возвращает строку в ВЕРХНЕМ регистре                           |
//+----------------------------------------------------------------------------+
string StringUpper(string s) {
  int c, i, k=StringLen(s), n;
  for (i=0; i<k; i++) {
    n=0;
    c=StringGetChar(s, i);
    if (c>96 && c<123) n=c-32;    // a-z -> A-Z
    if (c>223 && c<256) n=c-32;   // а-я -> А-Я
    if (c==184) n=168;            //  ё  ->  Ё
    if (n>0) s=StringSetChar(s, i, n);
  }
  return(s);
}


The StringToArrayDouble() function.

This function splits the string into its component real numbers, and each number is added to the array as a separate element. As many real numbers appear in the string, the same number of elements will be added to the array. A semicolon is recognized as a separator. The StringToArrayDouble() function returns the number of array elements, and takes the following mandatory parameters:

  • st - A string of real numbers separated by a semicolon.
  • ad - An array of real numbers.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 10.10.2008                                                     |
//|  Описание : Перенос вещественных чисел из строки в массив                  |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    st - строка вещественных чисел через точку с запятой                    |
//|    ad - массив вещественных чисел                                          |
//+----------------------------------------------------------------------------+
//|  Возврат:                                                                  |
//|    Количество элементов в массиве                                          |
//+----------------------------------------------------------------------------+
int StringToArrayDouble(string st, double& ad[]) {
  int    i=0, np;
  string stp;

  ArrayResize(ad, 0);
  while (StringLen(st)>0) {
    np=StringFind(st, ";");
    if (np<0) {
      stp=st;
      st="";
    } else {
      stp=StringSubstr(st, 0, np);
      st=StringSubstr(st, np+1);
    }
    i++;
    ArrayResize(ad, i);
    ad[i-1]=StrToDouble(stp);
  }
  return(ArraySize(ad));
}
 

The StringToArrayInt() function.

This function splits the string into its component integers, and each number is added to the array as a separate element. As many integers as there are in the string, the same number of elements will be added to the array. A comma is recognized as a separator. The StringToArrayDouble() function returns the number of array elements, and takes the following mandatory parameters:

  • st - Comma separated string of integer values.
  • ai - Integer array.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Перенос целочисленных значений из строки в массив              |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    st - строка целочисленных значений через запятую                        |
//|    ai - целочисленный массив                                               |
//+----------------------------------------------------------------------------+
//|  Возврат:                                                                  |
//|    Количество элементов в массиве                                          |
//+----------------------------------------------------------------------------+
int StringToArrayInt(string st, int& ai[]) {
  int    i=0, np;
  string stp;

  ArrayResize(ai, 0);
  while (StringLen(st)>0) {
    np=StringFind(st, ",");
    if (np<0) {
      stp=st;
      st="";
    } else {
      stp=StringSubstr(st, 0, np);
      st=StringSubstr(st, np+1);
    }
    i++;
    ArrayResize(ai, i);
    ai[i-1]=StrToInteger(stp);
  }
  return(ArraySize(ai));
}

The StrSplit() function.

This function splits a string into its substring, so that each substring becomes a separate element of the array. The separator is specified by a parameter and may be arbitrary. The StrSplit() function returns the number of array elements and accepts the following parameters:

  • st - String with separators.
  • as - The array of elements of the string type.
  • de - Separator. Optional parameter. Default value - "," (comma).
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 23.06.2008                                                     |
//|  Описание : Разбиение строки на массив элементов                           |
//+----------------------------------------------------------------------------+
//|  Возврат:                                                                  |
//|    Количество элементов в массиве                                          |
//|  Параметры:                                                                |
//|    st - строка с разделителями                                             |
//|    as - строковый массив                                                   |
//|    de - разделитель                                                        |
//+----------------------------------------------------------------------------+
int StrSplit(string st, string& as[], string de=",") { 
  int    i=0, np;
  string stp;

  ArrayResize(as, 0);
  while (StringLen(st)>0) {
    np=StringFind(st, ",");
    if (np<0) {
      stp=st;
      st="";
    } else {
      stp=StringSubstr(st, 0, np);
      st=StringSubstr(st, np+1);
    }
    i++;
    ArrayResize(as, i);
    as[i-1]=stp;
  }
  return(ArraySize(as));
}
 

The StrTran() function.

This function replaces a substring. All occurrences of it are replaced. For example, you can replace all commas with dots or vice versa in one fell swoop. The StrSplit() function returns the resulting string and accepts the following mandatory parameters:

  • str - The string in which the substring strFrom is being replaced.
  • strFrom - substituted substring. If the substring strFrom is found in string str, it will be replaced by substring strTo.
  • strTo - Substituted substring.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  описание : Замена подстроки                                               |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    str     - текстовая строка, в которой производится замена               |
//|    strFrom - заменяемая подстрока                                          |
//|    strTo   - заменяющая подстрока                                          |
//+----------------------------------------------------------------------------+
string StrTran(string str, string strFrom, string strTo) {
  int    n;
  string strOut="", strTemp;

  for (n=0; n<StringLen(str); n++) {
    strTemp=StringSubstr(str, n, StringLen(strFrom));
    if (strTemp==strFrom) {
      strOut=StringConcatenate(strOut, strTo);
      n=n+StringLen(strFrom)-1;
    } else strOut=StringConcatenate(strOut, StringSubstr(str, n, 1));
  }
  return(strOut);
}
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 23.04.2009                                                     |
//|  Описание : Перенос уровня стопа в безубыток                               |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   ( ""  - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   ( -1  - любая позиция)                  |
//|    mn - MagicNumber                ( -1  - любой магик)                    |
//+----------------------------------------------------------------------------+
void MovingInWL(string sy="", int op=-1, int mn=-1) {
  double po, pp;
  int    i, k=OrdersTotal();

  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 (mn<0 || OrderMagicNumber()==mn) {
          po=MarketInfo(OrderSymbol(), MODE_POINT);
          if (OrderType()==OP_BUY) {
            if (OrderStopLoss()-OrderOpenPrice()<LevelWLoss*po) {
              pp=MarketInfo(OrderSymbol(), MODE_BID);
              if (pp-OrderOpenPrice()>LevelProfit*po) {
                ModifyOrder(-1, OrderOpenPrice()+LevelWLoss*po, -1);
              }
            }
          }
          if (OrderType()==OP_SELL) {
            if (OrderStopLoss()==0 || OrderOpenPrice()-OrderStopLoss()<LevelWLoss*po) {
              pp=MarketInfo(OrderSymbol(), MODE_ASK);
              if (OrderOpenPrice()-pp>LevelProfit*po) {
                ModifyOrder(-1, OrderOpenPrice()-LevelWLoss*po, -1);
              }
            }
          }
        }
      }
    }
  }
}
 

Function isTradeTimeString().

This function returns the flag allowing you to trade by time. Actually, it actually checks if the current time of the trade server is inside a certain time interval. If it is inside, the isTradeTimeString() function returns true, otherwise it returns false. The feature of this function is the possibility to specify the time interval both inside and outside a day. This will be shown in details in the examples of use. The isTradeTimeString() function accepts the following optional parameters:

  • TimeBegin - String in the format "HH:MM", it sets the time of trade start. Default value is "00:00".
  • TimeEnd - String in the format "HH:MM", specifies the trade end time. Default value is "00:00".
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 29.04.2009                                                     |
//|  Описание : Возвращает флаг разрешения торговли по времени.                |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    TimeBegin - время начала торговли         (ЧЧ:ММ)                       |
//|    TimeEnd   - время окончания торговли      (ЧЧ:ММ)                       |
//+----------------------------------------------------------------------------+
bool isTradeTimeString(string TimeBegin="00:00", string TimeEnd="00:00") {
  datetime dtBegin, dtEnd;        // Время начала и окончания работы
  int      hc, he;                // Часы текущего времени и окончания работы

  dtBegin=StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeBegin);
  dtEnd  =StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeEnd);
  hc     =TimeHour(TimeCurrent());
  he     =TimeHour(dtEnd);
  if (dtBegin>=dtEnd) {
    if (hc>=he) dtEnd+=24*60*60; else dtBegin-=24*60*60;
  }

  if (TimeCurrent()>=dtBegin && TimeCurrent()<=dtEnd) return(True);
  else return(False);
}

Function isTradeTimeInt().

This function returns the flag allowing to trade by time. The returned value is true or false. Function isTradeTimeInt() is similar to function isTradeTimeString() by the principle of time interval recognition, i.e. the trade start time can be both larger (time interval within a day) and smaller (time interval in different days). Function isTradeTimeInt() accepts the following optional parameters:

  • hb - Number, specifies the hour of trade start time. The default value is 0.
  • mb - A number, specifies the minutes of trade start time. Default value - 0.
  • he - A number to specify the hours of trade end time. The default value - 0.
  • me - A number to specify the minutes of trade end time. Default value - 0.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 30.04.2009                                                     |
//|  Описание : Возвращает флаг разрешения торговли по времени.                |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    hb - часы времени начала торговли                                       |
//|    mb - минуты времени начала торговли                                     |
//|    he - часы времени окончания торговли                                    |
//|    me - минуты времени окончания торговли                                  |
//+----------------------------------------------------------------------------+
bool isTradeTimeInt(int hb=0, int mb=0, int he=0, int me=0) {
  datetime db, de;           // Время начала и окончания работы
  int      hc;               // Часы текущего времени торгового сервера

  db=StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+hb+":"+mb);
  de=StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+he+":"+me);
  hc=TimeHour(TimeCurrent());
  if (db>=de) {
    if (hc>=he) de+=24*60*60; else db-=24*60*60;
  }

  if (TimeCurrent()>=db && TimeCurrent()<=de) return(True);
  else return(False);
}
 
satop:
The file contains everything in one archive.
Files:
kimiv.zip  187 kb
 
Igor Kim published his functions both here and on his website as "collections of functions", in one file. It was not possible to use these collections as plug-in libraries in this form. However, it is very convenient, especially when developing EAs, to use the libraries to simplify and reduce the code of an EA. In addition, this removes all questions about the correct usage of trading operations, and allows you to focus on the strategy, which is especially valuable for traders with beginner programming skills.
The attached files contain the same collections of functions, designed in the form of libraries. The libraries are simply placed in the .../experts/include directory, they do not need to be compiled, an example of their connection is given below.
After their connection, it is enough to call the required function from the EA code.
#include <b-Positions_include.mqh>       // Библиотека функций для работы с позициями 
#include <b-KimIV_include.mqh>           // Библиотека дополнительных функций
#include <b-Orders_include.mqh>          // Библиотека функций для работы с ордерами
 

Dear, where in the line.

if (dg==0) if (StringFind(OrderSymbol(), "JPY")<0) dg=4; else dg=2;
появляется "JPY"??????

satop:

The isCloseLastPosByStop() function.

This function returns a flag to close the last position by stop. Flag is up - True - triggered StopLoss. 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 you set this parameter, 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.

 
I understand the functions were written at a time when there were no 5 digits yet. The JPY served as a kind of comparison example.
 
hoz:
I understand the functions were written at a time when there were no 5 digits yet. The JPY served as a kind of comparison example.

It's not hard to increase by one!
Reason: