Only "Useful features from KimIV". - page 2

 

The NumberOfOrders() function.

This function returns the number of orders and functionally completely overrides ExistOrders(). To replace the ExistOrders() function with the NumberOfOrders() function, it is necessary and sufficient to check the return value so that it is greater than zero. You can limit the list of orders to be checked using the function parameters:

  • sy - Name of 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 pending order. Valid values: OP_BUYLIMIT, OP_BUYSTOP, OP_SELLLIMIT, OP_SELLSTOP or -1. The default value of -1 means any order.
  • mn - Order identifier (MagicNumber). Default value -1 means any MagicNumber.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 28.11.2006                                                     |
//|  Описание : Возвращает количество ордеров.                                 |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любой ордер)                    |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
int NumberOfOrders(string sy="", int op=-1, int mn=-1) {
  int i, k=OrdersTotal(), ko=0, ot;

  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      ot=OrderType();
      if (ot>1 && ot<6) {
        if ((OrderSymbol()==sy || sy=="") && (op<0 || ot==op)) {
          if (mn<0 || OrderMagicNumber()==mn) ko++;
        }
      }
    }
  }
  return(ko);
}
 

The ClosePosBySelect() function.

Closes one pre-selected position. This function is rather auxiliary, because it is called from several other functions, which help to select positions to close by some conditions.

void ClosePosBySelect() {
  bool   fc;
  color  clClose;
  double ll, pa, pb, pp;
  int    err, it;

  if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
    for (it=1; it<=NumberOfTry; it++) {
      if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) break;
      while (!IsTradeAllowed()) Sleep(5000);
      RefreshRates();
      pa=MarketInfo(OrderSymbol(), MODE_ASK);
      pb=MarketInfo(OrderSymbol(), MODE_BID);
      if (OrderType()==OP_BUY) {
        pp=pb; clClose=clCloseBuy;
      } else {
        pp=pa; clClose=clCloseSell;
      }
      ll=OrderLots();
      fc=OrderClose(OrderTicket(), ll, pp, Slippage, clClose);
      if (fc) {
        if (UseSound) PlaySound(NameFileSound); break;
      } else {
        err=GetLastError();
        if (err==146) while (IsTradeContextBusy()) Sleep(1000*11);
        Print("Error(",err,") Close ",GetNameOP(OrderType())," ",
              ErrorDescription(err),", try ",it);
        Print(OrderTicket(),"  Ask=",pa,"  Bid=",pb,"  pp=",pp);
        Print("sy=",OrderSymbol(),"  ll=",ll,"  sl=",OrderStopLoss(),
              "  tp=",OrderTakeProfit(),"  mn=",OrderMagicNumber());
        Sleep(1000*5);
      }
    }
  } else Print("Некорректная торговая операция. Close ",GetNameOP(OrderType()));
}
 

The ClosePosBySizeProfitInCurrency() function.

This function closes only those positions for which the profit in the deposit currency exceeds a certain specified value. You can specify which positions must be closed using the function parameters:

  • sy - Name of instrument. If you set this parameter, the function will only check positions 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). Default value -1 - means any MagicNumber.
  • pr - Profit level in the deposit currency. Default value - 0.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Закрытие тех позиций, у которых профит в валюте депозита       |
//|             превысил некоторое значение                                    |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//|    pr - профит                                                             |
//+----------------------------------------------------------------------------+
void ClosePosBySizeProfitInCurrency(string sy="", int op=-1, int mn=-1, double pr=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 (OrderProfit()+OrderSwap()>pr) ClosePosBySelect();
          }
        }
      }
    }
  }
}
 
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 25.04.2008                                                     |
//|  Описание : Закрытие тех позиций, у которых убыток в валюте депозита       |
//|             превысил некоторое значение                                    |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//|    pr - профит/убыток                                                      |
//+----------------------------------------------------------------------------+
void ClosePosBySizeLossInCurrency(string sy="", int op=-1, int mn=-1, double pr=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 (OrderProfit()+OrderSwap()<-MathAbs(pr)) ClosePosBySelect();
          }
        }
      }
    }
  }
}

The ClosePositions() function.

This function closes positions whose parameters meet the specified values:

  • sy - Name of instrument. If you set this parameter, the function will only check positions 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). Default value -1 - any MagicNumber.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Закрытие позиций по рыночной цене                              |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
void ClosePositions(string sy="", int op=-1, int mn=-1) {
  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) ClosePosBySelect();
        }
      }
    }
  }
}
 

The ClosePosFirstProfit() function.

This function closes positions in a certain order, i.e. profitable positions first, followed by all other positions. A more accurate selection of positions to be closed is defined by external parameters:

  • sy - Name of instrument. If this parameter is set, the function will only check positions of the specified instrument. NULL means the current instrument, while "" (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.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Закрытие позиций по рыночной цене сначала прибыльных           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
void ClosePosFirstProfit(string sy="", int op=-1, int mn=-1) {
  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 (OrderProfit()+OrderSwap()>0) ClosePosBySelect();
          }
        }
      }
    }
  }
  // Потом все остальные
  k=OrdersTotal();
  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) ClosePosBySelect();
        }
      }
    }
  }
}
 

The ClosePosWithMaxProfitInCurrency() function.

This function closes one position with the maximum positive profit in the deposit currency. That is, out of five positions, each of which has a profit of -34, 15, 73, -90, 41, the position with a profit of 73 units in the deposit currency will be closed. A more accurate selection of positions to be closed is specified using external parameters:

  • sy - Instrument name. If we set this parameter, the function will only check positions of the specified instrument. NULL means the current instrument, while "" (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.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Закрытие одной позиции с максимальным положительным профитом   |
//|             в валюте депозита                                              |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
void ClosePosWithMaxProfitInCurrency(string sy="", int op=-1, int mn=-1) {
  double pr=0;
  int    i, k=OrdersTotal(), np=-1;

  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 (mn<0 || OrderMagicNumber()==mn) {
          if (pr<OrderProfit()+OrderSwap()) {
            pr=OrderProfit()+OrderSwap();
            np=i;
          }
        }
      }
    }
  }
  if (np>=0) {
    if (OrderSelect(np, SELECT_BY_POS, MODE_TRADES)) {
      ClosePosBySelect();
    }
  }
}
 

DistMarketAndPos() function.

Here we go! Here come more interesting functions! For example, it returns the distance in pips between the market and the nearest position. The more accurate selection of positions to be checked is set by external parameters:

  • sy - Name of the instrument. If this parameter is set, the function will only check positions of the specified instrument. The "" or NULL means the current symbol.
  • 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.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Возвращает расстояние в пунктах между рынком и ближайшей       |
//|             позицей                                                        |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   ("" или NULL - текущий символ)          |
//|    op - торговая операция          (    -1      - любая позиция)           |
//|    mn - MagicNumber                (    -1      - любой магик)             |
//+----------------------------------------------------------------------------+
int DistMarketAndPos(string sy="", int op=-1, int mn=-1) {
  double d, p;
  int i, k=OrdersTotal(), r=1000000;

  if (sy=="" || sy=="0") sy=Symbol();
  p=MarketInfo(sy, MODE_POINT);
  if (p==0) if (StringFind(sy, "JPY")<0) p=0.0001; else p=0.01;
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if ((OrderSymbol()==sy) && (op<0 || OrderType()==op)) {
        if (mn<0 || OrderMagicNumber()==mn) {
          if (OrderType()==OP_BUY) {
            d=MathAbs(MarketInfo(sy, MODE_ASK)-OrderOpenPrice())/p;
            if (r>d) r=NormalizeDouble(d, 0);
          }
          if (OrderType()==OP_SELL) {
            d=MathAbs(OrderOpenPrice()-MarketInfo(sy, MODE_BID))/p;
            if (r>d) r=NormalizeDouble(d, 0);
          }
        }
      }
    }
  }
  return(r);
}
 

Function ExistOPNearMarket().

This function returns a flag that an order or position exists near the market (at a specified distance in pips from the market). A more accurate selection of orders or positions to be checked is specified by external parameters:

  • sy - Name of instrument. If this parameter is set, the function will only check orders or positions of the specified instrument. The "" or NULL means the current symbol.
  • op - Trade operation, order or position type. Valid values: OP_BUY, OP_SELL, OP_BUYLIMIT, OP_SELLLIMIT, OP_BUYSTOP, OP_SELLSTOP or -1. The default value of -1 means any trade operation.
  • mn - Identifier of the order or position (MagicNumber). The default value of -1 means any identifier.
  • ds - Distance from market in pips. The default value is 1000000.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Возвращает флаг существования позиции или ордера около рынка   |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента        ("" или NULL - текущий символ)     |
//|    op - торговая операция               (    -1      - любая операция)     |
//|    mn - MagicNumber                     (    -1      - любой магик)        |
//|    ds - расстояние в пунктах от рынка   (  1000000   - по умолчанию)       |
//+----------------------------------------------------------------------------+
bool ExistOPNearMarket(string sy="", int op=-1, int mn=-1, int ds=1000000) {
  int i, k=OrdersTotal(), ot;

  if (sy=="" || sy=="0") sy=Symbol();
  double p=MarketInfo(sy, MODE_POINT);
  if (p==0) if (StringFind(sy, "JPY")<0) p=0.0001; else p=0.01;
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      ot=OrderType();
      if ((OrderSymbol()==sy) && (op<0 || ot==op)) {
        if (mn<0 || OrderMagicNumber()==mn) {
          if (ot==OP_BUY || ot==OP_BUYLIMIT || ot==OP_BUYSTOP) {
            if (MathAbs(MarketInfo(sy, MODE_ASK)-OrderOpenPrice())<ds*p) return(True);
          }
          if (ot==OP_SELL || ot==OP_SELLLIMIT || ot==OP_SELLSTOP) {
            if (MathAbs(OrderOpenPrice()-MarketInfo(sy, MODE_BID))<ds*p) return(True);
          }
        }
      }
    }
  }
  return(False);
}
 

Function ExistPosByPrice().

This function returns a flag for the existence of a position at a given open price. A more accurate selection of positions to be checked is defined by external parameters:

  • sy - Name of the market instrument. If you specify this parameter, the function will only check positions of a specified 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.
  • pp - Position open price. Default value 0 means any price.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Возвращает флаг существования позиций по цене открытия         |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - торговая операция          (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//|    pp - цена                       ( 0   - любая цена)                     |
//+----------------------------------------------------------------------------+
bool ExistPosByPrice(string sy="", int op=-1, int mn=-1, double pp=0) {
  double px, py;
  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()==OP_BUY || OrderType()==OP_SELL) {
          if (mn<0 || OrderMagicNumber()==mn) {
            d=MarketInfo(OrderSymbol(), MODE_DIGITS);
            px=NormalizeDouble(pp, d);
            py=NormalizeDouble(OrderOpenPrice(), d);
            if (pp<=0 || px==py) return(True);
          }
        }
      }
    }
  }
  return(False);
}
 

The GetAmountLotFromOpenPos() function.

This function returns the sum of lots of open positions. A more accurate selection of positions to be taken into account is specified by external parameters:

  • sy - Name of market instrument. If this parameter is set, the function will consider only positions of the specified symbol. 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.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Возвращает сумму лотов открытых позиций                        |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   ( ""  - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - торговая операция          ( -1  - любая позиция)                  |
//|    mn - MagicNumber                ( -1  - любой магик)                    |
//+----------------------------------------------------------------------------+
double GetAmountLotFromOpenPos(string sy="", int op=-1, int mn=-1) {
  double l=0;
  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) {
              l+=OrderLots();
            }
          }
        }
      }
    }
  }
  return(l);
}
Reason: