//+------------------------------------------------------------------+
//|                                        Ind_Execution_Monitor.mq5 |
//|                                  Copyright 2026, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright   "Copyright 2026, MetaQuotes Ltd."
#property link        "https://www.mql5.com"
#property version     "1.20"
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_plots   3

#property indicator_label1  "Historical Bar Spread"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1

#property indicator_label2  "Statistical Dynamic Ceiling"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrOrangeRed
#property indicator_style2  STYLE_DASH
#property indicator_width2  1

#property indicator_label3  "Absolute Spread Hard Cap"
#property indicator_type3   DRAW_LINE
#property indicator_color3  clrCrimson
#property indicator_style3  STYLE_SOLID
#property indicator_width3  2

#include <Execution_Filter\Execution_Filter.mqh>

input long   InpHardCapSpread    = 40;   // Absolute Spread Hard Cap (Points)
input double InpZScoreThreshold  = 2.0;  // Dynamic Z-score Multiplier
input int    InpBaselinePeriod   = 30;   // Baseline Historical Period (Bars >= 10)

double BufferSpread[];
double BufferDynamicCeiling[];
double BufferHardCap[];

CExecutionFilter *g_filter;

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- Map indicator data buffers
   SetIndexBuffer(0, BufferSpread, INDICATOR_DATA);
   SetIndexBuffer(1, BufferDynamicCeiling, INDICATOR_DATA);
   SetIndexBuffer(2, BufferHardCap, INDICATOR_DATA);

//--- Set empty plot values
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetDouble(2, PLOT_EMPTY_VALUE, EMPTY_VALUE);

//--- Define plot drawing start shifts
   PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpBaselinePeriod);
   PlotIndexSetInteger(1, PLOT_DRAW_BEGIN, InpBaselinePeriod);
   PlotIndexSetInteger(2, PLOT_DRAW_BEGIN, InpBaselinePeriod);

//--- Initialize filter engine instance
   g_filter = new CExecutionFilter(_Symbol, InpHardCapSpread, InpZScoreThreshold, InpBaselinePeriod);
   if(g_filter == NULL)
      return INIT_FAILED;

   return INIT_SUCCEEDED;
  }

//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- Clean dynamic filter memory
   if(CheckPointer(g_filter) == POINTER_DYNAMIC)
      delete g_filter;

   Comment("");
  }

//+------------------------------------------------------------------+
//| 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[])
  {
//--- Check minimal bar availability
   if(rates_total <= InpBaselinePeriod)
      return 0;

//--- Enforce chronological indexing (index 0 = oldest)
   ArraySetAsSeries(spread, false);
   ArraySetAsSeries(BufferSpread, false);
   ArraySetAsSeries(BufferDynamicCeiling, false);
   ArraySetAsSeries(BufferHardCap, false);

//--- Determine calculation starting index
   int start = prev_calculated - 1;
   if(start < 0)
     {
      start = 0;
      //--- Initialize warm-up section with EMPTY_VALUE
      for(int j = 0; j < InpBaselinePeriod && j < rates_total; j++)
        {
         BufferSpread[j]         = EMPTY_VALUE;
         BufferDynamicCeiling[j] = EMPTY_VALUE;
         BufferHardCap[j]        = EMPTY_VALUE;
        }
      start = InpBaselinePeriod;
     }

//--- Historical buffer calculation loop
   for(int i = start; i < rates_total && !IsStopped(); i++)
     {
      BufferSpread[i]  = (double)spread[i];
      BufferHardCap[i] = (double)InpHardCapSpread;

      //--- Calculate rolling mean over completed preceding bars
      double sum = 0.0;
      for(int k = 0; k < InpBaselinePeriod; k++)
        {
         int idx = (i - 1) - k;
         if(idx < 0)
            break;
         sum += (double)spread[idx];
        }
      double mean = sum / InpBaselinePeriod;

      //--- Calculate rolling standard deviation
      double sum_sq = 0.0;
      for(int k = 0; k < InpBaselinePeriod; k++)
        {
         int idx = (i - 1) - k;
         if(idx < 0)
            break;
         double diff = (double)spread[idx] - mean;
         sum_sq += diff * diff;
        }
      double std = MathSqrt(sum_sq / (InpBaselinePeriod - 1));

      BufferDynamicCeiling[i] = mean + (InpZScoreThreshold * std);
     }

//--- Update live on-chart telemetry dashboard
   if(CheckPointer(g_filter) != POINTER_INVALID)
     {
      ExecutionGateReport report;
      bool passed = g_filter.EvaluateAll(report);

      string status_text = passed ? "ALLOWED (GREEN)" : "BLOCKED (RED)";
      string dashboard = StringFormat(
         "=== Pre-Trade Execution Filter Monitor ===\n"
         "Symbol: %s | Gate Outcome: %s\n"
         "Current Spread: %d pt | Hard Cap: %d pt\n"
         "Rolling Baseline Mean: %.1f pt | StdDev: %.1f pt\n"
         "Spread Z-score: %.2f | Quote Age: %u ms\n"
         "Resolved Filling Mode: %s\n"
         "Status Reason: %s",
         _Symbol, status_text,
         report.current_spread, InpHardCapSpread,
         report.baseline_mean, report.baseline_std,
         report.z_score, report.quote_age_ms,
         EnumToString(report.resolved_filling),
         report.rejection_reason
      );
      Comment(dashboard);
     }

   return rates_total;
  }
//+------------------------------------------------------------------+