Cualquier pregunta de los recién llegados sobre MQL4 y MQL5, ayuda y discusión sobre algoritmos y códigos - página 852

 
No se puede acceder al sitio web
 

Hola desarrolladores,

Ver cualquier probador de estrategia con fecha personalizada o cualquier opción de fecha

Ver imagen:

probador de estrategias

Quiero obtener los valores de la fecha de inicio y fin en mi programa en la función OnInit ().

¿Cómo puedo conseguirlo?

 
Artyom Trishkin:

Formar todo el bucle en una función, y devolver el número de barra de ella si se encuentra, o WRONG_VALUE si no se encuentra.


Buenas tardes. Creo que he terminado de trabajar con el problemático iCustom de ayer. Lo he hecho todo en forma de función y he utilizado"Comentario" e "Impresión" para el control.

La idea de este Asesor Experto de prueba es captar las señales en forma de flechas arriba/abajo del indicador iCrossAD y convertirlas en orden de COMPRA o VENTA para utilizarlas en un futuro programa.

Tengo un poco de experiencia, así que por favor no juzguéis, pero se agradecerían críticas y consejos bien razonados.

De hecho, para el bien de esto y escribió un post. Archivos de EA e indicadores adjuntos, el código a continuación.

//+------------------------------------------------------------------+
//|                                                  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); 
  }
//+------------------------------------------------------------------+
Archivos adjuntos:
iCrossAD.mq5  49 kb
 
Hola, mi Asesor Experto tiene una función para eliminar las órdenes pendientes cuando otra orden se dispara. ¿Cómo puedo prescribir en los parámetros externos para poder desactivar esta función? Muchas gracias de antemano.
Archivos adjuntos:
ths42o20.txt  1 kb
 

¡Hola!

He convertido el indicador de MT4 a MT5. Quiero utilizar el indicador como un filtro adicional.

Sólo estoy estudiando MT5. Pero no puedo encontrar el error. Mis reflexiones МТ4 y МТ5 son diferentes.

Tengo una petición para los expertos - por favor, ayúdenme a encontrar un error en el archivo *.mql5.

Adjunto el código fuente.

Estoy muy, muy agradecido por su ayuda.

Archivos adjuntos:
ReVoIn.mq4  4 kb
ReVoIn.mq5  11 kb
 
Priffekt:
Hola, tengo una función en mi EA para eliminar las órdenes pendientes cuando se dispara otra orden. ¿Cómo puedo prescribir en los parámetros externos para poder desactivar esta función? Muchas gracias de antemano.
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 es su código, es mejor adjuntarlo de esta manera.

 

Por supuesto, no soy muy adecuado para el papel de asesor, pero la tarea parece no ser difícil.

Ten en cuenta que no me he metido en tu código propiamente dicho, hay mucha controversia, incluso para mí (los tontos), empezando por el hecho de que tu función es de tipo void. Este tipo se utiliza bien para indicar que la función no devuelve un valor, o bien como parámetro de la función indica la ausencia de parámetros. Y tienes return(Exist) al final de tu código;

Declare una variable de entrada, escríbala como un parámetro para su función y salga de la función si establece 'esta variable a False.

 
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:
Hola, tengo en mi EA la función de eliminar las órdenes pendientes cuando se dispara otra orden. ¿Cómo puedo prescribir en los parámetros externos que esta función puede ser desactivada. Muchas gracias de antemano.

Encuentre todos los falsos y verdaderos en el texto de su código. Sustitúyelos por falso y verdadero. Este lenguaje distingue entre mayúsculas y minúsculas.

 
Sergey Voytsekhovsky:

Encuentre todos los falsos y verdaderos en el texto de su código. Sustitúyelos por falso y verdadero. Este lenguaje distingue entre mayúsculas y minúsculas.

Buenas tardes, he cambiado todos los valores, pero me interesa la posibilidad de desactivar la función en sí en la configuración del Asesor Experto.
DeleteOppositeOrders(); void DeleteOppositeOrders() { bool fd, fep1, fep2; fep1=ExistPosition(1); fep2=ExistPosition(2); for (int i=OrdersTotal()-1; i>=0; i--) { si (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { si (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++) { si (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if (OrderSymbol()==Symbol() && OrderMagicNumber()== Magik) { if (OrderType()==OP_BUY || OrderType()==OP_SELL) { Exist=true; break; } } return(Exist); }
Razón de la queja: