Useful features from KimIV - page 110

 
Thanks for the clarification, I will now move on)))))
 

Function WritingLineInFile().

I've rewritten this function the other day, added the parameter fs, which is responsible for writing the first line of the file, which is different from other lines, for example, the header of the table. The first line will be written to the file only if two conditions are met simultaneously: the length of the line is greater than zero and the file size is zero. And in order to maintain compatibility with the previous version, the new parameter has been made optional.

Parameters of the WritingLineInFile() function:

  • fn - file name
  • st - the string to be written into the file
  • fs - first line (table header)

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 28.04.2012                                                     |
//+----------------------------------------------------------------------------+
//|  Описание : Запись строки в файл                                           |
//|  Параметры:                                                                |
//|    fn - имя файла                                                          |
//|    st - строка                                                             |
//|    fs - первая строка (шапка таблицы)                                      |
//+----------------------------------------------------------------------------+
void WritingLineInFile(string fn, string st, string fs="") {
  int fh=FileOpen(fn, FILE_READ|FILE_WRITE, " ");

  if (fh>0) {
    if (FileSize(fh)==0 && StringLen(fs)>0) FileWrite(fh, fs);
    FileSeek (fh, 0, SEEK_END);
    FileWrite(fh, st);
    FileClose(fh);
  }
}

ZS. Attached is a script to test function.

 
Good evening, Igor! Stopped at the function
DateBeginQuarter

first of all I'm trying to understand the lines:

int ye=Year()-MathFloor(nq/4);
  nq=MathMod(nq, 4);

By default nq = 0, so it is not clear what we get from MathMod(nq/4) expression, as the result will always be 0. Also the second line is not clear, as 0/4 has no remainder, please clarify.

 

Thank you, Natasha, for your question. Thanks to you, I rechecked the function and found the error. In the line

int ye=Year()-MathFloor(nq/4);

I need to replace the minus sign with a plus sign.

int ye=Year()+MathFloor(nq/4);

And now to the substance of your question. nq is not always equal to zero. There can be any integer values, including negative ones. These lines work when nq is a multiple of 4, i.e. when you need to add or subtract 4 quarters (year).

 
KimIV:

Thank you, Natasha, for your question. Thanks to you, I rechecked the function and found the error. In the line

I need to replace the minus sign with a plus sign.

And now to the substance of your question. nq is not always equal to zero. There can be any integer values, including negative ones. The lines you have specified work in cases where nq is a multiple of 4, i.e. when you need to add or subtract 4 quarters (year).

Thanks for your reply, Igor.... it took me longer than usual to deal with the function, but I still figured it out))))))) in the same function, it seems to me that I don't need to decrease the year in the expression:

 if (mo<1) {
    mo+=12;
    ye--;

then it will be correct.

 
Lisi4ka330:

...in the same function, I don't think you need to reduce the year in the expression...

Justify, Natasha, why not? On the contrary, it seems logical to me to decrease the year after closing the monthly circle in the opposite direction. In your expression, making the year smaller is the same as moving the hour hand back by one hour after the minute hand has been wound back a full circle. Give us your version of the function, and we'll discuss it... Maybe your version will be more successful than mine.
 

GetDrawdownOpenPosInPoint() function

Well, I've finished thorough testing of this function. I've taken into account the spread where necessary, tried to optimize it... The function returns the maximal drawdown of the currently opened positions in pips. Traditionally, you can pass parameters to the function and thus filter out positions you need for analysis:

  • sy - Name of instrument. If this parameter is passed, the function will check positions only of the specified instrument. NULL means the current instrument, and "" (by default) means any instrument.
  • op - Trade operation, position type. Valid values: OP_BUY, OP_SELL or -1. The default value -1 means any position.
  • mn - Position identifier (MagicNumber). The default value of -1 means any MagicNumber.
  • tf - Chart timeframe, on which the values of High and Low bars are to be looked at. The default value is 0 - the current timeframe.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.05.2012                                                     |
//|  Описание : Возвращает максимальную просадку в пунктах текущих открытых    |
//|             позиций.                                                       |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//|    tf - таймфрейм                  ( 0   - текущий таймфрейм)              |
//+----------------------------------------------------------------------------+
int GetDrawdownOpenPosInPoint(string sy="", int op=-1, int mn=-1, int tf=0) {
  if (sy=="0") sy=Symbol();
  if (tf==0) tf=Period();

  datetime to=TimeOpenFirstPos(sy, op, mn); // Время открытия первой позиции
  datetime tb=GetTimeOpenBar(sy, tf, to);
  int      dd, md=0;                        // Просадка
  double   po, sp;                          // Пункт, спрэд
  int      i, k=OrdersTotal();              // Номера позиций
  int      nb;                              // Номер бара

  if (tb>0) {
    while (tb<TimeCurrent()) {
      dd=0;
      for (i=0; i<k; i++) {
        if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
          if ((OrderSymbol()==sy || sy=="") && (mn<0 || OrderMagicNumber()==mn)) {
            if ((op<0 || OrderType()==op) && (OrderType()==OP_BUY || OrderType()==OP_SELL)) {
              if (tb>OrderOpenTime()) {
                nb=iBarShift(OrderSymbol(), tf, tb, True);
                if (nb>=0) {
                  po=MarketInfo(OrderSymbol(), MODE_POINT);
                  if (po==0) Message("В обзоре рынка отсутствует символ "+OrderSymbol()+". Точность расчётов не гарантируется!");
                  else {
                    if (OrderType()==OP_BUY) {
                      dd+=(OrderOpenPrice()-iLow(OrderSymbol(), tf, nb)+po)/po;
                    }
                    if (OrderType()==OP_SELL) {
                      sp=po*MarketInfo(OrderSymbol(), MODE_SPREAD);
                      dd+=(iHigh(OrderSymbol(), tf, nb)-OrderOpenPrice()+sp)/po;
                    }
                  }
                }
              }
            }
          }
        }
      }
      if (md<dd) md=dd;
      tb+=60*tf;
    }
  }
  return(md);
}

SZZ. Attached is a script for testing the function GetDrawdownOpenPosInPoint().

 
KimIV:
Justify, Natasha, why not? On the contrary, it seems logical to me to decrease the year after closing the monthly circle in the opposite direction. Reducing the year in the expression you just mentioned is the same as moving the hour hand back one hour after the minute hand has been wound back a full circle. Give us your version of the function, and we'll discuss it... Maybe your version will be more successful than mine.

I reasoned like this: let's say we need to determine the start of Q7 in past and future, then nq= -7 and nq=7 respectively. Mathfloor will return -2 for the past and +1 for the future (judging from the function description in the documentation), hence for the situation in the past we will subtract one more year than we add in the future..... if we continue further calculations for the past, we will have to reduce the year again and we will end up at 2009.....

Unfortunately due to lack of time (I barely have time to read the site page), I can not provide the code I think is correct, but I think if necessary, it will not be difficult to correct it.

 
Lisi4ka330:

I reasoned like this: let's say we need to determine the start of Q7 in past and future, then nq= -7 and nq=7 respectively. Mathfloor will return -2 for the past and +1 for the future (judging from the description of the function in the documentation), hence for the situation in the past we will subtract one more year than we add in the future..... if we continue further calculations for the past we will have to reduce the year again and we will end up in 2009...

I agree with your reasoning, but you are forgetting about the data types involved in the operations. MathFloor() can be omitted altogether. See the result of the script in the attachment.

Files:
test.mq4  1 kb
 
Good afternoon, Igor)))) To be honest, I didn't quite understand your answer, and even the attached script didn't bring clarity, but rather the opposite... )))) but I think I'll figure it out in time)))) Could you please tell me why there are pluses in the return(StrToTime(ye+"."+mo+".01") line.