Useful features from KimIV - page 44

 

Examples of how to use GetNearestDownFractal().

  • The price level of the nearest upward fractal on the current chart. The fractal formula is 2-2 (standard).
    Message(GetNearestUpFractal());
  • The price level of the nearest upper fractal on USDJPY H1 chart. The formula of the fractal 5-2.
    Message(GetNearestUpFractal("USDJPY", PERIOD_H1, 5));
  • Draw a horizontal line through the price level of the nearest upper fractal 4-3 on the current chart.
    double p=GetNearestUpFractal(NULL, 0, 4, 3);
    SetHLine(Red, "", p);

SZY. Attached is a script to test the GetNearestUpFractal() function.

 

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 and correct 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);
}
SZY. Attached is a script for testing the CorrectTF() function.
Files:
 

The DateBeginQuarter() function.

This function returns the start date of the quarter by its number. For example, if it is now 27.08.2008, the start date 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"));
}

P.S. Attached is a script to test the DateBeginQuarter() function.

 

The DateOfMonday() function.

This function returns the start date of the week (the date of 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 value returned 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);
}

P.S. Attached is a script to test the DateOfMonday() function.

Files:
 

The Fibonacci() function.

This function returns an element of a 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);
}

P.S. Attached is a script to test Fibonacci().

Files:
 

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");
  }
}
 
KimIV писал (а) >>

GetNameMA() function.

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

Don't think of it as a nitpicking ....

default       : return("Unknown Method");

It's just that if you're going to be consistent, you have to go all the way...
 
TheXpert писал (а) >>

Don't think of it as picking on....

by all means... thank you! Corrected!

 
KimIV

Good afternoon !

Help me get the expo across just a little bit.

I can't believe he's opening orders and not closing this stack on condition.

I.e. if a deal is just one, it will get out of the pose and if there are 2 deals, it shuts down.

Files:
panzer.mq4  5 kb
 

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