//±-----------------------------------------------------------------+
//|                                                          MAA.mq5 |
//|                                  Copyright 2024, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//±-----------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property indicator_separate_window
#property indicator_buffers 6
#property indicator_plots   5

// Plot settings for MA difference
#property indicator_label1  "MADiff"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrRed
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1

// Plot settings for Mean + StdDev
#property indicator_label2  "Mean + StdDev"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrGreen
#property indicator_style2  STYLE_DOT
#property indicator_width2  1

// Plot settings for Mean - StdDev
#property indicator_label3  "Mean - StdDev"
#property indicator_type3   DRAW_LINE
#property indicator_color3  clrGreen
#property indicator_style3  STYLE_DOT
#property indicator_width3  1

// Plot settings for Mean + 2StdDev
#property indicator_label4  "Mean + 2StdDev"
#property indicator_type4   DRAW_LINE
#property indicator_color4  clrBlue
#property indicator_style4  STYLE_DASH
#property indicator_width4  1

// Plot settings for Mean - 2StdDev
#property indicator_label5  "Mean - 2StdDev"
#property indicator_type5   DRAW_LINE
#property indicator_color5  clrBlue
#property indicator_style5  STYLE_DASH
#property indicator_width5  1

// Input parameters
input int periodForStats = 20; // Период для расчета mean и stddev
input int periodM1 = 10;
input int periodM5 = 10;
input int periodM15 = 10;
input int periodM30 = 10;
input int periodH1 = 10;
input int periodH4 = 10;
input int periodD1 = 252;
input int periodW1 = 55;
input int periodMN1 = 12;

// Indicator buffers
double MAaBuffer[];
double MADiffBuffer[];
double MeanPlusStdDevBuffer[];
double MeanMinusStdDevBuffer[];
double MeanPlus2StdDevBuffer[];
double MeanMinus2StdDevBuffer[];

// Define periods for different timeframes
int PeriodForTimeframe(ENUM_TIMEFRAMES tf)
  {
   switch(tf)
     {
      case PERIOD_M1   :
         return periodM1;
      case PERIOD_M5   :
         return periodM5;
      case PERIOD_M15  :
         return periodM15;
      case PERIOD_M30  :
         return periodM30;
      case PERIOD_H1   :
         return periodH1;
      case PERIOD_H4   :
         return periodH4;
      case PERIOD_D1   :
         return periodD1;
      case PERIOD_W1   :
         return periodW1;
      case PERIOD_MN1  :
         return periodMN1;
      default          :
         return 14; // Default period
     }
  }

// Current period based on timeframe
int period;

//±-----------------------------------------------------------------+
//| Custom indicator initialization function                        |
//±-----------------------------------------------------------------+
int OnInit()
  {
// Indicator buffers mapping
   SetIndexBuffer(0, MADiffBuffer, INDICATOR_DATA);
   SetIndexBuffer(5, MAaBuffer, INDICATOR_CALCULATIONS);
   SetIndexBuffer(1, MeanPlusStdDevBuffer, INDICATOR_DATA);
   SetIndexBuffer(2, MeanMinusStdDevBuffer, INDICATOR_DATA);
   SetIndexBuffer(3, MeanPlus2StdDevBuffer, INDICATOR_DATA);
   SetIndexBuffer(4, MeanMinus2StdDevBuffer, INDICATOR_DATA);

// Initialization done
   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[])
  {
// Adjust the period dynamically if needed
   period = PeriodForTimeframe(Period());

// Check if there are enough bars for calculation
   if(rates_total < period || rates_total < periodForStats)
      return 0;

// Starting point for calculation
   int start = prev_calculated > 0 ? prev_calculated - 1 : period - 1;

// Calculate moving average and MADiff
   for(int i = start; i < rates_total; i++)
     {
      double sum = 0.0;
      for(int j = 0; j < period; j++)
        {
         sum += close[i - j];
        }
      MAaBuffer[i] = sum / period;
      MADiffBuffer[i] = -((MAaBuffer[i] - close[i]) / close[i]) * 100;
     }

   double stddev = 0.0;
   double mean = 0.0;
   
// Calculate mean and standard deviation for MADiffBuffer
   for(int i = start; i < rates_total; i++)
     {
      if(i >= periodForStats - 1)
        {
         double mean_sum = 0.0;
         double stddev_sum = 0.0;

         // Calculate mean over the periodForStats
         for(int j = 0; j < periodForStats; j++)
           {
            mean_sum += MADiffBuffer[i - j];
           }
         mean = mean_sum / periodForStats;

         // Calculate standard deviation over the periodForStats
         for(int j = 0; j < periodForStats; j++)
           {
            stddev_sum += MathPow(MADiffBuffer[i - j] - mean, 2);
           }
         stddev = MathSqrt(stddev_sum / periodForStats);
        }
     }
     
   for(int i = start; i < rates_total; i++)
     {
      // Populate buffer values
      MeanPlusStdDevBuffer[i] = mean + stddev;
      MeanMinusStdDevBuffer[i] = mean - stddev;
      MeanPlus2StdDevBuffer[i] = mean + 2 * stddev;
      MeanMinus2StdDevBuffer[i] = mean - 2 * stddev;
     }
     
   Comment(StringFormat("Mean: %.5f, StdDev: %.5f, MA Period: %d, Stats Period: %d", mean, stddev, period, periodForStats));

// Return value of prev_calculated for next call
   return rates_total;
  }
//±-----------------------------------------------------------------+
//+------------------------------------------------------------------+
 нужно что бы MeanPlusStdDevBuffer и дугие линии отображались только по последним расчетам