Quaisquer perguntas de recém-chegados sobre MQL4 e MQL5, ajuda e discussão sobre algoritmos e códigos - página 852

 
Não é possível acessar o site
 

Olá desenvolvedores,

Veja qualquer testador de estratégia com data personalizada ou qualquer opção de data

Ver imagem:

testador de estratégia

Quero obter os valores das datas de início e fim em meu programa na função OnInit ().

Como posso obtê-lo?

 
Artyom Trishkin:

Formar todo o laço em uma função, e retornar o número da barra se encontrado, ou WRONG_VALUE se não for encontrado.


Boa tarde. Acho que terminei de trabalhar com o problemático iCustom de ontem. Fiz tudo sob a forma de uma função e usei"Comentar" e "Imprimir" para controle.

A idéia deste Expert Advisor experimental é capturar sinais na forma de setas para cima/para baixo do indicador iCrossAD e transformá-los em comando BUY ou SELL para serem usados em um programa futuro.

Tenho um pouco de experiência, portanto, não julgue severamente, mas críticas e conselhos bem fundamentados sobre como fazê-lo melhor seriam apreciados.

Na verdade, por causa disso e escreveu um post. EA e arquivos indicadores anexados, o código abaixo.

//+------------------------------------------------------------------+
//|                                                  Test_iCusom.mq5 |
//|                        Copyright 2018, MetaQuotes Software Corp. |
//|                             https://mql5.com/ru/users/artmedia70 |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018, MetaQuotes Software Corp."
#property link      "https://mql5.com/ru/users/artmedia70"
#property version   "1.00"
#property description ""
#property strict
//--- includes
#include <DoEasy\Engine.mqh>
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
//---
enum Indicator_Direction
   {
   Direction_BUY,
   Direction_SELL,
   Direction_FLAT
   };
//---
input string   Inp_param_indi_iCrossAD = "Input parameters indicator iCrossAD";//----- "Внешние параметры индикатора iCrossAD" -----
input uint     InpPeriodFind           = 400;                 // Bars for calculate
input uint     InpUnheckedBars         = 2;                   // Unchecked bars
input uint     InpPeriodIND            = 21;                  // CCI period

//--- global variables

CEngine        engine;
CTrade         trade;
CPositionInfo  apos;
CSymbolInfo    asymbol;

int            CrossAD;                           //Хэндл индикатора iCrossAD

double         Buf_Arrow_Sell[],                  //Массив буфера для приема значений последних стрелок ВНИЗ из индикатора iCrossAD
               Last_Arrow_Sell_volume,            //Переменная для записи значения цены последней стрелки ВНИЗ индикатора iCrossAD
               Last_Arrow_Sell_index;             //Переменная для записи значения индекса свечи последней стрелки ВНИЗ индикатора iCrossAD
datetime       Last_Arrow_Buy_time;               //Переменная для записи времени стрелки
               
double         Buf_Arrow_Buy[], Last_Arrow_Buy_volume, Last_Arrow_Buy_index;
datetime       Last_Arrow_Sell_time;
   
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   ArraySetAsSeries(Buf_Arrow_Buy, true);
   ArraySetAsSeries(Buf_Arrow_Sell, true);
//---
   CrossAD = iCustom(asymbol.Name(), _Period, "iCrossAD",InpPeriodFind,InpUnheckedBars,InpPeriodIND);
   if (CrossAD == INVALID_HANDLE)
   {
      Print("Не удалось создать описатель индикатора iCrossAD!");
      return(INIT_FAILED);
   }
      else Print("Хендл iCrossAD = ",CrossAD);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- delete objects
   ObjectsDeleteAll(0,"",-1);
   Comment("");
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
  
   string direction = "no information";
   switch(iCustom_iCrossAD(InpPeriodFind))
      {
      case Direction_BUY: direction = "BUY";
         break;
      case Direction_SELL: direction = "SELL";
         break;
      case Direction_FLAT: direction = "FLAT";
         break;
      case WRONG_VALUE: direction = "no information";
         break;   
      }
   Comment("-------------------------", 
            "\n Last_Arrow_Buy_volume     = ",Last_Arrow_Buy_volume,
            "\n Last_Arrow_Buy_index        = ",Last_Arrow_Buy_index,
            "\n Last_Arrow_Buy_time         = ",Last_Arrow_Buy_time,
            "\n ---------------------- ",
            "\n Last_Arrow_Sell_volume     = ",Last_Arrow_Sell_volume,
            "\n Last_Arrow_Sell_index        = ",Last_Arrow_Sell_index,
            "\n Last_Arrow_Sell_time         = ",Last_Arrow_Sell_time,
            "\n ---------------------- ",
            "\n Indicator_Direction             = ",direction
            ); 
  }
//+------------------------------------------------------------------+
int iCustom_iCrossAD(uint PeriodFind) 
  { 
   Indicator_Direction direct = Direction_FLAT;
   
   if (CopyBuffer(CrossAD, 1, 0, PeriodFind, Buf_Arrow_Buy) != PeriodFind)
      {  
         Print("НЕ удалось правильно скопировать данные из 1-го буфера индикатора iCrossAD, error code %d",GetLastError());
         return(WRONG_VALUE);
      }
         for(int n=0; n<(int)PeriodFind; n++)
            {
               if(n==0)
                  Print("Last_Arrow_Buy_index n==",n," Last_Arrow_Buy_time = ",iTime(_Symbol,0,n));
               if(Buf_Arrow_Buy[n]==EMPTY_VALUE)
                  Print("Last_Arrow_Buy_index n==",n," Last_Arrow_Buy_time = ",iTime(_Symbol,0,n));
               if(Buf_Arrow_Buy[n]!=EMPTY_VALUE)
               {
                  Last_Arrow_Buy_volume = iOpen(_Symbol,_Period,n);
                  Last_Arrow_Buy_time   = iTime(_Symbol,0,n);
                  Last_Arrow_Buy_index  = n;
                  Print("Last_Arrow_Buy_volume = ",Last_Arrow_Buy_volume,", Last_Arrow_Buy_index = ",Last_Arrow_Buy_index,", Last_Arrow_Buy_time = ",Last_Arrow_Buy_time);
                  break;
               }   
            }
         
   if (CopyBuffer(CrossAD, 2, 0, PeriodFind, Buf_Arrow_Sell) != PeriodFind)
      {  
         Print("НЕ удалось правильно скопировать данные из 2-го буфера индикатора iCrossAD, error code %d",GetLastError());
         return(WRONG_VALUE);
      }
         for(int n=0; n<(int)PeriodFind; n++)
            {
               if(n==0)
                  Print("Last_Arrow_Sell_index n==",n," Last_Arrow_Sell_time = ",iTime(_Symbol,0,n));
               if(Buf_Arrow_Sell[n]==EMPTY_VALUE)
                  Print("Last_Arrow_Sell_index n==",n," Last_Arrow_Sell_time = ",iTime(_Symbol,0,n));
               if(Buf_Arrow_Sell[n]!=EMPTY_VALUE)
               {
                  Last_Arrow_Sell_volume = iOpen(_Symbol,_Period,n);
                  Last_Arrow_Sell_time   = iTime(_Symbol,0,n);
                  Last_Arrow_Sell_index  = n;
                  Print("Last_Arrow_Sell_volume = ",Last_Arrow_Sell_volume,", Last_Arrow_Sell_index = ",Last_Arrow_Sell_index,", Last_Arrow_Sell_time = ",Last_Arrow_Sell_time);
                  break;
               }
            }
   if(Last_Arrow_Buy_index < Last_Arrow_Sell_index)direct = Direction_BUY;
      else if(Last_Arrow_Buy_index > Last_Arrow_Sell_index)direct = Direction_SELL;
         else direct = Direction_FLAT;         
   return(direct); 
      //return(WRONG_VALUE); 
  }
//+------------------------------------------------------------------+
Arquivos anexados:
iCrossAD.mq5  49 kb
 
Olá, meu consultor especializado tem uma função para apagar ordens pendentes quando outra ordem é acionada. Como posso prescrever nos parâmetros externos para poder desativar esta função? Muito obrigado de antemão.
Arquivos anexados:
ths42o20.txt  1 kb
 

Olá!

Eu converti o indicador de MT4 para MT5. Quero usar o indicador como um filtro adicional.

Eu estou estudando apenas o MT5. Mas eu não consigo encontrar o erro. Minhas reflexões МТ4 e МТ5 são diferentes.

Tenho um pedido aos especialistas - por favor, me ajude a encontrar um erro no arquivo *.mql5.

Estou anexando o código fonte.

Estou muito, muito grato por sua ajuda.

Arquivos anexados:
ReVoIn.mq4  4 kb
ReVoIn.mq5  11 kb
 
Priffekt:
Olá, eu tenho uma função em meu EA para apagar pedidos pendentes quando outro pedido é acionado. Como posso prescrever nos parâmetros externos para poder desativar esta função? Muito obrigado de antemão.
DeleteOppositeOrders();
void DeleteOppositeOrders() {
  bool fd, fep1, fep2;

  fep1=ExistPosition(1);
  fep2=ExistPosition(2);

  for (int i=OrdersTotal()-1; i>=0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==Symbol()) {
        fd=False;
        if (OrderType()==OP_BUYSTOP && OrderMagicNumber()== Magik) {
          if (fep2) fd=OrderDelete(OrderTicket());
        }
        if (OrderType()==OP_SELLSTOP && OrderMagicNumber()== Magik) {
          if (fep1) fd=OrderDelete(OrderTicket());
        }
        if (fd && UseSound) PlaySound(NameFileSound);
      }
    }
  }
}
bool ExistPosition(int mn) {
  bool Exist=False;
  for (int i=0; i<OrdersTotal(); i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==Symbol() && OrderMagicNumber()== Magik) {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          Exist=True; break;
        }
      }
    }
  }
  return(Exist);
}

Este é o seu código, é melhor anexar desta forma.

 

É claro que não sou muito adequado para o papel de conselheiro, mas a tarefa parece não ser difícil.

Note que não vou entrar no seu código em si, há muita controvérsia, mesmo para mim (dummies), a começar pelo fato de que sua função é do tipo void. Este tipo é usado ou para indicar que a função não retorna um valor, ou como um parâmetro de função indica a ausência de parâmetros. E você tem retorno(Existente) no final de seu código;

Declare uma variável de entrada, escreva-a como um parâmetro para sua função e saia da função se você definir 'esta variável como Falsa'.

 
input bool On_Off = true;
DeleteOppositeOrders(On_Off);
void DeleteOppositeOrders(bool on_off) {

  if(on_off==false)return;

  bool fd, fep1, fep2;

  fep1=ExistPosition(1);
  fep2=ExistPosition(2);

  for (int i=OrdersTotal()-1; i>=0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==Symbol()) {
        fd=False;
        if (OrderType()==OP_BUYSTOP && OrderMagicNumber()== Magik) {
          if (fep2) fd=OrderDelete(OrderTicket());
        }
        if (OrderType()==OP_SELLSTOP && OrderMagicNumber()== Magik) {
          if (fep1) fd=OrderDelete(OrderTicket());
        }
        if (fd && UseSound) PlaySound(NameFileSound);
      }
    }
  }
}
bool ExistPosition(int mn) {
  bool Exist=False;
  for (int i=0; i<OrdersTotal(); i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==Symbol() && OrderMagicNumber()== Magik) {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          Exist=True; break;
        }
      }
    }
  }
  return(Exist);
}
 
Priffekt:
Olá, tenho em minha EA a função de apagar pedidos pendentes quando outro pedido é acionado. Como posso prescrever nos parâmetros externos que esta função pode ser desativada. Muito obrigado de antemão.

Encontre tudo Falso e Verdadeiro no texto de seu código. Substituí-los por falsos e verdadeiros. Esta linguagem é sensível a maiúsculas e minúsculas.

 
Sergey Voytsekhovsky:

Encontre tudo Falso e Verdadeiro no texto de seu código. Substituí-los por falsos e verdadeiros. Esta linguagem é sensível a maiúsculas e minúsculas.

Boa tarde, mudei todos os valores, mas estou interessado na possibilidade de desativar a própria função nas configurações do Expert Advisor.
DeleteOppositeOrders(); void DeleteOppositeOrders() { bool fd, fep1, fep2; fep1=ExistPosition(1); fep2=ExistPosition(2); for (int i=OrdersTotal()-1; i>=0; i--) { se (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { se (OrderSymbol()==Symbol()) { fd=false; if (OrderType()==OP_BUYSTOP && OrderMagicNumber()== Magik) { if (fep2) fd=OrderDelete(OrderTicket()); } if (OrderType()==OP_SELLSTOP && OrderMagicNumber()== Magik) { if (fep1) fd=OrderDelete(OrderTicket()); } if (fd && UseSound) PlaySound(NameFileSound); } } } bool ExistPosition(int mn) { bool Exist=false; for (int i=0; i<OrdersTotal(); i+++) { se (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if (OrderSymbol()==Symbol() && OrderMagicNumber()== Magik) { if (OrderType()==OP_BUY || OrderType()==OP_SELLL) { Exist=true; break; } } } return(Exist); }