Useful features from KimIV - page 13

 
olyakish:

Igor, I asked you a question in the 'Library of functions to work with INI files.' but there was no reply :(


Thanks... replied...

 

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.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия  : 19.02.2008                                                      |
//|  Описание: Закрытие одной предварительно выбранной позиции                 |
//+----------------------------------------------------------------------------+
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()));
}
 
KimIV:

Thank you... answered...

Another question (or rather statement) there too :)

 
KimIV:

The ClosePosBySelect() function.

Closes one pre-selected position. This function is rather auxiliary because it is called from several other functions that help select positions to be closed according to some conditions.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия  : 19.02.2008                                                      |
//|  Описание: Закрытие одной предварительно выбранной позиции                 |
//+----------------------------------------------------------------------------+
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()));
}

Hello!

Excuse me !

1) I don't understand the meaning of the line for (it=1; it<=NumberOfTry; it++)

what kind of loop is this?

2) I also do not understand the condition if (!testing() ......) break;

3) and lastly, what function is this ? ErrorDescription(err)," ,

If you don't mind, please explain .

 

1. this is a cycle of trade attempts. If the trade server returns errors, the function will make NumberOfTry attempts to close the position after all. I usually set NumberOfTry=5.

2. this condition implements the ability to correctly exit the cycle of attempts when the Expert Advisor working online is stopped. Without this condition, in order to call, for example, properties of the EA, we had either to wait until the EA uses all trade attempts, or remove the EA from the chart.

3. Look in file ..\experts\libraries\stdlib.mq4

 

I would like to ask how to make an EA work in an infinite loop, while having access to the settings of its parameters?

I wrote in start like this

while (true)
{
  // проверка на останов и прочее
      if (IsStopped()) 
        return(-1);
  while (isRefresh == false)
       isRefresh = RefreshRates();
      
  // некий код
  // задержка
  Sleep(G_Period);   
}

But in this case, the Expert Advisor hangs and I cannot do anything with it except remove it from the chart

 

Valera, make it so:


while (IsExpertEnabled() && !IsStopped())
{
  while (!RefreshRates()) Sleep(500);
      
  // некий код
  // задержка
  Sleep(G_Period);   
}
 

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 define 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();
          }
        }
      }
    }
  }
}
 
KimIV:

Valera, make it so:


while (IsExpertEnabled() && !IsStopped())
{
  while (!RefreshRates()) Sleep(500);
      
  // некий код
  // задержка
  Sleep(G_Period);   
}

Alas, this also broadcasts the ekspert and does not give access to its parameters until you remove it from the chart

 
scorpionk:

Alas, this also broadcasts the EA and does not give access to its parameters until you remove it from the chart

It does, however, give you the option of stopping the EA by pressing the 'EAs' button on the toolbar.

Reason: