English Русский 中文 Español Deutsch 日本語
Indicador de linhas de tendências considerando a abordagem de T. Demark

Indicador de linhas de tendências considerando a abordagem de T. Demark

MetaTrader 4Exemplos | 4 fevereiro 2016, 12:10
813 0
Genkov
Genkov

Introdução

A luta entre os compradores ("ursos") e vendedores ("touros") pode ser demonstrada utilizando linhas de tendências. Thomas Demark desenvolveu os métodos de objetivo escolhendo dois pontos para a linha TD do gráfico da tendência (você pode ver a informação detalhada sobre a abordagem de T. Demark na análise técnica aqui).

Desde então, de acordo com T. Demark, a coisa mais importante para um investidor é o último estado do mercado, na versão sugerida do indicador a última direção da tendência é desenhada com uma linha sólida e espessa, e não será incomum para a análise do estado atual conhecer a direção precedente mais próxima da tendência, que é desenhada com uma linha pontilhada fina.

Alguns recursos do código MQL4 do indicador sugerido


Quatro buffers (estoques) são usados no indicador. Dois buffers são para o código de setas das direções das linhas e dois são para o alongamento da linha TD no lado esquerdo.

As primeiras dez barras (para a esquerda do segundo ponto TD) são desenhadas pelos buffers do indicador na cor «aqua».

#property indicator_chart_window
#property indicator_buffers 4
#property indicator_color1 Chartreuse
#property indicator_color2 Tomato
#property indicator_color3 Aqua
#property indicator_color4 Aqua
 
// ----- indicator_buffers
double   TrendUpBuffer[];
double   TrendDownBuffer[];
double   TrendLineBufferUp[];
double   TrendLineBufferDown[];

Inicialize as funções que controlam o cálculo e a visualização do indicador.

int init()
  {
//---- indicators
   SetIndexStyle(0,DRAW_ARROW);        // the type and the style of the indicator line
   SetIndexArrow(0,236);               // the icon for the indicator line
   SetIndexBuffer(0,TrendUpBuffer);    // the declaration of the unidimensional array
   SetIndexEmptyValue(0,0.0);          // the size of the empty value of the indicator
   SetIndexStyle(1,DRAW_ARROW);
   SetIndexArrow(1,238);
   SetIndexBuffer(1,TrendDownBuffer);
   SetIndexEmptyValue(1,0.0);
   SetIndexStyle(2,DRAW_LINE);         
   SetIndexBuffer(2,TrendLineBufferUp);    // for the rising line
   SetIndexEmptyValue(2,0.0);           
   SetIndexStyle(3,DRAW_LINE);
   SetIndexBuffer(3,TrendLineBufferDown);  // for the descending line
   SetIndexEmptyValue(3,0.0);
//----
   return(0);

A desinicialização pode ficar em branco por padrão.

int deinit()
  {
  //  DelObj1();  
  //  DelObj2();
  return(0);
  }

Crie a função para excluir o objeto que possui o nome especificado.

  void DelObj1()
  {
  ObjectDelete("TrDdown"); // Deleting of the object with the specified name. 
  }
  void DelObj2()
  {
  ObjectDelete("TrDup");
  }

Vamos procurar pelos pontos de verificação (por conveniência) em ciclos separados para picos e avanços. Iniciamos a busca a partir da segunda barra porque precisaremos compará-la com a barra da direita (não zero) para esclarecer a veracidade da linha de tendência.

Vamos verificar a condição 1 (o preço da barra Máx. deve ser maior do que os preços da barra direita e esquerda).

for(int i=2;i<48;i++) // 48 hours - 2 days  // i- index of the bar to be verified
    {
     if(High[i]>High[i+1]&&High[i]>High[i-1]) 
      {

Vamos verificar a condição 2 (o preço máximo de suporte deve ser maior do que o preço de fechamento após as duas barras antes do registro).

No caso em que as condições 1 e 2 sejam satisfeitas, colocaremos o contador de correspondências.

if(High[i]>Close[i+2])  
       { 
        U++; // the counter of matches of the 1st and the 2nd conditions
        if(U==1)
         {

Então passamos para o registro por picos dos parâmetros do primeiro ponto de verificação:

         // The price of the First check point when the conditions #1 and #2 are fulfilled
         TD_up[1]=High[i];  
         index_up_1=i;                               // the index of the First check point
         Pr_up_Cl_1=Close[i-1]; // the close price of the bar that follows the check point
         time_up_1=iTime(NULL,0,index_up_1);          // the time of the first check point

Aqui inserimos o seguinte código de verificação para controlar o programa em execução:

         // this is an easy-to-follow time to control the operators processing
         Time_up_1=TimeToStr(time_up_1,TIME_DATE|TIME_MINUTES); 
         Print("  Up price of First check point = ",TD_up[1],"  ;  index = ",
               index_up_1,"  time = ",Time_up_1);

Já que o contador foi ativado uma vez, descobrimos o segundo ponto nas interações seguintes e passamos para o registro por picos dos parâmetros do segundo ponto de verificação:

          }  
          if(U==2)
           { 
           // The price of the Second check point when the conditions #1 and #2 are fulfilled
           TD_up[2]=High[i]; 
           index_up_2=i;            // the index of the Second check point
           time_up_2=iTime(NULL,0,index_up_2);// the time of the Second check point

Aqui inserimos o seguinte código de verificação para controlar o programa em execução:

           Time_up_2=TimeToStr(time_up_2,TIME_DATE|TIME_MINUTES); 
           Print("  Up price of Second check point = ",TD_up[2],"  ;  index = ",
                 index_up_2,"  time = ",Time_up_2);

Agora temos dois pontos de verificação de TD, precisamos verificar a condição da tendência de queda, isto é, o preço do primeiro ponto de verificação deve ser menor do que o do segundo ponto de verificação.

           // the condition of the downtrend (the right TD-point must be lower than the left one)
           if((U==2 && TD_up[1]<TD_up[2])==false) 
             {  
              Print(" Up the conditions of the downtrend are not fulfilled "); 
              U--; TD_up[2]=0.0; index_up_2=0; time_up_2=0;  continue; 
              }

Se a condição não for satisfeita, diminuímos o contador por um e zeramos os valores do preço, índice, tempo e retornamos ao início do ciclo, para assim pesquisar outro segundo ponto de verificação. Se a condição for satisfeita, calculamos a velocidade da queda da linha TD.

            else
             { 
              Print(" Up the conditions of the downtrend are fulfilled ");
              // the calculation of the speed of TD_max falling by two discovered points
              V_up=(TD_up[2]-TD_up[1])/(index_up_2-index_up_1);//speed(pips/bar)
              // the calculated value of TD-line on the first bars which is to the right of Max
              Pr_Tr_up_1=TD_up[1]-V_up;
              // if we subtract the product of speed of TD-line falling times number of bars
              // from the price of the 1-st check point, we'll obtain the price of the 
              Pr_Tr_up_0=TD_up[1]-(index_up_1*V_up);           // downtrend on the "0" bar

Agora vamos verificar a condição 3 (para o último preço máximo de suporte o preço de fechamento para a próxima barra (à direita) deve ser menor do que o valor calculado da velocidade da queda da linha TD) - é a condição de veracidade da tendência de queda.

              // let's check the condition #3 (for the last supporting price maximum the close
              // price for the next (to the right) bar must be lower than the calculated
              // value of the speed of TD-line falling)
              if((Pr_up_Cl_1< Pr_Tr_up_1)==false)
               {
                Print(" Up The condition of verity of downtrend is not fulfilled!");
                i=index_up_1+2; TD_up[1]=0.0; TD_up[2]=0.0; time_up_1=0; 
                time_up_2=0; index_up_1=50; index_up_2=50; U=0; continue;
                }

Se a condição 3 de veracidade da tendência de queda não for satisfeita, então a pesquisa por pontos TD deve iniciar novamente. Para fazer isso é necessário zerar os valores de todas as variáveis obtidas anteriormente e começar a pesquisa da barra que está à esquerda por 2 barras do primeiro valor encontrado, no primeiro ponto de verificação.


Se a condição for satisfeita, memorizamos os valores das variáveis calculadas para desenhar a linha de tendência.

             else
               { // if the condition #3 is fulffiled, the trend is true
               Print("  Up the conditions of Downtrend verity are fulfilled ");
               // memorize the values of variables for drawing the TD_Down line
                TDu1=TD_up[1];  // price of the 1-st point
                T_u1=time_up_1; // time of the 1-st point
                TDu2=TD_up[2];  // price of the 2-nd point
                T_u2=time_up_2; // price of the 2-nd point
                TrendDownBuffer[index_up_1]=TDu1+5*Point;// put the down arrow

Agora vamos preencher o estoque (buffer) com 10 valores da linha de tendência para a esquerda do segundo ponto de verificação:

                // prices of 10 bars of the trend line to the left of TD-point
                for(int k=index_up_2;k<index_up_2+10;k++) 
                TrendLineBufferDown[k]=Pr_Tr_up_0+k*V_up;
                Print("  exit from the cycle of searching, because 2 TD-points are found");   
                break;      
                }

Insira as chaves ausentes.

               } 
              } 
             }  
            } 
//==================================================================================+

Se a condição de veracidade for satisfeita, a linha de tendência será desenhada para a esquerda do segundo ponto de verificação por 10 barras. Agora essa linha deverá ser desenhada para a direita usando a função ObjectCreate(). Para esse propósito o fim do programa contém um bloco de desenhos de linhas de tendência.

Neste bloco, os dois primeiros operadores controlam a espessura da linha TD (STYLE_SOLID) envolvendo a única linha de tendência neste estágio. Desenhamos a linha descendente e saímos do ciclo de pesquisa dos picos para pontos TD, excluindo preliminarmente a linha anterior existente.

Usando a razão mencionada acima, escrevemos o código para a linha ascendente.

//==================================================================================+
   // for Min points (troughs)   
   for(int j=2;j<48;j++) // 48 hours - 2 days  // j- index of the bar to be checked
    { 
     // let's check the conditon #1 (the price of the bar must be lower than the prices of the left and the right bars) 
     if(Low[j]<Low[j+1]&&Low[j]<Low[j-1])
      {
       // let's check the condition #2 (The supporting price Minimum must be lower than
       // the close price of the bar beyond two bars before the registration <to the left of Min>)
       if(Low[j]<Close[j+2])
        { 
         D++;  // the counter of coincidences of the 1-st and the 2-nd conditions
         if(D==1)
          { 
           TD_down[1]=Low[j]; 
           index_down_1=j;
           Pr_down_Cl_1=Close[j-1]; 
           time_down_1=iTime(NULL,0,j);
           
           Time_down_1=TimeToStr(time_down_1,TIME_DATE|TIME_MINUTES);            
           Print(" D price of the First check point ",TD_down[1]," ; index ",index_down_1,
           " ; Close to the right ",Pr_down_Cl_1,"  ; ",Time_down_1);           
           } 
           if(D==2)
            { 
             TD_down[2]=Low[j]; 
             index_down_2=j; 
             time_down_2=iTime(NULL,0,j);
             
             Time_down_2=TimeToStr(time_down_2,TIME_DATE|TIME_MINUTES);
             Print(" D price of the Second check point ",TD_down[2]," index ",index_down_2,
                   "  time ",Time_down_2);             
             // the condition of the rising trend (the right Min point must be higher than the left one)
             if((D==2 && TD_down[1]>TD_down[2])==false)
              {
                 Print(" D The conditions of the Rising trend are not fulfilled! "); 
                 D--;   TD_down[2]=0.0;  continue; 
                 } 
                else 
            { 
             Print(" D the conditions of the Rising trend are fulfilled");            
             // the calculation of the speed of TD_min rising by two discovered points
             V_down=(TD_down[1]-TD_down[2])/(index_down_2-index_down_1);
             // the calculated value of the line on the 1-st bar to the right of Min
             Pr_Tr_down_1=TD_down[1]+V_down;
             } 
             // let's check the condition #3 (for the last (to the right) price minimum,
             // the close price of the next bar must be higher than the calculated value
             // of the speed of TD-line rising).
             if((Pr_down_Cl_1> Pr_Tr_down_1)==false)
              {
                i=index_down_1+1; TD_down[1]=0.0; TD_down[2]=0.0; time_down_1=0; 
                time_down_2=0; index_down_1=50; index_down_2=50; D=0; continue;
                }
             else
              { // the condition #3 is fulfilled, the trend is true
               Print("  D the conditions of Rising trend verity are fulfilled ");
               TDd1=TD_down[1]; 
               T_d1=time_down_1; 
               TDd2=TD_down[2];  
               T_d2=time_down_2;
               // the calculated price of the trend line on the "0" bar
               Pr_Tr_down_0=TD_down[1]+(index_down_1*V_down); 
               TrendUpBuffer[index_down_1]=TDd2-2*Point; // put the up arrow
               // the price of 10 bars of the trend line to the right of the Second check point
               for(int n=index_down_2;n<index_down_2+10;n++)
                TrendLineBufferUp[n]=Pr_Tr_down_0-n*V_down;
               Print("  D exit the cycle of searching, because two TD-points are found ");
               break;                   
               } 
              } 
             } 
            } 
           } 
          }
// ----------------------------------------------------------------------------+ 

O bloco de desenho das linhas de tendência é desenvolvido de modo que a linha TD mais nova seja desenhada com a linha sólida em negrito (STYLE_SOLID), e a linha anterior a ela mas com a direção oposta é desenhada com uma linha fina pontilhada (STYLE_DOT).

Pode ocorrer uma situação onde a tendência segue uma direção por um longo período. Nisso, o segundo ponto TD da tendência contrária não será encontrado e os valores intermediários do preço, tempo e índice serão escritos nas variáveis. Para fazer esses valores intermediários não afetarem o desenho da linha de tendência, você deve inserir o filtro das condições de desenho da linha: por exemplo, se a segunda linha TD não for encontrada, o valor do preço será definido para "0", e ao mesmo tempo, o valor do índice do primeiro ponto será fixo, e se esse valor aparecer como sendo menor do que o valor do primeiro ponto TD da linha na direção oposta, então a última linha de tendência que possui os parâmetros verdadeiros pode ser desenhada com o outro estilo e cor. É por isso que o filtro de tempo é especificado. Olhe o arquivo em anexo.

// ----------------------------------------------------------------------------+
// the drawing of the trend lines to the right of the Second check point
// ----------------------------------------------------------------------------+
    if(TDd2==0.0)   index_down_1=50;
    if(TDu2==0.0)   index_up_1=50;
     else
    {    
    Print("  TDd2 = ",TDd2,"   index_up_1 = ",index_up_1,"  >  index_down_1 = ",index_down_1);
     Print("  Up We draw the Descending one and exit from the cycle of searching the peaks for the TD-points");
       DelObj1(); // preliminary deleting the previously existed line
        ObjectCreate("TrDdown",OBJ_TREND,0,T_u2,TDu2,T_u1,TDu1); 
     if(index_up_1>index_down_1) 
      {           // the previous direction of the trend is drawn with:
       ObjectSet("TrDdown",OBJPROP_COLOR,Yellow);
       ObjectSet("TrDdown",OBJPROP_WIDTH,1);  // thin line and 
       ObjectSet("TrDdown",OBJPROP_STYLE,STYLE_DOT);// dotted line
       }
      else
       {                // the very last direction of the trend is drawn with:
        ObjectSet("TrDdown",OBJPROP_COLOR,Yellow);
        ObjectSet("TrDdown",OBJPROP_WIDTH,2);           // thicker line
        ObjectSet("TrDdown",OBJPROP_STYLE,STYLE_SOLID); // solid line
       }
      }
// -----------------------------
 
     if(TDd2==0.0)   index_down_1=50;
      else
      {
    Print("  TDd1 = ",TDd1,"   index_up_1 = ",index_up_1,"  <  index_down_1 = ",index_down_1);
      Print("  D We draw the Rising one and exit from the cycle of searching the troughs for TD-points");
        DelObj2(); // preliminary deleting the previously existed line
         ObjectCreate("TrDup",OBJ_TREND,0,T_d2,TDd2,T_d1,TDd1); 
       if(index_up_1<index_down_1)
        {   
 
         ObjectSet("TrDup",OBJPROP_COLOR,Yellow); 
         ObjectSet("TrDup",OBJPROP_WIDTH,1); 
        ObjectSet("TrDup",OBJPROP_STYLE,STYLE_DOT);
        }
         else
          {
          ObjectSet("TrDup",OBJPROP_COLOR,Yellow); 
          ObjectSet("TrDup",OBJPROP_WIDTH,2);  
          ObjectSet("TrDup",OBJPROP_STYLE,STYLE_SOLID);
          }
         }
// ----------------------------------------------------------------------------+
   return(0);
  }

Nota: quase todos os operadores "Print(...)" servem para o controle visual da execução do programa, para que possam ser "comentados", os operadores de tipo de string (linha) (TimeToStr()) são também necessários para o controle.


Conclusão

Espero que o indicador sugerido possa não somente ser usado por investidores iniciantes, mas também pelos experientes, tanto para negociações no mercado quanto para análise dos pedidos realizados.

Traduzido do russo pela MetaQuotes Ltd.
Artigo original: https://www.mql5.com/ru/articles/1507

Arquivos anexados |
TL_by_Demark_v6.mq4 (13.44 KB)
Usando o MetaTrader 4 para análise de padrões baseados em tempo Usando o MetaTrader 4 para análise de padrões baseados em tempo
A análise de padrões baseados em tempo pode ser usada no mercado financeiro para determinar o melhor momento para entrar em uma negociação ou momento no qual uma negociação deve ser totalmente evitada. Aqui usamos o MetaTrader 4 para analisar os dados históricos de mercado e produzir resultados otimizados que podem ser úteis para aplicação em sistemas de negociações mecânicas.
Prevendo séries temporais financeiras Prevendo séries temporais financeiras
A previsão de séries temporais financeiras é um elemento necessário de qualquer atividade investigativa. O conceito de investigação por si - investir dinheiro agora para ganhar lucros no futuro - é baseado no conceito de prever o futuro. Portanto, prever séries temporais financeiras delineiam as atividades de toda a indústria de investimento - todas as trocas organizadas e outros sistemas de negociação de segurança.
Especulação confortável Especulação confortável
Esse artigo descreve o método para criar uma ferramenta para a especulação (scalping) confortável. Entretanto, tal abordagem a uma abertura de negócios pode ser aplicada a qualquer negociação.
Mapeamento de equivolumes revisitado Mapeamento de equivolumes revisitado
O artigo trata do método de construir tabelas, onde cada barra consiste de um número igual de ticks.