//+------------------------------------------------------------------+
#include <Math\Stat\Normal.mqh>
#include <Math\Stat\Cauchy.mqh>
#include <Math\Stat\Math.mqh>
#include <Graphics\Graphic.mqh>
//+------------------------------------------------------------------+
input datetime t_rates = D'2026.03.20 00:00';
input int n_rates = 70;
input ENUM_TIMEFRAMES tf_rates = PERIOD_D1;
//+------------------------------------------------------------------+
void OnStart()
{ // download quotes
  MqlRates rates[];
  int nres = CopyRates(Symbol(), tf_rates, t_rates, n_rates, rates);
  if (nres < n_rates)
  { Print("Insufficient quotes");
    return;
  }
// find log returns
  double log_returns[];
  ArrayResize(log_returns, n_rates);
  for (int i = 0; i < n_rates; ++i)
    log_returns[i] = MathLog(rates[i].close / rates[i].open);
// calculate the characteristics of the log-return sample (mean, variance, median, interquartile range)
// used to fit theoretical distributions to the sample
  double lr_mean, lr_var, lr_median, lr_iqr;
  lr_mean = MathMean(log_returns);
  lr_var = MathVariance(log_returns);
  lr_median = MathMedian(log_returns);
  double probs[] = {0.25, 0.75}, quarts[2];
  if (!MathQuantile(log_returns, probs, quarts))
  { Print("MathQuantile() error");
    return;
  }
  lr_iqr = quarts[1] - quarts[0];
// QQ-plot graphs for the Cauchy and normal distributions (for comparison, the line y=x)
  double normal_qs[], cauchy_qs[], pseq[];
  ArraySort(log_returns);
  if (!MathSequenceByCount(1.0 / (n_rates + 1.0), 1.0 - 1.0 / (n_rates + 1.0), n_rates, pseq))
  { Print("MathSequenceByCount() error");
    return;
  }
  if (!MathQuantileNormal(pseq, lr_mean, MathSqrt(lr_var), normal_qs))
  { Print("MathQuantileNormal() error");
    return;
  }
  if (!MathQuantileCauchy(pseq, lr_median, 0.5 * lr_iqr, cauchy_qs))
  { Print("MathQuantileCauchy() error");
    return;
  }
  ChartSetInteger(0, CHART_SHOW, false);
  CGraphic graphic;
  graphic.Create(0, "G", 0, 0, 0, 750, 400);
  graphic.CurveAdd(normal_qs, log_returns, CURVE_LINES, "Normal");
  graphic.CurveAdd(cauchy_qs, log_returns, CURVE_LINES, "Cauchy");
  graphic.CurveAdd(log_returns, log_returns, CURVE_LINES, "Y=X");
  graphic.CurvePlotAll();
  graphic.Update();
  MessageBox("Press OK to close QQ-plot graph", "Close graph");
  ChartSetInteger(0, CHART_SHOW, true);
  graphic.Destroy();
}
//+------------------------------------------------------------------+
