Características úteis da KimIV - página 13

 
olyakish:

Igor, fiz-lhe uma pergunta na 'Biblioteca de funções para trabalhar com arquivos INI', mas não obtive resposta :(


Obrigado... respondeu...

 

A função ClosePosBySelect().

Fecha uma posição pré-selecionada. Esta função é bastante auxiliar, pois é chamada de várias outras funções, que ajudam a selecionar posições a serem fechadas por algumas condições.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. 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:

Obrigado... respondeu...

Outra pergunta (ou melhor, uma declaração) também aí :)

 
KimIV:

A função ClosePosBySelect().

Fecha uma posição pré-selecionada. Esta função é bastante auxiliar porque é chamada de várias outras funções que ajudam a selecionar posições a serem fechadas de acordo com algumas condições.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. 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()));
}

Olá!

Desculpe-me!

1) Eu não entendo o significado da linha para (it=1; it<=NumberOfTry; it++)

que tipo de loop é este?

2) Eu também não entendo a condição se (!testing() ......) quebrar;

3) e por último, que função é esta ? ErrorDescription(err)," ,

Se você não se importa, por favor explique .

 

1. este é um ciclo de tentativas comerciais. Se o servidor comercial retornar erros, a função fará com que a NumberOfTry tente fechar a posição afinal de contas. Normalmente, eu defino NumberOfTry=5.

2. Esta condição implementa a capacidade de sair corretamente do ciclo de tentativas quando o Expert Advisor que trabalha on-line é interrompido. Sem esta condição, a fim de chamar, por exemplo, propriedades da EA, tivemos que esperar até que a EA utilizasse todas as tentativas comerciais, ou remover a EA do gráfico.

3. Ver em arquivo ..peritagem de bibliotecas ..ss.mdlib.mq4

[Excluído]  

Gostaria de perguntar como fazer um EA funcionar em um loop infinito, mas com acesso às configurações de seus parâmetros?

Eu escrevi no início assim

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

Mas neste caso, o Expert Advisor fica pendurado e eu não posso fazer nada com ele, exceto removê-lo do gráfico.

 

Valera, que assim seja:


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

A função ClosePosBySizeProfitInCurrency().

Esta função fecha somente aquelas posições para as quais o lucro na moeda do depósito excede um determinado valor especificado. Você pode especificar quais posições devem ser fechadas usando os parâmetros da função:

  • sy - Nome do instrumento. Se você definir este parâmetro, a função só verificará as posições do instrumento especificado. NULL significa o instrumento atual, e "" (por padrão) significa qualquer instrumento.
  • op - Operação comercial, tipo de posição. Valores válidos: OP_BUY, OP_SELL ou -1. O valor padrão -1 significa qualquer posição.
  • mn - Identificador de posição (MagicNumber). Valor por default -1 - significa qualquer MagicNumber.
  • pr - Nível de lucro na moeda do depósito. Valor padrão - 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();
          }
        }
      }
    }
  }
}
[Excluído]  
KimIV:

Valera, que assim seja:


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

Infelizmente, isto também transmite o ekspert e não dá acesso a seus parâmetros até que você o remova do gráfico.

 
scorpionk:

Infelizmente, isto também transmite a EA e não dá acesso a seus parâmetros até que você a remova do gráfico.

No entanto, ele lhe dá a opção de parar a EA ao pressionar o botão "EAs" na barra de ferramentas.