Useful features from KimIV - page 107

 
143alex:

Don't you have (ready and willing to buy)))) the same but to work with excel?

nope, not available... )))

 

The GetPotentialLossInCurrency() function returns the total potential loss of open positions in the deposit currency. The calculation is performed based on the opening price of the position and StopLoss price level. If StopLoss is not set for any position, this function returns the current equity of the trading account.

GetPotentialLossInCurrency() function accepts the following parameters:

  • sy - Name of instrument. If we set this parameter, the function will only check positions of the specified instrument. NULL means current instrument, while "" (default) means any instrument.
  • op - Trade operation, position type. Valid values: OP_BUY, OP_SELL or -1. Default value -1 - means any position.
  • mn - Position identifier (MagicNumber). Default value -1 means any magik.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 17.02.2012                                                     |
//|  Описание : Возвращает суммарный потенциальный убыток                      |
//|             открытых позиций в валюте депозита.                            |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
double GetPotentialLossInCurrency(string sy="", int op=-1, int mn=-1) {
  double pl=0;
  double po, tv;                   // Пункт, спрэд и стоимость пункта
  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=="") && (mn<0 || OrderMagicNumber()==mn)) {
        if ((OrderType()==OP_BUY || OrderType()==OP_SELL) && (op<0 || OrderType()==op)) {
          if (OrderStopLoss()>0) {
            po=MarketInfo(OrderSymbol(), MODE_POINT);
            if (po==0) Message("В обзоре рынка отсутствует символ "+OrderSymbol()+". Точность расчётов не гарантируется!");
            else {
              tv=MarketInfo(OrderSymbol(), MODE_TICKVALUE);
              if (OrderType()==OP_BUY) {
                pl+=(OrderOpenPrice()-OrderStopLoss())/po*OrderLots()*tv;
              }
              if (OrderType()==OP_SELL) {
                pl+=(OrderStopLoss()-OrderOpenPrice())/po*OrderLots()*tv;
              }
              pl+=OrderCommission()+OrderSwap();
            }
          } else {
            pl=AccountBalance();
            break;
          }
        }
      }
    }
  }
  return(pl);
}

Attached is a script to test the GetPotentialLossInCurrency() function.

 

Hello Igor. Kudos to you for your set of very useful features.

Can I ask you for some help... I want to make some sort of partial locker. But so far I don't know how to arrange it. The idea is like this :

There are 4 - orders let's say -200$ -175$ -150$ and -25$ and there are 5+ orders totaling +400$

If 400 > -200+-175 but less than -200+-175+-150 then close 5 plus and minus orders -200 -175, that is 2 orders with a loss of more to less.

this example is rather crude but I think I have got the idea...

The first problem is that I need something to write them down. (I don't really understand Array) or find some other way.

The 2nd problem follows from the first one. Suppose I got los[x] with lots from 4 different orders... should I load lots ( los[x]) into a module that will search for tiket according to price or do I add 1 (los[price]) and 2 (los2[tiket]) while sorting lots?

Maybe you can point me in a place where you can do this or teach me something I can't =)

 

Probably every trader sooner or later starts to calculate the number of pips remaining before the deposit is lost. The calculation is simple: we take the money, divide it by the number of lots in the market, by the point value and get the answer we are looking for. This is exactly what my new function ReserveDepositInPoint() does, it takes the following parameters:

  • sy - Name of instrument. If you set this parameter, the function will check the positions of only the specified instrument. NULL means the current instrument, while "" (by default) means any instrument.
  • op - Trade operation, position type. Valid values: OP_BUY, OP_SELL or -1. Default value -1 - means any position.
  • mn - Position identifier (MagicNumber). The default value of -1 means any MagicNumber.

The ReserveDepositInPoint() function handles opposing positions correctly, namely, it calculates the difference between Sell and Buy lots and uses exactly this difference in the calculations. The calculations are based on equity, i.e. it is supposed that the stopout is 100%. Swaps, taxes and commissions are not considered.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 29.02.2012                                                     |
//|  Описание : Возвращает запас депозита в пунктах.                           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
int ReserveDepositInPoint(string sy="", int op=-1, int mn=-1) {
  int    i, k=OrdersTotal();      // Номера позиций
  int    n, r;                    // Номер символа в массиве, запас депозита в пунктах
  double ol[], tv;                // Массив лотов, стоимость пункта
  string os[];                    // Массив символов

  if (sy=="0") sy=Symbol();
  ArrayResize(os, 0);
  ArrayResize(ol, 0);

  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if ((OrderSymbol()==sy || sy=="") && (mn<0 || OrderMagicNumber()==mn)) {
        n=ArraySearchString(os, OrderSymbol());
        if (n<0) {
          n=ArraySize(os);
          ArrayResize(os, n+1);
          ArrayResize(ol, n+1);
        }
        os[n]=OrderSymbol();
        if ((op<0 || OrderType()==op) && (OrderType()==OP_BUY || OrderType()==OP_SELL)) {
          if (OrderType()==OP_BUY ) ol[n]+=OrderLots();
          if (OrderType()==OP_SELL) ol[n]-=OrderLots();
        }
      }
    }
  }

  n=ArraySize(os);
  for (i=0; i<n; i++) {
    tv=MarketInfo(os[i], MODE_TICKVALUE);
    if (tv==0) Message("В обзоре рынка отсутствует символ "+os[i]+". Точность расчётов не гарантируется!");
    else {
      if (ol[i]!=0) {
        ol[i]=MathAbs(ol[i]);
        r+=AccountEquity()/tv/ol[i];
      }
    }
  }
  if (n>1) r/=n*n;

  return(r);
}

Attached is an Expert Advisor to check ReserveDepositInPoint()function .

 

Function SetFibo().

This function sets the OBJ_FIBO object Fibonacci levels on the current chart.

  • cl - Array of colours of the Fibonacci Levels object. Obligatory parameter. Two elements. The first one sets the object colour, the second - the colour of lines of the levels.
  • st - Array of object styles Fibonacci levels. Required parameter. Two elements. The first sets the object style, the second - the style of the lines of the levels.
  • wd - Array ofobject widths Fibonacci levels. Required parameter. Two elements. The first sets the width of the object, the second - the widths of the lines of the levels.
  • fl - Array of Fibonacci levels. Required parameter.
  • nm - Name of the object. When the default value is passed - "", the opening time of the current bar is used as the name.
  • t1 - First coordinate of object setting time. Default value - 0 - opening time of the tenth bar.
  • p1 - First coordinate of object setting price. Default value - 0 - minimum of the tenth bar.
  • t2 - Second coordinate of object setting time. Default value - 0 - open time of the current bar.
  • p2 - Second coordinate of object setting price. Default value - 0 - current bar low.
  • ry - Flag of the BLUE property. The default value is False.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 12.03.2012                                                     |
//|  Описание : Установка объекта OBJ_FIBO Уровни Фибоначчи.                   |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    cl - массив цветов линий                                                |
//|    st - массив стилей линий                                                |
//|    wd - массив ширин линий                                                 |
//|    fl - массив уровней Фибоначчи                                           |
//|    nm - наименование               (  ""  - время открытия текущего бара)  |
//|    t1 - время открытия бара        (  0   - Time[10]                       |
//|    p1 - ценовой уровень            (  0   - Low[10])                       |
//|    t2 - время открытия бара        (  0   - текущий бар)                   |
//|    p2 - ценовой уровень            (  0   - Bid)                           |
//|    ry - луч                        (False - не луч)                        |
//+----------------------------------------------------------------------------+
void SetFibo(color& cl[], int& st[], int& wd[], double& fl[], string nm="",
             datetime t1=0, double p1=0, datetime t2=0, double p2=0,
             bool ry=False) {
  if (nm=="") nm=DoubleToStr(Time[0], 0);
  if (t1<=0) t1=Time[10];
  if (p1<=0) p1=Low[10];
  if (t2<=0) t2=Time[0];
  if (p2<=0) p2=Bid;

  int i, k=ArraySize(fl);

  if (ObjectFind(nm)<0) ObjectCreate(nm, OBJ_FIBO, 0, 0,0, 0,0);
  ObjectSet(nm, OBJPROP_TIME1     , t1);
  ObjectSet(nm, OBJPROP_PRICE1    , p1);
  ObjectSet(nm, OBJPROP_TIME2     , t2);
  ObjectSet(nm, OBJPROP_PRICE2    , p2);
  ObjectSet(nm, OBJPROP_COLOR     , cl[0]);
  ObjectSet(nm, OBJPROP_RAY       , ry);
  ObjectSet(nm, OBJPROP_STYLE     , st[0]);
  ObjectSet(nm, OBJPROP_WIDTH     , wd[0]);
  ObjectSet(nm, OBJPROP_LEVELCOLOR, cl[1]);
  ObjectSet(nm, OBJPROP_LEVELSTYLE, st[1]);
  ObjectSet(nm, OBJPROP_LEVELWIDTH, wd[1]);
  if (k>0) {
    ObjectSet(nm, OBJPROP_FIBOLEVELS, k);
    for (i=0; i<k; i++) {
      ObjectSet(nm, OBJPROP_FIRSTLEVEL+i, fl[i]);
      ObjectSetFiboDescription(nm, i, DoubleToStr(100*fl[i], 1));
    }
  }
}
Attached is a script to test SetFibo() function.
Files:
 

GetLastThreeExtremumZZ() function.

Performs search for the last three extrema of the ZigZag and returns their values: bar number and price level for each extremum. All this data is contained in a two-dimensional array which is passed as a parameter to the function. Here is the entire list of the function parameters:

  • zz - two-dimensional array of ZigZag values. Bar numbers are added to the first column, and price values are added to the second column. The array dimension should be zz[3,2].
  • sy - Instrument name. "" or NULL - current symbol. Default value is NULL.
  • tf - Timeframe. Default value 0 - current symbol.
  • dp, dv, bs - ZigZaga parameters: ExtDepth, ExtDeviation, ExtBackstep.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 12.03.2012                                                     |
//|  Описание : Возвращает последние три экстремума ЗигЗага.                   |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    zz - двумерный массив значений ЗигЗага                                  |
//|    sy - наименование инструмента   (NULL или "" - текущий символ)          |
//|    tf - таймфрейм                  (      0     - текущий ТФ)              |
//|    dp - ExtDepth                                                           |
//|    dv - ExtDeviation                                                       |
//|    bs - ExtBackstep                                                        |
//+----------------------------------------------------------------------------+
bool GetLastThreeExtremumZZ(double& zz[][], string sy="", int tf=0, int dp=12, int dv=5, int bs=3) {
  if (sy=="" || sy=="0") sy=Symbol();
  double z;
  int i, k=iBars(sy, tf), ke=0;
  ArrayInitialize(zz, 0);

  for (i=0; i<k; i++) {
    z=iCustom(sy, tf, "ZigZag", dp, dv, bs, 0, i);
    if (z!=0) {
      zz[ke][0]=i;
      zz[ke][1]=NormalizePrice(z, sy);
      ke++;
      if (ke>3) return(True);
    }
  }
  Print("GetLastThreeExtremumZZ(): Недостаточно баров!");
  return(False);
}

Attached is a script to test GetLastThreeExtremumZZ() function.

 

The NumberOfOrdersByPrice() function.

Returns the number of orders set at a given price level. You can limit the list of orders to be checked with 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 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 of -1 is any price.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 13.03.2012                                                     |
//|  Описание : Возвращает количество ордеров, установленных по заданной цене. |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//|    pp - цена                       (-1   - любая цена)                     |
//+----------------------------------------------------------------------------+
int NumberOfOrdersByPrice(string sy="", int op=-1, int mn=-1, double pp=-1) {
  int d, i, k=OrdersTotal(), ko=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()>1 && OrderType()<6) {
          d=MarketInfo(OrderSymbol(), MODE_DIGITS);
          pp=NormalizeDouble(pp, d);
          if (pp<0 || pp==NormalizeDouble(OrderOpenPrice(), d)) {
            if (mn<0 || OrderMagicNumber()==mn) ko++;
          }
        }
      }
    }
  }
  return(ko);
}

 

The NumberOfLastLossPosFromDate() function.

This function returns the last series of losing positions (number in a row) closed since a certain date. A more accurate selection of positions to be taken into account is specified using external parameters:

  • sy - Name of market instrument. If this parameter is set, the function will only consider positions of this instrument. The default value -" means any market instrument. NULL means the current 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. Default value -1 means any identifier.
  • dt - Date and time in seconds since 1970. Default value - 0 means all positions available in history are taken into account.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 14.03.2012                                                     |
//|  Описание : Возвращает последнюю серию убыточных позиций                   |
//|             (количество подряд), закрытых с определённой даты.             |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента             (""   - любой символ,         |
//|                                               NULL - текущий символ)       |
//|    op - операция                             (-1   - любая позиция)        |
//|    mn - MagicNumber                          (-1   - любой магик)          |
//|    dt - Дата и время в секундах с 1970 года  ( 0   - с начала истории)     |
//+----------------------------------------------------------------------------+
int NumberOfLastLossPosFromDate(string sy="", int op=-1, int mn=-1, datetime dt=0) {
  int i, k=OrdersHistoryTotal(), kp=0;

  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 (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (mn<0 || OrderMagicNumber()==mn) {
            if (dt<OrderCloseTime()) {
              if (OrderProfit()<0) kp++; else kp=0;
            }
          }
        }
      }
    }
  }
  return(kp);
}

 

The ClosePosExceptTicket() function.

This function closes all positions at the market price except the one with the passed ticket. A more accurate selection of positions to be closed is specified by external parameters:

  • sy - Name of instrument. If this parameter is set, the function checks positions only for the specified instrument. NULL means the current instrument, while "" (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). Default value -1 - any MagicNumber.
  • ti - Ticket to position. Default value 0 - any ticket.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 20.03.2009                                                     |
//|  Описание : Закрытие позиций по рыночной цене за исключением одной,        |
//|           :  с переданным тикетом.                                         |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//|    ti - тикет позиции              ( 0   - любой тикет)                    |
//+----------------------------------------------------------------------------+
void ClosePosExceptTicket(string sy="", int op=-1, int mn=-1, int ti=0) {
  int i, k=OrdersTotal();

  if (sy=="0") sy=Symbol();
  for (i=k-1; i>=0; 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) {
            if (ti==0 || ti!=OrderTicket()) ClosePosBySelect();
          }
        }
      }
    }
  }
}

 

GetChangeBalance() function.

Returns non-trading (deposits, withdrawals, internal transfers, interest accruals, bonuses) balance changes from a certain date passed as a parameter.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 30.04.2010                                                     |
//|  Описание : Возвращает неторговое изменение баланса с определённой даты    |
//|             (пополнения, снятия, внутренние переводы).                     |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    dt - Дата и время в секундах с 1970 года  (0 - с начала истории)        |
//+----------------------------------------------------------------------------+
double GetChangeBalance(datetime dt=0)
{
  double p=0;
  int    i, k=OrdersHistoryTotal();

  for (i=0; i<k; i++) {
    if (OrderType()==6) {
      if (dt<OrderCloseTime()) p+=OrderProfit();
    }
  }
  return(p);
}