Bibliotecas: Expert - página 3

 
Um exemplo de outro aplicativo da biblioteca

Fórum sobre negociação, sistemas de negociação automatizados e teste de estratégias de negociação

ParameterGetRange()

fxsaber, 2018.11.16 09:17

#include <fxsaber\Expert.mqh> // https://www.mql5.com/pt/code/19003

#define  TOSTRING(A) (" " + #A + " = " + (string)(A))

// Coleta dados sobre a gama de parâmetros de entrada para otimização
string OptimizationData( void )
{
  string Str = NULL;
  MqlParam Params[];
  string Names[];
  
  if (EXPERT::Parameters(0, Params, Names))
  {
    const int Size = ArraySize(Names);
    bool Enable;
    long Value, Start, Step, Stop;
    long Total = 1;
    
    Str = Params[0].string_value;
    
    for (int i = 0; i < Size; i++)
      if (ParameterGetRange(Names[i], Enable, Value, Start, Step, Stop))
      {
        const long Interval = Stop - Start + 1;
        const long Amount =  Enable ? Interval / Step + ((bool)(Interval % Step) ? 1 : 0) : 1;
        
        Str += "\n" + Names[i] + " = " + (string)Value + (Enable ? TOSTRING(Start) + TOSTRING(Step) + TOSTRING(Stop) + TOSTRING(Amount) : NULL);
        
        Total *= Amount;
      }
      
    Str += "\n" + TOSTRING(Total);
  }
  
  return(Str);
}

input int Range1 = 5;
input int Range2 = 5;
input int Range3 = 5;

void OnTesterInit()
{
  ParameterSetRange("Range1", true, 5, 1, 2, 3);
  
  Print(__FUNCTION__ + "\n" + OptimizationData());
}

void OnTesterDeinit()
{
  Print(__FUNCTION__ + "\n" + OptimizationData());
  
  ChartClose();
}

int OnInit()
{
  return(INIT_FAILED);
}


OnTesterInit
Experts\fxsaber\Test3.ex5
Range1 = 5 Start = 5 Step = 1 Stop = 50 Amount = 46
Range2 = 5 Start = 23 Step = 1 Stop = 78 Amount = 56
Range3 = 5 Start = 26 Step = 5 Stop = 83 Amount = 12
 Total = 30912

OnTesterDeinit
Experts\fxsaber\Test3.ex5
Range1 = 5 Start = 1 Step = 2 Stop = 3 Amount = 2
Range2 = 5 Start = 23 Step = 1 Stop = 78 Amount = 56
Range3 = 5 Start = 26 Step = 5 Stop = 83 Amount = 12
 Total = 1344
 
Bug corrigido.
 
Erro corrigido. Última versão.
 

Como é possível executar um Expert Advisor no formato .ex4 conectando-o a um Expert Advisor com um nome diferente, e é necessário que os parâmetros de entrada sejam exibidos, ou seja, que seja possível trabalhar totalmente com ele.

Temos um Expert Advisor compilado com o nome "Trade.ex4".

Crie um novo Consultor especialista com o nome "Hand.ex4".

Como combiná-los de modo que, quando o "Hand.ex4" for iniciado, o "Trade.ex4" esteja totalmente funcional e o "Trade.ex4" esteja incorporado ao "Hand.ex4".

Ou seja, temos apenas o arquivo Hand.ex4 na máquina, mas usamos o Trade.ex4 no trabalho

Muito obrigado!

 
Vitaly Muzichenko:

Como é possível executar um Expert Advisor no formato .ex4...

A biblioteca, em sua forma atual, funciona apenas com o EX5.

 
Sergey Eremin:

Eu mesmo, como parte de um determinado projeto, resolvi dessa forma (com a tag "name" assim mesmo):

Obrigado, funciona assim!

Só que eu adicionei chartId ao nome do modelo salvo, para que EAs idênticos em gráficos diferentes não lutem pelo mesmo arquivo.


@fxsaber, há "#ifndef __MQL5__" no código, por que não levar a plataforma cruzada à sua conclusão lógica?

Para que isso funcione, adicionamos ao início do código:

#property strict

#ifdef __MQL4__
        class SubstringParser
        {
           private:
              string m_text;
              string m_subStart;
              string m_subEnd;
           
           public:
              SubstringParser(const string text, const string subStart, const string subEnd)
              {
                 m_text = text;
                 m_subStart = subStart;
                 m_subEnd = subEnd;
              }
              
              string Get()
              {
                 int startPhraseLengt = StringLen(m_subStart);
                 int startPos = StringFind(m_text, m_subStart) + startPhraseLengt;
                 int endPos = StringFind(m_text, m_subEnd, startPos);
                         
                 if(startPos >= startPhraseLengt && endPos > startPos)
                 {
                    return StringSubstr(m_text, startPos, endPos - startPos);      
                 }
                 else
                 {
                    return "";
                 }
              }
        };

   string GetChartEAName(const long chartId)
   {
      if(!SaveTemplate(chartId))
      {
         return "";
      }
      
      string result = "";
      
      int handle = FileOpen("ea_name_checking_" + (string)chartId + ".tpl",FILE_TXT|FILE_READ);
      if(handle == INVALID_HANDLE)
      {
         Print
         (
            "Error in ", __FILE__,", line ", __LINE__,
            ": can't open template file 'ea_name_checking_" + (string)chartId + ".tpl', error code = ", GetLastError()
         );
      }
      else
      {
         string text = "";
         
         while(!FileIsEnding(handle)) 
         { 
            text = text + FileReadString(handle, (uint)FileSize(handle)) +"\r\n";
         }
         
         SubstringParser eaSectionTextParser(text, "<expert>", "</expert>");            
         string eaSectionText = eaSectionTextParser.Get();
         
         if(StringTrimLeft(StringTrimRight(eaSectionText)) != "")
         {
            SubstringParser eaNameParser(eaSectionText, "name=","\r\n");
            string eaName = StringTrimLeft(StringTrimRight(eaNameParser.Get()));
            
            if(eaName != "")               
            {
               result = eaName;
            }
         }            
      }
      
      FileClose(handle);
      FileDelete("ea_name_checking_" + (string)chartId + ".tpl");
      
      return result;
   }
   
   bool SaveTemplate(const long chartId)
   {
      ResetLastError();
      
      if(!ChartSaveTemplate(chartId, "\\Files\\ea_name_checking_" + (string)chartId + ".tpl"))
      {            
         Print
         (
            "Error in ", __FILE__,", line ", __LINE__,
            ": can't save template to the file 'ea_name_checking_" + (string)chartId + ".tpl', error code = ", GetLastError()
         );
         
         return false;
      }
      
      return true;
   }      
 #endif

E corrigir a própria função:

  static bool Is( const long Chart_ID = 0 )
  {
                #ifdef __MQL4__
                        string chartEAName = GetChartEAName(Chart_ID);
                #endif 
                
                #ifdef __MQL5__     
                        string chartEAName = ChartGetString(Chart_ID, CHART_EXPERT_NAME);
                #endif
                return(chartEAName != NULL);
  }


Alguma outra dificuldade?

 
Andrey Khatimlianskii:

Alguma outra dificuldade?

Um gráfico com apenas um indicador em execução.


ZY É assim que deve funcionar

SubstringParser eaSectionTextParser(text, "\r\n\r\n<expert>", "</expert>");
 

Toda a funcionalidade da biblioteca agora funciona no MT4.

A biblioteca tornou-se multiplataforma.

 
Toda a funcionalidade da biblioteca agora funciona no MT4.
A biblioteca tornou-se multiplataforma.


Exemplo do MT4:

Форум по трейдингу, автоматическим торговым системам и тестированию торговых стратегий

Библиотеки: Especialista

fxsaber, 2019.04.09 13:19

#include <fxsaber\Expert.mqh> // https://www.mql5.com/ru/code/19003

void OnStart()
{
  MqlParam Params[2];

  // Путь к советнику
  Params[0].string_value = "Moving Average";
  
  // Первый входной параметр советника
  Params[1].type = TYPE_DOUBLE;
  Params[1].double_value = 0.5;  

  Print(EXPERT::Run(ChartOpen(_Symbol, _Period), Params));
}
 
Vitaly Muzichenko:

Qual é a melhor maneira de executar um EA em .ex4...

#include <fxsaber\Expert.mqh> // https://www.mql5.com/pt/code/19003

void OnStart()
{
  MqlParam Params[2];

  // Caminho para ser um conselheiro
  Params[0].string_value = "Moving Average";
  
  // O primeiro parâmetro de entrada do Expert Advisor
  Params[1].type = TYPE_DOUBLE;
  Params[1].double_value = 0.5;  

  Print(EXPERT::Run(ChartOpen(_Symbol, _Period), Params));
}