Putting two colors buffer calculation problems

 

Hi ! I'm building an indicator based on an existing tradingview indicator and I want to put two colors on the indicator one is red and the other is green. Green will be when there will be buy signal and red is when there will be sell signal. 


Indicator 

The indicator consist of a mixing of the MACD with a bollinger band.


Steps

So I watched an article about putting two colors on an indicator where in the exemple they used the rsi indicators and they were able to paint a mix of random blue colors where there would be possibility of 50 index colors. In my program I want two colors only red and green. My indicator consist of MACD with a bollinger band. And I'm stuck at the stage of the MACD to put the two colors. I kind of follow the same tutorial as the RSI exemple but sometimes it just isn't drawing the line or the line is drawing on lower timeframe like h1 and still it's not working perfectly I separed my code in two files one where there's the MACD with one color and the other where I want to put two colors. 

Source code of two files 

AK Macd Comparison.mq5

//+------------------------------------------------------------------+

//|                                                         MACD.mq5 |

//|                   Copyright 2009-2020, MetaQuotes Software Corp. |

//|                                              http://www.mql5.com |

//+------------------------------------------------------------------+

#property copyright   "2009-2020, MetaQuotes Software Corp."

#property link        "http://www.mql5.com"

#property description "Moving Average Convergence/Divergence"

#include <MovingAverages.mqh>

//--- indicator settings

#property indicator_separate_window

#property indicator_buffers 5

#property indicator_plots   2

#property indicator_type1   DRAW_COLOR_LINE

#property indicator_color1  clrGreen

#property indicator_color2  clrLightBlue

#property indicator_width1  2

#property indicator_width2  1

#property indicator_label1  "MACD"

#property indicator_label2  "Signal"

//--- input parameters

input int                InpFastEMA=12;               // Fast EMA period

input int                InpSlowEMA=26;               // Slow EMA period

input int                InpSignalSMA=9;              // Signal SMA period

input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // Applied price

//--- indicator buffers

double ExtMacdBuffer[];

double ExtMACDBufferColor[];

double ExtSignalBuffer[];

double ExtFastMaBuffer[];

double ExtSlowMaBuffer[];



int    ExtFastMaHandle;

int    ExtSlowMaHandle;

//+------------------------------------------------------------------+

//| Custom indicator initialization function                         |

//+------------------------------------------------------------------+



void setPlotColor(int plot)

{

   PlotIndexSetInteger(plot,PLOT_COLOR_INDEXES,50); //Set number of colors

   

   for(int i=0;i<=24;i++)

   {

      PlotIndexSetInteger(plot,PLOT_LINE_COLOR,i,StringToColor("\"0,175,"+IntegerToString(i*7)+"\""));

   }

   

   for(int i=0; i<=24;i++)

   {

      PlotIndexSetInteger(plot,PLOT_LINE_COLOR,i+25,StringToColor("\"0,"+IntegerToString(175-i*7)+",175\""));

   }



}





int getPlotColor(double current,double min,double max)

{

   return ((int)NormalizeDouble((50/(max-min))*current, 0));

}



void OnInit()

  {

//--- indicator buffers mapping

   SetIndexBuffer(0,ExtMacdBuffer,INDICATOR_DATA);

   SetIndexBuffer(1,ExtMACDBufferColor,INDICATOR_COLOR_INDEX);

   SetIndexBuffer(2,ExtSignalBuffer,INDICATOR_DATA);

   SetIndexBuffer(3,ExtFastMaBuffer,INDICATOR_CALCULATIONS);

   SetIndexBuffer(4,ExtSlowMaBuffer,INDICATOR_CALCULATIONS);



   //Set colors

   setPlotColor(0);

   ////////////////////////////////////////////////////////



  

   //--- set accuracy

   IndicatorSetInteger(INDICATOR_DIGITS,2);

   //--- sets first bar from what index will be drawn

   PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,InpSignalSMA-1);

//--- name for indicator subwindow label

   string short_name=StringFormat("MACD(%d,%d,%d)",InpFastEMA,InpSlowEMA,InpSignalSMA);

   IndicatorSetString(INDICATOR_SHORTNAME,short_name);

//--- get MA handles

   ExtFastMaHandle=iMA(NULL,0,InpFastEMA,0,MODE_EMA,InpAppliedPrice);

   ExtSlowMaHandle=iMA(NULL,0,InpSlowEMA,0,MODE_EMA,InpAppliedPrice);

  }

  

//+------------------------------------------------------------------+

//| get color index                                                  |

//+------------------------------------------------------------------+

int getIndexOfColor(int i)

  {

   int j=i%200;

   if(j<100) return(0);// first index

   return(1); // second index

  } 

  

//+------------------------------------------------------------------+

//| Moving Averages Convergence/Divergence                           |

//+------------------------------------------------------------------+

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;

  

   if(rates_total<InpSignalSMA)

      return(0);

//--- not all data may be calculated

   int calculated=BarsCalculated(ExtFastMaHandle);

   if(calculated<rates_total)

     {

      Print("Not all data of ExtFastMaHandle is calculated (",calculated," bars). Error ",GetLastError());

      return(0);

     }

   calculated=BarsCalculated(ExtSlowMaHandle);

   if(calculated<rates_total)

     {

      Print("Not all data of ExtSlowMaHandle is calculated (",calculated," bars). Error ",GetLastError());

      return(0);

     }

//--- we can copy not all data

   int to_copy;

   if(prev_calculated>rates_total || prev_calculated<0)

      to_copy=rates_total;

   else

     {

      to_copy=rates_total-prev_calculated;

      if(prev_calculated>0)

         to_copy++;

     }

//--- get Fast EMA buffer

   if(IsStopped()) // checking for stop flag

      return(0);

   if(CopyBuffer(ExtFastMaHandle,0,0,to_copy,ExtFastMaBuffer)<=0)

     {

      Print("Getting fast EMA is failed! Error ",GetLastError());

      return(0);

     }

//--- get SlowSMA buffer

   if(IsStopped()) // checking for stop flag

      return(0);

   if(CopyBuffer(ExtSlowMaHandle,0,0,to_copy,ExtSlowMaBuffer)<=0)

     {

      Print("Getting slow SMA is failed! Error ",GetLastError());

      return(0);

     }

//---

   int start;

   if(prev_calculated==0)

      start=0;

   else

      start=prev_calculated-1;

//--- calculate MACD

   for(int i=start; i<rates_total && !IsStopped(); i++)

      ExtMacdBuffer[i]=ExtFastMaBuffer[i]-ExtSlowMaBuffer[i];

      ExtMACDBufferColor[i] = getPlotColor(ExtMACDBufferColor[i],0,100);



//--- calculate Signal

   SimpleMAOnBuffer(rates_total,prev_calculated,0,InpSignalSMA,ExtMacdBuffer,ExtSignalBuffer);

//--- OnCalculate done. Return new prev_calculated.

   return(rates_total);

  }

//+------------------------------------------------------------------+

AK Macd.mq5

//+------------------------------------------------------------------+

//|                                                         MACD.mq5 |

//|                   Copyright 2009-2020, MetaQuotes Software Corp. |

//|                                              http://www.mql5.com |

//+------------------------------------------------------------------+

#property copyright   "2009-2020, MetaQuotes Software Corp."

#property link        "http://www.mql5.com"

#property description "Moving Average Convergence/Divergence"

#include <MovingAverages.mqh>

//--- indicator settings

#property indicator_separate_window

#property indicator_buffers 5

#property indicator_plots   2

#property indicator_type1   DRAW_LINE

#property indicator_type2   DRAW_LINE

#property indicator_color1  clrGreen, clrRed

#property indicator_width1  2

#property indicator_width2  1

#property indicator_label1  "MACD"

#property indicator_label2  "Signal"

//--- input parameters

input int                InpFastEMA=12;               // Fast EMA period

input int                InpSlowEMA=26;               // Slow EMA period

input int                InpSignalSMA=9;              // Signal SMA period

input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // Applied price

//--- indicator buffers

double ExtMacdBuffer[];

double ExtMACDBufferColor[];

double ExtSignalBuffer[];

double ExtFastMaBuffer[];

double ExtSlowMaBuffer[];



int    ExtFastMaHandle;

int    ExtSlowMaHandle;

//+------------------------------------------------------------------+

//| Custom indicator initialization function                         |

//+------------------------------------------------------------------+

void OnInit()

  {

//--- indicator buffers mapping

   SetIndexBuffer(0,ExtMacdBuffer,INDICATOR_DATA);

   SetIndexBuffer(1,ExtSignalBuffer,INDICATOR_DATA);

   SetIndexBuffer(2,ExtFastMaBuffer,INDICATOR_CALCULATIONS);

   SetIndexBuffer(3,ExtSlowMaBuffer,INDICATOR_CALCULATIONS);

//--- sets first bar from what index will be drawn

   PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,InpSignalSMA-1);

//--- name for indicator subwindow label

   string short_name=StringFormat("MACD(%d,%d,%d)",InpFastEMA,InpSlowEMA,InpSignalSMA);

   IndicatorSetString(INDICATOR_SHORTNAME,short_name);

//--- get MA handles

   ExtFastMaHandle=iMA(NULL,0,InpFastEMA,0,MODE_EMA,InpAppliedPrice);

   ExtSlowMaHandle=iMA(NULL,0,InpSlowEMA,0,MODE_EMA,InpAppliedPrice);

  }

//+------------------------------------------------------------------+

//| Moving Averages Convergence/Divergence                           |

//+------------------------------------------------------------------+

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

  {

   if(rates_total<InpSignalSMA)

      return(0);

//--- not all data may be calculated

   int calculated=BarsCalculated(ExtFastMaHandle);

   if(calculated<rates_total)

     {

      Print("Not all data of ExtFastMaHandle is calculated (",calculated," bars). Error ",GetLastError());

      return(0);

     }

   calculated=BarsCalculated(ExtSlowMaHandle);

   if(calculated<rates_total)

     {

      Print("Not all data of ExtSlowMaHandle is calculated (",calculated," bars). Error ",GetLastError());

      return(0);

     }

//--- we can copy not all data

   int to_copy;

   if(prev_calculated>rates_total || prev_calculated<0)

      to_copy=rates_total;

   else

     {

      to_copy=rates_total-prev_calculated;

      if(prev_calculated>0)

         to_copy++;

     }

//--- get Fast EMA buffer

   if(IsStopped()) // checking for stop flag

      return(0);

   if(CopyBuffer(ExtFastMaHandle,0,0,to_copy,ExtFastMaBuffer)<=0)

     {

      Print("Getting fast EMA is failed! Error ",GetLastError());

      return(0);

     }

//--- get SlowSMA buffer

   if(IsStopped()) // checking for stop flag

      return(0);

   if(CopyBuffer(ExtSlowMaHandle,0,0,to_copy,ExtSlowMaBuffer)<=0)

     {

      Print("Getting slow SMA is failed! Error ",GetLastError());

      return(0);

     }

//---

   int start;

   if(prev_calculated==0)

      start=0;

   else

      start=prev_calculated-1;

//--- calculate MACD

   for(int i=start; i<rates_total && !IsStopped(); i++)

      ExtMacdBuffer[i]=ExtFastMaBuffer[i]-ExtSlowMaBuffer[i];

      

//--- calculate Signal

   SimpleMAOnBuffer(rates_total,prev_calculated,0,InpSignalSMA,ExtMacdBuffer,ExtSignalBuffer);

//--- OnCalculate done. Return new prev_calculated.

   return(rates_total);

  }

//+------------------------------------------------------------------+


Conclusion

Sorry I'm a beginner in this language and I don't seem to understand the logic behind building indicators any help will be greatly appreciated. Yesterday I was able to put two colors red and green but when I compared with the default MACD sometimes the line was shifted compared to the default macd but that's not what I want it seems like when I'm adding a buffer in the program the compiler has to make additional calculation which screw the actual results or I don't know what's the issue


Открой новые возможности в MetaTrader 5 с сообществом и сервисами MQL5
Открой новые возможности в MetaTrader 5 с сообществом и сервисами MQL5
  • 2022.12.30
  • www.mql5.com
MQL5: язык торговых стратегий для MetaTrader 5, позволяет писать собственные торговые роботы, технические индикаторы, скрипты и библиотеки функций
Files:
 

Please edit your post to place a code by using the CODE button (Alt-S)!

Use the CODE button

 

If you use the search feature here: https://www.mql5.com/en/search#!keyword=multicolor&module=mql5_module_articles

with multicolor and select Articles you'll find several examples which you can us as templates ....

 

@Carl Schreiber

That's not the point my point is that when I compare the two colored indicators some values are completely shifted from their current position compared to the indicators who has the same color all the time

 

@Carl Schreiber


From my understanding it's the logic of my code that execute the problem that cause the issue of the data to have problems because my problems are definitely buffers calculations

 
Alexis Autotte #: From my understanding it's the logic of my code that execute the problem that cause the issue of the data to have problems because my problems are definitely buffers calculations

If you want a proper answer then please fix your post.

Edit it (don't create a new post) and place your code properly (with "</>" or Alt-S), or just attach the original file directly with "+ Attach".

 

@Fernando Carreiro

Done you can now clearly see my code

 
Alexis Autotte #: @Fernando Carreiro Done you can now clearly see my code

I'm confused! Which of the two files is your attempt at coding MACD with Bollinger (or dual colour MACD)?

 
It's the 

AK Macd Comparison.mq5 

 
From my understanding when I hover some of the point of the MACD without the dual color and come back to my dual MACD color it seems like the tooltip display the correct data but somehow the line doesn't render as I want
 
Alexis Autotte #: It's the AK Macd Comparison.mq5 

I've removed stuff from your code that was unnecessary and also to simplify the answer. I've highlighted the important parts ...

 

//+------------------------------------------------------------------+
//|                                                         MACD.mq5 |
//|                   Copyright 2009-2020, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright   "2009-2020, MetaQuotes Software Corp."
#property link        "http://www.mql5.com"
#property description "Moving Average Convergence/Divergence"
#include <MovingAverages.mqh>
//--- indicator settings
#property indicator_separate_window
#property indicator_buffers 5
#property indicator_plots   2
#property indicator_type1   DRAW_COLOR_LINE
#property indicator_color1  clrGreen, clrRed
#property indicator_color2  clrLightBlue
#property indicator_width1  2
#property indicator_width2  1
#property indicator_label1  "MACD"
#property indicator_label2  "Signal"
//--- input parameters
input int                InpFastEMA=12;               // Fast EMA period
input int                InpSlowEMA=26;               // Slow EMA period
input int                InpSignalSMA=9;              // Signal SMA period
input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // Applied price
//--- indicator buffers
double ExtMacdBuffer[];
double ExtMACDBufferColor[];
double ExtSignalBuffer[];
double ExtFastMaBuffer[];
double ExtSlowMaBuffer[];

int    ExtFastMaHandle;
int    ExtSlowMaHandle;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+

void OnInit()
  {
//--- indicator buffers mapping
   SetIndexBuffer(0,ExtMacdBuffer,INDICATOR_DATA);
   SetIndexBuffer(1,ExtMACDBufferColor,INDICATOR_COLOR_INDEX);
   SetIndexBuffer(2,ExtSignalBuffer,INDICATOR_DATA);
   SetIndexBuffer(3,ExtFastMaBuffer,INDICATOR_CALCULATIONS);
   SetIndexBuffer(4,ExtSlowMaBuffer,INDICATOR_CALCULATIONS);

   //--- set accuracy
   IndicatorSetInteger(INDICATOR_DIGITS,2);
   //--- sets first bar from what index will be drawn
   PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,InpSignalSMA-1);
//--- name for indicator subwindow label
   string short_name=StringFormat("MACD(%d,%d,%d)",InpFastEMA,InpSlowEMA,InpSignalSMA);
   IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- get MA handles
   ExtFastMaHandle=iMA(NULL,0,InpFastEMA,0,MODE_EMA,InpAppliedPrice);
   ExtSlowMaHandle=iMA(NULL,0,InpSlowEMA,0,MODE_EMA,InpAppliedPrice);
  }
  
//+------------------------------------------------------------------+
//| Moving Averages Convergence/Divergence                           |
//+------------------------------------------------------------------+
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[])
  {
   if(rates_total<InpSignalSMA)
      return(0);
//--- not all data may be calculated
   int calculated=BarsCalculated(ExtFastMaHandle);
   if(calculated<rates_total)
     {
      Print("Not all data of ExtFastMaHandle is calculated (",calculated," bars). Error ",GetLastError());
      return(0);
     }
   calculated=BarsCalculated(ExtSlowMaHandle);
   if(calculated<rates_total)
     {
      Print("Not all data of ExtSlowMaHandle is calculated (",calculated," bars). Error ",GetLastError());
      return(0);
     }
//--- we can copy not all data
   int to_copy;
   if(prev_calculated>rates_total || prev_calculated<0)
      to_copy=rates_total;
   else
     {
      to_copy=rates_total-prev_calculated;
      if(prev_calculated>0)
         to_copy++;
     }
//--- get Fast EMA buffer
   if(IsStopped()) // checking for stop flag
      return(0);
   if(CopyBuffer(ExtFastMaHandle,0,0,to_copy,ExtFastMaBuffer)<=0)
     {
      Print("Getting fast EMA is failed! Error ",GetLastError());
      return(0);
     }
//--- get SlowSMA buffer
   if(IsStopped()) // checking for stop flag
      return(0);
   if(CopyBuffer(ExtSlowMaHandle,0,0,to_copy,ExtSlowMaBuffer)<=0)
     {
      Print("Getting slow SMA is failed! Error ",GetLastError());
      return(0);
     }
//---
   int start;
   if(prev_calculated==0)
      start=0;
   else
      start=prev_calculated-1;
//--- calculate MACD
   for(int i=start; i<rates_total && !IsStopped(); i++)
   {
      ExtMacdBuffer[i]=ExtFastMaBuffer[i]-ExtSlowMaBuffer[i];
      ExtMACDBufferColor[i] = ExtMacdBuffer[i] >= 0.0 ? 0 : 1;
   }

//--- calculate Signal
   SimpleMAOnBuffer(rates_total,prev_calculated,0,InpSignalSMA,ExtMacdBuffer,ExtSignalBuffer);
//--- OnCalculate done. Return new prev_calculated.
   return(rates_total);
  }
//+------------------------------------------------------------------+
Reason: