preview
Interactive Supply and Demand Zone Manager in MQL5 (Part VI): Dual-Timeframe Zone Detection and Lifecycle Management

Interactive Supply and Demand Zone Manager in MQL5 (Part VI): Dual-Timeframe Zone Detection and Lifecycle Management

MetaTrader 5 — Examples |
140 0
Francis Nyoike Thumbi
Francis Nyoike Thumbi

Introduction

Snapshot persistence provides the zone engine with a way to preserve stored zone records and their lifecycle state between runs. This capability, introduced in Part V, becomes particularly useful as we add a second source timeframe: chart switching can restore existing records rather than reconstruct their state from detection alone. Automatic history scans still run after restoration to identify eligible candidates.

In Part VI, our architectural focus shifts from chart-bound processing to explicitly configured source timeframes. Each active source keeps an independent runtime context, detailed in Phase 1. The existing detection and lifecycle functions receive the appropriate source timeframe and ATR value.

The organizing principle is permanent source ownership. A zone retains the timeframe that produced it through editing, lifecycle transitions, logging, and restoration. Visibility depends on the zone’s stored source and the displayed chart period. New manual rectangles receive that period as their source only when registration succeeds on an active source chart.

This part extends zone detection and lifecycle processing to two configured source timeframes, with single-source mode also supported. Trading coordination between sources is outside this extension.

What We Will Build

  • Source configuration: select a single lower source or a valid lower/higher pair and initialize their runtime contexts.
  • Independent source processing: allocate separate ATR handles, read completed-bar volatility, and coordinate detection and lifecycle passes using each source’s bar clock.
  • Source-aware zone management: retain source ownership through creation, duplicate checks, merging, blacklisting, and lifecycle transitions.
  • Chart visibility and interaction: display zones on their source timeframe, register manual rectangles on active source charts, and handle editing and deletion through tracked zone records.
  • Logging and persistence: record source timeframes in the event log and preserve source-tagged zones and blacklist entries in the snapshot.
  • Practical verification: demonstrate configuration, chart switching, and restoration while documenting the implementation's boundaries.


Phase 1: Establishing the Source-Timeframe Architecture

The first architectural change is to separate the timeframe being processed from the timeframe displayed on the chart. Previously, chart-bound calls could obtain their period implicitly through _Period. The extended structural engine instead passes a configured source timeframe to detection, scoring, and lifecycle functions.

Three inputs define the configuration.
//--- Part VI new: single or dual source timeframe inputs
input group "--- Source Timeframes ---"
input bool            InpUseDualTimeframe = true;         // Part VI new: false selects the lower source only
input ENUM_TIMEFRAMES InpLowerTimeframe   = PERIOD_M15;   // Part VI new: primary source in single and dual modes
input ENUM_TIMEFRAMES InpHigherTimeframe  = PERIOD_H1;    // Part VI new: additional source in dual mode

Note: The existing detection, scoring, merging, and decay parameters remain unchanged from the earlier parts of the series and are contained in the codebase. Their original definitions and roles are retained here, while Part VI focuses on extending zone processing to two independently configured source timeframes.

Defining Independent Source Contexts

Each active source receives an SSourceContext. This structure contains its timeframe, dedicated ATR handle, cached ATR value, current-bar stamp, closed-bar stamp, and initial-scan completion flag. An M15 processing pass does not advance the H1 source’s stamps or replace its ATR cache. Both sources nevertheless share the configured detection, scoring, and lifecycle settings.

//+------------------------------------------------------------------+
//| Part VI new: source-timeframe runtime context                    |
//| One independent context per ACTIVE source. Zone ownership is     |
//| permanent (CZone.source_tf); the chart/display timeframe is      |
//| used only for display and initial manual registration.           |
//+------------------------------------------------------------------+
#define MAX_SOURCE_TF  2                                   // 1 = single mode, 2 = dual mode
#define SRC_ATR_PERIOD 14                                  // ATR period, applied per source timeframe

struct SSourceContext
  {
   ENUM_TIMEFRAMES   tf;                                   // Permanent source timeframe identity
   int               atr_handle;                           // Dedicated ATR handle for this source
   double            cached_atr;                           // Last ATR read returned successfully by THIS source
   datetime          bar0_time;                            // Part VI new: source bar stamp or startup baseline
   datetime          bar1_time;                            // Part VI new: closed source bar stamp or startup baseline
   bool              initial_scan_done;                    // Part VI new: initial detection completed
  };
//--- Part VI updated: persistence state for source-tagged zones
CZonePersistence g_persist;                               // Binary persistence engine
bool g_persist_loaded      = false;                       // Startup reconstruction completed
bool g_persist_read_failed = false;                       // Blocks writeback after a failed read
bool g_persist_dirty       = false;                       // State changes require saving

//--- Part VI updated: zone containers and source runtime state
CArrayObj      active_zones;                              // Tracked zones, including inactive sources
CArrayString   blacklist;                                 // AUTO entries keyed as "<period>|<price>"
SSourceContext g_src[MAX_SOURCE_TF];                      // Per-source ATR state and bar clocks
int            g_src_count = 0;                           // Number of configured sources

Resolving the Active Sources

ResolveSourceTimeframes() validates the selected periods and detection-window settings, then initializes the contexts. A concrete timeframe is required; PERIOD_CURRENT is not accepted as a source selection. In single-source mode, the function completes after configuring the lower source, ignoring the higher selection. In dual-source mode, the second selection must be valid and strictly longer than the first.
//+------------------------------------------------------------------+
//| Part VI new: configure active source contexts                    |
//+------------------------------------------------------------------+
bool ResolveSourceTimeframes(void)
  {
   g_src_count = 0;

   if(!ZPValidSource((int)InpLowerTimeframe) || SwingBars < 1 ||
      VelocityLookaheadBars < 1 || LookbackBars <= SwingBars + VelocityLookaheadBars)
      return false;                                   // Invalid source or detection window

   g_src[0].tf         = InpLowerTimeframe;
   g_src[0].atr_handle = INVALID_HANDLE;
   g_src[0].cached_atr = 0.0;
   g_src[0].bar0_time  = 0;
   g_src[0].bar1_time  = 0;
   g_src[0].initial_scan_done = false;
   g_src_count         = 1;

   if(!InpUseDualTimeframe)
      return true;                                    // single mode: the higher selection is ignored entirely

   if(!ZPValidSource((int)InpHigherTimeframe))
      return false;                                   // an explicit concrete timeframe is required
   if(PeriodSeconds(InpHigherTimeframe) <= PeriodSeconds(InpLowerTimeframe))
      return false;                                   // duplicate or reversed pair

   g_src[1].tf         = InpHigherTimeframe;
   g_src[1].atr_handle = INVALID_HANDLE;
   g_src[1].cached_atr = 0.0;
   g_src[1].bar0_time  = 0;
   g_src[1].bar1_time  = 0;
   g_src[1].initial_scan_done = false;
   g_src_count         = 2;
   return true;
  }

SourceIndex() locates a timeframe’s context, while IsActiveSource() tests membership in the current configuration.

//+------------------------------------------------------------------+
//| Part VI new: locate an active source context                     |
//+------------------------------------------------------------------+
int SourceIndex(ENUM_TIMEFRAMES tf)
  {
   for(int i = 0; i < g_src_count; i++)
      if(g_src[i].tf == tf)
         return i;
   return -1;
  }

//+------------------------------------------------------------------+
//| Part VI new: test configured source membership                   |
//+------------------------------------------------------------------+
bool IsActiveSource(ENUM_TIMEFRAMES tf)
  {
   return (SourceIndex(tf) >= 0);
  }

Architectural note: “Lower” and “higher” describe the shorter and longer configured source periods, not their relationship to the current chart. Neither source is automatically derived from the chart period. Structural processing follows those selections; the display and initial manual registration use the chart period. The inherited trading exception is described in Phase 3.

Assigning Permanent Zone Ownership

The zone class gains a source_tf field, and its parameterized constructor accepts the source explicitly. Automatic creation supplies the detection source; manual registration supplies the chart timeframe, subject to active-source validation.

The constructor also receives the source ATR used to establish initial thickness. Automatic object names include the timeframe identifier, price, and creation timestamp. The stored source_tf remains the authoritative ownership field.

//--- CZone field declaration
ENUM_TIMEFRAMES source_tf; // Part VI new: persistent source timeframe

//--- Part VI updated: constructor accepts the source timeframe
CZone(double p, ENUM_ZONE_TYPE t, datetime ct,
      double current_atr, ENUM_TIMEFRAMES tf)
  {
//--- Existing geometry and lifecycle initialization omitted.

   source_tf = tf; // Part VI new: source supplied at construction

//--- Part VI updated: source-tagged object name
   name = (type == ZONE_SUPPORT ? "S_" : "R_") +
          IntegerToString((int)tf) + "_" +
          DoubleToString(p, _Digits) + "_" +
          IntegerToString((long)ct);

//--- Remaining initialization omitted.
  }

The following flowchart brings these steps together, showing how source configuration leads to timeframe assignment for automatic and manual zones.

Fig. 1. New Zone Processing Flow

Fig. 1. Source Configuration and Zone Ownership

Phase 5 carries this ownership field into the snapshot so restoration preserves the same identity.


Phase 2: Preparing Source Data and Coordinating Processing

Allocating Source ATR Handles

CreateSourceHandles() allocates an ATR handle for each active source using SRC_ATR_PERIOD. If allocation fails, initialization releases previously allocated handles and stops. UpdateVolatilityCache() reads buffer position 1, corresponding to the last completed source bar. It updates the cache only after a successful read of a valid positive value. Failed reads leave the previous cache untouched but defer the processing pass.

//+------------------------------------------------------------------+
//| Part VI new: allocate source ATR handles                         |
//+------------------------------------------------------------------+
bool CreateSourceHandles(void)
  {
   for(int i = 0; i < g_src_count; i++)
     {
      g_src[i].atr_handle = iATR(_Symbol, g_src[i].tf, SRC_ATR_PERIOD);
      if(g_src[i].atr_handle == INVALID_HANDLE)
         return false;
     }
   return true;
  }
//+------------------------------------------------------------------+
//| Part VI updated: read completed-bar source ATR                   |
//+------------------------------------------------------------------+
bool UpdateVolatilityCache(const int src_index)
  {
   if(src_index < 0 || src_index >= g_src_count || g_src[src_index].atr_handle == INVALID_HANDLE)
     {
      //--- Unknown source index or missing ATR handle: report failure, leave cache untouched
      return false;
     }

   int atr_handle = g_src[src_index].atr_handle;  // handle dedicated to THIS source only
   static double atr_buffer[1]; // Static single-element buffer avoids per-tick array re-allocation

   if(CopyBuffer(atr_handle, 0, 1, 1, atr_buffer) == 1 &&
      MathIsValidNumber(atr_buffer[0]) && atr_buffer[0] > 0.0)
     {
      g_src[src_index].cached_atr = atr_buffer[0];
      return true;
     }

   return false;
  }

The release helpers close allocated handles and clear their caches during cleanup.

//+------------------------------------------------------------------+
//| Part VI new: release one source ATR handle                       |
//+------------------------------------------------------------------+
void ReleaseSourceHandle(const int idx)
  {
   if(idx < 0 || idx >= MAX_SOURCE_TF)
      return;
   if(g_src[idx].atr_handle != INVALID_HANDLE)
     {
      IndicatorRelease(g_src[idx].atr_handle);
      g_src[idx].atr_handle = INVALID_HANDLE;
     }
   g_src[idx].cached_atr = 0.0;
  }

//+------------------------------------------------------------------+
//| Part VI new: release source ATR handles                          |
//+------------------------------------------------------------------+
void ReleaseSourceHandles(void)
  {
   for(int i = 0; i < MAX_SOURCE_TF; i++)
      ReleaseSourceHandle(i);
  }

Checking History Availability

ATR availability alone does not establish that enough history exists for detection and scoring. SourceHistoryReady() requests a window covering the configured lookback, swing comparisons, volume sampling, and departure lookahead. It also checks that a completed source bar is available.

//+--------------------------------------------------------------------+
//| Part VI new: check the history window required by candidate scoring|
//+--------------------------------------------------------------------+
bool SourceHistoryReady(ENUM_TIMEFRAMES tf)
  {
   int required = LookbackBars + MathMax(SwingBars * 2,14) + VelocityLookaheadBars + 5;
   MqlRates check[];
   if(CopyRates(_Symbol,tf,0,required,check) != required)
      return false;
   MqlRates closed[];
   if(CopyRates(_Symbol,tf,1,1,closed) != 1)
      return false;
   return (closed[0].time > 0 && MathIsValidNumber(closed[0].close) &&
           closed[0].high >= closed[0].low);
  }

Architectural note: Initial historical candidates use the latest cached completed-bar ATR for that source. The engine does not retrieve pivot-specific historical ATR values. Consequently, ATR-dependent estimates for historical candidates reflect recent source volatility.

Initializing and Restoring the Engine

OnInit() resolves sources, creates their handles, and attempts to prime their ATR caches. It then initializes logging and restores the snapshot before automatic detection. Restored zones and blacklist entries consequently participate in creation checks. ReconcileChartObjects() recreates or synchronizes their drawings using stored ownership and geometry.

Each source with available data receives an initial detection scan. A successful scan establishes its bar stamps and marks the initial scan complete. Other sources remain eligible for retries from OnTick(). If initialization fails, OnDeinit() releases the allocated source handles and closes the logger. Its snapshot-save step is skipped when persistence initialization has not completed.

//+------------------------------------------------------------------+
//| Part VI updated: initialize sources and restore records          |
//+------------------------------------------------------------------+
int OnInit(void)
  {
//--- Part VI updated: configure sources, restore state, and scan available history
//--- New manual registrations take the chart timeframe; existing ownership is retained.

//--- Container setup and chart event configuration omitted.

//--- Part VI new: validate the source selections and detection window
   if(!ResolveSourceTimeframes())
     {
      Print("[BOOT ERROR] Invalid source selection/pair or detection lookback settings.");
      return(INIT_PARAMETERS_INCORRECT);
     }

//--- Part VI new: allocate an ATR handle for each active source
   if(!CreateSourceHandles())
     {
      Print("[BOOT ERROR] Failed to instantiate an ATR handle for an active source timeframe.");
      ReleaseSourceHandles();   // release whatever was created before failing
      return(INIT_FAILED);
     }

//--- Part VI new: prime available source ATR caches. Sources without ready data are retried on later ticks.
   for(int s = 0; s < g_src_count; s++)
      UpdateVolatilityCache(s);   // best effort per source
   logger.Initialize(g_src_count, g_src[0].tf, (g_src_count > 1) ? g_src[1].tf : PERIOD_CURRENT);

//--- Part VI updated: restore records before automatic detection. Restored zones and blacklist entries participate in source-specific creation checks. 
//--- Inactive-source records are retained without lifecycle processing.
//--- Stored source ownership, geometry, and lifecycle fields are restored. Initial detection runs separately for each active source with available data.
   SetupPersistencePath();
   LoadPersistState();
   if(g_persist_read_failed)
     {
      Print("[V6][BOOT] Existing snapshot could not be read; initialization stopped without overwriting it.");
      return INIT_FAILED;
     }
   ReconcileChartObjects();

//--- Part VI updated: initial scan on each active source
//--- Candidate and scoring comparisons exclude the forming bar.
   for(int s = 0; s < g_src_count; s++)
     {
      if(!UpdateVolatilityCache(s))
         continue;                                              // no ATR for this source: skip its boot scan
      if(!SourceHistoryReady(g_src[s].tf))
         continue;                                              // history not ready: retried from OnTick
      if(!DetectDynamicZones(g_src[s].tf, g_src[s].cached_atr, true))
         continue;
      g_src[s].bar1_time = iTime(_Symbol,g_src[s].tf,1);
      g_src[s].initial_scan_done = true;                        // retried from OnTick until it succeeds
      g_src[s].bar0_time = iTime(_Symbol, g_src[s].tf, 0);      // Startup detection baseline; no lifecycle replay
     }
//--- Restored states follow lifecycle processing; no quote-based startup purge runs here.
//--- Part VI updated: save the baseline, including inactive-source records
   SavePersistState();
   g_persist_loaded = true;

//--- Existing trading initialization and startup message omitted.

   return(INIT_SUCCEEDED);
  }

Processing One Source Bar

SourceHasNewBar() checks initialized sources for a current-bar timestamp different from their recorded stamp.

//+------------------------------------------------------------------+
//| Part VI new: detect an unprocessed source bar                    |
//+------------------------------------------------------------------+
bool SourceHasNewBar(void)
  {
   for(int s = 0; s < g_src_count; s++)
     {
      if(!g_src[s].initial_scan_done)
         continue;

      datetime bar0 = iTime(_Symbol, g_src[s].tf, 0);
      if(bar0 != 0 && bar0 != g_src[s].bar0_time)
         return true;
     }
   return false;
  }

ProcessSourceBar() requires a completed initial scan, a new source bar, a successful ATR update, and sufficient history. Detection runs first, followed by pending-interaction resolution, merging, and touch monitoring. Creation checks therefore use existing records before their pending states are resolved, and newly accepted zones join the remaining stages of the same pass.

Source stamps are recorded after these pipeline calls return. Readiness or detection failures leave them unchanged for another attempt.

//+------------------------------------------------------------------+
//| Part VI new: process one active source bar                       |
//+------------------------------------------------------------------+
bool ProcessSourceBar(const int s)
  {
   if(s < 0 || s >= g_src_count)
      return false;

   datetime bar0 = iTime(_Symbol, g_src[s].tf, 0);
   if(bar0 == 0 || !g_src[s].initial_scan_done)
      return false;                                   // source history not ready
   if(bar0 == g_src[s].bar0_time)
      return false;                                   // this source bar was already processed
   if(!UpdateVolatilityCache(s))
      return false;                                   // ATR unavailable: do not consume the bar
   if(g_src[s].cached_atr <= 0.0)
      return false;                                   // ATR not warm yet: consume nothing
   if(!SourceHistoryReady(g_src[s].tf))
      return false;                                   // required history unavailable: consume nothing

//--- Part VI updated: detection precedes lifecycle processing for this source
//--- Strategy entry data still follows the unchanged chart-timeframe implementation.
   if(!DetectDynamicZones(g_src[s].tf, g_src[s].cached_atr, false))
      return false;
   ResolvePendingInteractions(g_src[s].tf, g_src[s].cached_atr);
   MergeZones(g_src[s].tf, g_src[s].cached_atr);
   MonitorZoneLifecycle(logger, active_zones, g_src[s].tf, g_src[s].cached_atr, MergeSensitivity);

//--- Part VI updated: record source bar stamps after the pipeline calls return
   g_src[s].bar1_time = iTime(_Symbol, g_src[s].tf, 1);
   g_src[s].bar0_time = bar0;
   return true;
  }

Coordinating the Sources in OnTick

OnTick() saves pending persistence changes before source processing. It then saves again after processing to capture changes produced during the tick. It also retries incomplete initial scans. Unsuccessful source attempts receive a one-second delay measured with GetTickCount64(). The same per-source retry timestamp serves initial scans and ordinary source passes; it does not distinguish their failure causes. Initialized sources with unprocessed bars are handled independently. A failed H1 attempt does not prevent an available M15 source from completing its pass.

After a successful initial scan or source pass, the engine forces visual synchronization and redraws the chart. Otherwise, the engine services manual movement checks and updates visibility and appearance without forced geometry synchronization. These between-bar operations still traverse the tracked zone collection, so their cost grows with the number of records.
//+------------------------------------------------------------------+
//| Part VI updated: coordinate source processing                    |
//+------------------------------------------------------------------+
void OnTick(void)
  {
   bool any_new_bar = false;
   static ulong retry_after[MAX_SOURCE_TF] = {};
   const ulong retry_delay_ms = 1000;
   ulong now_ms = GetTickCount64();

//--- Part VI updated: save pending state changes

   if(g_persist_dirty)
      SavePersistState();

//--- Part VI new: retry initial scans when source data becomes available
   for(int s = 0; s < g_src_count; s++)
     {
      if(g_src[s].initial_scan_done)
         continue;
      if(now_ms < retry_after[s])
         continue;

      //--- Throttle unsuccessful attempts without consuming the source bar.
      retry_after[s] = now_ms + retry_delay_ms;

      if(!UpdateVolatilityCache(s))
         continue;                                   // still no ATR: retry on a later tick
      if(!SourceHistoryReady(g_src[s].tf))
         continue;                                   // history still unavailable: retry on a later tick
      if(!DetectDynamicZones(g_src[s].tf, g_src[s].cached_atr, true))
         continue;
      g_src[s].bar1_time = iTime(_Symbol,g_src[s].tf,1);
      g_src[s].initial_scan_done = true;
      g_src[s].bar0_time = iTime(_Symbol, g_src[s].tf, 0);

      retry_after[s] = 0;
      any_new_bar = true;
     }

   if(SourceHasNewBar())
     {
      //--- Part VI new: process each active source separately

      for(int s = 0; s < g_src_count; s++)
        {
         if(!g_src[s].initial_scan_done)
            continue;

         datetime bar0 = iTime(_Symbol, g_src[s].tf, 0);
         if(bar0 == 0 || bar0 == g_src[s].bar0_time)
            continue;
         if(now_ms < retry_after[s])
            continue;

         //--- A failed source pass leaves its bar stamp unchanged.
         if(!ProcessSourceBar(s))     // Source pass completed
           {
            retry_after[s] = now_ms + retry_delay_ms;
            continue;
           }

         retry_after[s] = 0;
         any_new_bar = true;
        }
     }

//--- Part VI updated: refresh chart objects using source visibility rules
   if(any_new_bar)
     {
      UpdateZoneVisuals(true);
      ChartRedraw(0);
     }
   else
     {
      //--- Part VI updated: service manual drag checks between source bars
      ServiceSourceDragEdits();

      UpdateZoneVisuals(false);
     }

   if(g_persist_dirty)
      SavePersistState();

//--- Existing risk management and trailing-stop updates omitted.
  }

ServiceSourceDragEdits() supplies cached source ATR to manual movement checks between source bars. It skips contexts whose initial scan is incomplete or whose current bar remains unprocessed.

//+------------------------------------------------------------------+
//| Part VI new: service off-bar manual movement checks              |
//+------------------------------------------------------------------+
void ServiceSourceDragEdits(void)
  {
   for(int s = 0; s < g_src_count; s++)
     {
      if(g_src[s].cached_atr <= 0.0 || !g_src[s].initial_scan_done ||
         iTime(_Symbol,g_src[s].tf,0) != g_src[s].bar0_time)
         continue;                                    // no usable ATR context for this source yet
      MonitorZoneLifecycle(logger, active_zones, g_src[s].tf, g_src[s].cached_atr, MergeSensitivity);
     }
  }

The following flowchart shows how source processing, retries, and visual updates fit together.

Fig. 2. Source Processing

Fig. 2. Source Processing and Retry Coordination


Phase 3: Extending Creation and Lifecycle Operations

Detecting and Scoring Source Candidates

DetectDynamicZones() receives the source timeframe and ATR explicitly. Its rate request uses that source, and the same arguments pass into scoring and creation. An initial scan examines the historical range. Subsequent scans examine one mature pivot index per source bar, which may qualify as a high candidate, a low candidate, or neither. A negative candidate-scoring result aborts the scan for retry without rolling back zones already accepted during that attempt.

//+------------------------------------------------------------------+
//| Part VI updated: scan candidate pivots on one source             |
//+------------------------------------------------------------------+
bool DetectDynamicZones(ENUM_TIMEFRAMES tf, double atr, bool is_initial_scan)
  {
   if(atr <= 0.0)
      return false;

   MqlRates rates[];
   ArraySetAsSeries(rates, true);

//--- Allocate the detection history window
   int bars_to_copy = LookbackBars + (SwingBars * 2) + VelocityLookaheadBars;

   if(CopyRates(_Symbol, tf, 0, bars_to_copy, rates) < bars_to_copy)
      return false;

//--- Choose an initial history scan or the latest mature candidate
   int start_index = SwingBars + VelocityLookaheadBars;
   int end_index   = is_initial_scan ? LookbackBars : (start_index + 1);

//--- Compare each candidate with neighboring source bars
   for(int i = start_index; i < end_index; i++)
     {
      bool is_high_confirmed = true;
      bool is_low_confirmed  = true;

      for(int j = 1; j <= SwingBars; j++)
        {
         if(rates[i].high <= rates[i-j].high || rates[i].high <= rates[i+j].high)
            is_high_confirmed = false;

         if(rates[i].low >= rates[i-j].low || rates[i].low >= rates[i+j].low)
            is_low_confirmed = false;

         if(!is_high_confirmed && !is_low_confirmed)
            break;
        }

      int calculated_score   = 0;
      string calculated_tier = "";
      double vol_ratio       = 0.0;
      double velo_pips       = 0.0;

      if(is_high_confirmed)
        {
         calculated_score = AnalyzeZoneCandidate(i, ZONE_RESISTANCE,
                                                 rates[i].high, tf,
                                                 atr,
                                                 vol_ratio,
                                                 velo_pips,
                                                 calculated_tier);

         if(calculated_score < 0)
            return false;
         if(calculated_score >= MinZoneScore)
           {
            TryCreateAutoZone(rates[i].high,
                              tf,
                              ZONE_RESISTANCE,
                              rates[i].time,
                              atr,
                              calculated_score,
                              calculated_tier,
                              vol_ratio,
                              velo_pips);
           }
        }

      if(is_low_confirmed)
        {
         calculated_score = AnalyzeZoneCandidate(i, ZONE_SUPPORT,
                                                 rates[i].low, tf,
                                                 atr,
                                                 vol_ratio,
                                                 velo_pips,
                                                 calculated_tier);

         if(calculated_score < 0)
            return false;
         if(calculated_score >= MinZoneScore)
           {
            TryCreateAutoZone(rates[i].low,
                              tf,
                              ZONE_SUPPORT,
                              rates[i].time,
                              atr,
                              calculated_score,
                              calculated_tier,
                              vol_ratio,
                              velo_pips);
           }
        }
     }
   return true;
  }

AnalyzeZoneCandidate() retains the established volume, departure, and symmetry components. Its market data and supplied ATR now belong to the selected source. Unfavorable signed departure is recorded as zero in velocity_pips, while the signed calculation remains the input to departure scoring.

//+------------------------------------------------------------------+
//| Part VI updated: score candidates using source data              |
//+------------------------------------------------------------------+
int AnalyzeZoneCandidate(int pivot_idx, ENUM_ZONE_TYPE type, double p, ENUM_TIMEFRAMES tf, double atr, double &vol_ratio, double &velocity_pips, string &tier)
  {
   MqlRates rates[];
   ArraySetAsSeries(rates, true);

//--- Allocate the candidate scoring window
   int macro_window = SwingBars * 2;
   int sample_period = 14;

//--- Include the larger volume or symmetry history requirement
   int max_historical_offset = (macro_window > sample_period) ? macro_window : sample_period;
   int check_bars = pivot_idx + max_historical_offset + VelocityLookaheadBars + 5; // dynamic padding margin

   if(CopyRates(_Symbol, tf, 0, check_bars, rates) < check_bars)
     {
      vol_ratio = 1.0;
      velocity_pips = 0.0;
      tier = "LOW";
      return -1;
     }

//--- Unchanged tick-volume scoring omitted.

//--- ATR-normalized departure component
   int velocity_score = 0;
   velocity_pips = 0.0;

   if(pivot_idx >= 1)
     {
      double price_departure = 0.0;
      //--- Use a post-pivot close from the scoring window.
      int forward_target_idx = (pivot_idx >= VelocityLookaheadBars) ? (pivot_idx - VelocityLookaheadBars) : 1;

      if(type == ZONE_RESISTANCE)
         price_departure = p - rates[forward_target_idx].close;
      else
         price_departure = rates[forward_target_idx].close - p;

      double pip_multiplier = (_Digits == 3 || _Digits == 5) ? 10.0 : 1.0;
      //--- Store favorable departure only; unfavorable movement is zero for telemetry and persistence.
      velocity_pips = (MathMax(0.0, price_departure) / _Point) / pip_multiplier;

      double displacement_ratio = (atr > 0) ? (price_departure / atr) : 1.0;

      //--- Unchanged velocity-score mapping omitted.
     }

//--- Unchanged symmetry scoring, combined score, tier assignment,
//--- and return statement omitted.
  }

Applying Source-Specific Creation Checks

TryCreateAutoZone() filters candidate direction against the current quote, then applies duplicate and proximity checks within the candidate’s source. Duplicate detection considers creation timestamp, type, and timeframe. Blacklist proximity and nearby-zone suppression are also source-specific. An M15 record therefore does not suppress an H1 candidate solely because their prices are close.

//+------------------------------------------------------------------+
//| Part VI updated: source-specific creation checks                 |
//+------------------------------------------------------------------+
void TryCreateAutoZone(double p, ENUM_TIMEFRAMES tf,
                       ENUM_ZONE_TYPE t,
                       datetime dt,
                       double atr,
                       int score,
                       string tier,
                       double vol_ratio,
                       double velo_pips)
  {
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);

//--- Filter candidate direction against the current quote
   if(t == ZONE_SUPPORT && p > bid)
      return;

   if(t == ZONE_RESISTANCE && p < ask)
      return;

//--- Part VI updated: check duplicate timestamp, type, and source
   for(int i = 0; i < active_zones.Total(); i++)
     {
      CZone *z = (CZone*)active_zones.At(i);
      if(z == NULL)
         continue;

      if(z.created == dt && z.type == t && z.source_tf == tf)   // duplicate identity is source-aware
         return;
     }

   double merge_threshold = atr * MergeSensitivity;

//--- Part VI updated: check blacklist proximity within the same source
   for(int i = 0; i < blacklist.Total(); i++)
     {
      ENUM_TIMEFRAMES bl_tf = PERIOD_CURRENT;              // blacklist identity is source-aware
      double blacklisted_price = 0.0;
      if(!ParseBlacklistKey(blacklist.At(i), bl_tf, blacklisted_price))
         continue;
      if(bl_tf != tf)
         continue;
      if(MathAbs(blacklisted_price - p) < merge_threshold)
         return;
     }

//--- Part VI updated: prevent nearby candidates within the same source
   for(int i = 0; i < active_zones.Total(); i++)
     {
      CZone *z = (CZone*)active_zones.At(i);
      if(z == NULL)
         continue;

      if(z.source_tf == tf && MathAbs(z.price_level - p) < merge_threshold)   // same source timeframe only
         return;
     }

//--- Construct the automatic zone with its source timeframe
   CZone *nz = new CZone(p, t, dt, atr, tf);
   if(CheckPointer(nz) == POINTER_INVALID)
     {
      PrintFormat("[V6][AUTO] Zone allocation failed for source %s.",
                  EnumToString(tf));
      return;
     }

//--- Part VI updated: include source timeframe in the object ID
   string tf_id = IntegerToString((int)tf);   // the zone's OWN source timeframe, not the chart timeframe

   nz.name = (t == ZONE_SUPPORT ? "S_" : "R_") + tf_id + "_" +
             DoubleToString(p, _Digits) + "_" +
             IntegerToString((long)dt);

// Do not take ownership of an existing object with the generated name.
   if(GetZoneByName(nz.name) != NULL || ObjectFind(0, nz.name) >= 0)
     {
      PrintFormat("[V6][AUTO] Creation skipped: zone/object name '%s' already exists.",
                  nz.name);
      delete nz;
      return;
     }

   nz.is_user_zone = false;

//--- Assign candidate scoring fields
   nz.zone_score         = score;
   nz.Current_zone_score = score;
   nz.zone_tier          = tier;
   nz.initial_volume_ratio = vol_ratio;
   nz.departure_velocity   = velo_pips;

//--- Initialize lifecycle telemetry
   nz.touch_count        = 0;
   nz.bounce_count       = 0;
   nz.failure_count      = 0;
   nz.resurrection_count = 0;
   nz.max_reaction_pips  = 0.0;
   nz.breakout_quality   = "NONE";

//--- Normalize bounds before logging
   if(nz.top <= 0.0 || nz.bottom <= 0.0)
     {
      nz.top    = (t == ZONE_RESISTANCE) ? p : p + atr * 0.5;
      nz.bottom = (t == ZONE_SUPPORT) ? p : p - atr * 0.5;
      nz.height = nz.top - nz.bottom;
      nz.price_level = (nz.top + nz.bottom) / 2.0;
     }

//--- Register the zone and schedule persistence
   if(!active_zones.Add(nz))
     {
      PrintFormat("[V6][AUTO] Registration failed for zone '%s'.", nz.name);
      delete nz;
      return;
     }

   MarkPersistDirty();   // Schedule the new zone for persistence

//--- Build creation telemetry
   string context_info = StringFormat(
                            "SrcTF:%s|Score:%d|Tier:%s|VolRatio:%.2f|VeloPips:%.1f|Touches:%d|Bounces:%d|Failures:%d|Resurrections:%d|MaxReaction:%.1f|AgeBars:0|Absorbed:NONE|Status:CREATED",
                            EnumToString(nz.source_tf),
                            nz.zone_score,
                            nz.zone_tier,
                            nz.initial_volume_ratio,
                            nz.departure_velocity,
                            nz.touch_count,
                            nz.bounce_count,
                            nz.failure_count,
                            nz.resurrection_count,
                            nz.max_reaction_pips
                         );

   string explicit_type = (t == ZONE_SUPPORT) ? "SUPPORT" : "RESISTANCE";

   string details = StringFormat(
                       ">>> Quantitative automated %s zone registered successfully.",
                       explicit_type
                    );

//--- Part VI updated: log creation with source ownership
   logger.LogZone("AUTO",
                  ZE_CREATED,
                  nz.name,
                  "ZONE_" + explicit_type,
                  tf,
                  nz.top,
                  nz.bottom,
                  context_info,
                  details);
  }

For a removed AUTO zone, the stored price is its midpoint. Candidate suppression compares the candidate price with that midpoint using the source ATR multiplied by MergeSensitivity; it does not compare against the removed zone’s full bounds. Source tagging prevents cross-source suppression but does not guarantee suppression across the deleted zone’s entire price range.

//+------------------------------------------------------------------+
//| Part VI new: build a source-tagged blacklist key                 |
//+------------------------------------------------------------------+
string BlacklistKey(ENUM_TIMEFRAMES tf, double price)
  {
   return IntegerToString((int)tf) + "|" + DoubleToString(price, _Digits);
  }

//+------------------------------------------------------------------+
//| Part VI new: parse a source-tagged blacklist key                 |
//+------------------------------------------------------------------+
bool ParseBlacklistKey(const string key, ENUM_TIMEFRAMES &tf, double &price)
  {
   int sep = StringFind(key, "|");
   if(sep <= 0)
      return false;
   tf    = (ENUM_TIMEFRAMES)StringToInteger(StringSubstr(key, 0, sep));
   price = StringToDouble(StringSubstr(key, sep + 1));
   return ZPValidSource((int)tf) && MathIsValidNumber(price);
  }

In the code above, accepted candidates receive a source-tagged name and enter the tracking collection before their rectangles are created. The name-collision check prevents adoption of an existing chart object.

Architectural note: Historical pivots are filtered against the current quote. The initial scan is not a complete reconstruction of every zone that might have existed historically. It evaluates historical candidates in the current price context.

Monitoring and Resolving Interactions

MonitorZoneLifecycle() uses source-bar stamps and filters records by source_tf. Normal touches use the latest completed source bar; manual movement checks use the current bid. A touch starts an interaction only when none is pending. ResolvePendingInteractions() handles break and bounce confirmation on subsequent source passes.

//+------------------------------------------------------------------+
//| Part VI updated: source-bar and manual touch checks              |
//+------------------------------------------------------------------+
void MonitorZoneLifecycle(CLogger &log_instance, CArrayObj &zones, ENUM_TIMEFRAMES tf, double atr, double multiplier)
  {
   int src_index = SourceIndex(tf);
   if(src_index < 0)
      return;                                         // pass bound to an inactive source: nothing to do
   datetime bar_time = iTime(_Symbol, tf, 1);         // this source's last CLOSED bar (index 1)
   if(bar_time == 0)
      return;                                         // source history not ready on this tick

   bool is_new_bar = (bar_time != g_src[src_index].bar1_time &&
                      iTime(_Symbol,tf,0) != g_src[src_index].bar0_time);

//--- Process a new source bar, or a pending manual movement check
   if(!is_new_bar)
     {
      bool work_to_do = false;
      for(int i = 0; i < zones.Total(); i++)
        {
         CZone *z = (CZone*)zones.At(i);
         if(z != NULL)
           {
            if(z.source_tf == tf && z.is_user_zone && z.was_recently_moved)
              {
               work_to_do = true;
               break;
              }
           }
        }
      if(!work_to_do)
        {
         return;
        }
     }
   else
     {
      // ProcessSourceBar() records bar1_time after its pipeline calls return.
     }

   double tolerance = atr * multiplier;

//--- Read the latest completed source bar
   double high  = iHigh(_Symbol, tf, 1);              // this source's last closed bar
   double low   = iLow(_Symbol, tf, 1);
   double close = iClose(_Symbol, tf, 1);

//--- Reject unavailable bar values before processing zones
   if(high <= 0.0 || low <= 0.0 || close <= 0.0)
      return;                                         // bar data unavailable: skip this monitoring call

//--- Read the current bid for manual movement checks
   double live_bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

   for(int i = zones.Total() - 1; i >= 0; i--)
     {
      CZone *z = (CZone*)zones.At(i);
      if(z == NULL || z.is_broken || z.source_tf != tf) // Only live structures of THIS source
         continue;

      //--- Select completed-bar or manual movement evaluation
      bool evaluation_triggered = false;
      bool touched = false;

      //--- Manual movement: evaluate the current bid
      if(z.is_user_zone && z.was_recently_moved)
        {
         evaluation_triggered = true;
         z.was_recently_moved = false; // Clear the pending movement flag before evaluating the touch

         double upper_limit = z.top + tolerance;
         double lower_limit = z.bottom - tolerance;
         touched = (live_bid <= upper_limit && live_bid >= lower_limit);
        }
      //--- Completed-bar evaluation
      else
         if(is_new_bar)
           {
            evaluation_triggered = true;

            //--- Apply shared decay settings on this source bar
            if(EnableTemporalDecay)
              {
               z.Current_zone_score = MathMax(0.0, z.Current_zone_score - DecayRatePerBar);
               MarkPersistDirty();   // Part VI updated: temporal decay -> persist evolving score
              }

            touched = (low <= z.top + tolerance && high >= z.bottom - tolerance);
           }

      // Skip zones without an evaluation trigger.
      if(!evaluation_triggered)
         continue;

      //--- Start a touch only when no interaction is pending
      if(z.is_pending || !touched)
         continue;

      //--- Enter pending state and increment the touch count
      z.is_pending = true;
      z.touch_count++;
      MarkPersistDirty();   // Part VI updated: touch + pending-state change -> persist telemetry/lifecycle
      z.last_touch_time = iTime(_Symbol,tf,(z.is_user_zone && !is_new_bar) ? 0 : 1); // source bar of interaction
      z.consecutive_rejection_closes = 0; // Reset rejection validation counter

      //--- Calculate current live age of the structure in bars
      int current_age = iBarShift(_Symbol, tf, z.created);   // age measured on the zone's own source timeframe

      //--- Part VI updated: include source timeframe in touch telemetry
      string context = StringFormat("SrcTF:%s|Score:%d|CurrentScore:%.2f|Birth Tier:%s|VolRatio:%.2f|VeloPips:%.1f|Touches:%d|Bounces:%d|Failures:%d|Resurrections:%d|MaxReaction:%.1f|AgeBars:%d|Status:PENDING_TEST",
                                    EnumToString(z.source_tf), z.zone_score, z.Current_zone_score, z.zone_tier, z.initial_volume_ratio, z.departure_velocity,
                                    z.touch_count, z.bounce_count, z.failure_count, z.resurrection_count, z.max_reaction_pips, current_age);

      string details = StringFormat(">>> LIVE ZONE PENDING %s | T:%d B:%d F:%d Status:%s",
                                    z.name, z.touch_count, z.bounce_count, z.failure_count, EnumToString(z.status));

      string dynamic_source = z.is_user_zone ? "USER" : "AUTO";

      log_instance.LogZone(dynamic_source,
                           ZE_UPDATED,
                           z.name,
                           EnumToString(z.type),
                           z.source_tf,
                           z.top,
                           z.bottom,
                           context,
                           details);
     }
  }
ResolvePendingInteractions() reads completed source prices and applies the existing confirmation, ghost expiry, and resurrection rules. Zone ages are measured in source bars. The retained strategy reads chart-timeframe candles, so its call is limited to the lower source and only when the chart matches that source. Successful trades do not consume zones. Later entries remain subject to existing strategy and position checks. Code that does not carry the new source coordination — trading internals, trailing-stop handling, and unchanged lifecycle rules — remains in the downloadable sources and is omitted from the implementation listings.
//+------------------------------------------------------------------+
//| Part VI updated: resolve source-bar interactions                 |
//+------------------------------------------------------------------+
void ResolvePendingInteractions(ENUM_TIMEFRAMES tf, double atr)
  {
   double last_close  = iClose(_Symbol, tf, 1);        // this source's last CLOSED bar
   double last_high   = iHigh(_Symbol, tf, 1);
   double last_low    = iLow(_Symbol, tf, 1);

//--- Existing pip conversion and entry warning omitted.

   for(int i = active_zones.Total() - 1; i >= 0; i--)
     {
      CZone *z = (CZone*)active_zones.At(i);

      if(z == NULL || z.type == ZONE_NEUTRAL || z.source_tf != tf)   // this source only
         continue;

      int current_age = iBarShift(_Symbol, tf, z.created);   // age measured on the zone's own source timeframe

      //--- Existing reaction tracking, ghost expiry, and resurrection omitted.

      //--- Pending interaction resolution
      if(!z.is_pending)
         continue;
      //--- A completed bar predating this interaction cannot confirm it.
      if(iTime(_Symbol,tf,1) < z.last_touch_time)
         continue;

      //--- Part VI updated: lower-source entry bridge to the unchanged strategy
      // The chart must match the lower source because the strategy reads _Period candles.
      if(tf == InpLowerTimeframe &&
         (ENUM_TIMEFRAMES)_Period == InpLowerTimeframe &&
         CheckTradingSignals && g_strategy != NULL && g_trade != NULL)
        {
         if(g_strategy.EvaluateSingleZoneSignal(g_trade, atr, z.name, z.type, z.top, z.bottom,
                                                z.is_broken, z.is_pending, z.Current_zone_score,
                                                z.buy_triggered, z.sell_triggered))
           {
            // The strategy reported successful execution routing.
           }
        }

      //--- Existing break/bounce confirmation omitted.
     }
  }

Restricting Merges

MergeZones() permits same type AUTO zones to merge within one source. Manual and broken zones are excluded, leaving ghosts to expiry and resurrection.

//+------------------------------------------------------------------+
//| Part VI updated: merge AUTO zones within one source              |
//+------------------------------------------------------------------+
void MergeZones(ENUM_TIMEFRAMES tf, double atr)
  {
   if(atr <= 0.0)
      return;
   double merge_threshold = atr * MergeSensitivity;

   for(int i = active_zones.Total() - 1; i >= 1; i--)
     {
      CZone* z1 = (CZone*)active_zones.At(i);
      if(z1 == NULL || z1.source_tf != tf)      // never merge across source timeframes
         continue;

      //--- Leave broken zones to expiry or resurrection
      if(z1.is_broken)
         continue;

      for(int j = i - 1; j >= 0; j--)
        {
         CZone* z2 = (CZone*)active_zones.At(j);
         if(z2 == NULL || z2.source_tf != tf)   // never merge across source timeframes
            continue;

         //--- Leave broken zones to expiry or resurrection
         if(z2.is_broken)
            continue;

         if(z1.type != z2.type)
            continue;

         //--- Exclude manual zones from merging
         if(z1.is_user_zone || z2.is_user_zone)
            continue;

         double space_distance = MathAbs(z1.price_level - z2.price_level);
         if(space_distance > merge_threshold)
            continue;

         //--- Capture the absorbed zone name before removal
         string z2_dead_name = z2.name;

         //--- Existing score, telemetry, pending-state, and geometry consolidation omitted.

         //--- Part VI updated: measure age in source bars
         int consolidated_age = iBarShift(_Symbol, tf, z1.created);   // age on the zone's own source timeframe

         //--- Merge telemetry and logging omitted.

         //--- Remove the absorbed zone object and record
         ObjectDelete(0, z2_dead_name);
         MarkPersistDirty();   // Part VI updated: absorbed AUTO zone persisted active state keeps survivor only
         active_zones.Delete(j);
         break;
        }
     }
  }

The excerpt shows the source-specific merge conditions; the field-consolidation steps are omitted.


Phase 4: Source-Specific Display and Manual Interaction

Applying Visibility Rules

Both sources can continue processing independently, but their drawings must remain associated with the timeframe that produced them. Switching the chart period must not change a zone’s source ownership.

SourceVisibilityMask() first checks whether the zone’s source belongs to the active configuration. Inactive sources receive OBJ_NO_PERIODS, keeping their drawings hidden while retaining their records. An active source receives the visibility flag for its own chart period. ApplyZoneVisibility() assigns this mask to the rectangle and permits selection only when its source is active and matches the displayed chart period. It clears selection only when these conditions are not met, preserving the user’s selection during valid editing.

//+------------------------------------------------------------------+
//| Part VI new: source-specific chart visibility                    |
//+------------------------------------------------------------------+
long SourceVisibilityMask(ENUM_TIMEFRAMES tf)
  {
   if(!IsActiveSource(tf))
      return OBJ_NO_PERIODS;
   switch(tf)
     {
      case PERIOD_M1:
         return OBJ_PERIOD_M1;
      case PERIOD_M2:
         return OBJ_PERIOD_M2;
      case PERIOD_M3:
         return OBJ_PERIOD_M3;
      case PERIOD_M4:
         return OBJ_PERIOD_M4;
      case PERIOD_M5:
         return OBJ_PERIOD_M5;
      case PERIOD_M6:
         return OBJ_PERIOD_M6;
      case PERIOD_M10:
         return OBJ_PERIOD_M10;
      case PERIOD_M12:
         return OBJ_PERIOD_M12;
      case PERIOD_M15:
         return OBJ_PERIOD_M15;
      case PERIOD_M20:
         return OBJ_PERIOD_M20;
      case PERIOD_M30:
         return OBJ_PERIOD_M30;
      case PERIOD_H1:
         return OBJ_PERIOD_H1;
      case PERIOD_H2:
         return OBJ_PERIOD_H2;
      case PERIOD_H3:
         return OBJ_PERIOD_H3;
      case PERIOD_H4:
         return OBJ_PERIOD_H4;
      case PERIOD_H6:
         return OBJ_PERIOD_H6;
      case PERIOD_H8:
         return OBJ_PERIOD_H8;
      case PERIOD_H12:
         return OBJ_PERIOD_H12;
      case PERIOD_D1:
         return OBJ_PERIOD_D1;
      case PERIOD_W1:
         return OBJ_PERIOD_W1;
      case PERIOD_MN1:
         return OBJ_PERIOD_MN1;
     }
   return OBJ_NO_PERIODS;
  }
//+------------------------------------------------------------------+
//| Part VI new: apply visibility and selection rules                |
//+------------------------------------------------------------------+
void ApplyZoneVisibility(const CZone *z)
  {
   if(z != NULL && ObjectFind(0, z.name) >= 0)
     {
      ObjectSetInteger(0, z.name, OBJPROP_TIMEFRAMES, SourceVisibilityMask(z.source_tf));

      //--- Selection is permitted only on the active source chart
      bool is_current_tf = IsActiveSource(z.source_tf) &&
                           z.source_tf == (ENUM_TIMEFRAMES)_Period;
      ObjectSetInteger(0, z.name, OBJPROP_SELECTABLE, is_current_tf);

      //--- Preserve selection during valid user interaction
      if(!is_current_tf)
         ObjectSetInteger(0, z.name, OBJPROP_SELECTED, false);
     }
  }

Visibility determines where a rectangle appears; visual synchronization determines how that rectangle reflects the stored zone state. These responsibilities must remain separate from the source’s detection and lifecycle processing.

UpdateZoneVisuals() creates rectangles for records not yet marked as drawn and applies the source visibility rules. Further synchronization is restricted to active-source zones whose source matches the displayed chart period. When force_time_extension is true, it copies the stored price bounds and advances the right edge. AUTO rectangles retain their creation timestamp as the left anchor, while USER rectangles retain their existing left anchor. Color and fill are then updated from the zone’s stored state. Other-source drawings retain their previous geometry in this routine until reconciliation, or a later synchronization updates them.

//+------------------------------------------------------------------+
//| Part VI updated: synchronize source-chart visuals                |
//+------------------------------------------------------------------+
void UpdateZoneVisuals(bool force_time_extension)
  {
   int total_zones = active_zones.Total();
   if(total_zones == 0)
      return;

   for(int i = 0; i < total_zones; i++)
     {
      CZone *z = (CZone*)active_zones.At(i);
      if(z == NULL)
         continue;

      //--- Part VI updated: create tracked objects and apply source visibility.
      //--- Active-source objects display only on their source chart; inactive sources are hidden.
      if(!z.was_drawn)
        {
         if(!ObjectCreate(0, z.name, OBJ_RECTANGLE, 0, z.created, z.top, TimeCurrent(), z.bottom))
            continue;

         ObjectSetInteger(0, z.name, OBJPROP_BACK, true);
         ObjectSetInteger(0, z.name, OBJPROP_RAY_RIGHT, true); // Set the rectangle right-ray property
         ObjectSetInteger(0, z.name, OBJPROP_SELECTABLE, z.source_tf == (ENUM_TIMEFRAMES)_Period);
         ObjectSetString(0, z.name, OBJPROP_TEXT, z.is_user_zone ? "USER" : "AUTO");

         //--- Record that the chart object was created.
         z.was_drawn = true;
        }

      ApplyZoneVisibility(z);

      //--- Part VI updated: limit visual synchronization to the active source chart Other-source objects retain their stored bounds in this routine.
      //--- Lifecycle processing uses separate source passes.
      if(!IsActiveSource(z.source_tf) || z.source_tf != (ENUM_TIMEFRAMES)_Period)
         continue;

      if(force_time_extension)
        {
         //--- Synchronize prices and the managed right edge USER price bounds come from stored edits; their left anchor is retained.
         //--- AUTO left anchors use the zone creation timestamp. The right edge is advanced only for the displayed active source.
         if(!z.is_user_zone)
           {
            ObjectSetInteger(0, z.name, OBJPROP_TIME, 1, TimeCurrent()); // Move edge to live bar
            ObjectSetInteger(0, z.name, OBJPROP_TIME, 0, z.created);    // Keep anchored to origin
           }

         else
           {
            ObjectSetInteger(0, z.name, OBJPROP_TIME, 1, TimeCurrent()); // USER: refresh right anchor only
           }
         ObjectSetDouble(0, z.name, OBJPROP_PRICE, 0, z.top);
         ObjectSetDouble(0, z.name, OBJPROP_PRICE, 1, z.bottom);
        }

      //--- Synchronize color and fill with the stored state
      ObjectSetInteger(0, z.name, OBJPROP_COLOR, z.GetColor());
      ObjectSetInteger(0, z.name, OBJPROP_FILL, z.is_broken ? false : true);
     }
  }

For example, an M15 source attached to M30 continues processing M15 data. Its managed zones are hidden on M30 and displayed when the chart switches to M15.

Registering Manual Rectangles

A manually drawn rectangle needs a definite source before it can participate in the engine’s lifecycle. Registration therefore uses the chart period at the moment the drawing is accepted, provided that period is an active source.

RegisterUserZone() rejects missing objects, already tracked objects, and objects that are not rectangles. It then validates the chart period and locates its source context. The rectangle’s midpoint relative to the current bid determines its initial support or resistance type. The constructor receives that source’s cached ATR, after which the user’s actual price bounds replace the constructor’s initial geometry. 

The new record retains the rectangle's original name and receives the manual score baseline of MinZoneScore. That baseline is an initial score rather than a protected floor; subsequent lifecycle scoring can move the live score below it. Once added to the tracked collection, its visibility is applied and the persistence state is marked dirty.

//+------------------------------------------------------------------+
//| Part VI updated: register on an active source chart              |
//+------------------------------------------------------------------+
bool RegisterUserZone(string obj_name)
  {
   if(ObjectFind(0, obj_name) < 0 || GetZoneByName(obj_name) != NULL)   // Skip missing or already tracked objects
      return false;

   if(ObjectGetInteger(0, obj_name, OBJPROP_TYPE) != OBJ_RECTANGLE)
      return false;

//--- Part VI updated: register rectangles only on an active source chart. 
//--- Rectangles on other chart timeframes are not registered by this function.
   if(!IsActiveSource((ENUM_TIMEFRAMES)_Period))
     {
      //--- Diagnostic omitted.
      return false;
     }

   int source_index = SourceIndex((ENUM_TIMEFRAMES)_Period);
   if(source_index < 0 || source_index >= g_src_count)
     {
      //--- Diagnostic omitted.
      return false;
     }

   double boundary_p1 = ObjectGetDouble(0, obj_name, OBJPROP_PRICE, 0);
   double boundary_p2 = ObjectGetDouble(0, obj_name, OBJPROP_PRICE, 1);
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

//--- Part VI updated: use the registration chart as the source timeframe.
//--- The constructor receives that source ATR cache; manual bounds replace its initial bounds.
   double passed_atr = g_src[source_index].cached_atr;

   ENUM_ZONE_TYPE derived_type = ((boundary_p1 + boundary_p2) / 2.0 > bid) ? ZONE_RESISTANCE : ZONE_SUPPORT;
   CZone* new_zone = new CZone((boundary_p1 + boundary_p2) / 2.0, derived_type, TimeCurrent(), passed_atr, (ENUM_TIMEFRAMES)_Period);

   if(CheckPointer(new_zone) == POINTER_INVALID)
     {
      //--- Diagnostic omitted.
      return false;
     }

   new_zone.name      = obj_name;
   new_zone.source_tf = (ENUM_TIMEFRAMES)_Period;   // permanent source: the chart timeframe at registration
   new_zone.is_user_zone = true;
   new_zone.was_recently_moved = true;
   new_zone.top = MathMax(boundary_p1, boundary_p2);
   new_zone.bottom = MathMin(boundary_p1, boundary_p2);
   new_zone.height = new_zone.top - new_zone.bottom;
   new_zone.price_level = (new_zone.top + new_zone.bottom) / 2.0;
   new_zone.was_drawn = true;

//--- Manual zone baseline: seed the score at MinZoneScore Candidate scoring is applied to automatic zones, not manual drawings.
   new_zone.zone_score           = MinZoneScore;
   new_zone.Current_zone_score   = MinZoneScore;

//--- Existing tier assignment and time-anchor setup omitted.

   if(!active_zones.Add(new_zone))
     {
      delete new_zone;
      //--- Diagnostic omitted.
      return false;
     }

//--- Existing chart-object styling omitted.

   ApplyZoneVisibility(new_zone);
   MarkPersistDirty();   // Part VI updated: newly registered USER zone must be persisted
   return true;
  }

Architectural note: Reconciliation does not automatically adopt untracked rectangles already on the chart. Registration occurs through creation events or the accepted edit path. The registration listing omits diagnostic messages. A rectangle rejected on a non-source chart remains unregistered; it does not acquire source ownership merely by remaining on the chart.

Editing and Deleting Tracked Zones

Chart events must distinguish a new manual drawing from an existing managed zone. This prevents an engine-created rectangle from being registered again and keeps the event log consistent with the action actually accepted.

OnChartEvent() handles creation, editing, and deletion through exact tracked-name lookup. Creation events attempt registration only for untracked rectangles. Drag and edit events call UpdateZoneCoordinates() and use its acceptance result: an existing record produces a modification event, while an accepted untracked rectangle produces a creation event.

For deletion, the handler first checks that the drawing is still absent, avoiding an earlier notification for an object already restored. It then removes tracked records belonging to active sources. Inactive-source records are retained even when their chart object has been deleted.

//+------------------------------------------------------------------+
//| Part VI updated: source-aware chart event handling               |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
  {
//--- Manual rectangle creation
   if(id == CHARTEVENT_OBJECT_CREATE)
     {
      //--- Exclude objects already registered by the zone engine
      if(GetZoneByName(sparam) != NULL)
         return;

      if(ObjectFind(0, sparam) >= 0 &&
         ObjectGetInteger(0, sparam, OBJPROP_TYPE) == OBJ_RECTANGLE)
        {
         if(RegisterUserZone(sparam))
           {
            CZone *z = GetZoneByName(sparam);
            if(z == NULL)
               return;

            //--- Creation message and ZE_CREATED logging omitted.
           }
        }
     }

//--- Manual rectangle drag and edit events
   else
      if(id == CHARTEVENT_OBJECT_DRAG || id == CHARTEVENT_OBJECT_ENDEDIT)
        {
         if(ObjectFind(0, sparam) >= 0 &&
            ObjectGetInteger(0, sparam, OBJPROP_TYPE) == OBJ_RECTANGLE)
           {
            bool was_tracked = (GetZoneByName(sparam) != NULL);
            bool edit_accepted = UpdateZoneCoordinates(sparam);

            CZone *z = GetZoneByName(sparam);
            if(edit_accepted && z != NULL)
              {
               if(was_tracked)
                 {
                  //--- Modification message and ZE_MODIFIED logging omitted.
                 }
               else
                 {
                  //--- An untracked rectangle accepted here is a new registration.
                  //--- Creation message and ZE_CREATED logging omitted.
                 }
              }
            ChartRedraw(0);
           }
        }

      //--- Chart object deletion
      else
         if(id == CHARTEVENT_OBJECT_DELETE)
           {
            //--- Ignore an earlier deletion notification if the object has been restored.
            if(ObjectFind(0, sparam) >= 0)
               return;

            CZone *z = GetZoneByName(sparam);
            if(z == NULL)
               return;

            //--- Part VI updated: preserve records belonging to inactive sources.
            //--- Removing their chart object does not remove the stored zone here.
            if(!IsActiveSource(z.source_tf))
              {
               ChartRedraw(0);
               return;
              }

            //--- Deletion diagnostic omitted; RemoveZoneByName() logs ZE_DELETED.

            //--- Remove the tracked record for an active source
            RemoveZoneByName(sparam);
            ChartRedraw(0);
           }
  }

Editing a rectangle may change its geometry and management status but must preserve its source timeframe. The engine therefore validates the edit against the tracked record before accepting the new coordinates.

UpdateZoneCoordinates() rejects edits when the stored source is inactive or differs from the chart period. It restores the saved price bounds and time anchors before returning false. An untracked rectangle instead passes through manual registration.

For an accepted tracked edit, the function recalculates the bounds, height, and midpoint, then marks the zone for movement evaluation. An AUTO zone becomes USER-managed and its support or resistance type is recalculated against the current bid. An already-manual zone retains its type. In both cases, source_tf remains unchanged. The accepted left anchor is captured, the managed right edge is reset to the current time, and the updated state is marked for persistence.

//+------------------------------------------------------------------+
//| Part VI updated: accept source-chart geometry edits              |
//+------------------------------------------------------------------+
bool UpdateZoneCoordinates(string obj_name)
  {
   if(ObjectFind(0, obj_name) < 0 ||
      ObjectGetInteger(0, obj_name, OBJPROP_TYPE) != OBJ_RECTANGLE)
      return false;

   CZone* existing_zone = NULL;

   for(int z = 0; z < active_zones.Total(); z++)
     {
      CZone* zone_ptr = (CZone*)active_zones.At(z);
      if(zone_ptr != NULL && zone_ptr.name == obj_name)
        {
         existing_zone = zone_ptr;
         break;
        }
     }

//--- Part VI updated: reject edits from another source chart.
//--- Restore stored price bounds and time anchors on rejection.
   if(existing_zone != NULL &&
      (existing_zone.source_tf != (ENUM_TIMEFRAMES)_Period ||
       !IsActiveSource(existing_zone.source_tf)))
     {
      ObjectSetDouble(0, obj_name, OBJPROP_PRICE, 0, existing_zone.top);
      ObjectSetDouble(0, obj_name, OBJPROP_PRICE, 1, existing_zone.bottom);
      ObjectSetInteger(0, obj_name, OBJPROP_TIME, 0,
                       (existing_zone.time_left != 0) ? existing_zone.time_left : existing_zone.created);
      ObjectSetInteger(0, obj_name, OBJPROP_TIME, 1,
                       (existing_zone.time_right != 0) ? existing_zone.time_right : TimeCurrent());
      ApplyZoneVisibility(existing_zone);
      ChartRedraw(0);
      return false;
     }

//--- Skip logical edits for unknown objects or inactive sources
   if(existing_zone == NULL)
     {
      //--- Attempt manual registration for an untracked rectangle, regardless of its name prefix.
      return RegisterUserZone(obj_name);
     }

   double boundary_p1 = ObjectGetDouble(0, obj_name, OBJPROP_PRICE, 0);
   double boundary_p2 = ObjectGetDouble(0, obj_name, OBJPROP_PRICE, 1);

   existing_zone.top = MathMax(boundary_p1, boundary_p2);
   existing_zone.bottom = MathMin(boundary_p1, boundary_p2);
   existing_zone.height = existing_zone.top - existing_zone.bottom;
   existing_zone.price_level = (existing_zone.top + existing_zone.bottom) / 2.0;
   existing_zone.was_recently_moved = true;

//--- Convert a manually edited automatic zone to user ownership
   if(!existing_zone.is_user_zone)
     {
      existing_zone.is_user_zone = true;
      ObjectSetString(0, existing_zone.name, OBJPROP_TEXT, "USER");

      //--- Reclassify support/resistance when converting an automatic zone.
      double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
      existing_zone.type = (existing_zone.price_level > bid) ? ZONE_RESISTANCE : ZONE_SUPPORT;
     }

//--- Part VI updated: retain source ownership during accepted edits.
//--- The guard above accepts geometry edits only on the source chart.
//--- Synchronize the edited anchors and appearance
   existing_zone.time_left  = (datetime)ObjectGetInteger(0, obj_name, OBJPROP_TIME, 0);   // Part V: capture the accepted left anchor
   existing_zone.time_right = TimeCurrent();
   ObjectSetInteger(0, obj_name, OBJPROP_TIME, 1, existing_zone.time_right); // Reset the managed right edge
   ObjectSetInteger(0, obj_name, OBJPROP_RAY_RIGHT, true);
   ObjectSetInteger(0, obj_name, OBJPROP_COLOR, existing_zone.GetColor());
   MarkPersistDirty();   // Part VI updated: zone geometry modified persist updated bounds
   return true;
  }  

Deleting an active-source drawing removes its tracked logical record. For an AUTO zone, deletion also adds source-specific suppression for nearby automatic candidates.

RemoveZoneByName() finds the record by its exact name. If the record is still AUTO-managed, it adds a blacklist key containing the source timeframe and price level. USER-managed records do not receive this suppression, including former AUTO zones converted through editing. A similar AUTO zone can therefore be created later if it passes the normal creation checks.

Before releasing the record, the function captures its event details, marks persistence dirty, and logs ZE_DELETED with the stored source timeframe. It then removes the zone from the tracked collection. The blacklist consequently remains source-specific rather than suppressing candidates across both timeframes.

//+------------------------------------------------------------------+
//| Part VI updated: remove zone and tag AUTO blacklist              |
//+------------------------------------------------------------------+
void RemoveZoneByName(string obj_name)
  {
   for(int i = active_zones.Total() - 1; i >= 0; i--)
     {
      CZone* z = (CZone*)active_zones.At(i);
      if(z == NULL)
         continue;

      if(z.name == obj_name)
        {
         if(!z.is_user_zone)
           {
            //--- Part VI updated: blacklist the price within its source timeframe
            blacklist.Add(BlacklistKey(z.source_tf, z.price_level));   // source-aware identity
           }

         //--- Clear the drawing flag before removing the record
         z.was_drawn = false;

         //--- Capture event fields before releasing the zone
         string z_source = z.is_user_zone ? "USER" : "AUTO";
         string z_type = EnumToString(z.type);
         double z_top = z.top;
         double z_bottom = z.bottom;

         //--- Record logical removal
         string details = ">>> Memory cleared for internal object tracking array handle: " + obj_name;
         MarkPersistDirty();   // Schedule removal state for persistence

         //--- Log the event before deleting the zone object
         logger.LogZone(z_source,
                        ZE_DELETED,
                        obj_name,
                        z_type,
                        z.source_tf,
                        z_top,
                        z_bottom,
                        "State:CLEANUP",
                        details);

         active_zones.Delete(i);
        }
     }
  }


Phase 5: Logging and Preserving Source Ownership

Extending the Event Log

With two sources producing events, the audit trail must identify which timeframe owns each zone. Chart switching should continue the same symbol’s log without relabeling existing zones according to the newly displayed period.

CLogger::Initialize() closes any existing handle and opens a symbol-scoped file in the Common Files folder. The CSV10 filename suffix separates this ten-column layout from earlier log layouts. A new empty file receives the header; an existing file is positioned for appending.

The startup row records single or dual mode and the active source list. Subsequent zone events use the same schema, with SourceTF carrying the zone’s own source timeframe.

   void              Initialize(int source_count, ENUM_TIMEFRAMES lower_tf, ENUM_TIMEFRAMES higher_tf)
     {
      //--- Part VI updated: close any existing handle before reopening the log
      Shutdown();

      //--- Verify sandbox folder path exists (Common\Files\DynamicSR6)
      FolderCreate("DynamicSR6", FILE_COMMON);

      //--- Establish identity per SYMBOL only (chart-timeframe independent)
      string path = "DynamicSR6\\DynamicSR6_Events_CSV10_" + _Symbol + ".csv";

      //--- Open with combined READ and WRITE access to facilitate appending without erasing data
      m_file_handle = FileOpen(path, FILE_WRITE|FILE_READ|FILE_CSV|FILE_ANSI|FILE_SHARE_READ|FILE_COMMON, ';');

      if(m_file_handle == INVALID_HANDLE)
        {
         Print("!!! PROTOTYPE LOGGER ERROR: FileOpen failed. Code: ", GetLastError());
         return;
        }

      //--- Write column matrix headers only if this is a brand new file allocation
      if(FileSize(m_file_handle) == 0)
        {
         string header[10] = {"Time", "Source", "Event", "Zone_ID", "Type", "SourceTF", "Top", "Bottom", "Context", "Message"};
         WriteCSV(header);
        }

      //--- Skip straight to the historical end of the file to protect old data rows
      FileSeek(m_file_handle, 0, SEEK_END);

      //--- Startup audit line: reports single/dual mode and the ACTIVE source timeframes
      string active_sources = EnumToString(lower_tf);
      if(source_count > 1)
         active_sources += " + " + EnumToString(higher_tf);

      string startup_msg = StringFormat("Startup: %s | mode: %s | active sources: %s",
                                        _Symbol,
                                        (source_count > 1) ? "dual" : "single",
                                        active_sources);

      string startup_cols[10];
      startup_cols[0] = Now();
      startup_cols[1] = "SYSTEM";
      startup_cols[2] = "STARTUP";
      startup_cols[3] = "CORE";
      startup_cols[4] = "NONE";
      startup_cols[5] = active_sources;            // Active source timeframes (not the chart timeframe)
      startup_cols[6] = "0.0";
      startup_cols[7] = "0.0";
      startup_cols[8] = "INIT";
      startup_cols[9] = startup_msg;

      //--- Simultaneous Execution: Commit row data and output directly to chart log
      WriteCSV(startup_cols);
      Print(startup_cols[9]);
     }

Once the file is initialized, both sources share the same LogZone() path. The caller supplies the zone’s stored source timeframe together with its name, type, bounds, event, and context. LogZone() places these values into the ten-column row and passes it to WriteCSV(), which appends and flushes the file. It also prints the compact message and context to the terminal. Source ownership therefore travels with each logged zone event rather than being inferred from the chart period.

   void              LogZone(string src, ENUM_ZONE_EVENT event_type, string zone_name, string zone_type, ENUM_TIMEFRAMES zone_tf, double top, double bottom, string context_data, string compact_msg)
     {
      string cols[10];
      cols[0] = Now();
      cols[1] = src;                               // "USER", "AUTO", or "SYSTEM"
      cols[2] = EnumToString(event_type);          // Action state tracking enum
      cols[3] = zone_name;                         // Target chart handle object reference
      cols[4] = zone_type;                         // ZONE_SUPPORT / ZONE_RESISTANCE / NONE
      cols[5] = EnumToString(zone_tf);             // SOURCE timeframe of the zone (never the chart TF)
      cols[6] = DoubleToString(top, _Digits);      // High boundary price
      cols[7] = DoubleToString(bottom, _Digits);   // Low boundary price
      cols[8] = context_data;                      // Internal metric tracking indicators (e.g. Score Matrix | Evolution Targets)
      cols[9] = compact_msg;                       // Clean, streamlined message copy

      //--- 1. Commit the full row to the persistent asset file matrix
      WriteCSV(cols);

      //--- 2. Direct unified mirror print to Terminal incorporating the Part III metrics pipeline
      Print(StringFormat("%s | Matrix Data: %s", cols[9], cols[8]));
     }

Reinitialization must release the previous log handle before the engine opens the same symbol’s file again. Shutdown() closes a valid handle and resets it to INVALID_HANDLE, making repeated cleanup calls safe. The displayed code calls it during deinitialization and before reopening the logger in Initialize(). This gives each initialization cycle a fresh handle while retaining the existing audit file.

   //--- Part VI new: release the log file before EA reinitialization
   void              Shutdown()
     {
      if(m_file_handle != INVALID_HANDLE)
        {
         FileClose(m_file_handle);
         m_file_handle = INVALID_HANDLE;
        }
     }

Extending the Snapshot Format

Source ownership must survive a restart or chart-period change. Saving only a zone’s geometry would leave restoration without the timeframe needed to resume its source-specific processing.

Snapshot format 3 stores source_tf in each zone record and represents every blacklist entry as a source/price pair. An M15 suppression entry therefore retains its M15 identity after restoration. The snapshot stores the current logical state used to rebuild the engine, while the CSV log retains the sequence of recorded events.

The version identifies the binary layout expected by the reader. LoadSnapshot() accepts only format 3. ReadZone() retains older time-anchor branches, but its version guard makes those branches unreachable; earlier snapshot formats are not loaded or migrated.

#define ZP_FOLDER          "DynamicSR6\\V6"  // Folder under Terminal/Common/Files
#define ZP_MAGIC           0x44535236        // 'D','S','R','6' magic marker
#define ZP_FILE_PREFIX     "DSR6_"
#define ZP_FORMAT_VERSION  3                 // Current binary format version (v3 adds source ownership and tagged blacklist)
struct SBlacklistPersist
  {
   int               source_tf;
   double            price;
  }; 

Saving must capture enough logical state to reconstruct a zone without treating it as a newly detected candidate. PersistZoneToRecord() copies the runtime zone into a plain snapshot record. Alongside its name and source timeframe, it preserves geometry, timestamps, scores, telemetry, pending and broken flags, confirmation counters, trigger flags, and time anchors. This record separates the state being saved from the runtime object that manages the zone.

//+------------------------------------------------------------------+
//| Part VI updated: copy source ownership into snapshot             |
//+------------------------------------------------------------------+
void PersistZoneToRecord(const CZone *z, SZonePersist &r)
  {
   r.name                  = z.name;
   r.zone_type             = (int)z.type;
   r.zone_status           = (int)z.status;
   r.is_user_zone          = z.is_user_zone;
   r.source_tf             = (int)z.source_tf;
   r.top                   = z.top;
   r.bottom                = z.bottom;
   r.created               = z.created;
   r.last_touch_time       = z.last_touch_time;
   r.broken_time           = z.broken_time;
   r.zone_score            = z.zone_score;
   r.current_zone_score    = z.Current_zone_score;
   r.zone_tier             = z.zone_tier;
   r.initial_volume_ratio  = z.initial_volume_ratio;
   r.departure_velocity    = z.departure_velocity;
   r.touch_count           = z.touch_count;
   r.bounce_count          = z.bounce_count;
   r.failure_count         = z.failure_count;
   r.max_reaction_pips     = z.max_reaction_pips;
   r.resurrection_count    = z.resurrection_count;
   r.breakout_quality      = z.breakout_quality;
   r.is_pending            = z.is_pending;
   r.is_broken             = z.is_broken;
   r.consecutive_closes_outside     = z.consecutive_closes_outside;
   r.consecutive_rejection_closes   = z.consecutive_rejection_closes;
   r.buy_triggered         = z.buy_triggered;
   r.sell_triggered        = z.sell_triggered;
   r.time_left             = z.time_left;              // Stored time anchors
   r.time_right            = z.time_right;
  }
//+------------------------------------------------------------------+
//| Part VI updated: restore source ownership and state              |
//+------------------------------------------------------------------+
CZone* RebuildZoneFromRecord(const SZonePersist &r)
  {
   CZone *z = new CZone((r.top + r.bottom) / 2.0,
                        (ENUM_ZONE_TYPE)r.zone_type,
                        r.created,
                        SourceCachedAtr((ENUM_TIMEFRAMES)r.source_tf), (ENUM_TIMEFRAMES)r.source_tf);
   if(z == NULL)
      return NULL;
//--- Part VI updated: restore saved counters and telemetry
//--- Resume from the saved state without replaying offline source bars or resetting counters.
   z.name        = r.name;
   z.is_user_zone= r.is_user_zone;
   z.source_tf   = (ENUM_TIMEFRAMES)r.source_tf;   // permanent source ownership restored
   z.top         = r.top;
   z.bottom      = r.bottom;
   z.price_level = (r.top + r.bottom) / 2.0;
   z.height      = r.top - r.bottom;
   z.created          = r.created;
   z.last_touch_time  = r.last_touch_time;
   z.broken_time      = r.broken_time;
   z.status       = (ENUM_ZONE_STATUS)r.zone_status;
   z.is_broken    = r.is_broken;
   z.is_pending   = r.is_pending;
   z.consecutive_closes_outside   = r.consecutive_closes_outside;
   z.consecutive_rejection_closes = r.consecutive_rejection_closes;
   z.buy_triggered  = r.buy_triggered;
   z.sell_triggered = r.sell_triggered;
   z.time_left  = r.time_left;                         // Stored time anchors
   z.time_right = r.time_right;
   z.zone_score           = r.zone_score;
   z.Current_zone_score   = r.current_zone_score;
   z.zone_tier            = r.zone_tier;
   z.initial_volume_ratio = r.initial_volume_ratio;
   z.departure_velocity   = r.departure_velocity;
   z.touch_count        = r.touch_count;
   z.bounce_count       = r.bounce_count;
   z.failure_count      = r.failure_count;
   z.max_reaction_pips  = r.max_reaction_pips;
   z.resurrection_count = r.resurrection_count;
   z.breakout_quality   = r.breakout_quality;
   z.was_drawn          = false;
   return z;
  }

The snapshot record must be written in a predictable order so the reader can recover the same fields. WriteZone() serializes identity and source ownership first, followed by geometry, timing, scores, telemetry, lifecycle flags, and time anchors. The binary layout relies on this field order. Derived values such as the midpoint and height are reconstructed from the saved geometry rather than stored as separate fields.

//+------------------------------------------------------------------+
//| CZonePersistence::WriteZone                                      |
//| Persist the reconstructable logical fields. Derived/visual       |
//| values (height, was_drawn, was_recently_moved) are recomputed.   |
//+------------------------------------------------------------------+
void CZonePersistence::WriteZone(int h,const SZonePersist &z)
  {
//--- Identity / Direction
   WriteString(h,z.name);
   FileWriteInteger(h,z.zone_type,INT_VALUE);
   FileWriteInteger(h,z.zone_status,INT_VALUE);
   WriteBool(h,z.is_user_zone);
   FileWriteInteger(h,z.source_tf,INT_VALUE);

//--- Geometry
   FileWriteDouble(h,z.top);
   FileWriteDouble(h,z.bottom);

//--- Timing
   FileWriteLong(h,(long)z.created);
   FileWriteLong(h,(long)z.last_touch_time);
   FileWriteLong(h,(long)z.broken_time);

//--- Score
   FileWriteInteger(h,z.zone_score,INT_VALUE);
   FileWriteDouble(h,z.current_zone_score);
   WriteString(h,z.zone_tier);

//--- Telemetry
   FileWriteDouble(h,z.initial_volume_ratio);
   FileWriteDouble(h,z.departure_velocity);
   FileWriteInteger(h,z.touch_count,INT_VALUE);
   FileWriteInteger(h,z.bounce_count,INT_VALUE);
   FileWriteInteger(h,z.failure_count,INT_VALUE);
   FileWriteDouble(h,z.max_reaction_pips);
   FileWriteInteger(h,z.resurrection_count,INT_VALUE);
   WriteString(h,z.breakout_quality);

//--- Lifecycle flags
   WriteBool(h,z.is_pending);
   WriteBool(h,z.is_broken);
   FileWriteInteger(h,z.consecutive_closes_outside,INT_VALUE);
   FileWriteInteger(h,z.consecutive_rejection_closes,INT_VALUE);
   WriteBool(h,z.buy_triggered);
   WriteBool(h,z.sell_triggered);

//--- Time anchors retained in V6 format 3
   FileWriteLong(h,(long)z.time_left);
   FileWriteLong(h,(long)z.time_right);
  }

ReadZone() reads the fields in the corresponding order and validates the recovered record before accepting it. Its checks include the source timeframe, type and status ranges, ordered finite price bounds, timestamps, scores, and nonnegative counters. File-position and read-error checks reject incomplete records. These checks establish that the stored values satisfy the reader’s requirements; they do not reconstruct or verify the zone’s market history.

//+------------------------------------------------------------------+
//| CZonePersistence::ReadZone                                       |
//| Reverse of WriteZone. Sets record fields directly.               |
//+------------------------------------------------------------------+
bool CZonePersistence::ReadZone(int h,SZonePersist &z,const int format_version)
  {
   if(m_read_error || format_version != 3 || format_version > ZP_FORMAT_VERSION)
      return false;

   z.name = ReadString(h);

   if(m_read_error || z.name == "" || FileTell(h) > FileSize(h) || FileSize(h) - FileTell(h) < 65)
      return false;

   ResetLastError();
   z.zone_type = FileReadInteger(h,INT_VALUE);
   z.zone_status = FileReadInteger(h,INT_VALUE);
   z.is_user_zone = ReadBool(h);
   z.source_tf = FileReadInteger(h,INT_VALUE);

   z.top = FileReadDouble(h);
   z.bottom = FileReadDouble(h);

   z.created = (datetime)FileReadLong(h);
   z.last_touch_time = (datetime)FileReadLong(h);
   z.broken_time = (datetime)FileReadLong(h);

   z.zone_score = FileReadInteger(h,INT_VALUE);
   z.current_zone_score = FileReadDouble(h);
   if(GetLastError() != 0)
      return false;
   z.zone_tier = ReadString(h);

   if(m_read_error || FileTell(h) > FileSize(h) || FileSize(h) - FileTell(h) < 40)
      return false;

   ResetLastError();
   z.initial_volume_ratio = FileReadDouble(h);
   z.departure_velocity = FileReadDouble(h);
   z.touch_count = FileReadInteger(h,INT_VALUE);
   z.bounce_count = FileReadInteger(h,INT_VALUE);
   z.failure_count = FileReadInteger(h,INT_VALUE);
   z.max_reaction_pips = FileReadDouble(h);
   z.resurrection_count = FileReadInteger(h,INT_VALUE);
   if(GetLastError() != 0)
      return false;
   z.breakout_quality = ReadString(h);

   if(m_read_error || FileTell(h) > FileSize(h) || FileSize(h) - FileTell(h) < (ulong)(12 + (format_version >= 2 ? 16 : 0)))
      return false;

   ResetLastError();
   z.is_pending = ReadBool(h);
   z.is_broken = ReadBool(h);
   z.consecutive_closes_outside = FileReadInteger(h,INT_VALUE);
   z.consecutive_rejection_closes = FileReadInteger(h,INT_VALUE);
   z.buy_triggered = ReadBool(h);

   z.sell_triggered = ReadBool(h);

//--- Real-time anchors (format v2+).
   if(format_version >= 2)
     {
      z.time_left  = (datetime)FileReadLong(h);
      z.time_right = (datetime)FileReadLong(h);
     }
   else
     {
      //--- v1 fallback: preserve legacy rebuild behavior (left = created, right = extend to now / ray)
      z.time_left  = z.created;
      z.time_right = 0;
     }

   if(GetLastError() != 0)
      return false;

   if(!ZPValidSource(z.source_tf))
      return false;
   if(z.zone_type < 0 || z.zone_type > 2 || z.zone_status < 0 || z.zone_status > 2)
      return false;
   if(!MathIsValidNumber(z.top) || !MathIsValidNumber(z.bottom) || z.top < z.bottom)
      return false;
   if(z.created <= 0 || z.last_touch_time < 0 || z.broken_time < 0 || z.time_left < 0 || z.time_right < 0)
      return false;
   if(z.zone_score < 0 || !MathIsValidNumber(z.current_zone_score) || z.current_zone_score < 0.0)
      return false;
   if(!MathIsValidNumber(z.initial_volume_ratio) || z.initial_volume_ratio < 0.0 ||
      !MathIsValidNumber(z.departure_velocity) || z.departure_velocity < 0.0 ||
      !MathIsValidNumber(z.max_reaction_pips) || z.max_reaction_pips < 0.0)
      return false;
   if(z.touch_count < 0 || z.bounce_count < 0 || z.failure_count < 0 || z.resurrection_count < 0 ||
      z.consecutive_closes_outside < 0 || z.consecutive_rejection_closes < 0)
      return false;

   return true;
  }

Startup must distinguish a missing snapshot from an existing file that cannot be safely restored. An unreadable snapshot must not be silently replaced with a fresh engine state. LoadSnapshot() checks the path, file access, magic marker, format version, zone records, and source-tagged blacklist data. A missing file returns -1, allowing a fresh start. Corrupt data, an unsupported version, or path and access failures return other negative results.

LoadPersistState() interprets these results and sets the read-failure guard. OnInit() stops when that guard is set, while SavePersistState() blocks writeback. A successful load instead supplies the records used to rebuild the tracked zones and blacklist.

int CZonePersistence::LoadSnapshot(SZonePersist &zones[],SBlacklistPersist &blacklist_entries[])
  {
   ResetLastError();
   m_read_error = false;
   ArrayResize(zones,0);
   ArrayResize(blacklist_entries,0);
   if(m_path == "")
     {
      Print("[V6][PERSIST] Snapshot path is empty.");
      return -4;
     }

//--- Confirm absence separately from access or other file errors.
   ResetLastError();
   if(!FileIsExist(m_path,FILE_COMMON))
     {
      int existence_error = GetLastError();
      if(existence_error == ERR_FILE_NOT_EXIST)
         return -1;

      PrintFormat("[V6][PERSIST] Cannot verify snapshot '%s'. Error: %d",
                  m_path, existence_error);
      return -4;
     }

   ResetLastError();
   int h = FileOpen(m_path,FILE_READ|FILE_BIN|FILE_COMMON);
   if(h == INVALID_HANDLE)
     {
      int open_error = GetLastError();
      PrintFormat("[V6][PERSIST] Cannot open snapshot '%s'. Error: %d",
                  m_path, open_error);
      return -4;
     }

   if(FileSize(h) < 16)
     {
      FileClose(h);
      return -2;
     }

//--- Header
   int magic = FileReadInteger(h,INT_VALUE);
   if(GetLastError() != 0 || magic != (int)ZP_MAGIC)
     {
      FileClose(h);
      return -2;
     }
   int version = FileReadInteger(h,INT_VALUE);
   if(GetLastError() != 0)
     {
      FileClose(h);
      return -2;
     }
   if(version != ZP_FORMAT_VERSION)
     {
      FileClose(h);
      return -3;
     }
//--- Only V6 format 3 is accepted. Legacy snapshots are not migrated or modified.

//--- Zones
   int zc = FileReadInteger(h,INT_VALUE);
   if(GetLastError() != 0 || zc < 0 || zc > 100000)
     {
      FileClose(h);
      return -2;
     }
   if(ArrayResize(zones,zc) != zc)
     {
      FileClose(h);
      ArrayResize(zones,0);
      return -2;
     }
   for(int i=0;i<zc;i++)
     {
      if(!ReadZone(h,zones[i],version))
        {
         FileClose(h);
         ArrayResize(zones,0);
         return -2;
        }
     }

//--- Blacklist
   if(FileTell(h) > FileSize(h) || FileSize(h) - FileTell(h) < 4)
     {
      FileClose(h);
      ArrayResize(zones,0);
      return -2;
     }
   ResetLastError();
   int bc = FileReadInteger(h,INT_VALUE);
   if(GetLastError() != 0 || bc < 0 || bc > 100000)
     {
      FileClose(h);
      ArrayResize(zones,0);
      return -2;
     }
   if(FileTell(h) > FileSize(h) || FileSize(h) - FileTell(h) != (ulong)bc * 12)
     {
      FileClose(h);
      ArrayResize(zones,0);
      return -2;
     }
   if(ArrayResize(blacklist_entries,bc) != bc)
     {
      FileClose(h);
      ArrayResize(zones,0);
      ArrayResize(blacklist_entries,0);
      return -2;
     }
   for(int i=0;i<bc;i++)
     {
      ResetLastError();
      blacklist_entries[i].source_tf = FileReadInteger(h,INT_VALUE);
      blacklist_entries[i].price = FileReadDouble(h);
      if(GetLastError() != 0 || !ZPValidSource(blacklist_entries[i].source_tf) || !MathIsValidNumber(blacklist_entries[i].price))
        {
         FileClose(h);
         ArrayResize(zones,0);
         ArrayResize(blacklist_entries,0);
         return -2;
        }
     }

   FileClose(h);
   return version;
  }

After validation, LoadPersistState() reconstructs the runtime collections. It rebuilds each blacklist key from its saved source/price pair and passes each zone record to RebuildZoneFromRecord(). Records are restored even when their sources are outside the current configuration. Active-source checks determine which records participate in processing; restoration itself preserves their saved ownership.

//+------------------------------------------------------------------+
//| Part VI updated: load source-tagged records                      |
//+------------------------------------------------------------------+
void LoadPersistState(void)
  {
   active_zones.Clear();
   blacklist.Clear();

   SZonePersist records[];
   SBlacklistPersist blk[];
   int version = g_persist.LoadSnapshot(records, blk);
   if(version < 0)
     {
      g_persist_read_failed = (version != -1);
      PrintFormat("[V6][PERSIST] No usable snapshot (code %d): -1 missing file, -2 corrupt/incompatible data, -3 unsupported version, -4 path/existence/open failure. Legacy V5 paths are not loaded. Missing file starts fresh; other failures block initialization.", version);
      return;
     }

   g_persist_read_failed = false;

   int bc = ArraySize(blk);
   for(int i = 0; i < bc; i++)
      blacklist.Add(BlacklistKey((ENUM_TIMEFRAMES)blk[i].source_tf, blk[i].price));

   int n = ArraySize(records);
   for(int i = 0; i < n; i++)
     {
      CZone *z = RebuildZoneFromRecord(records[i]);
      if(z != NULL)
         active_zones.Add(z);
     }

   PrintFormat("[V6][PERSIST] Restored %d zones / %d blacklist entries (format v%d). Zones of inactive sources are retained but not processed.",
               active_zones.Total(), blacklist.Total(), version);
  }

Restoring Drawings and Retaining Inactive Sources

Rebuilding logical records restores the engine’s state; their chart drawings must then be reconstructed from that state.

ReconcileChartObjects() finds each saved rectangle by name or creates it when absent. It restores the stored bounds, time anchors, source visibility, and color. When an anchor is unspecified, the function uses the creation timestamp for the left edge or the current time for the right edge.

Inactive-source records are retained and their drawings are reconciled during initialization. Their visibility masks hide them, and their lifecycle processing remains suspended. These hidden drawings still contribute to the chart-object count.

If an inactive-source drawing is deleted, its logical record survives, but the drawing is not recreated by routine visual updates because its drawn flag remains set. Reconciliation runs again at the next initialization. Untracked rectangles already on the chart are not adopted by this routine.

//+------------------------------------------------------------------+
//| Part VI updated: restore objects with source masks               |
//+------------------------------------------------------------------+
void ReconcileChartObjects(void)
  {
//--- Part VI updated: rebuild chart objects for saved zones and apply source masks
   for(int i = 0; i < active_zones.Total(); i++)
     {
      CZone *z = (CZone*)active_zones.At(i);
      if(z == NULL)
         continue;

      if(ObjectFind(0, z.name) < 0)
        {
         if(ObjectCreate(0, z.name, OBJ_RECTANGLE, 0, (z.time_left != 0) ? z.time_left : z.created, z.top, (z.time_right != 0) ? z.time_right : TimeCurrent(), z.bottom))   // Restore stored anchors (right edge remains framework-managed)
           {
            ObjectSetInteger(0, z.name, OBJPROP_BACK, true);
            ObjectSetInteger(0, z.name, OBJPROP_RAY_RIGHT, true);
            ObjectSetInteger(0, z.name, OBJPROP_SELECTABLE, true);
            ObjectSetInteger(0, z.name, OBJPROP_FILL, !z.is_broken);
            ObjectSetString(0, z.name, OBJPROP_TEXT, z.is_user_zone ? "USER" : "AUTO");
            z.was_drawn = true;
           }
        }
      else
        {
         ObjectSetDouble(0, z.name, OBJPROP_PRICE, 0, z.top);
         ObjectSetDouble(0, z.name, OBJPROP_PRICE, 1, z.bottom);
         z.was_drawn = true;
        }

      ApplyZoneVisibility(z);
      ObjectSetInteger(0, z.name, OBJPROP_COLOR, z.GetColor());
      //--- Restore persisted time anchors
      ObjectSetInteger(0, z.name, OBJPROP_TIME, 0, (z.time_left != 0) ? z.time_left : z.created);
      ObjectSetInteger(0, z.name, OBJPROP_TIME, 1, (z.time_right != 0) ? z.time_right : TimeCurrent());
     }

//--- Untracked rectangles are not adopted during reconciliation.
//--- New registrations use OBJECT_CREATE; saved records restore existing ownership.
  }

Saving must preserve the complete tracked state, including records whose sources are temporarily inactive. SavePersistState() converts all non-null tracked zones into snapshot records. It also parses the runtime blacklist keys and saves valid entries as source/price pairs. The resulting arrays are passed to SaveSnapshot(). The dirty flag follows the reported save result: success clears it, while failure leaves the state eligible for a later retry. The read-failure guard prevents saving over a snapshot that startup could not restore. Each save rewrites the complete snapshot; this implementation does not use atomic replacement or backup rotation. A failed or interrupted write can therefore lose the previous usable snapshot; the startup read-failure guard does not protect against this.

//+------------------------------------------------------------------+
//| Part VI updated: save all tracked source records                 |
//+------------------------------------------------------------------+
void SavePersistState(void)
  {
   if(g_persist_read_failed)
      return;
   SZonePersist records[];
   int n = active_zones.Total();
   if(n <= 0)
      ArrayResize(records, 0);
   else
     {
      ArrayResize(records, n);
      int fill = 0;
      for(int i = 0; i < n; i++)
        {
         CZone *z = (CZone*)active_zones.At(i);
         if(z == NULL)
            continue;
         PersistZoneToRecord(z, records[fill]);
         fill++;
        }
      ArrayResize(records, fill);
     }

   SBlacklistPersist blk[];
   int bc = blacklist.Total();
   int blk_fill = 0;                              // compaction index: only valid source-tagged keys are persisted
   if(bc <= 0)
      ArrayResize(blk, 0);
   else
     {
      ArrayResize(blk, bc);
      for(int i = 0; i < bc; i++)
        {
         ENUM_TIMEFRAMES bkey_tf;
         double          bkey_price;
         if(ParseBlacklistKey(blacklist.At(i), bkey_tf, bkey_price))
           {
            blk[blk_fill].source_tf = (int)bkey_tf;
            blk[blk_fill].price     = bkey_price;
            blk_fill++;
           }
        }

      ArrayResize(blk, blk_fill);              // persist only valid, source-tagged entries
     }

   g_persist_dirty = !g_persist.SaveSnapshot(records, blk);
  }

Chart cleanup during shutdown must not be interpreted as deliberate deletion of the saved zones.

OnDeinit() attempts to save the logical state before removing managed drawings. It disables chart deletion notifications during cleanup, clears the runtime collections, releases the source handles and existing trading objects, and closes the logger. This ordering separates removal of the current chart presentation from removal of the zone records stored for restoration.

//+------------------------------------------------------------------+
//| Part VI updated: save state and release source handles           |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- Part VI updated: save state before chart cleanup
   if(g_persist_loaded)
      SavePersistState();

//--- Part VI updated: disable deletion notifications during cleanup
   ChartSetInteger(0, CHART_EVENT_OBJECT_DELETE, false);
   RemoveManagedChartObjects();   // Remove tracked AUTO and USER rectangles.

   active_zones.Clear();
   blacklist.Clear();

   for(int s = 0; s < MAX_SOURCE_TF; s++)
     {
      // Release this source handle if allocated.
      ReleaseSourceHandle(s);
     }

//--- Release trading module objects
   if(CheckPointer(g_trade) == POINTER_DYNAMIC)
     {
      delete g_trade;
      g_trade = NULL;
     }
   if(CheckPointer(g_strategy) == POINTER_DYNAMIC)
     {
      delete g_strategy;
      g_strategy = NULL;
     }

//--- Part VI new: close the log before reinitialization
   logger.Shutdown();

   PrintFormat(">>> Deinitialization Engine detached smoothly. Reason Code: %d", reason);
   ChartRedraw();
  }

Architectural Notes and Known Limitations

  • Source scope: At most two source timeframes are supported.
  • Latest-bar processing: Restoration preserves saved state, but missed lifecycle bars are not replayed individually. Ordinary passes evaluate the latest completed source bar.
  • Tick-driven updates: Saved drawings are restored during initialization. Delayed source-data retries and subsequent routine visual updates require incoming ticks; no timer-based recovery or refresh is implemented.
  • Source readiness: A configured source whose ATR or required history remains unavailable does not complete its initial scan. Tick-driven retries continue with a one-second throttle, but these readiness failures have no dedicated status message.
  • Manual evaluation: Moved manual zones can be checked against the current bid, so evaluation is not exclusively completed-bar based. A touch started between source bars is timestamped with the forming bar and cannot be resolved until that bar becomes a completed source bar.
  • Inactive records: Inactive-source zones remain stored and hidden without automatic purging; retained zones and blacklist entries can accumulate over time.
  • Snapshot saves: Frequent state changes can cause frequent saves; failed saves remain eligible for tick-driven retries.
  • Storage ownership: Snapshot and log paths are symbol-scoped in Common Files. They do not distinguish accounts, magic numbers, or EA instances. Multiple writers can contend for these files or overwrite shared snapshot state. Use one writer per symbol. CSV logs and runtime blacklists have no rotation or pruning.
  • Merge-state handling: pending histories and confirmation counters are not fully reconciled when live AUTO zones merge.


Practical Walkthrough

For this test, we attached the Expert Advisor to USDJPY with M15 and H1 configured as the two source timeframes. Switching to M15 reveals its zones, while switching to H1 displays the zones belonging to that source. We then visit chart periods outside the configured pair, where the managed rectangles remain hidden. Returning to either source period makes its zones visible again.

Fig. 3. Chart Switching

Fig. 3. Source-specific zone visibility during chart-period switching.

The telemetry below follows the same chart-switching sequence. Each chart-period change is followed by shutdown and initialization messages, a report of the restored zone and blacklist record counts, and the configured M15 and H1 source pair. These reported counts remain unchanged across the switches shown, including visits to chart periods outside the configured pair. Together with the GIF, the example illustrates source-specific visibility and the initialization reports produced during normal chart switching.

Fig. 4. Output

Fig. 4. Reported restoration counts and configured sources across chart-period switches.

The screenshot shows the terminal output captured during the test. Across the displayed initialization cycles, the engine reports 12 restored zones, 0 blacklist entries, and 0 zones belonging to inactive sources. The output also shows an automatic creation attempt being skipped because the corresponding zone already exists. These messages illustrate the restoration and existing-zone checks observed during this test.

Note: The restoration output was captured with an existing snapshot available for loading.


Conclusion

Part VI establishes source timeframe ownership as the organizing principle of the zone engine. Detection and lifecycle processing now follow explicitly configured sources, while chart switching controls which zones are displayed. Logging and persistence preserve that ownership across events and restarts. 

This dual-timeframe foundation can later be extended to multiple timeframes, allowing higher-timeframe zones to provide context for lower-timeframe trading signals. Offline lifecycle reconciliation would also help account for price interactions missed while the engine was not running.

The following table summarizes the accompanying source files and their roles.

File Description
MasterLog2.mqh
Records zone events in a symbol-scoped CSV log, including each zone’s source timeframe.
DynamicSR6.mq5
The main Expert Advisor. Configures single or dual sources and coordinates zone detection, lifecycle processing, chart interaction, logging, and persistence.
TradeManager.mqh
Provides the existing trade execution and position management layer, including trailing-stop updates.
ZoneStrategy.mqh
Provides the existing trading filters and signal evaluation. Its entry bridge is limited to lower-source zones when the chart matches that source.
ZonePersistence.mqh
Stores and restores source-tagged zone records and blacklist entries using binary snapshot format 3.
MQL5.zip
Contains the main Expert Advisor and accompanying include files. Extract its contents into the terminal’s data folder, preserving the supplied MQL5 folder structure.
Attached files |
MQL5.zip (38 KB)
Marginal Drawdown Contribution Analyzer in MQL5: Which Configuration Deepens Your Portfolio Drawdown Marginal Drawdown Contribution Analyzer in MQL5: Which Configuration Deepens Your Portfolio Drawdown
We show how to attribute realized portfolio drawdown to individual configurations inside MetaTrader 5. Using daily results grouped by magic (optionally magic and symbol), the tool rebuilds the portfolio curve and quantifies three contributions: leave-one-out drawdown, shares of the deepest drawdown episodes, and Euler variance share. Flags are checked for stability across sample halves and rolled up into a heuristic A+–F score for practical diagnostics.
Connecting MQL5 to Apache Cassandra: A Native CQL Binary Protocol (v4) Client for Tick-Level Feature Archival Connecting MQL5 to Apache Cassandra: A Native CQL Binary Protocol (v4) Client for Tick-Level Feature Archival
This article builds a driverless MQL5 client for Cassandra's CQL binary protocol v4 using outbound TCP sockets. It explains frame headers and primitives, SASL PLAIN, prepared statements, and UNLOGGED batches, then demonstrates an EA that writes per‑tick feature vectors with batched throughput and a reconnect‑and‑retry flush path verified on a real node.
Automating Chart Patterns in MQL5 (Part 4): The Flag and Pennant Automating Chart Patterns in MQL5 (Part 4): The Flag and Pennant
This article implements a flag and pennant detector in MQL5 using swing-structure data from a higher timeframe. The pole is validated by ATR-based height and a maximum bar duration, and the subsequent consolidation is replayed bar by bar on the chart timeframe with limits on minimum length, lifetime, and retracement. A three-state machine trades a fresh breakout once and projects a measured-move target from the pole's height.
Aggregating Order Flow Delta from Tick Data in MQL5 Aggregating Order Flow Delta from Tick Data in MQL5
Compute and visualize order flow delta in MQL5 from raw ticks, either per bar or cumulatively. The implementation applies the tick rule, threads state through bars, and annotates price–cumulative delta divergences closed on bars. Pure classes isolate logic for testing, and a synthetic tick script confirms behavior, improving robustness and clarity of the output.