//+------------------------------------------------------------------+
//|                                                 PlateauCheck.mq5 |
//|                                         Copyright 2026, B. Aliev |
//|  Trap 6: is the best optimization result a plateau or a peak?    |
//|  Input: a CSV file in MQL5\Files with a header line and three    |
//|  columns: Result;Param1;Param2 (save the optimization table from |
//|  the tester to Excel, keep these three columns, save as CSV).    |
//|  For each set the script averages its grid neighbours (up to 8). |
//|  A good set has good neighbours. A lonely peak is luck.          |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, B. Aliev"
#property version   "1.00"
#property script_show_inputs

input string InpFile      = "opt_results.csv"; // File in MQL5\Files
input string InpSeparator = ";";               // Column separator
input int    InpTop       = 10;                // How many best sets to show
input double InpPeakRatio = 0.5;               // Peak if neighbours average < ratio * result

//+------------------------------------------------------------------+
double ToNumber(string s)
  {
   StringTrimLeft(s);
   StringTrimRight(s);
   StringReplace(s, " ", "");
   StringReplace(s, ",", ".");                 // decimal comma from Excel
   return(StringToDouble(s));
  }

//+------------------------------------------------------------------+
int AddUnique(double &arr[], const double v)
  {
   int n = ArraySize(arr);
   for(int i = 0; i < n; i++)
      if(MathAbs(arr[i] - v) < 1e-9)
         return(i);
   ArrayResize(arr, n + 1);
   arr[n] = v;
   return(n);
  }

//+------------------------------------------------------------------+
void OnStart()
  {
   int fh = FileOpen(InpFile, FILE_READ | FILE_TXT | FILE_ANSI);
   if(fh == INVALID_HANDLE)
     {
      Print("Cannot open MQL5\\Files\\", InpFile);
      return;
     }
   ushort sep = StringGetCharacter(InpSeparator, 0);
   double res[], pa[], pb[];
   bool header = true;
   while(!FileIsEnding(fh))
     {
      string line = FileReadString(fh);
      if(header)
        {
         header = false;
         continue;
        }
      string f[];
      if(StringSplit(line, sep, f) < 3)
         continue;
      int n = ArraySize(res);
      ArrayResize(res, n + 1);
      ArrayResize(pa, n + 1);
      ArrayResize(pb, n + 1);
      res[n] = ToNumber(f[0]);
      pa[n] = ToNumber(f[1]);
      pb[n] = ToNumber(f[2]);
     }
   FileClose(fh);
   int n = ArraySize(res);
   if(n == 0)
     {
      Print("No rows read");
      return;
     }
//--- grid coordinates of each row
   double ua[], ub[];
   for(int i = 0; i < n; i++)
     {
      AddUnique(ua, pa[i]);
      AddUnique(ub, pb[i]);
     }
   ArraySort(ua);
   ArraySort(ub);
   int na = ArraySize(ua), nb = ArraySize(ub);
   double grid[];
   bool   has[];
   ArrayResize(grid, na * nb);
   ArrayResize(has, na * nb);
   ArrayInitialize(has, false);
   int ia[], ib[];
   ArrayResize(ia, n);
   ArrayResize(ib, n);
   for(int i = 0; i < n; i++)
     {
      ia[i] = ArrayBsearch(ua, pa[i]);
      ib[i] = ArrayBsearch(ub, pb[i]);
      grid[ia[i] * nb + ib[i]] = res[i];
      has[ia[i] * nb + ib[i]] = true;
     }
//--- neighbour average for every row
   double nmean[];
   int    ncnt[];
   ArrayResize(nmean, n);
   ArrayResize(ncnt, n);
   int plateau_best = 0;
   for(int i = 0; i < n; i++)
     {
      double s = 0;
      int c = 0;
      for(int da = -1; da <= 1; da++)
         for(int db = -1; db <= 1; db++)
           {
            if(da == 0 && db == 0)
               continue;
            int a = ia[i] + da, b = ib[i] + db;
            if(a < 0 || a >= na || b < 0 || b >= nb || !has[a * nb + b])
               continue;
            s += grid[a * nb + b];
            c++;
           }
      ncnt[i] = c;
      nmean[i] = c > 0 ? s / c : 0.0;
      if(ncnt[i] >= 3 && (ncnt[plateau_best] < 3 || nmean[i] > nmean[plateau_best]))
         plateau_best = i;
     }
//--- the best sets by result, each with its neighbours
   bool used[];
   ArrayResize(used, n);
   ArrayInitialize(used, false);
   PrintFormat("PlateauCheck: %d sets, grid %d x %d", n, na, nb);
   int peaks = 0;
   int top = MathMin(InpTop, n);
   for(int k = 0; k < top; k++)
     {
      int best = -1;
      for(int i = 0; i < n; i++)
         if(!used[i] && (best < 0 || res[i] > res[best]))
            best = i;
      used[best] = true;
      bool peak = (ncnt[best] == 0 || nmean[best] <= 0 || nmean[best] < InpPeakRatio * res[best]);
      if(peak)
         peaks++;
      PrintFormat("  #%d  p1=%g p2=%g  result %.2f  neighbours %.2f (%d)  %s", k + 1, pa[best], pb[best], res[best],
                  nmean[best], ncnt[best], peak ? "PEAK" : "plateau");
     }
   PrintFormat("  peaks among the top %d: %d", top, peaks);
   PrintFormat("  best neighbourhood: p1=%g p2=%g, own result %.2f, neighbours %.2f",
               pa[plateau_best], pb[plateau_best], res[plateau_best], nmean[plateau_best]);
  }
//+------------------------------------------------------------------+
