Perguntas de Iniciantes MQL4 MT4 MetaTrader 4 - página 223

 

Tento preencher o buffer indicador da outra ponta (ArraySetAsSeries (..., falso)), tudo funciona bem por um tempo, mas depois algo acontece com o buffer e o último índice do array é preenchido, embora não deva ser.
Acho que, em algum momento, o terminal prende o buffer e o peso do buffer é preenchido mesmo com o último índice da matriz. Talvez o buffer da matriz deva ser liberado em algum momento, mas quando? Você pode corrigir o exemplo de teste?


#property indicator_buffers 1

double ExtMapBuffer[]; // AQUA   "Line"
int      LastData;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping

   SetIndexBuffer(0,ExtMapBuffer);
   SetIndexStyle(0,DRAW_LINE,STYLE_SOLID,7,clrAqua);
   SetIndexEmptyValue(0,0.0);
   SetIndexLabel(0,"Line");

   LastData=0;
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---
   int    i;
   bool Series=false;
   ArraySetAsSeries(ExtMapBuffer,Series);
   ArraySetAsSeries(high,Series);

   i=prev_calculated-1;

   if(i<1) 
     {
      LastData=0;
      i=1;
      while(i<rates_total-1)
        {
         ExtMapBuffer[i]=high[i];
         i++; 
         LastData=i;
        }
     }
   else
     {
      i=LastData;
     }

   while(i<rates_total-1)
     {
      ExtMapBuffer[i]=high[i];
      i++;
      LastData=i;
     }

   return(rates_total);
  }
//+------------------------------------------------------------------+
 

Olá.

Você pode me dizer por que este indicador raramente desenha setas no histórico, mas quando você começa a comercializar ele começa a desenhar com freqüência.

Então, se você fechar o MT4 e abri-lo novamente, então no mesmo lugar onde em tempo real o indicador como uma metralhadora fez negócios, é novamente 1-2 negócios.

Quando olho para a história, parece que o indicador deve negociar bem, mas assim que eu mudo para o comércio em tempo real eu recebo todo tipo de coisas estranhas.

Por favor, explique por quê? Aqui está o código de indicador:

//---- indicator settings
#property  indicator_chart_window
#property  indicator_buffers 2
#property  indicator_color1  Blue
#property  indicator_color2  Red
//---- indicator parameters
extern int  period = 4; //12
extern int  shift  = 0; //сдвиг по бару
//---- indicator buffers
double BufferUp[],BufferDn[];
int q,st=5;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
   IndicatorBuffers(2);
//---- drawing settings
   SetIndexStyle(0,DRAW_ARROW,2);
   SetIndexArrow(0,233);
   SetIndexStyle(1,DRAW_ARROW,2);
   SetIndexArrow(1,234);

   SetIndexBuffer(0,BufferUp);//стрелка синяя верх
   SetIndexBuffer(1,BufferDn);//стрелка красная вниз
//---- name for DataWindow and indicator subwindow label
   IndicatorShortName("T3MA-ALARM ("+period+")");
//---- initialization done
   if(Digits==3 || Digits==5) q=10;
   st=st*q;
   return(0);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int deinit()
  {
   ObjectDelete("low");
   ObjectDelete("high");
  }
//+----------------------------------------------------------------------+
//| Moving Average of Oscillator                                         |
//+----------------------------------------------------------------------+
int start()
  {
//---- ArraySetAsSeries --------------------------------------------------  
   double Ma[],MaOn[];
   double y0[],y1[],y2[];
//   int i;
   int    i;
   ArraySetAsSeries(Ma,true);
//---- IndicatorCounted --------------------------------------------------
   int counted_bars=IndicatorCounted();
   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
   int limit1=Bars-counted_bars;
   if(counted_bars==0) limit1-=1+MathMax(period,shift)+2;

   int buffer_size=ArraySize(BufferUp);
   ArrayResize(Ma,buffer_size);
   ArrayResize(MaOn,buffer_size);

   ArrayResize(y0,buffer_size+shift+2);
   ArrayResize(y1,buffer_size+shift+2);
   ArrayResize(y2,buffer_size+shift+2);

   int limit=ArraySize(Ma);
//---- EMA --------------------------------------------------------------- 
   for(i=limit1; i>=0; i--)  Ma[i]  =iMA(NULL,0,period,0,MODE_EMA,PRICE_CLOSE,i);
   for(i=limit1; i>=0; i--)  MaOn[i]=iMAOnArray(Ma,limit,period,0,MODE_EMA,i);

   for(i=limit1; i>=0; i--)
     {
      y0[i+shift]=MaOn[i+shift];
      y1[i+1+shift]=MaOn[i+1+shift];
      y2[i+2+shift]=MaOn[i+2+shift];

      if(y0[i+shift]-y1[i+1+shift]<0 && y1[i+1+shift]-y2[i+2+shift]>0){BufferDn[i+1]=High[i+1]+st*Point;}
      if(y0[i+shift]-y1[i+1+shift]>0 && y1[i+1+shift]-y2[i+2+shift]<0){BufferUp[i+1]=Low[i+1]-st*Point;}
      //---- Signal Trend Up || Dn ---------------------------------------------   
      if(y0[i]-y1[i+1]>0) Comment("\n SWAPLONG = ",MarketInfo(Symbol(),MODE_SWAPLONG),
         "   SWAPSHORT = ",MarketInfo(Symbol(),MODE_SWAPSHORT),"\n BUY TREND ",DoubleToStr(Close[i],Digits));

      else if(y0[i]-y1[i+1]<0) Comment("\n SWAPLONG = ",MarketInfo(Symbol(),MODE_SWAPLONG),
         "   SWAPSHORT = ",MarketInfo(Symbol(),MODE_SWAPSHORT),"\n SELL TREND ",DoubleToStr(Close[i],Digits));
     }

//---- done
   return(0);
  }
//+---------------------------------------------------------------------+
Документация по MQL5: Константы, перечисления и структуры / Константы индикаторов / Стили рисования
Документация по MQL5: Константы, перечисления и структуры / Константы индикаторов / Стили рисования
  • www.mql5.com
При создании пользовательского индикатора можно указать один из 18 типов графического построения (способа отображения на главном окне графика или в подокне графика), значения которых указаны в перечислении ENUM_DRAW_TYPE. В зависимости от стиля рисования, может потребоваться от одного до четырех буферов значений (отмеченных как INDICATOR_DATA...
 

tente substituir 0 por 1 em cada 3 lugares

   int limit=ArraySize(Ma);
//---- EMA --------------------------------------------------------------- 
   for(i=limit1; i>=1; i--)  Ma[i]  =iMA(NULL,0,period,0,MODE_EMA,PRICE_CLOSE,i);
   for(i=limit1; i>=1; i--)  MaOn[i]=iMAOnArray(Ma,limit,period,0,MODE_EMA,i);

   for(i=limit1; i>=1; i--)
 
Aleksei Stepanenko:

tente substituir 0 por 1 em cada 3 lugares

   int limit=ArraySize(Ma);
//---- EMA --------------------------------------------------------------- 
   for(i=limit1; i>=1; i--)  Ma[i]  =iMA(NULL,0,period,0,MODE_EMA,PRICE_CLOSE,i);
        // вот сюда
   for(i=limit1; i>=1; i--)  MaOn[i]=iMAOnArray(Ma,limit,period,0,MODE_EMA,i);

   for(i=limit1; i>=1; i--)

Eu também moveria isto

 
Vitaly, eu notei que as pessoas escreverão uma pergunta e se dedicarão a seus negócios, enquanto nós nos divertimos uns com os outros. Às vezes, há várias páginas de trechos.
 
Aleksei Stepanenko:

tente substituir 0 por 1 em cada 3 lugares

Muito obrigado. Agora, como faço para que eu abra negócios somente no final da vela atual, no período de tempo atual? :)) Não sei quando abre negócios agora... As setas parecem estar certas e, olhando para os castiçais, tudo está bem, mas os negócios parecem ser abertos no meio ou perto do fim da vela, em geral, em todos os lugares, mas não onde é necessário. :(

//---- indicator settings
#property  indicator_chart_window
#property  indicator_buffers 2
#property  indicator_color1  Blue
#property  indicator_color2  Red
//---- indicator parameters
extern int  period = 4; //12
extern int  shift  = 0; //сдвиг по бару
//---- indicator buffers
double BufferUp[],BufferDn[];
int q,st=5;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
   IndicatorBuffers(2);
//---- drawing settings
   SetIndexStyle(0,DRAW_ARROW,2);
   SetIndexArrow(0,233);
   SetIndexStyle(1,DRAW_ARROW,2);
   SetIndexArrow(1,234);

   SetIndexBuffer(0,BufferUp);//стрелка синяя верх
   SetIndexBuffer(1,BufferDn);//стрелка красная вниз
//---- name for DataWindow and indicator subwindow label
   IndicatorShortName("T3MA-ALARM ("+period+")");
//---- initialization done
   if(Digits==3 || Digits==5) q=10;
   st=st*q;
   return(0);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int deinit()
  {
   ObjectDelete("low");
   ObjectDelete("high");
  }
//+----------------------------------------------------------------------+
//| Moving Average of Oscillator                                         |
//+----------------------------------------------------------------------+
int start()
  {
//---- ArraySetAsSeries --------------------------------------------------  
   double Ma[],MaOn[];
   double y0[],y1[],y2[];
//   int i;
   int    i;
   ArraySetAsSeries(Ma,true);
//---- IndicatorCounted --------------------------------------------------
   int counted_bars=IndicatorCounted();
   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
   int limit1=Bars-counted_bars;
   if(counted_bars==0) limit1-=1+MathMax(period,shift)+2;

   int buffer_size=ArraySize(BufferUp);
   ArrayResize(Ma,buffer_size);
   ArrayResize(MaOn,buffer_size);

   ArrayResize(y0,buffer_size+shift+2);
   ArrayResize(y1,buffer_size+shift+2);
   ArrayResize(y2,buffer_size+shift+2);

   int limit=ArraySize(Ma);
//---- EMA --------------------------------------------------------------- 
   for(i=limit1; i>=1; i--)  Ma[i]  =iMA(NULL,0,period,0,MODE_EMA,PRICE_CLOSE,i);
   for(i=limit1; i>=1; i--)  MaOn[i]=iMAOnArray(Ma,limit,period,0,MODE_EMA,i);

   for(i=limit1; i>=1; i--)
     {
      y0[i+shift]=MaOn[i+shift];
      y1[i+1+shift]=MaOn[i+1+shift];
      y2[i+2+shift]=MaOn[i+2+shift];

      if(y0[i+shift]-y1[i+1+shift]<0 && y1[i+1+shift]-y2[i+2+shift]>0){BufferDn[i+1]=High[i+1]+st*Point;}
      if(y0[i+shift]-y1[i+1+shift]>0 && y1[i+1+shift]-y2[i+2+shift]<0){BufferUp[i+1]=Low[i+1]-st*Point;}
      //---- Signal Trend Up || Dn ---------------------------------------------   
      if(y0[i]-y1[i+1]>0) Comment("\n SWAPLONG = ",MarketInfo(Symbol(),MODE_SWAPLONG),
         "   SWAPSHORT = ",MarketInfo(Symbol(),MODE_SWAPSHORT),"\n BUY TREND ",DoubleToStr(Close[i],Digits));

      else if(y0[i]-y1[i+1]<0) Comment("\n SWAPLONG = ",MarketInfo(Symbol(),MODE_SWAPLONG),
         "   SWAPSHORT = ",MarketInfo(Symbol(),MODE_SWAPSHORT),"\n SELL TREND ",DoubleToStr(Close[i],Digits));
     }

//---- done
   return(0);
  }
//+---------------------------------------------------------------------+
 

Em geral, é costume abrir negócios no momento em que uma nova vela é formada, quando já há todas as informações sobre a vela que acabou de ser fechada

datetime LastTime=0;


void OnTick()
   {
   if(LastTime==iTime(symbol,frame,0)) return;
   LastTime=iTime(symbol,frame,0);
 
Vitaly Muzichenko:

Eu também mudaria isto.

Você tem certeza de que foi mostrado lá?

 int limit=ArraySize(Ma);
//---- EMA --------------------------------------------------------------- 
// а не вот сюда?
   for(i=limit1; i>=1; i--)  Ma[i]  =iMA(NULL,0,period,0,MODE_EMA,PRICE_CLOSE,i);
        
   for(i=limit1; i>=1; i--)  MaOn[i]=iMAOnArray(Ma,limit,period,0,MODE_EMA,i);

   for(i=limit1; i>=1; i--)
 
Aleksei Stepanenko:

Em geral, é costume abrir negócios no momento em que uma nova vela é formada, quando já há todas as informações sobre a vela que acabou de ser fechada

Onde devo inserir este código para que ele funcione corretamente? Não entendo muito bem, estou apenas no início da minha viagem...
 
Aleksei Stepanenko:
Vitaly, eu notei que as pessoas escreverão uma pergunta e se dedicarão a seus negócios, enquanto nós nos divertimos uns com os outros. Às vezes, há várias páginas de trechos.
Como você pode ver, nem sempre é assim. :))
Razão: