//+------------------------------------------------------------------+
//|                                     Scan_Trending_Pairs_v2.mq5 |
//|                                  Copyright 2023, Assistant Model |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, Assistant Model"
#property link      "https://www.mql5.com"
#property version   "1.01"
#property script_show_inputs

//--- Input Parameters
input ENUM_TIMEFRAMES InpTimeframe   = PERIOD_D1;   // Timeframe to scan
input int             InpScanPeriod  = 10;          // Analysis Period (Number of Bars)
input double          InpThreshold   = 0.25;        // Noise Threshold (for Indicator config)
input bool            InpIgnoreZero  = true;        // Ignore symbols with 0.0 efficiency

//--- Custom structure to hold symbol data
struct SymbolRank
  {
   string            name;
   double            efficiency;
  };

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   // 1. Initialize variables
   SymbolRank rankedSymbols[];
   int totalSymbols = SymbolsTotal(true); // true = only symbols in Market Watch
   int processedCount = 0;
   
   string tfName = EnumToString(InpTimeframe);
   PrintFormat("--- Starting Scan for %d symbols on %s (Period: %d Bars) ---", totalSymbols, tfName, InpScanPeriod);

   // 2. Loop through all Market Watch symbols
   for(int i = 0; i < totalSymbols; i++)
     {
      string currentSymbol = SymbolName(i, true);
      
      ResetLastError();

      // 3. Create handle using the USER SELECTED Timeframe (InpTimeframe)
      int handle = iCustom(currentSymbol, InpTimeframe, "Efficiency_Ratio", InpScanPeriod, InpThreshold);
      
      if(handle == INVALID_HANDLE)
        {
         Print("Failed to create indicator handle for ", currentSymbol, ". Error: ", GetLastError());
         continue;
        }

      // 4. Copy the Efficiency Buffer
      double buffer[];
      ArraySetAsSeries(buffer, true);
      
      int copyResult = -1;
      for(int attempt=0; attempt<3; attempt++)
      {
         // Copy from the selected buffer
         copyResult = CopyBuffer(handle, 0, 1, 1, buffer);
         if(copyResult > 0) break;
         Sleep(10); 
      }

      // 5. Store valid data
      if(copyResult > 0)
        {
         double erValue = buffer[0];
         
         if(!InpIgnoreZero || erValue != 0.0)
           {
            ArrayResize(rankedSymbols, processedCount + 1);
            rankedSymbols[processedCount].name = currentSymbol;
            rankedSymbols[processedCount].efficiency = erValue;
            processedCount++;
           }
        }
        
      IndicatorRelease(handle);
     }

   // 6. Sort the array (Descending: Highest Efficiency First)
   Print("Scanning complete. Sorting ", processedCount, " results...");
   
   for(int i = 0; i < processedCount - 1; i++)
     {
      for(int j = 0; j < processedCount - i - 1; j++)
        {
         if(rankedSymbols[j].efficiency < rankedSymbols[j + 1].efficiency)
           {
            SymbolRank temp = rankedSymbols[j];
            rankedSymbols[j] = rankedSymbols[j + 1];
            rankedSymbols[j + 1] = temp;
           }
        }
     }

   // 7. Output Results
   Print("==================================================");
   PrintFormat("MOST TRENDING PAIRS (%s - Past %d Bars)", tfName, InpScanPeriod);
   Print("==================================================");
   
   for(int i = 0; i < processedCount; i++)
     {
      string trendDesc = (rankedSymbols[i].efficiency > 0.6) ? "Strong Trend" : (rankedSymbols[i].efficiency < 0.3) ? "Noisy/Choppy" : "Moderate";
      
      PrintFormat("#%d %s: %.4f [%s]", 
                  i + 1, 
                  rankedSymbols[i].name, 
                  rankedSymbols[i].efficiency,
                  trendDesc);
     }
  }
//+------------------------------------------------------------------+