Only "Useful features from KimIV". - page 8

 

TakeProfitLastClosePos() function.

Returns the TakeProfit price level of the last closed position or -1. The TakeProfitLastClosePos() function accepts the following optional parameters:

  • sy - Name of the instrument. "" - any symbol, NULL - current symbol. Default value is "".
  • op - Trade operation. Valid values: -1, OP_BUY, OP_SELL. The default value is -1 - any trade.
  • mn - Trade identifier, MagicNumber. Default value -1 - any Magic.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 20.10.2008                                                     |
//|  Описание : Возвращает цену TakeProfit последней закрытой позиций или -1.  |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
double TakeProfitLastClosePos(string sy="", int op=-1, int mn=-1) {
  datetime t;
  double   r=-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 (t<OrderCloseTime()) {
                t=OrderCloseTime();
                r=OrderTakeProfit();
              }
            }
          }
        }
      }
    }
  }
  return(r);
}

Function MovingInWL().

Moves the StopLoss price level of the open positions to Breakeven. MovingInWL() function takes the following optional parameters:

  • sy - Name of the instrument. "" - any symbol, NULL - current symbol. Default value is "".
  • op - Trade operation. Valid values: -1, OP_BUY, OP_SELL. The default value is -1 - any trade.
  • mn - Trade identifier, MagicNumber. Default value -1 - any magik.

Moreover, MovingInWL() function has global variables (external parameters of script or Expert Advisor):

  • int LevelProfit - Level of profit in points, which a position must reach to have its stop moved to Breakeven level.
  • int LevelWLoss - Breakeven level in points, to which the stop will be transferred after its profit reaches the LevelProfit level in points.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 11.09.2008                                                     |
//|  Описание : Перенос уровня стопа в безубыток                               |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   ( ""  - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   ( -1  - любая позиция)                  |
//|    mn - MagicNumber                ( -1  - любой магик)                    |
//+----------------------------------------------------------------------------+
void MovingInWL(string sy="", int op=-1, int mn=-1) {
  double po, pp;
  int    i, k=OrdersTotal();

  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      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);
          }
        }
      }
    }
  }
}
 

SimpleTrailing() function.

Moves the StopLoss price level of open positions using the TrailingStop algorithm. Function SimpleTrailing() accepts the following optional parameters:

  • sy - Name of the instrument. "" - any symbol, NULL - current symbol. Default value is "".
  • op - Trade operation. Valid values: -1, OP_BUY, OP_SELL. The default value is -1 - any trade.
  • mn - Trade identifier, MagicNumber. Default value -1 - any magik.

In addition, the SimpleTrailing() function implies global variables (external parameters of the script or Expert Advisor):

  • bool TSProfitOnly - Switches the zone in which the trawl starts. If True, the trawl will only start working when the position profit reaches the value of TStop.Buy/Sell+TrailingStep points. If False, the Expert Advisor will simply make sure that the stop position relative to the current price is always no further than TStop.Buy/Sell+TrailingStep pips. In other words, if True, the Expert Advisor works only in the profit zone of the position, while if False it works in the negative zone of the position.
  • int TStop.Buy - Size of the trall in points to buy.
  • intTStop.Sell - Trawl size in points for selling.
  • int TrailingStep - Trailing step in points. It is needed in order not to disturb the dealer with frequent requests.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 11.09.2008                                                     |
//|  Описание : Сопровождение позиций простым тралом                           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   ( ""  - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   ( -1  - любая позиция)                  |
//|    mn - MagicNumber                ( -1  - любой магик)                    |
//+----------------------------------------------------------------------------+
void SimpleTrailing(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)) {
        po=MarketInfo(OrderSymbol(), MODE_POINT);
        if (mn<0 || OrderMagicNumber()==mn) {
          if (OrderType()==OP_BUY) {
            pp=MarketInfo(OrderSymbol(), MODE_BID);
            if (!TSProfitOnly || pp-OrderOpenPrice()>TStop.Buy*po) {
              if (OrderStopLoss()<pp-(TStop.Buy+TrailingStep-1)*po) {
                ModifyOrder(-1, pp-TStop.Buy*po, -1);
              }
            }
          }
          if (OrderType()==OP_SELL) {
            pp=MarketInfo(OrderSymbol(), MODE_ASK);
            if (!TSProfitOnly || OrderOpenPrice()-pp>TStop.Sell*po) {
              if (OrderStopLoss()>pp+(TStop.Sell+TrailingStep-1)*po || OrderStopLoss()==0) {
                ModifyOrder(-1, pp+TStop.Sell*po, -1);
              }
            }
          }
        }
      }
    }
  }
}

ArrayZ() function.

This function calculates and returns the Z-count of a numeric series passed in the array by reference.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 27.10.2008                                                     |
//|  Описание : Возвращает Z-счёт числового ряда.                              |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    arr - массив значений числового ряда                                    |
//+----------------------------------------------------------------------------+
double ArrayZ(double& arr[]) {
  double x, z;
  int    i, l=0, n=ArraySize(arr), r=1, w=0;

  for (i=0; i<n; i++) {
    if (i==0) r=1;
    else {
      if (arr[i-1]*arr[i]<0) r++;
    }
    if (arr[i]>0) w++; else l++;
  }

  if (n>2) {
    if (w>0 && l>0) {
      x=2*w*l;
      if (x!=n) z=(n*(r-0.5)-x)/MathSqrt(x*(x-n)/(n-1));
    } else {
      if (l==0) z=100; else z=-100;
      Print("ArrayZ(): Нет чередования серий!");
    }
    return(z);
  } else {
    Print("ArrayZ(): В массиве недостаточно элементов!");
    return(0);
  }
}
 

The ArrayDeleteInt() function

Executes the deletion of an array element with the given index. Returns the size of the new array or -1 if nothing was removed. The ArrayDeleteInt() function accepts the following mandatory parameters:

  • m - Array of elements.
  • i - Index of the array element.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 31.10.2008                                                     |
//|  Описание : Выполняет удаление элемента массива с заданным индексом.       |
//|             Возвращает размер нового массива или -1,                       |
//|             если не удалось ничего удалить.                                |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    m - массив элементов                                                    |
//|    i - индекс элемента                                                     |
//+----------------------------------------------------------------------------+
int ArrayDeleteInt(int& m[], int i) {
  int j, k=ArraySize(m);

  if (i>=0 && i<k) {
    for (j=i; j<k; j++) m[j]=m[j+1];
    k=ArrayResize(m, k-1);
    return(k);
  } else Print("ArrayDeleteInt(): Неверный индекс элемента массива! i=", i);

  return(-1);
}

The ArrayDeleteDouble() function

Deletes an element of the array with the given index. It returns the size of the new array or -1, if nothing could be deleted. The ArrayDeleteDouble() function accepts the following mandatory parameters:

  • m - Array of elements of type double.
  • i - Index of the array element.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 31.10.2008                                                     |
//|  Описание : Выполняет удаление элемента массива с заданным индексом.       |
//|             Возвращает размер нового массива или -1,                       |
//|             если не удалось ничего удалить.                                |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    m - массив элементов                                                    |
//|    i - индекс элемента                                                     |
//+----------------------------------------------------------------------------+
int ArrayDeleteDouble(double& m[], int i) {
  int j, k=ArraySize(m);

  if (i>=0 && i<k) {
    for (j=i; j<k; j++) m[j]=m[j+1];
    k=ArrayResize(m, k-1);
    return(k);
  } else Print("ArrayDeleteDouble(): Неверный индекс элемента массива! i=", i);

  return(-1);
}
 

The ArrayDeleteString() function

Executes the deletion of an array element with the given index. Returns the size of the new array or -1 if nothing could be removed. The ArrayDeleteString() function accepts the following mandatory parameters:

  • m - Array of elements of type string.
  • i - Index of the array items.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 31.10.2008                                                     |
//|  Описание : Выполняет удаление элемента массива с заданным индексом.       |
//|             Возвращает размер нового массива или -1,                       |
//|             если не удалось ничего удалить.                                |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    m - массив элементов                                                    |
//|    i - индекс элемента                                                     |
//+----------------------------------------------------------------------------+
int ArrayDeleteString(string& m[], int i) {
  int j, k=ArraySize(m);

  if (i>=0 && i<k) {
    for (j=i; j<k; j++) m[j]=m[j+1];
    k=ArrayResize(m, k-1);
    return(k);
  } else Print("ArrayDeleteString(): Неверный индекс элемента массива! i=", i);

  return(-1);
}

The ArrayInsertDouble() function

Inserts an element of the array with the specified index. It returns the number of elements (size) of the new array. The insertion is performed as follows. First, the size of the array is increased by one. Then all elements that have an index greater than or equal to the one to be inserted are shifted to the end of the array one by one, making room for the one to be inserted. Finally, the value is written into the required cell. The ArrayInsertDouble() function takes the following parameters:

  • m - An array of elements of type double.
  • e - Value of the array element to be inserted.
  • i - Index of the array element to be inserted. If the index value is less than zero or greater than or equal to the array size, the element will be added to the end of the array. The default value is -1.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 31.10.2008                                                     |
//|  Описание : Выполняет вставку элемента массива с заданным индексом.        |
//|             Возвращает размер нового массива.                              |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    m - массив элементов типа double                                        |
//|    e - значение элемента                                                   |
//|    i - индекс элемента                  (-1 - добавить в конец массива)    |
//+----------------------------------------------------------------------------+
int ArrayInsertDouble(double& m[], double e, int i=-1) {
  int j, k=ArraySize(m);

  ArrayResize(m, k+1);
  if (i>=0 && i<k) {
    for (j=k; j>i; j--) m[j]=m[j-1];
    m[i]=e;
  } else m[k]=e;

  return(k+1);
}
 

The BubbleSort2() function.

This function bubbles the elements of a two-dimensional array into an arbitrary column. You can also specify the sort direction. The BubbleSort2() function takes the following parameters:

  • a - Two-dimensional array of elements. Obligatory parameter.
  • r - Number (index) of the sorting column (column). The default value is 0 - the first column (column with a zero index).
  • m - Sorting direction. Valid values: MODE_ASCEND - ascending order, MODE_DESCEND - descending order. Default value is MODE_ASCEND.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 04.11.2008                                                     |
//|  Описание : Выполняет пузырьковую сортировку элементов двумерного массива. |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    a - массив элементов                                                    |
//|    r - колонка сортировки          (     0       - первая (с индексом 0))  |
//|    m - направление сортировки      (MODE_ASCEND  - по возрастанию,         |
//|                                     MODE_DESCEND - по убыванию)            |
//+----------------------------------------------------------------------------+
void BubbleSort2(double& a[][], int r=0, int m=MODE_ASCEND) {
  double t;
  int    e, i, j;
  int    k=ArrayRange(a, 1);      // Количество колонок
  int    n=ArrayRange(a, 0);      // Количество строк

  if (r<0) r=0;
  if (r>k) r=k;

  for (i=n-1; i>0; i--) {
    for (j=0; j<i; j++) {
      if (m==MODE_ASCEND) {
        // по возрастанию
        if (a[j][r]>a[j+1][r]) {
          for (e=0; e<k; e++) {
            t=a[j][e];
            a[j][e]=a[j+1][e];
            a[j+1][e]=t;
          }
        }
      } else {
        // по убыванию
        if (a[j][r]<a[j+1][r]) {
          for (e=0; e<k; e++) {
            t=a[j][e];
            a[j][e]=a[j+1][e];
            a[j+1][e]=t;
          }
        }
      }
    }
  }
}

The GetTypeLastDeleted() function.

This function returns the type of the last deleted order, or -1. There are situations where we need to tie the EA operation logic to the type of the just deleted order. For example, if you have just deleted BuyStop, you should do that, but if BuyLimit, you should do something else, etc. The GetTypeLastDeleted() function accepts the following optional parameters:

  • sy - Name of instrument. "" - any character, NULL - current character. The default value is "".
  • mn - user order identifier (MagicNumber). Default value -1 - any Magic.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 13.10.2008                                                     |
//|  Описание : Возвращает тип последнего удалённого ордера или -1             |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
int GetTypeLastDeleted(string sy="", int mn=-1) {
  datetime t;
  int      i, k=OrdersHistoryTotal(), r=-1;

  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
      if ((OrderSymbol()==sy || sy=="") && (mn<0 || OrderMagicNumber()==mn)) {
        if (OrderType()>1 && OrderType()<6 && t<OrderCloseTime()) {
          t=OrderCloseTime();
          r=OrderType();
        }
      }
    }
  }
  return(r);
}
 

The iBarLargest() function.

This function returns the index of the largest bar or -1. The size of the bar is measured by the function in one of two ways, determined by the input parameter ty - type of search items. Either just the body size or together with the shadows. The iBarLargest() function accepts the following optional parameters:

  • sy - Name of the tool. "" or NULL - the current symbol. Default value is "".
  • tf - Timeframe. The default value is 0 - the current timeframe.
  • ty - Type of search items. Valid values - 0 - High-Low, 1 - abs(Open-Close).
  • co - Number of time series items. Default value - 0 - all elements.
  • in - Index of the initial bar. Default value - 0 - current bar.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 28.03.2008                                                     |
//|  Описание : Возвращает индекс наибольшего бара или -1.                     |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (NULL или "" - текущий символ)          |
//|    tf - таймфрейм                  (          0 - текущий таймфрейм)       |
//|    ty - тип элементов поиска       (          0 - H-L, 1 - O-C)            |
//|    co - число элементов таймсерии  (          0 - все элементы)            |
//|    in - индекс начального бара     (          0 - текущий бар)             |
//+----------------------------------------------------------------------------+
int iBarLargest(string sy="", int tf=0, int ty=0, int co=0, int in=0) {
  if (sy=="" || sy=="0") sy=Symbol();
  if (tf<=0) tf=Period();
  if (in< 0) in=0;
  if (co<=0) co=iBars(sy, tf)-in;

  double r, rb=0;       // размер бара
  int    i, nb=-1;      // счётчик и номер бара

  for (i=co+in; i>=in; i--) {
    if (ty>0) r=MathAbs(iOpen(sy, tf, i)-iClose(sy, tf, i));
    else r=iHigh(sy, tf, i)-iLow(sy, tf, i);
    if (rb<r) {
      rb=r;
      nb=i;
    }
  }

  return(nb);
}

The iBarOfDayCalc() function.

This function returns the calculated number of the bar from the beginning of the day. The bars are numbered starting from one, i.e. the bar with the shortest opening time in the given day will be number one, the next bar will be number two, etc. This function is useful for optimizing entry/exit times. If anyone is interested in details, ask questions. I will do my best to answer them. The iBarOfDayCalc() function takes the following optional parameters:

  • tf - Timeframe. The default value is 0 - the current timeframe.
  • dt - Bar open date and time. Default value - 0 - current time.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 26.02.2008                                                     |
//|  Описание : Возвращает расчётный номер бара от начала суток.               |
//|           : Нумерация баров начинается с 1 (единица).                      |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    tf - таймфрейм                       (0 - текущий таймфрейм)            |
//|    dt - дата и время открытия бара      (0 - текущее время)                |
//+----------------------------------------------------------------------------+
int iBarOfDayCalc(int tf=0, datetime dt=0) {
  if (tf<=0) tf=Period();
  if (dt<=0) dt=TimeCurrent();
  if (tf>PERIOD_D1) {
    Print("iBarOfDayCalc(): Таймфрейм должен быть меньше или равен D1");
    return(0);
  }
  double ms=MathMod(dt/60, 1440);      // количество минут от начала суток
  int    bd=MathFloor(ms/tf)+1;        // номер бара от начала суток

  return(bd);
}
 

Function iBarOfDayReal().

This function returns the actual bar number from the beginning of the day. The bars are numbered with one, i.e. the bar with the shortest opening time in the given day will have number one, the next bar will have number two, etc. I haven't found any practical use for this function yet. But I have written it to have it :-) together with function iBarOfDayCalc(). The iBarOfDayReal() function accepts the following optional parameters:

  • sy - Name of the trading instrument. NULL or "" - current symbol. Default value is "".
  • tf - Timeframe. Default value - 0 - current timeframe.
  • dt - Date and time of bar opening. Default value - 0 - current time.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 26.02.2008                                                     |
//|  Описание : Возвращает реальный номер бара от начала суток.                |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (NULL или "" - текущий символ)          |
//|    tf - таймфрейм                  (          0 - текущий таймфрейм)       |
//|    dt - дата и время открытия бара (          0 - текущее время)           |
//+----------------------------------------------------------------------------+
int iBarOfDayReal(string sy="", int tf=0, datetime dt=0) {
  if (sy=="" || sy=="0") sy=Symbol();
  if (tf<=0) tf=Period();
  if (dt<=0) dt=TimeCurrent();
  if (tf>PERIOD_D1) {
    Print("iBarOfDayReal(): Таймфрейм должен быть меньше или равен D1");
    return(0);
  }

  int cd=TimeDay(dt);                       // текущий день месяца
  int nb=iBarShift(sy, tf, dt, False);      // номер текущего бара
  int bd=0;                                 // номер бара от начала суток

  while(TimeDay(iTime(sy, tf, nb))==cd) {
    nb++;
    bd++;
  }

  return(bd);
}

NameDayOfWeek() function

Returns the name of the day of the week by the number passed as a parameter:

  • ndw - Day of week number. Required parameter.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Возвращает наименование дня недели                             |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    ndw - номер дня недели                                                  |
//+----------------------------------------------------------------------------+
string NameDayOfWeek(int ndw) {
  if (ndw==0) return("Воскресенье");
  if (ndw==1) return("Понедельник");
  if (ndw==2) return("Вторник");
  if (ndw==3) return("Среда");
  if (ndw==4) return("Четверг");
  if (ndw==5) return("Пятница");
  if (ndw==6) return("Суббота");
}
 

Function NormalizeLot().

This function returns the normalized value of the lot being traded. Besides normalization, it also fits the lot size into the limits set by the dealing centre (minimum and maximum lot values and lot change step are checked). Function NormalizeLot() accepts the following parameters:

  • lo - NormalizeLot value. Required parameter.
  • ro - Rounding method. False - to the lesser side, True - to the greater side. Default value - False - to the lower side.
  • sy - Name of trade instrument. NULL or "" - current symbol. Default value - "".
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 16.05.2008                                                     |
//|  Описание : Возвращает нормализованное значение торгуемого лота.           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    lo - нормализуемое значение лота.                                       |
//|    ro - способ округления          (   False    - в меньшую,               |
//|                                        True     - в большую сторону)       |
//|    sy - наименование инструмента   ("" или NULL - текущий символ)          |
//+----------------------------------------------------------------------------+
double NormalizeLot(double lo, bool ro=False, string sy="") {
  double l, k;
  if (sy=="" || sy=="0") sy=Symbol();
  double ls=MarketInfo(sy, MODE_LOTSTEP);
  double ml=MarketInfo(sy, MODE_MINLOT);
  double mx=MarketInfo(sy, MODE_MAXLOT);

  if (ml==0) ml=0.1;
  if (mx==0) mx=100;

  if (ls>0) k=1/ls; else k=1/ml;
  if (ro) l=MathCeil(lo*k)/k; else l=MathFloor(lo*k)/k;

  if (l<ml) l=ml;
  if (l>mx) l=mx;

  return(l);
}

NormalizePrice() function.

This function returns the normalized price value. Normalization is performed using MarketInfo(MODE_TICKSIZE || MODE_DIGITS) function values. The NormalizePrice() function takes the following parameters:

  • np - Normalized lot value. Required parameter.
  • sy - Name of trade instrument. NULL or "" - current symbol. Default value is "".
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 21.08.2008                                                     |
//|  Описание : Возвращает нормализованное под размер тика значение цены.      |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    np - нормализуемое значение цены.                                       |
//|    sy - наименование инструмента        ("" или NULL - текущий символ)     |
//+----------------------------------------------------------------------------+
double NormalizePrice(double np, string sy="") {
  if (sy=="" || sy=="0") sy=Symbol();
  double pp, ts=MarketInfo(Symbol(), MODE_TICKSIZE);
  int    di=MarketInfo(Symbol(), MODE_DIGITS);

  if (ts>0) pp=NormalizeDouble(np/ts, 0)*ts;
  else {
    if (di>0) pp=NormalizeDouble(np*di, 0)/di; else pp=np;
  }
  return(pp);
}
 

The WeekOfMonth() function.

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

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. 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);
}

Function ClosePosBySortLots().

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

  • sy - Name of the trading instrument. "" - any instrument, NULL - current instrument. Default value - "".
  • 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 a trade operation. Default value -1 - any MagicNumber.
  • 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();
      }
    }
  }
}
 

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);
}

Function toTime().

This function converts two/three integers to a string in time format. If you pass two numbers 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);
}
Reason: