//+------------------------------------------------------------------+
//|                                          DivergenceEnginePro.mqh |
//|                                    Copyright 2026, soloharbinger |
//|                      https://www.mql5.com/en/users/soloharbinger |
//+------------------------------------------------------------------+
#property copyright   "Copyright 2026, soloharbinger"
#property link        "https://www.mql5.com/en/users/soloharbinger"
#property description "Divergence engine as a class: multi-pivot storage, separation, amplitude and zone filters, and a 0-100 score."
#property description "The oscillator is computed by DivergenceEngine.mqh, unchanged."

#ifndef DIVERGENCE_ENGINE_PRO_MQH
#define DIVERGENCE_ENGINE_PRO_MQH

#include <DivergenceEngine.mqh>

//+------------------------------------------------------------------+
//| Outcome of one evaluated pair                                    |
//+------------------------------------------------------------------+
enum ENUM_DIV_STATUS
  {
   DIV_ACCEPTED = 0,        // Passed every filter
   DIV_TOO_CLOSE,           // Pivots closer than MinSeparation
   DIV_SMALL_PRICE_MOVE,    // New extreme smaller than MinPriceExtATR
   DIV_SMALL_OSC_MOVE,      // Oscillator disagreement smaller than MinOscDelta
   DIV_OUTSIDE_ZONE,        // Older pivot's oscillator outside its zone
   DIV_LOW_SCORE            // Score below MinScore
  };

//+------------------------------------------------------------------+
//| Readable name for a status                                       |
//+------------------------------------------------------------------+
string DivStatusToString(const ENUM_DIV_STATUS status)
  {
   switch(status)
     {
      case DIV_ACCEPTED:
         return "ACCEPTED";
      case DIV_TOO_CLOSE:
         return "TOO_CLOSE";
      case DIV_SMALL_PRICE_MOVE:
         return "SMALL_PRICE_MOVE";
      case DIV_SMALL_OSC_MOVE:
         return "SMALL_OSC_MOVE";
      case DIV_OUTSIDE_ZONE:
         return "OUTSIDE_ZONE";
      case DIV_LOW_SCORE:
         return "LOW_SCORE";
     }
   return "UNKNOWN";
  }

//+------------------------------------------------------------------+
//| One oscillator pivot                                             |
//+------------------------------------------------------------------+
struct DivergencePivot
  {
   bool              isHigh;       // true = pivot high, false = pivot low
   int               bar;          // Shift in the current pass
   datetime          time;
   double            price;        // Bar high for a pivot high, bar low for a pivot low
   double            osc;          // Smoothed oscillator at the pivot
   int               confirmBar;   // Shift where the pivot became known
  };

//+------------------------------------------------------------------+
//| One evaluated pair: accepted, or the reason it was not           |
//+------------------------------------------------------------------+
struct DivergenceInfo
  {
   int               type;         // 1 = bullish, -1 = bearish
   ENUM_DIV_STATUS   status;
   datetime          time1;        // Older pivot
   datetime          time2;        // Newer pivot
   int               bar1;
   int               bar2;
   double            price1;
   double            price2;
   double            osc1;
   double            osc2;
   datetime          confirmTime;
   int               confirmBar;
   int               separation;   // Bars between the two pivots
   double            priceExtATR;  // How far price went past the older pivot, in ATR
   double            oscDelta;     // How far the oscillator disagreed, in oscillator points
   double            priceScore;   // 0..1
   double            oscScore;     // 0..1
   double            sepScore;     // 0..1
   double            score;        // 0..100
  };

//+------------------------------------------------------------------+
//| One-line description of a pair, for logs and tooltips            |
//+------------------------------------------------------------------+
string DivergenceInfoToString(const DivergenceInfo &d)
  {
   return StringFormat("%s %s | score %.0f | %s -> %s | price %.2f ATR -> %.2f | osc %.1f pts -> %.2f | spacing %d bars -> %.2f",
                       (d.type == 1 ? "BULLISH" : "BEARISH"),
                       DivStatusToString(d.status),
                       d.score,
                       TimeToString(d.time1, TIME_DATE | TIME_MINUTES),
                       TimeToString(d.time2, TIME_DATE | TIME_MINUTES),
                       d.priceExtATR, d.priceScore,
                       d.oscDelta, d.oscScore,
                       d.separation, d.sepScore);
  }

//+------------------------------------------------------------------+
//| Every setting in one struct                                      |
//+------------------------------------------------------------------+
struct DivergenceProConfig
  {
   //--- Market context
   string            Symbol;          // Empty = chart symbol
   ENUM_TIMEFRAMES   Timeframe;
   int               Lookback;        // Bars copied per pass

   //--- Oscillator, handed to DivergenceEngine.mqh
   ENUM_DIV_SOURCE   Source;
   int               MPOLength;
   int               MPOSmooth;
   int               RSIPeriod;
   int               PivotLength;     // Bars either side of an oscillator pivot

   //--- Pairing
   int               PairingDepth;    // Earlier pivots a new pivot is compared with (1 = the previous one only)
   int               MinSeparation;   // Bars
   int               MaxSeparation;   // Bars

   //--- Filters
   int               ATRPeriod;
   double            MinPriceExtATR;  // Price must pass the older pivot by at least this many ATR
   double            MinOscDelta;     // Oscillator must disagree by at least this many points
   bool              UseZone;
   double            BullZoneLevel;   // Bullish: older pivot's oscillator at or below this
   double            BearZoneLevel;   // Bearish: older pivot's oscillator at or above this
   double            MinScore;        // 0..100

   //--- Score
   double            PriceExtFullATR; // Extension that earns the full price score
   double            OscDeltaFull;    // Disagreement that earns the full oscillator score
   int               SepFullBars;     // Separation that earns the full spacing score
   double            WeightPrice;
   double            WeightOsc;
   double            WeightSep;

   //--- Diagnostics
   bool              LogRecords;      // Print every pair when its confirmation bar closes

   void              SetDefaults(void)
     {
      Symbol          = "";
      Timeframe       = PERIOD_CURRENT;
      Lookback        = 300;

      Source          = DIV_SRC_MPO;
      MPOLength       = 6;
      MPOSmooth       = 7;
      RSIPeriod       = 14;
      PivotLength     = 2;

      PairingDepth    = 3;
      MinSeparation   = 5;
      MaxSeparation   = 60;

      ATRPeriod       = 14;
      MinPriceExtATR  = 0.10;
      MinOscDelta     = 1.0;
      UseZone         = false;
      BullZoneLevel   = -30.0;
      BearZoneLevel   = 30.0;
      MinScore        = 0.0;

      PriceExtFullATR = 1.0;
      OscDeltaFull    = 10.0;
      SepFullBars     = 20;
      WeightPrice     = 1.0;
      WeightOsc       = 1.0;
      WeightSep       = 1.0;

      LogRecords      = false;
     }

                     DivergenceProConfig(void) { SetDefaults(); }
  };

//+------------------------------------------------------------------+
//| CDivergenceEnginePro                                             |
//+------------------------------------------------------------------+
class CDivergenceEnginePro
  {
private:
   DivergenceProConfig m_cfg;
   DivergenceEngine  m_base;          // Computes the oscillator; nothing else is used

   string            m_symbol;
   ENUM_TIMEFRAMES   m_tf;
   double            m_point;
   bool              m_initialized;

   //--- Pass state
   bool              m_ready;
   int               m_bars;
   int               m_limit;
   int               m_sizedFor;
   int               m_expect;        // The only bar ProcessBar() will accept next
   int               m_processedDown; // Oldest bar still to be processed is m_processedDown - 1
   int               m_barrier;       // Pivots stored before this index cannot be paired
   bool              m_usageWarned;

   //--- The window, series-indexed
   datetime          m_time[];
   double            m_open[];
   double            m_high[];
   double            m_low[];
   double            m_close[];
   double            m_atr[];
   int               m_lastSig[];     // Latest accepted pair as of each bar, -1 = none

   //--- Rebuilt on every pass
   DivergencePivot   m_pivots[];
   DivergenceInfo    m_infos[];

   bool              ValidateConfig(void);
   int               WarmUp(void);
   bool              AllocateBuffers(const int size);
   bool              CopyWindow(void);
   double            TrueRange(const int k);
   void              ComputeATR(void);
   int               PivotKindAt(const int p);
   int               AddPivot(const bool isHigh, const int p, const int i);
   void              PairNewPivot(const int newIdx, const int i);
   void              Measure(const DivergencePivot &older, const DivergencePivot &newer, const int i, DivergenceInfo &d);
   ENUM_DIV_STATUS   Classify(const DivergencePivot &older, const DivergenceInfo &d);
   bool              InZone(const DivergencePivot &older);
   int               AddInfo(const DivergenceInfo &d);
   bool              IndexUsable(const int shift);
   void              LogConfirmedAt(const int shift);
   void              WarnUsage(const string text);

public:
                     CDivergenceEnginePro(void);
                    ~CDivergenceEnginePro(void);

   //--- Lifecycle
   bool              Init(const DivergenceProConfig &cfg);
   void              Deinit(void);

   //--- Driving: Refresh() for the whole window, or the three calls inside a loop of your own
   bool              Refresh(void);
   bool              BeginPass(void);
   void              ProcessBar(const int i);
   void              ResetAt(const int i);

   //--- State
   bool              IsReady(void)          { return m_ready; }
   int               Limit(void)            { return m_limit; }
   int               BarCount(void)         { return m_bars; }
   string            GetSymbol(void)        { return m_symbol; }
   ENUM_TIMEFRAMES   GetTimeframe(void)     { return m_tf; }
   void              GetConfig(DivergenceProConfig &out) { out = m_cfg; }

   //--- Per-bar queries
   int               Type(const int shift = 1);
   int               Age(const int shift = 1);
   double            Score(const int shift = 1);
   bool              Latest(const int shift, DivergenceInfo &out);
   double            Oscillator(const int shift = 1);
   double            ATR(const int shift = 1);

   //--- The window the pass ran on
   datetime          BarTime(const int shift);
   double            BarOpen(const int shift);
   double            BarHigh(const int shift);
   double            BarLow(const int shift);
   double            BarClose(const int shift);

   //--- Everything the pass stored
   int               PivotCount(void)       { return ArraySize(m_pivots); }
   bool              PivotAt(const int k, DivergencePivot &out);
   int               InfoCount(void)        { return ArraySize(m_infos); }
   bool              InfoAt(const int k, DivergenceInfo &out);
  };

//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CDivergenceEnginePro::CDivergenceEnginePro(void)
  {
   m_symbol         = "";
   m_tf             = PERIOD_CURRENT;
   m_point          = 0.0;
   m_initialized    = false;
   m_ready          = false;
   m_bars           = 0;
   m_limit          = -1;
   m_sizedFor       = 0;
   m_expect         = -1;
   m_processedDown  = 0;
   m_barrier        = 0;
   m_usageWarned    = false;
   m_base.rsiHandle = INVALID_HANDLE;
  }

//+------------------------------------------------------------------+
//| Destructor                                                       |
//+------------------------------------------------------------------+
CDivergenceEnginePro::~CDivergenceEnginePro(void)
  {
   Deinit();
  }

//+------------------------------------------------------------------+
//| Reject settings that cannot work before anything is allocated    |
//+------------------------------------------------------------------+
bool CDivergenceEnginePro::ValidateConfig(void)
  {
   if(m_cfg.PivotLength <= 0 || m_cfg.MPOLength <= 0 || m_cfg.MPOSmooth <= 0 || m_cfg.RSIPeriod <= 0)
     {
      Print("[DivPro] Oscillator and pivot settings must be greater than 0.");
      return false;
     }
   if(m_cfg.PairingDepth < 1)
     {
      Print("[DivPro] PairingDepth must be at least 1.");
      return false;
     }
   if(m_cfg.MinSeparation < 0 || m_cfg.MaxSeparation <= m_cfg.MinSeparation)
     {
      Print("[DivPro] MaxSeparation must be greater than MinSeparation, and neither can be negative.");
      return false;
     }
   if(m_cfg.ATRPeriod <= 0)
     {
      Print("[DivPro] ATRPeriod must be greater than 0.");
      return false;
     }
   if(m_cfg.MinPriceExtATR < 0.0 || m_cfg.MinOscDelta < 0.0 || m_cfg.MinScore < 0.0 || m_cfg.MinScore > 100.0)
     {
      Print("[DivPro] Filter thresholds cannot be negative, and MinScore must be within [0..100].");
      return false;
     }
   if(m_cfg.PriceExtFullATR <= 0.0 || m_cfg.OscDeltaFull <= 0.0 || m_cfg.SepFullBars <= 0)
     {
      Print("[DivPro] Score references must be greater than 0.");
      return false;
     }
   if(m_cfg.WeightPrice < 0.0 || m_cfg.WeightOsc < 0.0 || m_cfg.WeightSep < 0.0 ||
      m_cfg.WeightPrice + m_cfg.WeightOsc + m_cfg.WeightSep <= 0.0)
     {
      Print("[DivPro] Score weights cannot be negative and cannot all be 0.");
      return false;
     }

//--- Zone levels are in the oscillator's own units: MPO4 is bounded at +/-50, RSI at 0..100
   if(m_cfg.UseZone)
     {
      double lowest  = (m_cfg.Source == DIV_SRC_RSI) ? 0.0 : -50.0;
      double highest = (m_cfg.Source == DIV_SRC_RSI) ? 100.0 : 50.0;
      if(m_cfg.BullZoneLevel < lowest || m_cfg.BearZoneLevel > highest || m_cfg.BullZoneLevel >= m_cfg.BearZoneLevel)
        {
         PrintFormat("[DivPro] Zone levels must satisfy %.0f <= BullZoneLevel < BearZoneLevel <= %.0f for this source.",
                     lowest, highest);
         return false;
        }
     }
   return true;
  }

//+------------------------------------------------------------------+
//| Bars at the old end of the window that only feed calculations    |
//+------------------------------------------------------------------+
int CDivergenceEnginePro::WarmUp(void)
  {
   return MathMax(GetRequiredLookback(m_base), m_cfg.ATRPeriod + 1);
  }

//+------------------------------------------------------------------+
//| Initialization                                                   |
//+------------------------------------------------------------------+
bool CDivergenceEnginePro::Init(const DivergenceProConfig &cfg)
  {
   Deinit();
   m_cfg = cfg;
   if(!ValidateConfig())
      return false;

   m_symbol = (StringLen(m_cfg.Symbol) == 0) ? _Symbol : m_cfg.Symbol;
   m_tf     = m_cfg.Timeframe;
   if(!SymbolSelect(m_symbol, true))
     {
      Print("[DivPro] Could not select ", m_symbol, " in Market Watch.");
      return false;
     }
   m_point = SymbolInfoDouble(m_symbol, SYMBOL_POINT);
   if(m_point <= 0.0)
     {
      Print("[DivPro] ", m_symbol, " reported a point size of 0.");
      return false;
     }

   if(!InitializeDivergenceEngine(m_base, m_cfg.Source, m_cfg.MPOLength, m_cfg.MPOSmooth,
                                  m_cfg.RSIPeriod, m_cfg.PivotLength, m_symbol, m_tf))
     {
      Print("[DivPro] The oscillator engine failed to initialize.");
      return false;
     }

//--- The window has to hold a pair at MaxSeparation plus the warm-up bars behind it
   int needed = WarmUp() + 2 * m_cfg.PivotLength + m_cfg.MaxSeparation + 10;
   if(m_cfg.Lookback < needed)
     {
      Print("[DivPro] Lookback (", m_cfg.Lookback, ") raised to ", needed, " so a pair at MaxSeparation fits the window.");
      m_cfg.Lookback = needed;
     }

   m_initialized = true;
   return true;
  }

//+------------------------------------------------------------------+
//| Release the RSI handle and every buffer                          |
//+------------------------------------------------------------------+
void CDivergenceEnginePro::Deinit(void)
  {
   ReleaseDivergenceEngine(m_base);

   ArrayFree(m_time);
   ArrayFree(m_open);
   ArrayFree(m_high);
   ArrayFree(m_low);
   ArrayFree(m_close);
   ArrayFree(m_atr);
   ArrayFree(m_lastSig);
   ArrayFree(m_pivots);
   ArrayFree(m_infos);

   m_initialized   = false;
   m_ready         = false;
   m_bars          = 0;
   m_limit         = -1;
   m_sizedFor      = 0;
   m_expect        = -1;
   m_processedDown = 0;
   m_barrier       = 0;
   m_usageWarned   = false;
  }

//+------------------------------------------------------------------+
//| Size the window buffers, once per size change                    |
//+------------------------------------------------------------------+
bool CDivergenceEnginePro::AllocateBuffers(const int size)
  {
   if(ArrayResize(m_time, size) != size ||
      ArrayResize(m_open, size) != size ||
      ArrayResize(m_high, size) != size ||
      ArrayResize(m_low, size) != size ||
      ArrayResize(m_close, size) != size ||
      ArrayResize(m_atr, size) != size ||
      ArrayResize(m_lastSig, size) != size)
     {
      PrintFormat("[DivPro] ArrayResize failed, size=%d, error=%d", size, GetLastError());
      return false;
     }

   if(!ArraySetAsSeries(m_time, true) ||
      !ArraySetAsSeries(m_open, true) ||
      !ArraySetAsSeries(m_high, true) ||
      !ArraySetAsSeries(m_low, true) ||
      !ArraySetAsSeries(m_close, true) ||
      !ArraySetAsSeries(m_atr, true) ||
      !ArraySetAsSeries(m_lastSig, true))
     {
      PrintFormat("[DivPro] ArraySetAsSeries failed, error=%d", GetLastError());
      return false;
     }

   if(!ResizeDivergenceBuffers(m_base, size))
      return false;

   m_sizedFor = size;
   return true;
  }

//+------------------------------------------------------------------+
//| Copy the window and work out the oldest bar the pass may use     |
//+------------------------------------------------------------------+
bool CDivergenceEnginePro::CopyWindow(void)
  {
   int available = ::Bars(m_symbol, m_tf);
   int want = MathMin(m_cfg.Lookback, available - 1);

//--- Too little history is not an error; the next call retries
   if(want < WarmUp() + 2 * m_cfg.PivotLength + 10)
      return false;

   if(want != m_sizedFor && !AllocateBuffers(want))
      return false;

   if(CopyTime(m_symbol, m_tf, 0, want, m_time) < want ||
      CopyOpen(m_symbol, m_tf, 0, want, m_open) < want ||
      CopyHigh(m_symbol, m_tf, 0, want, m_high) < want ||
      CopyLow(m_symbol, m_tf, 0, want, m_low) < want ||
      CopyClose(m_symbol, m_tf, 0, want, m_close) < want)
      return false;

   m_bars  = want;
   m_limit = m_bars - 1 - WarmUp();
   return (m_limit > 2 * m_cfg.PivotLength);
  }

//+------------------------------------------------------------------+
//| True range of one bar, using the previous close                  |
//+------------------------------------------------------------------+
double CDivergenceEnginePro::TrueRange(const int k)
  {
   return MathMax(m_high[k], m_close[k + 1]) - MathMin(m_low[k], m_close[k + 1]);
  }

//+------------------------------------------------------------------+
//| Simple average of true range, as MetaTrader's own ATR computes it|
//+------------------------------------------------------------------+
void CDivergenceEnginePro::ComputeATR(void)
  {
   int period = m_cfg.ATRPeriod;
   ArrayInitialize(m_atr, 0.0);

//--- The oldest bar with a full period of true ranges behind it
   int oldest = m_bars - 1 - period;
   if(oldest < 0)
      return;

   double sum = 0.0;
   for(int k = oldest; k < oldest + period; k++)
      sum += TrueRange(k);
   m_atr[oldest] = sum / period;

   for(int b = oldest - 1; b >= 0; b--)
     {
      sum += TrueRange(b) - TrueRange(b + period);
      m_atr[b] = sum / period;
     }
  }

//+------------------------------------------------------------------+
//| Start a pass: copy the window, seed the oscillator, clear storage|
//+------------------------------------------------------------------+
bool CDivergenceEnginePro::BeginPass(void)
  {
   m_ready  = false;
   m_expect = -1;

   if(!m_initialized)
      return false;
   if(!CopyWindow())
      return false;
   if(!UpdateDivergenceRSI(m_base, m_limit))
      return false;

   InitDivergenceBoundaries(m_base, m_limit);
   ComputeATR();

   ArrayResize(m_pivots, 0, 64);
   ArrayResize(m_infos, 0, 64);

   m_barrier       = 0;
   m_expect        = m_limit;
   m_processedDown = m_limit + 1;
   return true;
  }

//+------------------------------------------------------------------+
//| Process one bar. Bars must arrive from Limit() down to 0.        |
//+------------------------------------------------------------------+
void CDivergenceEnginePro::ProcessBar(const int i)
  {
   if(i != m_expect)
     {
      WarnUsage(StringFormat("ProcessBar(%d) called out of order, expected %d. Call BeginPass(), then loop from Limit() down to 0.",
                             i, m_expect));
      return;
     }

   CalculateOscillator(m_base, i, m_open, m_close, m_point);

//--- Inherit the previous bar's state
   m_lastSig[i] = (i < m_limit) ? m_lastSig[i + 1] : -1;

//--- A pivot at p is known once PivotLength bars on each side have been processed
   int p = i + m_cfg.PivotLength;
   if(p + m_cfg.PivotLength <= m_limit)
     {
      int kind = PivotKindAt(p);
      if(kind != 0)
         PairNewPivot(AddPivot(kind == 1, p, i), i);
     }

   m_processedDown = i;
   m_expect        = i - 1;

   if(i == 1 && m_cfg.LogRecords)
      LogConfirmedAt(1);
   if(i == 0)
      m_ready = true;
  }

//+------------------------------------------------------------------+
//| Clear the state of the bar just processed, and stop every later  |
//| pivot from pairing with a pivot stored before it                 |
//+------------------------------------------------------------------+
void CDivergenceEnginePro::ResetAt(const int i)
  {
   if(i != m_processedDown || i > m_limit)
     {
      WarnUsage(StringFormat("ResetAt(%d) ignored: only the bar just processed (%d) can be reset.", i, m_processedDown));
      return;
     }
   m_lastSig[i] = -1;
   m_barrier    = ArraySize(m_pivots);
  }

//+------------------------------------------------------------------+
//| Run a whole pass                                                 |
//+------------------------------------------------------------------+
bool CDivergenceEnginePro::Refresh(void)
  {
   if(!BeginPass())
      return false;
   for(int i = m_limit; i >= 0; i--)
      ProcessBar(i);
   return m_ready;
  }

//+------------------------------------------------------------------+
//| Strict oscillator pivot, the same test as DivergenceEngine.mqh   |
//| Returns 1 for a pivot high, -1 for a pivot low, 0 for neither    |
//+------------------------------------------------------------------+
int CDivergenceEnginePro::PivotKindAt(const int p)
  {
   double value  = GetOscillatorValue(m_base, p);
   bool   isLow  = true;
   bool   isHigh = true;

   for(int k = 1; k <= m_cfg.PivotLength; k++)
     {
      double older = GetOscillatorValue(m_base, p + k);
      double newer = GetOscillatorValue(m_base, p - k);
      if(!(value < older && value < newer))
         isLow = false;
      if(!(value > older && value > newer))
         isHigh = false;
     }

   if(isLow)
      return -1;
   if(isHigh)
      return 1;
   return 0;
  }

//+------------------------------------------------------------------+
//| Store a new pivot. Returns its index, or -1 on failure.          |
//+------------------------------------------------------------------+
int CDivergenceEnginePro::AddPivot(const bool isHigh, const int p, const int i)
  {
   int n = ArraySize(m_pivots);
   if(ArrayResize(m_pivots, n + 1, 64) != n + 1)
     {
      PrintFormat("[DivPro] Pivot storage could not grow, error=%d", GetLastError());
      return -1;
     }

   m_pivots[n].isHigh     = isHigh;
   m_pivots[n].bar        = p;
   m_pivots[n].time       = m_time[p];
   m_pivots[n].price      = isHigh ? m_high[p] : m_low[p];
   m_pivots[n].osc        = GetOscillatorValue(m_base, p);
   m_pivots[n].confirmBar = i;
   return n;
  }

//+------------------------------------------------------------------+
//| Compare a new pivot with earlier pivots of the same kind, newest |
//| first, and keep the first pair that passes every filter          |
//+------------------------------------------------------------------+
void CDivergenceEnginePro::PairNewPivot(const int newIdx, const int i)
  {
   if(newIdx < 0)
      return;

   DivergencePivot newer    = m_pivots[newIdx];
   bool            isHigh   = newer.isHigh;
   double          oscGuard = isHigh ? -DBL_MAX : DBL_MAX;
   int             examined = 0;
   bool            haveReject = false;
   DivergenceInfo  rejected;
   ZeroMemory(rejected);

   for(int k = newIdx - 1; k >= m_barrier && examined < m_cfg.PairingDepth; k--)
     {
      if(m_pivots[k].isHigh != isHigh)
         continue;

      DivergencePivot older = m_pivots[k];
      if(older.bar - newer.bar > m_cfg.MaxSeparation)
         break;
      examined++;

      //--- Price has to make a new extreme against the older pivot
      bool newExtreme = isHigh ? (newer.price > older.price) : (newer.price < older.price);
      if(!newExtreme)
         break;

      //--- The older pivot has to be the most extreme oscillator reading so far
      bool cleanStart = isHigh ? (older.osc > oscGuard) : (older.osc < oscGuard);
      oscGuard = isHigh ? MathMax(oscGuard, older.osc) : MathMin(oscGuard, older.osc);
      if(!cleanStart)
         continue;

      //--- The oscillator has to disagree with price
      bool disagrees = isHigh ? (newer.osc < older.osc) : (newer.osc > older.osc);
      if(!disagrees)
         continue;

      DivergenceInfo d;
      Measure(older, newer, i, d);
      if(d.status == DIV_ACCEPTED)
        {
         int idx = AddInfo(d);
         if(idx >= 0)
            m_lastSig[i] = idx;
         return;
        }

      if(!haveReject)
        {
         rejected   = d;
         haveReject = true;
        }
     }

//--- Nothing accepted: keep the nearest rejected pair so its reason can be read
   if(haveReject)
      AddInfo(rejected);
  }

//+------------------------------------------------------------------+
//| Measure a pair, score it, and classify it                        |
//+------------------------------------------------------------------+
void CDivergenceEnginePro::Measure(const DivergencePivot &older, const DivergencePivot &newer,
                                   const int i, DivergenceInfo &d)
  {
   ZeroMemory(d);
   d.type        = newer.isHigh ? -1 : 1;
   d.time1       = older.time;
   d.time2       = newer.time;
   d.bar1        = older.bar;
   d.bar2        = newer.bar;
   d.price1      = older.price;
   d.price2      = newer.price;
   d.osc1        = older.osc;
   d.osc2        = newer.osc;
   d.confirmTime = m_time[i];
   d.confirmBar  = i;
   d.separation  = older.bar - newer.bar;

//--- The three measurements
   double atr    = m_atr[newer.bar];
   d.priceExtATR = (atr > 0.0) ? MathAbs(newer.price - older.price) / atr : 0.0;
   d.oscDelta    = MathAbs(newer.osc - older.osc);

//--- Each measured against the value that earns its full score
   d.priceScore = MathMin(d.priceExtATR / m_cfg.PriceExtFullATR, 1.0);
   d.oscScore   = MathMin(d.oscDelta / m_cfg.OscDeltaFull, 1.0);
   if(m_cfg.SepFullBars > m_cfg.MinSeparation)
      d.sepScore = MathMax(0.0, MathMin((double)(d.separation - m_cfg.MinSeparation) /
                                        (m_cfg.SepFullBars - m_cfg.MinSeparation), 1.0));
   else
      d.sepScore = (d.separation >= m_cfg.MinSeparation) ? 1.0 : 0.0;

   double weights = m_cfg.WeightPrice + m_cfg.WeightOsc + m_cfg.WeightSep;
   d.score = 100.0 * (m_cfg.WeightPrice * d.priceScore +
                      m_cfg.WeightOsc   * d.oscScore +
                      m_cfg.WeightSep   * d.sepScore) / weights;

   d.status = Classify(older, d);
  }

//+------------------------------------------------------------------+
//| The filters, in order. The first one that fails names the pair.  |
//+------------------------------------------------------------------+
ENUM_DIV_STATUS CDivergenceEnginePro::Classify(const DivergencePivot &older, const DivergenceInfo &d)
  {
   if(d.separation < m_cfg.MinSeparation)
      return DIV_TOO_CLOSE;
   if(d.priceExtATR < m_cfg.MinPriceExtATR)
      return DIV_SMALL_PRICE_MOVE;
   if(d.oscDelta < m_cfg.MinOscDelta)
      return DIV_SMALL_OSC_MOVE;
   if(m_cfg.UseZone && !InZone(older))
      return DIV_OUTSIDE_ZONE;
   if(d.score < m_cfg.MinScore)
      return DIV_LOW_SCORE;
   return DIV_ACCEPTED;
  }

//+------------------------------------------------------------------+
//| The divergence has to start from an extreme oscillator reading   |
//+------------------------------------------------------------------+
bool CDivergenceEnginePro::InZone(const DivergencePivot &older)
  {
   if(older.isHigh)
      return (older.osc >= m_cfg.BearZoneLevel);
   return (older.osc <= m_cfg.BullZoneLevel);
  }

//+------------------------------------------------------------------+
//| Store a pair. Returns its index, or -1 on failure.               |
//+------------------------------------------------------------------+
int CDivergenceEnginePro::AddInfo(const DivergenceInfo &d)
  {
   int n = ArraySize(m_infos);
   if(ArrayResize(m_infos, n + 1, 64) != n + 1)
     {
      PrintFormat("[DivPro] Pair storage could not grow, error=%d", GetLastError());
      return -1;
     }
   m_infos[n] = d;
   return n;
  }

//+------------------------------------------------------------------+
//| Print every pair confirmed on a given bar                        |
//+------------------------------------------------------------------+
void CDivergenceEnginePro::LogConfirmedAt(const int shift)
  {
   for(int k = ArraySize(m_infos) - 1; k >= 0 && m_infos[k].confirmBar <= shift; k--)
      if(m_infos[k].confirmBar == shift)
         Print("[DivPro] ", m_symbol, " ", DivergenceInfoToString(m_infos[k]));
  }

//+------------------------------------------------------------------+
//| Report a usage mistake once rather than on every bar             |
//+------------------------------------------------------------------+
void CDivergenceEnginePro::WarnUsage(const string text)
  {
   if(m_usageWarned)
      return;
   Print("[DivPro] ", text);
   m_usageWarned = true;
  }

//+------------------------------------------------------------------+
//| A bar is readable once the current pass has processed it         |
//+------------------------------------------------------------------+
bool CDivergenceEnginePro::IndexUsable(const int shift)
  {
   return (m_limit >= 0 && shift >= m_processedDown && shift <= m_limit);
  }

//+------------------------------------------------------------------+
//| Latest accepted divergence type as of a bar: 1, -1 or 0          |
//+------------------------------------------------------------------+
int CDivergenceEnginePro::Type(const int shift)
  {
   if(!IndexUsable(shift) || m_lastSig[shift] < 0)
      return 0;
   return m_infos[m_lastSig[shift]].type;
  }

//+------------------------------------------------------------------+
//| Bars since that divergence was confirmed, or -1 for none         |
//+------------------------------------------------------------------+
int CDivergenceEnginePro::Age(const int shift)
  {
   if(!IndexUsable(shift) || m_lastSig[shift] < 0)
      return -1;
   return m_infos[m_lastSig[shift]].confirmBar - shift;
  }

//+------------------------------------------------------------------+
//| Its score, 0..100, or 0 for none                                 |
//+------------------------------------------------------------------+
double CDivergenceEnginePro::Score(const int shift)
  {
   if(!IndexUsable(shift) || m_lastSig[shift] < 0)
      return 0.0;
   return m_infos[m_lastSig[shift]].score;
  }

//+------------------------------------------------------------------+
//| The full record of that divergence                               |
//+------------------------------------------------------------------+
bool CDivergenceEnginePro::Latest(const int shift, DivergenceInfo &out)
  {
   if(!IndexUsable(shift) || m_lastSig[shift] < 0)
      return false;
   out = m_infos[m_lastSig[shift]];
   return true;
  }

//+------------------------------------------------------------------+
//| Smoothed oscillator at a bar                                     |
//+------------------------------------------------------------------+
double CDivergenceEnginePro::Oscillator(const int shift)
  {
   if(!IndexUsable(shift))
      return 0.0;
   return GetOscillatorValue(m_base, shift);
  }

//+------------------------------------------------------------------+
//| ATR at a bar, 0 where the window holds too few bars              |
//+------------------------------------------------------------------+
double CDivergenceEnginePro::ATR(const int shift)
  {
   if(shift < 0 || shift >= m_bars)
      return 0.0;
   return m_atr[shift];
  }

//+------------------------------------------------------------------+
//| Window accessors                                                 |
//+------------------------------------------------------------------+
datetime CDivergenceEnginePro::BarTime(const int shift)
  {
   if(shift < 0 || shift >= m_bars)
      return 0;
   return m_time[shift];
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double CDivergenceEnginePro::BarOpen(const int shift)
  {
   if(shift < 0 || shift >= m_bars)
      return 0.0;
   return m_open[shift];
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double CDivergenceEnginePro::BarHigh(const int shift)
  {
   if(shift < 0 || shift >= m_bars)
      return 0.0;
   return m_high[shift];
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double CDivergenceEnginePro::BarLow(const int shift)
  {
   if(shift < 0 || shift >= m_bars)
      return 0.0;
   return m_low[shift];
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double CDivergenceEnginePro::BarClose(const int shift)
  {
   if(shift < 0 || shift >= m_bars)
      return 0.0;
   return m_close[shift];
  }

//+------------------------------------------------------------------+
//| Stored pivot by index, oldest first                              |
//+------------------------------------------------------------------+
bool CDivergenceEnginePro::PivotAt(const int k, DivergencePivot &out)
  {
   if(k < 0 || k >= ArraySize(m_pivots))
      return false;
   out = m_pivots[k];
   return true;
  }

//+------------------------------------------------------------------+
//| Stored pair by index, oldest first                               |
//+------------------------------------------------------------------+
bool CDivergenceEnginePro::InfoAt(const int k, DivergenceInfo &out)
  {
   if(k < 0 || k >= ArraySize(m_infos))
      return false;
   out = m_infos[k];
   return true;
  }

#endif // DIVERGENCE_ENGINE_PRO_MQH
//+------------------------------------------------------------------+
