My code works on init but stops after new bar

 

Why did you post your MT4 question in the MT5 Indicators section instead of the MQL4 section, (bottom of the Root page)?
          General rules and best pratices of the Forum. - General - MQL5 programming forum? (2017)
Next time, post in the correct place. I have moved this thread.

Hi guys im stuck while adding mtf macd value to an indicator.

I tried many ways but cant solve the problem: Indicator works well when init, but stops calculating after new bar.

Without imacd values does not stop after new bar, works well already.

Im trying to get imacd values for 5min timeframe while my chart timeframe 1min

Could someone help me please.

MACD - Oscillators - Technical Indicators - Price Charts, Technical and Fundamental Analysis - MetaTrader 5 Help
MACD - Oscillators - Technical Indicators - Price Charts, Technical and Fundamental Analysis - MetaTrader 5 Help
  • www.metatrader5.com
Moving Average Convergence/Divergence (MACD) is a trend-following dynamic indicator. It indicates the correlation between two Moving Averages of a...
Files:
ut.mq4  14 kb
 
#property copyright "2"
#property version "1.0"
#property strict
#property indicator_chart_window
#property indicator_buffers 6
#property indicator_plots 2
#property indicator_label1 "Arrow Up"
#property indicator_type1  DRAW_ARROW
#property indicator_color1 clrBlue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
#property indicator_label2 "Arrow Down"
#property indicator_type2  DRAW_ARROW
#property indicator_color2 clrRed
#property indicator_style2 STYLE_SOLID
#property indicator_width2 1
#property indicator_type2 DRAW_NONE
//--- indicator buffers
double ArrowUp[];
double ArrowDn[];
double xATRTrailingStop[];
double MainBuffer[];
double SignalBuffer[];
double HistBuffer[];

//--- variables
double nLoss, xATR;

// ------------------------------------------------------------------
input double m          = 2;     // Key value:
input double atrPeriods = 1;    // ATR periods:
input bool   h          = false; // Signals From Heinken Ashi Candles

input string T1                    = "== Notifications =="; // ————————————
input bool   notifications         = false;                 // Notifications On?
input bool   desktop_notifications = false;                 // Desktop MT4 Notifications
input bool   email_notifications   = false;                 // Email Notifications
input bool   push_notifications    = false;                 // Push Mobile Notifications
bool         oneNotifyByCandle     = true;                  // One Notification By Candle?
bool         allowToNotify         = true;
int          minutesBetwenNotify   = 1; // Minutes Betwen Notifications
int          timeNextNotify        = 0;

input string T2         = "== Set Arrows =="; // ————————————
input bool   ArrowsOn   = true;               // Arrows On?
input color  ArrowUpClr = clrNavy;            // Arrow Up Color:
input color  ArrowDnClr = clrCrimson;         // Arrow Down Color:
// ------------------------------------------------------------------

class CNewCandle
{
  private:
    int    _initialCandles;
    string _symbol;
    int    _tf;

  public:
    CNewCandle(string symbol, int tf) : _symbol(symbol), _tf(tf), _initialCandles(iBars(symbol, tf)) {}
    CNewCandle()
    {
        // toma los valores del chart actual
        _initialCandles = iBars(Symbol(), Period());
        _symbol         = Symbol();
        _tf             = Period();
    }
    ~CNewCandle() { ; }

    bool IsNewCandle()
    {
        int _currentCandles = iBars(_symbol, _tf);
        if (_currentCandles > _initialCandles) {
            _initialCandles = _currentCandles;
            return true;
        }

        return false;
    }
};
CNewCandle newCandle();

// ------------------------------------------------------------------
int OnInit()
{
    //--- indicator buffers mapping
    SetIndexBuffer(0, ArrowUp, INDICATOR_DATA);
    SetIndexArrow(0, 233);
    SetIndexStyle(0, DRAW_ARROW, EMPTY, 1, ArrowUpClr);
    SetIndexBuffer(1, ArrowDn, INDICATOR_DATA);
    SetIndexArrow(1, 234);
    SetIndexStyle(1, DRAW_ARROW, EMPTY, 1, ArrowDnClr);
    SetIndexBuffer(2, xATRTrailingStop);
    SetIndexBuffer(3, MainBuffer);
    SetIndexBuffer(4, SignalBuffer);
    SetIndexBuffer(5, HistBuffer);
    SetIndexStyle(2, DRAW_NONE);
    IndicatorDigits(5);

    if (!ArrowsOn) {
        SetIndexStyle(0, DRAW_NONE);
        SetIndexStyle(1, DRAW_NONE);
    }
    //---
    return (INIT_SUCCEEDED);
}
void OnDeinit(const int reason) {}
// ------------------------------------------------------------------

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 = Bars(Symbol(), Period()) / 2;
    datetime TimeArray[];
    if (i >= rates_total)
        i = rates_total - 1;
    ArrayCopySeries(TimeArray,MODE_TIME,Symbol(),5);
    int iTF = i;    
    for (; i >= 0; i--) {
    while(Time[i]>TimeArray[iTF]) iTF--;
    xATR  = iATR(NULL, 0, atrPeriods, i);
    nLoss = m * xATR;

    double cl  = close[i];
    double cl1 = close[i + 1];

    // clang-format off
    xATRTrailingStop[i] = cl > xATRTrailingStop[i + 1] && cl1 > xATRTrailingStop[i + 1] ? fmax(xATRTrailingStop[i + 1], cl - nLoss) : 
      cl < xATRTrailingStop[i + 1] && cl1 < xATRTrailingStop[i + 1] ? fmin(xATRTrailingStop[i + 1], cl + nLoss) : 
cl > xATRTrailingStop[i + 1] ? cl - nLoss : cl + nLoss;
    
bool crossUp = cl > xATRTrailingStop[i] && cl1 < xATRTrailingStop[i+1];
bool crossDn = cl < xATRTrailingStop[i] && cl1 > xATRTrailingStop[i+1];

    ArrowUp[i]= EMPTY_VALUE;
    ArrowDn[i]= EMPTY_VALUE;
    MainBuffer[i]=EMPTY_VALUE;
    SignalBuffer[i]=EMPTY_VALUE;
    HistBuffer[i]=EMPTY_VALUE;
    MainBuffer[i] = iMACD(Symbol(),5,12,26,9,0,0,iTF);
    SignalBuffer[i] = iMACD(Symbol(),5,12,26,9,0,1,iTF);
    HistBuffer[i] = MainBuffer[i]-SignalBuffer[i];
if (cl > xATRTrailingStop[i] && crossUp==true && HistBuffer[i] > 0)
    {
      ArrowUp[i] = low[i] - xATR/2;
    }
    if (cl < xATRTrailingStop[i] && crossDn == true && HistBuffer[i] < 0)
    {
      ArrowDn[i] = high[i] + xATR/2;

    }
  
    
    if(newCandle.IsNewCandle())
    {
        allowToNotify = true;
    }

    if(i == 0){
      if(ArrowUp[i]!= EMPTY_VALUE) { Notifications(0); }
      if(ArrowDn[i]!= EMPTY_VALUE) { Notifications(1); }
    }

  }

  return (rates_total);
}

// ------------------------------------------------------------------

void Notifications(int type)
{
  // time Control
    if(timeNextNotify != 0) if(TimeCurrent() < timeNextNotify) return;
    timeNextNotify = TimeCurrent() + (minutesBetwenNotify * 60);

  if(oneNotifyByCandle) { if(!allowToNotify) return; }

  string text = "";
  if (type == 0)
    text += _Symbol + " " + GetTimeFrame(_Period) + " BUY ";
  else
    text += _Symbol + " " + GetTimeFrame(_Period) + " SELL ";

  text += " ";

  if (!notifications) return;
  if (desktop_notifications) { Alert(text); allowToNotify = false; }
  if (push_notifications){ SendNotification(text); allowToNotify = false; }
  if (email_notifications){ SendMail("MetaTrader Notification", text); allowToNotify = false; }
}

string GetTimeFrame(int lPeriod)
{
  switch (lPeriod)
  {
    case PERIOD_M1:
      return ("M1");
    case PERIOD_M5:
      return ("M5");
    case PERIOD_M15:
      return ("M15");
    case PERIOD_M30:
      return ("M30");
    case PERIOD_H1:
      return ("H1");
    case PERIOD_H4:
      return ("H4");
    case PERIOD_D1:
      return ("D1");
    case PERIOD_W1:
      return ("W1");
    case PERIOD_MN1:
      return ("MN1");
  }
  return IntegerToString(lPeriod);
}
 
// Replace this:
int i = Bars(Symbol(), Period()) / 2;

// With proper initialization:
int limit = rates_total - prev_calculated;
if(prev_calculated > 0) limit++;
i = limit - 1;
You have incorrect array handling in OnCalculate. Your code uses Bars()/2 which becomes invalid when new bars form.