Only "Useful features from KimIV". - page 7

 

CorrectTF() function.

I wrote this function after discovering that sometimes I can easily specify an incorrect timeframe, which is equal to a whole number of minutes, in the input parameters of an indicator or an EA. For example, I entered 50 for hourly instead of 60. Well... kind of missed. It turns out that iRSI() function returns zero for an incorrect timeframe. I cannot say anything about other functions, because I did not check them. To avoid misunderstandings resulting from my own inattentive mistakes, I wrote this function as a primitive foolproof one. It adjusts the input parameter to the nearest appropriate timeframe and returns its value.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 02.03.2008                                                     |
//|  Описание : Корректирует таймфрейм под ближайший поддерживаемый МТ4.       |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    TimeFrame - таймфрейм (количество секунд)      (0 - текущий ТФ)         |
//+----------------------------------------------------------------------------+
int CorrectTF(int TimeFrame=0) {
  if (TimeFrame==0) TimeFrame=Period();
  if (TimeFrame< PERIOD_M5                         ) return(PERIOD_M1);
  if (TimeFrame>=PERIOD_M5  && TimeFrame<PERIOD_M15) return(PERIOD_M5);
  if (TimeFrame>=PERIOD_M15 && TimeFrame<PERIOD_M30) return(PERIOD_M15);
  if (TimeFrame>=PERIOD_M30 && TimeFrame<PERIOD_H1 ) return(PERIOD_M30);
  if (TimeFrame>=PERIOD_H1  && TimeFrame<PERIOD_H4 ) return(PERIOD_H1);
  if (TimeFrame>=PERIOD_H4  && TimeFrame<PERIOD_D1 ) return(PERIOD_H4);
  if (TimeFrame>=PERIOD_D1  && TimeFrame<PERIOD_W1 ) return(PERIOD_D1);
  if (TimeFrame>=PERIOD_W1  && TimeFrame<PERIOD_MN1) return(PERIOD_W1);
  if (TimeFrame>=PERIOD_MN1                        ) return(PERIOD_MN1);
}

Function DateBeginQuarter().

This function returns the start date of the quarter by its number. For example, if it is now 27.08.2008, then the date of the beginning of the current quarter will be 01.07.2008. The function takes only one parameter - the quarter number relative to the current quarter. For example, 0 is the current quarter, 1 is the next quarter and -1 is the previous quarter. That is, positive quarter numbers will request dates from the future, while zero and negative will request dates from the past. The value returned is the number of seconds elapsed since 00:00 1 January 1970.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 12.05.2008                                                     |
//|  Описание : Возвращает дату начала квартала                                |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|                                    (-2 - позапрошлый)                      |
//|                                    (-1 - прошлый)                          |
//|    nq - номер квартала             ( 0 - текущий)                          |
//|                                    ( 1 - следующий)                        |
//|                                    ( 2 - последующий)                      |
//+----------------------------------------------------------------------------+
datetime DateBeginQuarter(int nq=0) {
  int ye=Year()-MathFloor(nq/4);
  nq=MathMod(nq, 4);
  int mo=Month()-MathMod(Month()+2, 3)+3*nq;
  if (mo<1) {
    mo+=12;
    ye--;
  }
  if (mo>12) {
    mo-=12;
    ye++;
  }

  return(StrToTime(ye+"."+mo+".01"));
}
 

The DateOfMonday() function.

This function returns the start date of the week (Monday) by its number. For example, if it is now 29.08.2008, the date of the beginning of the current week will be 25.08.2008. The function takes only one parameter - the number of week relative to the current week. For example, 0 is the current week, 1 is the next week and -1 is the previous week. That is, positive week numbers will request dates from the future, while zero and negative numbers will request dates from the past. The return value is the number of seconds elapsed since 00:00 1 January 1970.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 13.05.2008                                                     |
//|  Описание : Возвращает дату понедельника по номеру недели                  |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|                                    (-2 - предпредыдущая неделя)            |
//|                                    (-1 - предыдущая неделя)                |
//|    nn - номер недели               ( 0 - текущая неделя)                   |
//|                                    ( 1 - следующая неделя)                 |
//|                                    ( 2 - последующая неделя)               |
//+----------------------------------------------------------------------------+
datetime DateOfMonday(int nn=0) {
  datetime dt=StrToTime(TimeToStr(TimeCurrent(), TIME_DATE));

  while (TimeDayOfWeek(dt)!=1) dt-=24*60*60;
  dt+=nn*7*24*60*60;

  return (dt);
}

The function Fibonacci().

This function returns an element of the Fibonacci series by its sequence number.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 07.08.2008                                                     |
//|  Описание : Возвращает элемент ряда Фибоначчи по его порядковому номеру.   |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    n - номер элемента ряда                                                 |
//+----------------------------------------------------------------------------+
int Fibonacci(int n) {
  int a=0, b=0, i=1, s=0;

  if (n==1) s=1;
  if (n>1) {
    s=1;
    while (i<n) {
      i++;
      a=b;
      b=s;
      s=a+b;
    }
  }
  return(s);
}
 

GetNameMA() function.

This function returns the MA method name(Moving Averages) by its identifier. This function is convenient to use in comments, indicators and Expert Advisors messages.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Возвращает наименование метода МА.                             |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    mm - идентификатор метода МА                                            |
//+----------------------------------------------------------------------------+
string GetNameMA(int mm) {
  switch (mm) {
    case MODE_SMA : return("SMA");
    case MODE_EMA : return("EMA");
    case MODE_SMMA: return("SMMA");
    case MODE_LWMA: return("LWMA");
    default       : return("Unknown Method");
  }
}
 

GetPriceDiffInPoint() function.

This function returns the price difference between two bars, which are specified by their numbers. The purpose of developing this function was to determine the value and direction of the price movement. The GetPriceDiffInPoint() function determines the reference points (Open or High or Low or Close) of the bars to take into account. The function accepts the following optional parameters:

  • sy - Instrument name. "" or NULL - current symbol. Default value is NULL.
  • tf - Timeframe. Default value 0 - current symbol.
  • n2 - Left bar number. Default value - 2.
  • n1 - Right bar number. Default value - 1.

Returned value:

  • positive - there was a rate rise between bars N2 and N1.
  • negative - there was a depreciation between bars N2 and N1.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Возвращает ценовую разницу в пунктах между двумя барами.       |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента        ("" или NULL - текущий символ)     |
//|    tf - таймфрейм                       (    0       - текущий таймфрейм)  |
//|    n2 - номер левого бара               (    2       - второй бар)         |
//|    n1 - номер правого бара              (    1       - первый бар)         |
//|  Возвращаемое значение:                                                    |
//|    положительное - между барами N2 и N1 был рост курса                     |
//|    отрицательное - между барами N2 и N1 было снижение курса                |
//+----------------------------------------------------------------------------+
int GetPriceDiffInPoint(string sy="0", int tf=0, int n2=2, int n1=1) {
  if (sy=="" || sy=="0") sy=Symbol();
  double p=MarketInfo(sy, MODE_POINT);
  int    d=MarketInfo(sy, MODE_DIGITS);
  int    dd=0, k=iBars(sy, tf);

  if (n1>k || n2>k)
    Print("GetPriceDiffInPoint(): Недостаточно баров для ",sy," ",GetNameTF(tf));
  else {
    if (n1>0 && n2>0) {
      int d1=NormalizeDouble((iHigh(sy, tf, n1)-iLow(sy, tf, n2))/p, d);
      int d2=NormalizeDouble((iLow(sy, tf, n1)-iHigh(sy, tf, n2))/p, d);

      if (MathAbs(d1)>MathAbs(d2)) dd=d1;
      if (MathAbs(d1)<MathAbs(d2)) dd=d2;
      if (MathAbs(d1)==MathAbs(d2)) {
        if (iOpen(sy, tf, n2)>iClose(sy, tf, n1)) dd=d2; else dd=d1;
      }
    }
  }

  return(dd);
}

The GetTypePrice() function

Returns the name of the price type. The function takes only one optional parameter. Valid values: PRICE_CLOSE, PRICE_OPEN, PRICE_HIGH, PRICE_LOW, PRICE_MEDIAN, PRICE_TYPICAL, PRICE_WEIGHTED. The default value is 0 - PRICE_CLOSE.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Возвращает наименование типа цены.                             |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    Applied_Price - тип цены                                                |
//+----------------------------------------------------------------------------+
string GetTypePrice(int Applied_Price=0) {
  switch (Applied_Price) {
    case PRICE_CLOSE   : return("Close");
    case PRICE_OPEN    : return("Open");
    case PRICE_HIGH    : return("High");
    case PRICE_LOW     : return("Low");
    case PRICE_MEDIAN  : return("Median");
    case PRICE_TYPICAL : return("Typical");
    case PRICE_WEIGHTED: return("Weighted");
    default            : return("Unknown Type Price");
  }
}
 

The ArrayLR() function.

This function generates an array of linear regression values. The function accepts the following mandatory parameters:

  • x is an array of numeric series values. This is the input parameter. This array must contain the values before the function is called.
  • y is an array of linear regression values. This is the output parameter, i.e. the array will be filled after the function is called.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 20.05.2008                                                     |
//|  Описание : Формирует массив значений линейной регрессии.                  |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    x - массив значений числового ряда                                      |
//|    y - массив значений линейной регрессии                                  |
//+----------------------------------------------------------------------------+
void ArrayLR(double& x[], double& y[]) {
  double a, b, c, sx=0, sx2=0, sxy=0, sy=0;
  int    i, n=ArraySize(x);

  if (n>1) {
    for (i=0; i<n; i++) {
      sx+=i+1;
      sy+=x[i];
      sxy+=(i+1)*x[i];
      sx2+=(i+1)*(i+1);
    }
    a=sx*sy-n*sxy;
    c=sx*sx-n*sx2;
    if (c!=0) a=a/c; else a=0;
    b=(sy-a*sx)/n;
    ArrayResize(y, n);
    for (i=0; i<n; i++) y[i]=a*(i+1)+b;
  } else Print("ArrayLR(): Недостаточное количество элементов ряда! n=", n);
}

ArrayMo() function.

Returns Modu - the maximum of the distribution density curve. The function accepts the following optional parameters:

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 21.06.2008                                                     |
//|  Описание : Возвращает Моду - максимум кривой плотности распределения.     |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    x - массив значений числового ряда                                      |
//|    d - точность значений числового ряда, количество знаков после запятой   |
//+----------------------------------------------------------------------------+
double ArrayMo(double& x[], int d=4) {
  double e, s=0;
  double m[][2];             // временный массив:
                             //  столбец 1 - количество значений
                             //  столбец 2 - значения
  int    i, k=ArraySize(x);
  int    n;                  // номер строки временного массива m
  int    r;                  // количество строк во временном массиве m

  if (k>0) {
    for (i=0; i<k; i++) {
      e=NormalizeDouble(x[i], d);
      n=ArraySearchDouble(m, e);
      if (n<0) {
        r=ArrayRange(m, 0);
        ArrayResize(m, r+1);
        m[r][0]++;
        m[r][1]=e;
      } else m[n][0]++;
    }
    ArraySort(m, WHOLE_ARRAY, 0, MODE_DESCEND);
    s=m[0][1];
  } else Print("ArrayMo(): Массив пуст!");

  return(s);
}
 

Function ExistOrdersByPrice().

Returns a flag for the existence of an order at the given set price. True - order exists (set), False - order does not exist (not set). You can limit the list of orders to be checked using the function parameters:

  • sy - Name of market instrument. If this parameter is given, the function will only check the orders of the specified instrument. NULL means the current instrument, and "" (by default) means any instrument.
  • op - Type of trade, type of pending order. Valid values: OP_BUYLIMIT, OP_BUYSTOP, OP_SELLLIMIT, OP_SELLSTOP or -1. The default value of -1 indicates any order type.
  • mn - Order identifier (MagicNumber). The default value of -1 means any MagicNumber.
  • pp - The price level at which the order is set. The default value is -1 - any price.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 30.07.2008                                                     |
//|  Описание : Возвращает флаг существования ордеров по цене установки        |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//|    pp - цена                       (-1   - любая цена)                     |
//+----------------------------------------------------------------------------+
bool ExistOrdersByPrice(string sy="", int op=-1, int mn=-1, double pp=-1) {
  int d, 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 (OrderType()>1 && OrderType()<6) {
          d=MarketInfo(OrderSymbol(), MODE_DIGITS);
          pp=NormalizeDouble(pp, d);
          if (pp<0 || pp==NormalizeDouble(OrderOpenPrice(), d)) {
            if (mn<0 || OrderMagicNumber()==mn) return(True);
          }
        }
      }
    }
  }
  return(False);
}

The ClosePosBySelect() function for the tester.

Executes closing of a single preselected position. This is a simplified version of the function of the same name that was previously described on page 13. Nothing superfluous. No extra features. In my practice, I have never had a position that was not closed in the tester. That is why there are no checks in this function. They are unnecessary in the tester.

//+----------------------------------------------------------------------------+
//|  Автор   : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                    |
//+----------------------------------------------------------------------------+
//|  Версия  : 13.06.2007                                                      |
//|  Описание: Закрытие одной предварительно выбранной позиции                 |
//+----------------------------------------------------------------------------+
void ClosePosBySelect() {
  double pp;

  if (OrderType()==OP_BUY) {
    pp=MarketInfo(OrderSymbol(), MODE_BID);
    OrderClose(OrderTicket(), OrderLots(), pp, Slippage, clCloseBuy);
  }
  if (OrderType()==OP_SELL) {
    pp=MarketInfo(OrderSymbol(), MODE_ASK);
    OrderClose(OrderTicket(), OrderLots(), pp, Slippage, clCloseSell);
  }
}
 

The CountOrders() function for the tester.

In my test versions (intended exclusively for use in the tester of MT4), function CountOrders() replaces the following functions: ExistOrders(), ExistPositions(), NumberOfOrders() and NumberOfPositions(). So, it can give information about the existence of any position or order and the amount of trades of each type. Such an exchange has its own advantages, which is expressed in a one-time reference to the orders base for one tick and obtaining all necessary information at once. And the above mentioned functions, especially when used together, each of them works with one and the same order base independently, so they repeatedly make the same calls. As a result, the CountOrders() function can reduce the time of one pass by several seconds, which allows to save hours of optimization.

Function CountOrders() takes the following parameters:

  • mo - Array of the number of orders by type. After the function has been executed, the array will have 6 (six) elements. Zero element - number of trades of Buy type, first element - number of Sell orders, second element - BuyLimit, third element - SellLimit, fourth element - BuyStop, fifth element - SellStop.
  • mn - Identifier of a position or orders (MagicNumber). The default value is -1 - any MagicNumber.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 03.08.2008                                                     |
//|  Описание : Рассчитывает количество ордеров по типам.                      |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    mo - массив количества ордеров по типам                                 |
//|    mn - MagicNumber                          (-1 - любой магик)            |
//+----------------------------------------------------------------------------+
void CountOrders(int& mo[], int mn=-1) {
  int i, k=OrdersTotal();

  if (ArraySize(mo)!=6) ArrayResize(mo, 6);
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (mn<0 || OrderMagicNumber()==mn) mo[OrderType()]++;
    }
  }
}

The ModifyOrder() function for the tester.

This is a light version of the ModifyOrder() function, published on page 7, and is intended for changing the absolute price levels of one pre-selected order or position.

The ModifyOrder() function accepts the following parameters:

  • pp - Order setting price. If you pass a value less than or equal to zero, the modification of this price level will not be performed. The default value is -1.
  • sl - Stop price level. If you pass a value less than zero, the modification of the price level will not be performed. The default value is 0.
  • tp - Take price level. If you pass a value less than 0, the modification of the price level will not be implemented. The default value is 0.
  • ex - Expiration date of the pending order. The default value is 0.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 28.03.2008                                                     |
//|  Описание : Модификация ордера. Версия функции для тестов на истории.      |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    pp - цена открытия позиции, установки ордера                            |
//|    sl - ценовой уровень стопа                                              |
//|    tp - ценовой уровень тейка                                              |
//|    ex - дата истечения                                                     |
//+----------------------------------------------------------------------------+
void ModifyOrder(double pp=-1, double sl=0, double tp=0, datetime ex=0) {
  int    dg=MarketInfo(OrderSymbol(), MODE_DIGITS), er;
  double op=NormalizeDouble(OrderOpenPrice() , dg);
  double os=NormalizeDouble(OrderStopLoss()  , dg);
  double ot=NormalizeDouble(OrderTakeProfit(), dg);
  color  cl;

  if (pp<=0) pp=OrderOpenPrice();
  if (sl<0 ) sl=OrderStopLoss();
  if (tp<0 ) tp=OrderTakeProfit();
  
  pp=NormalizeDouble(pp, dg);
  sl=NormalizeDouble(sl, dg);
  tp=NormalizeDouble(tp, dg);

  if (pp!=op || sl!=os || tp!=ot) {
    if (MathMod(OrderType(), 2)==0) cl=clModifyBuy; else cl=clModifySell;
    if (!OrderModify(OrderTicket(), pp, sl, tp, ex, cl)) {
      er=GetLastError();
      Print("Error(",er,") modifying order: ",ErrorDescription(er));
      Print("Ask=",Ask," Bid=",Bid," sy=",OrderSymbol(),
            " op="+GetNameOP(OrderType())," pp=",pp," sl=",sl," tp=",tp);
    }
  }
}
 

The IIFc() function.

A very handy function in terms of constructing forks. If so, this colour. And if it is not, then another colour. Function IIFc() takes three mandatory parameters:

  • condition - A logical expression. It can be true or false.
  • ifTrue - The colour that will be returned by IIFc() if the condition expression is true.
  • ifFalse - The colour that will be returned by IIFc() if condition is false.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 18.07.2008                                                     |
//|  Описание : Возвращает одно из двух значений взависимости от условия.      |
//+----------------------------------------------------------------------------+
color IIFc(bool condition, color ifTrue, color ifFalse) {
  if (condition) return(ifTrue); else return(ifFalse);
}

IIFd() function.

Similar convenience for real numbers. If so, it is a real number. If it is not, it is a different number. The IIFd() function takes three mandatory parameters:

  • condition - A logical expression. It can be true or false.
  • ifTrue - A real number that will be returned by IIFd() if the condition expression is true.
  • ifFalse - A real number that will be returned by IIFd() if condition is false.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.02.2008                                                     |
//|  Описание : Возвращает одно из двух значений взависимости от условия.      |
//+----------------------------------------------------------------------------+
double IIFd(bool condition, double ifTrue, double ifFalse) {
  if (condition) return(ifTrue); else return(ifFalse);
}

The IIFi() function.

Similar convenience for integers. If so, it is an integer. And if it is not, then another number. The IIFi() function takes three mandatory parameters:

  • condition - A logical expression. It can be true or false.
  • ifTrue - An integer number that will be returned by IIFi() if the condition expression is true.
  • ifFalse - An integer that will be returned by IIFi() if condition is false.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.02.2008                                                     |
//|  Описание : Возвращает одно из двух значений взависимости от условия.      |
//+----------------------------------------------------------------------------+
int IIFi(bool condition, int ifTrue, int ifFalse) {
  if (condition) return(ifTrue); else return(ifFalse);
}

IIFis() function.

A similar convenience for strings. If so, such a string. And if not, then another string. The IIFs() function takes three mandatory parameters:

  • condition - A logical expression. It can be true or false.
  • ifTrue - The string that will be returned by the IIFs() function, if the condition expression is true.
  • ifFalse - The string that will be returned by IIFs( ), if condition is false.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.02.2008                                                     |
//|  Описание : Возвращает одно из двух значений взависимости от условия.      |
//+----------------------------------------------------------------------------+
string IIFs(bool condition, string ifTrue, string ifFalse) {
  if (condition) return(ifTrue); else return(ifFalse);
}
 

The ExistInHistoryCloseBetween() function.

Returns a flag for the existence in the history of a position or order closed (deleted) between dates. Function ExistInHistoryCloseBetween() accepts the following parameters:

  • sy - Name of market instrument. "" - any symbol, NULL - current symbol. Default value is "".
  • op - Trade operation. Valid values: -1, OP_BUY, OP_SELL, OP_BUYLIMIT, OP_BUYSTOP, OP_SELLLIMIT, OP_SELLSTOP. Default value -1 - any operation.
  • mn - Identifier of trade operations, MagicNumber. Default value -1 - any magic number.
  • d1 - Position closing time (pending order deletion). The default value is 0 - any closing time (delete). Time d1 must be shorter than d2.
  • d2 - Position closing time (pending order delete). Default value - 0 - any close (delete) time. Time d2 must be longer than time d1.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 27.08.2008                                                     |
//|  Описание : Возвращает флаг существования в истории позиции или ордера,    |
//|           : закрытой (удалённого) между датами.                            |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая операция)                 |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//|    d1 - время закрытия             ( 0   - любое время закрытия)           |
//|    d2 - время закрытия             ( 0   - любое время закрытия)           |
//+----------------------------------------------------------------------------+
bool ExistInHistoryCloseBetween(string sy="", int op=-1, int mn=-1,
                                datetime d1=0, datetime d2=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 (mn<0 || OrderMagicNumber()==mn) {
          if (d1<=OrderCloseTime() && (d2==0 || d2>=OrderCloseTime())) return(True);
        }
      }
    }
  }
  return(False);
}

Function ExistInHistoryOpenBetween().

Returns the flag of existence in the history of a position or order opened (set) between dates. Function ExistInHistoryOpenBetween() receives the following parameters:

  • sy - Name of the instrument. "" - any character, NULL - the current symbol. Default value is "".
  • op - Trade operation. Valid values: -1, OP_BUY, OP_SELL, OP_BUYLIMIT, OP_BUYSTOP, OP_SELLLIMIT, OP_SELLSTOP. Default value -1 - any operation.
  • mn - Identifier of trade operations, MagicNumber. Default value -1 - any magic number.
  • d1 - Position opening time(pending order placing). The default value is 0 - any opening (setting) time. The d1 time should be less than the d2 time.
  • d2 - Time of position opening (pending order placing). The default value is 0 - any open (set) time. Time d2 must be longer than time d1.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 27.08.2008                                                     |
//|  Описание : Возвращает флаг существования в истории позиции или ордера,    |
//|           : открытой (установленного) между датами.                        |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//|    d1 - время открытия             ( 0   - любое время открытия)           |
//|    d2 - время открытия             ( 0   - любое время открытия)           |
//+----------------------------------------------------------------------------+
bool ExistInHistoryOpenBetween(string sy="", int op=-1, int mn=-1,
                               datetime d1=0, datetime d2=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 (mn<0 || OrderMagicNumber()==mn) {
          if (d1<=OrderOpenTime() && (d2==0 || d2>=OrderOpenTime())) return(True);
        }
      }
    }
  }
  return(False);
}
 

Function ExistInHistoryToDay().

Returns the flag of existence in the history of a position or order opened (set) today. Function ExistInHistoryToDay() receives the following parameters:

  • sy - Name of the instrument. "" - any symbol, NULL - the current symbol. Default value is "".
  • op - Trade operation. Valid values: -1, OP_BUY, OP_SELL, OP_BUYLIMIT, OP_BUYSTOP, OP_SELLLIMIT, OP_SELLSTOP. Default value -1 - any operation.
  • mn - Identifier of trade operations, MagicNumber. The default value is -1 - any magic number.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 06.08.2008                                                     |
//|  Описание : Возвращает флаг наличия ордера или позиции в истории за сегодня|
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
bool ExistInHistoryToDay(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 (op<0 || OrderType()==op) {
          if (mn<0 || OrderMagicNumber()==mn) {
            if (TimeDay  (OrderOpenTime())==Day()
            &&  TimeMonth(OrderOpenTime())==Month()
            &&  TimeYear (OrderOpenTime())==Year()) return(True);
          }
        }
      }
    }
  }
  return(False);
}

TakeProfitLastPos() function.

This function returns the price level of TakeProfit of the last open position or -1. The TakeProfitLastPos() 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 magik.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 06.08.2008                                                     |
//|  Описание : Возвращает цену TakeProfit последней открытой позиций или -1.  |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
double TakeProfitLastPos(string sy="", int op=-1, int mn=-1) {
  datetime t;
  double   r=-1;
  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=="") {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (op<0 || OrderType()==op) {
            if (mn<0 || OrderMagicNumber()==mn) {
              if (t<OrderOpenTime()) {
                t=OrderOpenTime();
                r=OrderTakeProfit();
              }
            }
          }
        }
      }
    }
  }
  return(r);
}