Questions from Beginners MQL4 MT4 MetaTrader 4 - page 223

 

I try to fill the indicator buffer from the other end (ArraySetAsSeries (..., false)), everything works fine for a while, but then something happens to the buffer and the very last array index is filled, though it should not be.
I guess, the terminal clips the buffer at some moment and the weight of the buffer is filled even with the last array index. Perhaps, the array buffer should be released at some moment, but when? Can you correct the test example?


#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);
  }
//+------------------------------------------------------------------+
 

Hello.

Can you please tell me why this indicator rarely draws arrows on the history, but when you start trading it starts drawing often.

Then if you close MT4 and open it again, then in the same place where in real time the indicator like a machine gun drew deals, it is again 1-2 deals.

When I look at the history it seems that the indicator should trade well, but as soon as I switch to real-time trading I get all sorts of weird stuff.

Please explain why? Here is the code of indicator:

//---- 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...
 

try replacing 0 with 1 in three places

   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:

try replacing 0 with 1 in three places

   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--)

I'd also move this

 
Vitaly, I've noticed that people will write a question and go about their business, while we have fun with each other. Sometimes there are several pages of excerpts.
 
Aleksei Stepanenko:

try replacing 0 with 1 in three places

Thank you very much. Now how do I get it to open trades only at the end of the current candle on the current timeframe? :)) I don't know when it opens deals now... The arrows seem to be right, and look at the candlesticks, everything is ok, but deals appear to be opened in the middle or near the end of the candle, in general, everywhere, but not where it is needed. :(

//---- 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);
  }
//+---------------------------------------------------------------------+
 

In general, it is customary to open trades at the moment a new candle is formed, when there is already all the information about the candle that has just been closed

datetime LastTime=0;


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

I'd also move this.

Are you sure that's where you were shown?

 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:

In general, it is customary to open trades at the moment a new candle is formed, when all the information about the candle that has just closed is already in place

Where should I insert this code to make it work properly? I do not understand it very well, I am just at the beginning of my journey...
 
Aleksei Stepanenko:
Vitaly, I've noticed that people will write a question and go about their business, while we have fun with each other. Sometimes there are several pages of excerpts.
As you can see, it's not always like that. :))