Useful features from KimIV - page 57

 

The ArrayInsertDouble() function

Inserts one element of an array with the given index. 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 inserted element of the array.
  • 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);
}

SZY. Please find attached scripts to test ArrayInsertDouble(), ArrayInsertInt(), ArrayInsertString() functions.

ZZZY. I updated the b-Array library on my site.

 

Igor, since we're talking about arrays, can we go back to my old request, about sorting arrays ('Useful functions from KimIV'). What was done earlier is a bit wrong, sorry for the indefinite TOR.

I need to sort a two-dimensional array by a given column (row), analog of the operation in EXCEL. This procedure is needed to use Spearman's statistic 'Spearman's Rank Correlation Coefficient', in some variant analysis of correlation matrices currencies (portfolios).

 

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;
          }
        }
      }
    }
  }
}
Attached is a script to test BubbleSort2() function.
Files:
 

GetTypeLastDeleted() function.

This function returns the type of the last deleted order, or -1. There may be situations where we need to tie the EA operation logic to the type of a 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 MagicNumber.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. 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);
}
 
beginner писал(а) >>

Yes, now this one.

#include "b-KimIV.mqh" // Additional functions library

Hello Oleg!

For error-free compilation of the b-Positions. mqh library, you need the functions that are already in this branch:

  • GetNameOP() - Returns trade operation name.
  • GetNameTF() - Returns the name of timeframe.
  • IIFc() - Returns one of two values depending on the condition.
  • Message() - Message output in comment and in log.

So, you can do the following:

  1. Create an empty file named b-kimiv.mqh in the same folder, where you have b-Positions.mqh
  2. Insert the above functions into it and compile b-Positions.mqh.

Good luck!

 

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);
}
ZS. Attached is a script to test iBarLargest() function.
Files:
 

The iBarOfDayCalc() function.

This function returns the calculated bar number from the beginning of the day. The bars are numbered from one, i.e. the bar with the shortest opening time in a 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. The default value is 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);
}

SZY. I attach a script to test the iBarOfDayCalc() function. The illustration below shows how to use the script.

Files:
 

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

SZY. I attach a script to test the iBarOfDayReal() function. The illustration below shows how to use the script.

Files:
 
KimIV писал(а) >>

The iBarOfDayReal() function.

I haven't found a practical application for this function yet.

yyyy... :)

I'm here as a training tool, decided to write a script which calculates the distance traveled.

If anyone knows there is a program that counts how many kilometres the mouse ran on the monitor.

So here, add up the open-close bars of the current day (week, month or year) or if you imagine

another way, like a thread and needle stitching a fur coat: Open-close-close-close-close-close-close-close-close... in the course of the graph.

Same thing but on the high-low...

*

The hitch started from the very first steps.

How do I filter the bars of the current day from the chart...

I'll try to apply your functions for this dabbling.

 

Igor. Good afternoon.

Maybe you can draw a simple task for you: the task (for me) is the following:

The task is as follows: set at what price value the signal line will cross the MACD, or, in other words, the MACD histogram will become equal to zero.

Solution of this problem is needed, for example, to calculate a stop price or order limit for the next bar in the signals of a trading system which uses this indicator,

which will visually show the price level, at which the MACD histogram will cross the nought line (i.e., the crossing of one line over the price - line on the chart)

This refers to the percentage MACD calculated using the formulaMACD= (FastEMA/SlowEMA - 1). Periods 12, 26, Signal 9.

I have codes for Omega and Metostock. I cannot find anywhere else how to implement it in MT4.

Thank you


Reason: