Only "Useful features from KimIV".

 

All functions are taken from this thread - h ttp://forum.mql4.com/ru/11287 , the thread contains a detailed description of each function and examples of their use

Content

 Page #1 SetOrder - Order setting. Function version for backtests. ExistOrders - Returns the flag for the existence of orders ExistPositions - Returns the flag for the existence of positions OpenPosition - Opening a position. Function version for backtests. OpenPosition - Opens a position and returns its ticket. For online . Message - Displaying a message in comments and in the log GetNameTF - Returns the name of the timeframe GetNameOP - Returns the name of the trading operation ModifyOrder - Modification of one pre-selected order. DeleteOrders - Delete orders. Function version for backtests. DeleteOrders - Delete orders . For online . FindNearFractal - Search for the nearest fractal ExistOrdersByLot - Returns the flag for the existence of an order by lot size. GetLotLastOrder - Returns the lot size of the last placed order, or -1 GetOrderOpenPrice - Returns the price of the last order, or 0. IndexByTicket - Returns the index of the order or position on the ticket
Page #2
NumberOfOrders - Returns the number of orders.

ClosePosBySelect - Closes one pre-selected position.

ClosePosBySizeProfitInCurrency - Close those positions that have a profit in the deposit currency of a certain value

ClosePosBySizeLossInCurrency - Closing those positions whose loss in the deposit currency exceeded a certain value

ClosePositions - Close positions at market price

ClosePosFirstProfit - Closing positions at the market price first profitable

ClosePosWithMaxProfitInCurrency - Close one position with the maximum positive profit in the deposit currency

DistMarketAndPos- Returns the distance in points between the market and the nearest position

ExistOPNearMarket - Returns the flag for the existence of a position or order near the market

ExistPosByPrice - Returns the flag for the existence of positions at the open price

GetAmountLotFromOpenPos - Returns the amount of lots of open positions

Page #3
GetIndexByTicket - Returns the index of the order or position by ticket.

Correlation - Returns the correlation of two series.

GetIndexLastPos - Returns the index of the last open position or -1

GetLotLastPos - Returns the lot size of the last open position or -1

GetMaxLotFromOpenPos - Returns the maximum lot size from open positions

GetMinLotFromOpenPos - Returns the minimum lot size from open positions

NumberOfPositions - Returns the number of positions.

GetProfitFromDateInCurrency - Returns the total profit in the deposit currency of positions closed since a certain date

GetProfitOpenPosInCurrency - Returns the total profit of open positions in the deposit currency

GetProfitOpenPosInPoint - Returns the total profit of open positions in points

GetTicketLastPos - Returns the ticket of the last open position or -1

Page#4
GetTypeLastClosePos - Returns the type of the last closed position or -1

GetTypeLastOpenPos - Returns the type of the last open position or -1

isCloseLastPosByStop - Returns the flag for closing the last position by stop

isCloseLastPosByTake - Returns the flag for closing the last position by take.

isLossLastPos - Returns the loss flag of the last position.

isTradeToDay - Returns the trade flag for today

NumberOfBarCloseLastPos - Returns the number of the closing bar of the last position or -1.

NumberOfBarOpenLastPos - Returns the number of the last position open bar or -1.

NumberOfLossPosToday - Returns the number of losing positions closed today.

PriceCloseLastPos - Returns the closing price of the last closed position.


Page #5
PriceOpenLastPos - Returns the opening price of the last open position.

PriceOpenLastClosePos - Returns the open price of the last closed position.

PriceOpenNearPos - Returns the open price of the nearest position.

TicketNearPos - Returns the ticket of the closest position to the market at the opening price.

TypeNearPos - Returns the type of position closest to the market, or -1.

TimeOpenLastPos - Returns the opening time of the last open position.

BubbleSort - Performs a bubble sort on the elements of an array.

BarsBetweenLastFractals - Returns the number of bars between the last two fractals.

SecondsAfterCloseLastPos - Returns the number of seconds after the last position was closed.

SecondsAfterOpenLastPos - Returns the number of seconds after the last position was opened.

DeleteOppositeOrders - Delete opposite order position

ArraySearchDouble - Searches for an element in an array by value and returns the index of the found element, or -1

ArraySearchInt - Searches for an element in an array by value and returns the index of the found element, or -1.

ArraySearchString - Searches for an array element by value and returns the index of the found element, or -1

GetLotLastClosePos - Returns the lot size of the last closed position or -1

ArrayMax - Returns the value of the maximum element in an array.


Page #6
ArrayMin - Returns the value of the minimum element in an array

GetExtremumZZBar - Returns the ZigZag extremum bar number by its number.

ArrayAvg - Returns the arithmetic mean of the array elements.

ArrayAvGeom - Returns the geometric mean of the array elements.

SetHLine - Set the OBJ_HLINE object to a horizontal line
SetVLine - Set the OBJ_VLINE object to a vertical line
SetTLine - Set the OBJ_TREND object to the trend line

SetTLineByAngle - Set the OBJ_TRENDBYANGLE object of the trend line by angle

SetArrow - Setting the icon on the chart, the OBJ_ARROW object.

SetLabel - Set a text label, an OBJ_LABEL object.

CrossPointOfLines - Calculates the coordinates of the intersection point of two lines. Each line is given by a pair of coordinates of its points.

SetRegression - Sets the OBJ_REGRESSION object to the linear regression channel.

EquationDirect - Equation of a straight line. Calculates the Y value for X at the point of intersection with the line.
GetArrowInterval - Returns the interval for setting signal pointers
GetArrowInterval - Returns the interval for setting signal pointers
FindNearFractal - Finding the nearest fractal. Returns the price level.
GetExtremumZZBar - Returns the ZigZag extremum bar number by its number.
GetExtremumZZPrice - Returns ZigZag extremum by its number.

GetFractalBar - Returns the fractal bar number by its number.

GetNearestDownFractal - Returns the price level of the nearest down fractal

GetNearestUpFractal - Returns the nearest up fractal


Page #7
CorrectTF - Corrects the timeframe to the nearest supported MT4.
DateBeginQuarter - Returns the start date of the quarter
DateOfMonday - Returns the date of Monday by week number

Fibonacci - Returns the element of the Fibonacci series by its ordinal number.
GetNameMA - Returns the name of the MA method.
GetPriceDiffInPoint - Returns the price difference in points between two bars.

GetTypePrice - Returns the price type name.
ArrayLR - Generates an array of linear regression values.
ArrayMo - Returns the Mode - the maximum of the distribution density curve.

ExistOrdersByPrice - Returns the flag for the existence of orders at the set price

ClosePosBySelect - Close one pre-selected position
CountOrders - Calculates the number of orders by type.
ModifyOrder - Order modification. Function version for backtests.

IIFc - Returns one of two values depending on the condition.

IIFd - Returns one of two values depending on the condition.
IIFi - Returns one of two values depending on the condition.
IIFs - Returns one of two values depending on the condition.
ExistInHistoryCloseBetween - Returns the flag of existence in the history of a position or order closed (deleted) between dates.

ExistInHistoryOpenBetween - Returns the flag of existence in the history of a position or order opened (set) between dates.

ExistInHistoryToDay - Returns the flag of the presence of an order or position in the history for today

TakeProfitLastPos - Returns the TakeProfit price of the last open position or -1.

Page #8
TakeProfitLastClosePos - Returns the TakeProfit price of the last closed position or -1.

MovingInWL - Moving the stop level to breakeven

SimpleTrailing - Tracking positions with a simple trawl

ArrayZ - Returns the Z-score of a number series.
ArrayDeleteInt - Deletes the array element at the given index. Returns the size of the new array, or -1 if nothing could be removed.
ArrayDeleteDouble - Deletes the array element at the given index. Returns the size of the new array, or -1
if nothing could be removed.
ArrayDeleteString - Deletes the array element at the given index. Returns the size of the new array, or -1,
if nothing could be removed.
ArrayInsertDouble - Inserts an array element at the given index. Returns the size of the new array.
BubbleSort2 - Performs a bubble sort on the elements of a two-dimensional array.
GetTypeLastDeleted - Returns the type of the last deleted order or -1
iBarLargest - Returns the index of the largest bar, or -1.
iBarOfDayCalc - Returns the calculated bar number from the beginning of the day. Bar numbering starts from 1 (one)
iBarOfDayReal - Returns the real number of the bar from the beginning of the day.
NameDayOfWeek - Returns the name of the day of the week
NormalizeLot - Returns the normalized value of the traded lot.
NormalizePrice - Returns the price value normalized to the tick size.
WeekOfMonth - Returns the week number of the month given the date
ClosePosBySortLots - Close positions in sort order by lot size.
AddLeadingZero - Adds enough leading zeros "0" to string S to make string S equal to length K.

toTime - Converts two/three integers to a string in time format

Page #9
StringLower - Returns a lowercase string

StringUpper - Returns a string in UPPER case

StringToArrayDouble - Transfer real numbers from string to array

StringToArrayInt - Transfer integer values from string to array

StrSplit - Splitting a string into an array of elements

StrTran - Substring Replacement

MovingInWL - Moving the stop level to breakeven

isTradeTimeString - Returns the time trading enable flag.

isTradeTimeInt - Returns the time trading permission flag.


Additionally:
All functions in one archive.
All functions are in the form of linked libraries.


 //+----------------------------------------------------------------------------+ //|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   | //+----------------------------------------------------------------------------+ //|  Версия  : 13.06.2007                                                      | //|  Описание : Установка ордера. Версия функции для тестов на истории.        | //+----------------------------------------------------------------------------+ //|  Параметры:                                                                | //|    sy - наименование инструмента   (NULL или "" - текущий символ)          | //|    op - операция                                                           | //|    ll - лот                                                                | //|    pp - цена                                                               | //|    sl - уровень стоп                                                       | //|    tp - уровень тейк                                                       | //|    mn - Magic Number                                                       | //|    ex - Срок истечения                                                     | //+----------------------------------------------------------------------------+ void SetOrder( string sy, int op, double ll, double pp,                double sl= 0 , double tp= 0 , int mn= 0 , datetime ex= 0 ) {    color clOpen;    int    err, ticket;      if (sy== "" || sy== "0" ) sy= Symbol ();    if (op==OP_BUYLIMIT || op==OP_BUYSTOP) clOpen=clOpenBuy; else clOpen=clOpenSell;   ticket= OrderSend (sy, op, ll, pp, Slippage, sl, tp, "" , mn, ex, clOpen);    if (ticket< 0 ) {     err= GetLastError ();      Print ( "Error(" ,err, ") set " ,GetNameOP(op), ": " ,ErrorDescription(err));      Print ( "Ask=" ,Ask, " Bid=" ,Bid, " sy=" ,sy, " ll=" ,ll,            " pp=" ,pp, " sl=" ,sl, " tp=" ,tp, " mn=" ,mn);   } } //+----------------------------------------------------------------------------+

ExistOrders() function.

Returns the order existence flag. It will answer the question whether the order is set or not. Using this function, you can request any order, as well as a more specific one. The request filter is configured using function parameters:

  • sy - Imposes a restriction on the name of the tool. By default, the parameter is "" - no restrictions, that is, any tool. If you pass NULL, then the selection of orders will be limited to the current instrument.
  • op - Places a limit on the order type. By default, there is no restriction, that is, the presence of an order of any type is checked. Valid parameter values are -1, OP_BUYLIMIT, OP_BUYSTOP, OP_SELLLIMIT, and OP_SELLSTOP.
  • mn - Imposes a limit on the identification ("magic") number of the order. By default, there is no limit, that is, the presence of an order with any magic number is checked.
  • ot - Imposes a limit on the order placement time. Checked. so that the order is placed later than the value of this parameter. By default, there is no limit, that is, the presence of an order with any setting time is checked.
 //+----------------------------------------------------------------------------+ //|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   | //+----------------------------------------------------------------------------+ //|  Версия   : 12.03.2008                                                     | //|  Описание : Возвращает флаг существования ордеров.                         | //+----------------------------------------------------------------------------+ //|  Параметры:                                                                | //|    sy - наименование инструмента   (""   - любой символ,                   | //|                                     NULL - текущий символ)                 | //|    op - операция                   (-1   - любой ордер)                    | //|    mn - MagicNumber                (-1   - любой магик)                    | //|    ot - время открытия             ( 0   - любое время установки)          | //+----------------------------------------------------------------------------+ bool ExistOrders( string sy= "" , int op=- 1 , int mn=- 1 , datetime ot= 0 ) {    int i, k= OrdersTotal (), ty;      if (sy== "0" ) sy= Symbol ();    for (i= 0 ; i<k; i++) {      if ( OrderSelect (i, SELECT_BY_POS, MODE_TRADES)) {       ty=OrderType();        if (ty> 1 && ty< 6 ) {          if ((OrderSymbol()==sy || sy== "" ) && (op< 0 || ty==op)) {            if (mn< 0 || OrderMagicNumber()==mn) {              if (ot<=OrderOpenTime()) return (True);           }         }       }     }   }    return (False); }
Полезные функции от KimIV
Полезные функции от KimIV
  • www.mql5.com
В этой теме я буду выкладывать коды своих функций на языке программирования MQL4, приводить примеры их использования и отвечать на вопросы, связанн...
 

The ExistPositions() function.

Designed to check for open purchases or sales. Similar to the ExistOrders function. By default, it checks all positions: current and other instruments. You can refine the selection with a combination of filters - function parameters:

  • sy - Imposes a restriction on the name of the instrument. The default parameter is "" - no restriction, i.e. any instrument. If you pass NULL, the position selection will be limited to the current instrument.
  • op - places a restriction on position type (Buy/Sell). By default, there is no constraint, that is, any position type is checked. Valid values for this parameter are -1, OP_BUY and OP_SELL.
  • mn - Applies restriction on the identification ("magic") number of the position. By default there is no constraint, i.e. the position with any magic number is checked.
  • ot - Applies restriction on position opening time. It checks if the position will be opened later than the value of this parameter. By default, there is no constraint, i.e., position with any open time is checked.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 06.03.2008                                                     |
//|  Описание : Возвращает флаг существования позиций                          |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//|    ot - время открытия             ( 0   - любое время открытия)           |
//+----------------------------------------------------------------------------+
bool ExistPositions(string sy="", int op=-1, int mn=-1, datetime ot=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) {
              if (ot<=OrderOpenTime()) return(True);
            }
          }
        }
      }
    }
  }
  return(False);
}

OpenPosition() function for the tester.


//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия  : 13.06.2007                                                      |
//|  Описание : Открытие позиции. Версия функции для тестов на истории.        |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   ("" - текущий символ)                   |
//|    op - операция                                                           |
//|    ll - лот                                                                |
//|    sl - уровень стоп                                                       |
//|    tp - уровень тейк                                                       |
//|    mn - MagicNumber                                                        |
//+----------------------------------------------------------------------------+
void OpenPosition(string sy, int op, double ll, double sl=0, double tp=0, int mn=0) {
  color  clOpen;
  double pp;
  int    err, ticket;
 
  if (sy=="") sy=Symbol();
  if (op==OP_BUY) {
    pp=MarketInfo(sy, MODE_ASK); clOpen=clOpenBuy;
  } else {
    pp=MarketInfo(sy, MODE_BID); clOpen=clOpenSell;
  }
  ticket=OrderSend(sy, op, ll, pp, Slippage, sl, tp, "", mn, 0, clOpen);
  if (ticket<0) {
    err=GetLastError();
    Print("Error(",err,") open ",GetNameOP(op),": ",ErrorDescription(err));
    Print("Ask=",Ask," Bid=",Bid," sy=",sy," ll=",ll,
          " pp=",pp," sl=",sl," tp=",tp," mn=",mn);
  }
}
 

OpenPosition() function for online.


//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 21.03.2008                                                     |
//|  Описание : Открывает позицию и возвращает её тикет.                       |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (NULL или "" - текущий символ)          |
//|    op - операция                                                           |
//|    ll - лот                                                                |
//|    sl - уровень стоп                                                       |
//|    tp - уровень тейк                                                       |
//|    mn - MagicNumber                                                        |
//+----------------------------------------------------------------------------+
int OpenPosition(string sy, int op, double ll, double sl=0, double tp=0, int mn=0) {
  color    clOpen;
  datetime ot;
  double   pp, pa, pb;
  int      dg, err, it, ticket=0;
  string   lsComm=WindowExpertName()+" "+GetNameTF(Period());
 
  if (sy=="" || sy=="0") sy=Symbol();
  if (op==OP_BUY) clOpen=clOpenBuy; else clOpen=clOpenSell;
  for (it=1; it<=NumberOfTry; it++) {
    if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) {
      Print("OpenPosition(): Остановка работы функции");
      break;
    }
    while (!IsTradeAllowed()) Sleep(5000);
    RefreshRates();
    dg=MarketInfo(sy, MODE_DIGITS);
    pa=MarketInfo(sy, MODE_ASK);
    pb=MarketInfo(sy, MODE_BID);
    if (op==OP_BUY) pp=pa; else pp=pb;
    pp=NormalizeDouble(pp, dg);
    ot=TimeCurrent();
    ticket=OrderSend(sy, op, ll, pp, Slippage, sl, tp, lsComm, mn, 0, clOpen);
    if (ticket>0) {
      if (UseSound) PlaySound(NameFileSound); break;
    } else {
      err=GetLastError();
      if (pa==0 && pb==0) Message("Проверьте в Обзоре рынка наличие символа "+sy);
      // Вывод сообщения об ошибке
      Print("Error(",err,") opening position: ",ErrorDescription(err),", try ",it);
      Print("Ask=",pa," Bid=",pb," sy=",sy," ll=",ll," op=",GetNameOP(op),
            " pp=",pp," sl=",sl," tp=",tp," mn=",mn);
      // Блокировка работы советника
      if (err==2 || err==64 || err==65 || err==133) {
        gbDisabled=True; break;
      }
      // Длительная пауза
      if (err==4 || err==131 || err==132) {
        Sleep(1000*300); break;
      }
      if (err==128 || err==142 || err==143) {
        Sleep(1000*66.666);
        if (ExistPositions(sy, op, mn, ot)) {
          if (UseSound) PlaySound(NameFileSound); break;
        }
      }
      if (err==140 || err==148 || err==4110 || err==4111) break;
      if (err==141) Sleep(1000*100);
      if (err==145) Sleep(1000*17);
      if (err==146) while (IsTradeContextBusy()) Sleep(1000*11);
      if (err!=135) Sleep(1000*7.7);
    }
  }
  return(ticket);
}
 
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Вывод сообщения в коммент и в журнал                           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    m - текст сообщения                                                     |
//+----------------------------------------------------------------------------+
void Message(string m) {
  Comment(m);
  if (StringLen(m)>0) Print(m);
} 
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Возвращает наименование таймфрейма                             |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    TimeFrame - таймфрейм (количество секунд)      (0 - текущий ТФ)         |
//+----------------------------------------------------------------------------+
string GetNameTF(int TimeFrame=0) {
  if (TimeFrame==0) TimeFrame=Period();
  switch (TimeFrame) {
    case PERIOD_M1:  return("M1");
    case PERIOD_M5:  return("M5");
    case PERIOD_M15: return("M15");
    case PERIOD_M30: return("M30");
    case PERIOD_H1:  return("H1");
    case PERIOD_H4:  return("H4");
    case PERIOD_D1:  return("Daily");
    case PERIOD_W1:  return("Weekly");
    case PERIOD_MN1: return("Monthly");
    default:         return("UnknownPeriod");
  }
}
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Возвращает наименование торговой операции                      |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    op - идентификатор торговой операции                                    |
//+----------------------------------------------------------------------------+
string GetNameOP(int op) {
  switch (op) {
    case OP_BUY      : return("Buy");
    case OP_SELL     : return("Sell");
    case OP_BUYLIMIT : return("Buy Limit");
    case OP_SELLLIMIT: return("Sell Limit");
    case OP_BUYSTOP  : return("Buy Stop");
    case OP_SELLSTOP : return("Sell Stop");
    default          : return("Unknown Operation");
  }
}
 

ModifyOrder() function.

The ModifyOrder function is designed to change one or more price levels of one pre-selected order. Here a pending order is understood as a Limit or Stop order, as well as a market Buy or Sell order, i.e. a position. Using the ModifyOrder function you can modify two price levels StopLoss and TakeProfit for the position, while for the pending order the OpenPrice setting price can be changed as well. The modified price levels are passed to the ModifyOrder function as parameters. If any of the parameters is negative, the corresponding price level will not be changed.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 28.11.2006                                                     |
//|  Описание : Модификация одного предварительно выбранного ордера.           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    pp - цена установки ордера                                              |
//|    sl - ценовой уровень стопа                                              |
//|    tp - ценовой уровень тейка                                              |
//|    cl - цвет значка модификации                                            |
//+----------------------------------------------------------------------------+
void ModifyOrder(double pp=-1, double sl=0, double tp=0, color cl=CLR_NONE) {
  bool   fm;
  double op, pa, pb, os, ot;
  int    dg=MarketInfo(OrderSymbol(), MODE_DIGITS), er, it;
 
  if (pp<=0) pp=OrderOpenPrice();
  if (sl<0 ) sl=OrderStopLoss();
  if (tp<0 ) tp=OrderTakeProfit();
  
  pp=NormalizeDouble(pp, dg);
  sl=NormalizeDouble(sl, dg);
  tp=NormalizeDouble(tp, dg);
  op=NormalizeDouble(OrderOpenPrice() , dg);
  os=NormalizeDouble(OrderStopLoss()  , dg);
  ot=NormalizeDouble(OrderTakeProfit(), dg);
 
  if (pp!=op || sl!=os || tp!=ot) {
    for (it=1; it<=NumberOfTry; it++) {
      if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) break;
      while (!IsTradeAllowed()) Sleep(5000);
      RefreshRates();
      fm=OrderModify(OrderTicket(), pp, sl, tp, 0, cl);
      if (fm) {
        if (UseSound) PlaySound(NameFileSound); break;
      } else {
        er=GetLastError();
        pa=MarketInfo(OrderSymbol(), MODE_ASK);
        pb=MarketInfo(OrderSymbol(), MODE_BID);
        Print("Error(",er,") modifying order: ",ErrorDescription(er),", try ",it);
        Print("Ask=",pa,"  Bid=",pb,"  sy=",OrderSymbol(),
              "  op="+GetNameOP(OrderType()),"  pp=",pp,"  sl=",sl,"  tp=",tp);
        Sleep(1000*10);
      }
    }
  }
}
 

DeleteOrders() function. Tester version.

Function DeleteOrders() is intended to delete pending orders BuyLimit, BuyStop, SellLimit and SellStop. The DeleteOrders() function is universal, i.e. it can be used to delete all pending orders present, as well as specific ones that meet the selection conditions set by the function parameters:

sy - Name of instrument. Since only the current symbol can be traded in the Strategy Tester, this parameter is not relevant for the Strategy Tester version and is only required for compatibility with the online version of this function. It is better to use values "" or NULL in the tester. The default value "" means any symbol.
op
- Type of trade operation, type of pending order. One of five values is possible: -1, OP_BUYLIMIT, OP_BUYSTOP, OP_SELLLIMIT or OP_SELLSTOP. The default value of -1 means any order.

mn - MagicNumber, identification number of a pending order. Default value -1 means any MagicNumber.


//+----------------------------------------------------------------------------+
//| Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                    |
//+----------------------------------------------------------------------------+
//| Версия   : 13.06.2007                                                      |
//| Описание : Удаление ордеров. Версия функции для тестов на истории.         |
//+----------------------------------------------------------------------------+
//| Параметры:                                                                 |
//| sy - наименование инструмента   (NULL - текущий символ)                    |
//| op - операция                   ( -1  - любой ордер)                       |
//| mn - MagicNumber                ( -1  - любой магик)                       |
//+----------------------------------------------------------------------------+
void DeleteOrders(string sy="", int op=-1, int mn=-1) {
  int i, k=OrdersTotal(), ot;
 
  if (sy=="" || sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      ot=OrderType();
      if (ot==OP_BUYLIMIT || ot==OP_BUYSTOP || ot==OP_SELLLIMIT || ot==OP_SELLSTOP) {
        if (OrderSymbol()==sy && (op<0 || ot==op)) {
          if (mn<0 || OrderMagicNumber()==mn) {
            OrderDelete(OrderTicket(), clDelete);
          }
        }
      }
    }
  }
}
 

DeleteOrders() function. Online version.


//+----------------------------------------------------------------------------+
//| Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                    |
//+----------------------------------------------------------------------------+
//| Версия   : 28.11.2006                                                      |
//| Описание : Удаление ордеров                                                |
//+----------------------------------------------------------------------------+
//| Параметры:                                                                 |
//|   sy - наименование инструмента   ( ""  - любой символ,                    |
//|                                    NULL - текущий символ)                  |
//|   op - операция                   (  -1 - любой ордер)                     |
//|   mn - MagicNumber                (  -1 - любой магик)                     |
//+----------------------------------------------------------------------------+
void DeleteOrders(string sy="", int op=-1, int mn=-1) {
  bool fd;
  int err, i, it, k=OrdersTotal(), ot;
  
  if (sy=="0") sy=Symbol();
  for (i=k-1; i>=0; 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) {
            for (it=1; it<=NumberOfTry; it++) {
              if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) break;
              while (!IsTradeAllowed()) Sleep(5000);
              fd=OrderDelete(OrderTicket(), clDelete);
              if (fd) {
                if (UseSound) PlaySound(NameFileSound); break;
              } else {
                err=GetLastError();
                Print("Error(",err,") delete order ",GetNameOP(ot),
                      ": ",ErrorDescription(err),", try ",it);
                Sleep(1000*5);
              }
            }
          }
        }
      }
    }
  }
}
 
//+----------------------------------------------------------------------------+
//| Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                    |
//+----------------------------------------------------------------------------+
//| Версия   : 07.10.2006                                                      |
//| Описание : Поиск ближайшего фрактала.                                      |
//+----------------------------------------------------------------------------+
//| Параметры:                                                                 |
//|   sy - наименование инструмента     (NULL - текущий символ)                |
//|   tf - таймфрейм                    (  0  - текущий ТФ)                    |
//|   mode - тип фрактала               (MODE_LOWER|MODE_UPPER)                |
//+----------------------------------------------------------------------------+
double FindNearFractal(string sy="0", int tf=0, int mode=MODE_LOWER) {
  if (sy=="" || sy=="0") sy=Symbol();
  double f=0;
  int d=MarketInfo(sy, MODE_DIGITS), s;
  if (d==0) if (StringFind(sy, "JPY")<0) d=4; else d=2;
 
  for (s=2; s<100; s++) {
    f=iFractals(sy, tf, mode, s);
    if (f!=0) return(NormalizeDouble(f, d));
  }
  Print("FindNearFractal(): Фрактал не найден");
  return(0);
}

Function ExistOrdersByLot().

Returns a flag for the existence of an order with the specified lot size. True - order exists (set), False - order doesn't exist (not set). You can limit the list of orders to be checked using the function parameters:

  • sy - Name of instrument. If you set this parameter, the function will only check the orders of the specified instrument. NULL means current instrument, and "" (by default) means any instrument.
  • op - Operation, 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.
  • lo - Size of a lot with an accuracy of two decimal places. The default value is 0 - any lot size.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 28.11.2006                                                     |
//|  Описание : Возвращает флаг существования ордера по размеру лота.          |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любой ордер)                    |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//|    lo - лот                        ( 0   - любой лот)                      |
//+----------------------------------------------------------------------------+
bool ExistOrdersByLot(string sy="", int op=-1, int mn=-1, double lo=0) {
  int i, k=OrdersTotal(), ot;
  lo=NormalizeDouble(lo, 2);

  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) {
            if (lo<=0 || NormalizeDouble(OrderLots(), 2)==lo) return(True);
          }
        }
      }
    }
  }
  return(False);
}
 

GetLotLastOrder() function.

Returns the lot size of the last placed order or -1. You can limit the list of orders to be checked using the function parameters:

  • sy - Name of the instrument. If this parameter is given, the function will only check the orders of the specified instrument. NULL means the current instrument, and "" (by default) means any instrument.
  • op - Operation, 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                                                     |
//|  Описание : Возвращает размер лота последнего выставленного ордера или -1  |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
double GetLotLastOrder(string sy="", int op=-1, int mn=-1) {
  datetime o;
  double   l=-1;
  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()>1 && OrderType()<6) {
          if (op<0 || OrderType()==op) {
            if (mn<0 || OrderMagicNumber()==mn) {
              if (o<OrderOpenTime()) {
                o=OrderOpenTime();
                l=OrderLots();
              }
            }
          }
        }
      }
    }
  }
  return(l);
}
 

GetOrderOpenPrice() function.

Returns the setting price of the last opened order or 0. You can limit the list of orders to be checked with function parameters:

  • sy - Name of the instrument. If this parameter is given, the function will only check the orders of the specified instrument. NULL means the current instrument, and "" (by default) means any instrument.
  • op - Operation, type of pending order. Valid values: OP_BUYLIMIT, OP_BUYSTOP, OP_SELLLIMIT, OP_SELLSTOP or -1. The default value of -1 indicates any order.
  • mn - Order identifier (MagicNumber). Default value -1 means any MagicNumber.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 28.11.2006                                                     |
//|  Описание : Возвращает цену установки последнего ордера или 0.             |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
double GetOrderOpenPrice(string sy="", int op=-1, int mn=-1) {
  datetime t;
  double   r=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()>1 && OrderType()<6) {
          if (op<0 || OrderType()==op) {
            if (mn<0 || OrderMagicNumber()==mn) {
              if (t<OrderOpenTime()) {
                t=OrderOpenTime();
                r=OrderOpenPrice();
              }
            }
          }
        }
      }
    }
  }
  return(r);
}
 

The IndexByTicket() function.

Returns the index (ordinal number in the general list of set orders or open positions) of the order or position on the ticket. If IndexByTicket() cannot find an order or position with the required ticket, it will return -1. We can limit the list of orders or positions to be checked using the function parameters:

  • sy - Name of instrument. If you specify this parameter, the function will only check orders and positions of the specified instrument. NULL means the current instrument, and "" (by default) means any instrument.
  • op - Trade operation, type of pending order or position. Valid values: OP_BUY, OP_BUYLIMIT, OP_BUYSTOP, OP_SELL, OP_SELLLIMIT, OP_SELLSTOP or -1. The default value of -1 indicates any order or position.
  • mn - Identifier of an order or position (MagicNumber). Default value -1 means any MagicNumber.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 20.04.2007                                                     |
//|  Описание : Возвращает индекс ордера или позиции по тикету                 |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    ti - тикет ордера, позиции                                              |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
int IndexByTicket(int ti, string sy="", int op=-1, int mn=-1) {
  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=="") && (op<0 || OrderType()==op)) {
        if ((mn<0 || OrderMagicNumber()==mn) && OrderTicket()==ti) return(i);
      }
    }
  }
  return(-1);
}
Reason: