← К каталогу
Исходный код · ID 5112

dynamicsr6.mq5

Вы автор или правообладатель?

Сообщите нам, если считаете, что материал размещён без разрешения.

Поиск по коду файла

#property version   "1.6"

#include <Arrays\ArrayObj.mqh>
#include <Arrays\ArrayString.mqh>
#include <Trade\Trade.mqh>
#include <DynamicSR\V6\MasterLog2.mqh>
#include <DynamicSR\V6\TradeManager.mqh>
#include <DynamicSR\V6\ZoneStrategy.mqh>
#include <DynamicSR\V6\ZonePersistence.mqh>       // Part VI updated: source-aware persistence module

void SetupPersistencePath(void);
void MarkPersistDirty(void);
void SavePersistState(void);
void LoadPersistState(void);
void ReconcileChartObjects(void);
string PersistFilePath(void);

enum ENUM_ZONE_TYPE
  {
   ZONE_SUPPORT,
   ZONE_RESISTANCE,
   ZONE_NEUTRAL
  };

enum ENUM_ZONE_STATUS
  {
   ZONE_VIRGIN,
   ZONE_BROKEN,
   ZONE_INACTIVE
  };

enum ENUM_ZONE_SOURCE
  {
   ZS_USER,
   ZS_EA
  };

input group "--- Core Engine Settings ---"
input int      ApproachPips        = 10;      // Reserved; not used by this main-file lifecycle
input int      LookbackBars        = 300;     // Historical structural scanning depth
input int      SwingBars           = 5;       // Symmetrical bars required for structural pivot
input double   MergeSensitivity    = 1.5;     // Proximity threshold multiplier for merging zones

input group "--- Breakout & Ghost State Settings ---"
input double   BreakBufferPct      = 0.10;    // Zone-height fraction; break buffer also includes source ATR
input int      BreakConfirmCloses  = 4;       // Consecutive completed source closes for break confirmation
input int      GhostBarLimit       = 10;      // Broken-zone age limit in source bars
input bool     AllowResurrection   = true;    // Re-activate ghost zones if price closes back inside range

input group "--- Part III Quantitative Scoring Matrix ---"
input int      MinZoneScore        = 50;      // AUTO candidate threshold; USER baseline score
input bool     EnableVolumeValidation = true; // Enable/disable tick-volume relationship checks
input int      VolumeWeight        = 30;      // Maximum weight for the tick-volume ratio component
input int      VelocityWeight      = 40;      // Max points allocated to escape velocity (Default: 40)
input int      StructureWeight     = 30;      // Max points allocated to geometric symmetry (Default: 30)
input int      VelocityLookaheadBars = 3;     // Bar count lookahead window for departure calculation

input group "--- Part III Live Zone Evolution Tracking ---"
input bool     EnableTemporalDecay = false;   // Enable score degradation over time
input double   DecayRatePerBar     = 0.05;    // Shared score reduction per evaluated source bar
input double   TouchScoreBonus     = 5.0;     // Score increase awarded for clean rejections
input double   PenetrationPenalty  = 5.0;     // Score reduction on confirmed break

input group "--- Symmetrical Bounce Settings ---"
input int      BounceConfirmCloses = 7;       // Consecutive source closes beyond the bounce distance
input double   BounceATRDistance   = 0.5;     // ATR Multiplier Filter for Movement Away
input int      BounceTimeoutBars   = 5;       // Reserved here; pending lifecycle has no timeout

input group "--- Part IV Automation Framework Switches ---"
input bool     CheckTradingSignals   = true;              // Enable automated execution signals
input ulong    MagicNumber           = 123456;            // EA Magic Number
input double   LotSize               = 0.10;              // Lot size

input group "--- Risk & Spread Protection ---"
input int      MaxSpreadPoints       = 30;                // Spread limit passed to the trading module
input double   RiskRewardRatio       = 2.0;               // Strategy mathematical target multiplier
input double   ATRBufferMultiplier   = 1.5;               // Structural volatility invalidation cushion

input group "--- Trailing Stop Settings ---"
input bool     UseTrailingStop       = true;              // Enable trailing-stop updates
input double   TrailingStartPips     = 15.0;              // Minimum pips gained to activate trailing layer
input double   TrailingStepPips      = 5.0;               // Trailing step distance adjustments

input group "--- HTF Trend Filter Parameters ---"
input bool            InpUseHTFFilter       = true;       // Enable Higher Timeframe Trend Filter
input ENUM_TIMEFRAMES InpHtfTimeframe       = PERIOD_H1;  // HTF Trend Timeframe
input int             InpHtfMaPeriod        = 50;         // HTF Trend EMA Period
input bool            InpUseHTFRsiFilter    = true;       // Enable HTF RSI Exhaustion Filter
input int             InpHtfRsiPeriod       = 14;         // HTF RSI Period
input double          InpHtfRsiOverbought   = 70.0;       // HTF RSI Overbought Threshold
input double          InpHtfRsiOversold     = 30.0;       // HTF RSI Oversold Threshold

input group "--- Approach Context Parameters"
input int             InpApproachBars     = 3;            // Bars Evaluated Before Touch (1-5)
input double          InpApproachThreshold = 1.5;         // Aggressive Sprint Threshold (ATR Mult)

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

#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
  };

CLogger logger;

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

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

CTradeManager *g_trade    = NULL;            // Trading execution module
CZoneStrategy *g_strategy = NULL;            // Trading signal module

class CZone : public CObject
  {
public:
   string              name;                             // Unique chart object identifier
   double              price_level;                      // Median reference price of the structure
   double              top;                              // Upper boundary ceiling price
   double              bottom;                           // Lower boundary floor price
   double              height;                           // Absolute distance within the zone range

   bool                is_broken;                        // Confirmed broken-zone flag
   datetime            broken_time;                      // Exact timestamp when breakout confirmation occurred
   int                 consecutive_closes_outside;       // Counter for closing candles beyond boundaries

   bool              is_pending;                         // True if an interaction is underway but unresolved
   int               consecutive_rejection_closes;
   bool              was_recently_moved;

   ENUM_ZONE_TYPE     type;                              // Structural classification (Support/Resistance)
   ENUM_ZONE_STATUS  status;                             // Operational state tracking (Virgin/Broken/Inactive)
   bool              is_user_zone;                       // Identifies if manually drawn or auto-generated
   bool              was_drawn;                          // Chart object creation flag (may be hidden)
   datetime          created;                            // Original generation timestamp
   ENUM_TIMEFRAMES   source_tf;                          // Part VI new: persistent source timeframe
   datetime          last_touch_time;                    // Last recorded price test interaction
   datetime          time_left;                          // Part V: stored left rectangle anchor
   datetime          time_right;                         // Part V: stored right rectangle anchor

   bool              buy_triggered;                      // Internal signal flag for support interaction
   bool              sell_triggered;                     // Internal signal flag for resistance interaction
   double            strength;                           // Structural weight ranking score

   int                zone_score;                        // Final calculated evaluation score (0 - 100)
   double             Current_zone_score;                // Current active score used by the engine
   string             zone_tier;                         // Categorized tier ("HIGH", "MODERATE", "LOW")
   double             initial_volume_ratio;              // Pivot tick-volume ratio
   double             departure_velocity;                // Post-pivot departure in pips

   int                touch_count;                       // Cumulative price test contacts
   int                bounce_count;                      // Successful rejections away from zone
   int                failure_count;                     // Confirmed break count
   double             max_reaction_pips;                 // Peak departure distance achieved before death
   int                resurrection_count;                // Total level reactivations logged
   string             breakout_quality;                  // Classified breakout force ("WEAK", "MODERATE", "STRONG")

                     CZone()
     {
      name = "";
      price_level = 0.0;
      top = 0.0;
      bottom = 0.0;
      height = 0.0;
      is_broken = false;
      broken_time = 0;
      consecutive_closes_outside = 0;
      type = ZONE_NEUTRAL;
      status = ZONE_VIRGIN;
      is_user_zone = true;                              // Defaulting an empty declaration as user-driven until specified
      was_drawn = false;
      created = TimeCurrent();
      source_tf = PERIOD_CURRENT;                       // Part VI new: placeholder until source assignment
      time_left = 0;                                    // Part V: anchors assigned during registration or restoration
      time_right = 0;
      last_touch_time = 0;
      buy_triggered = false;
      sell_triggered = false;
      strength = 1.0;
      was_recently_moved = false;

      Current_zone_score   =0.0;
      zone_score           = 0;
      zone_tier            = "NONE";
      initial_volume_ratio = 1.0;
      departure_velocity   = 0.0;
      touch_count          = 0;
      bounce_count         = 0;
      failure_count        = 0;
      max_reaction_pips    = 0.0;
      resurrection_count   = 0;
      breakout_quality     = "NONE";

      is_pending                 = false;
      consecutive_rejection_closes = 0;

     }

                     CZone(double p, ENUM_ZONE_TYPE t, datetime ct, double current_atr, ENUM_TIMEFRAMES tf)
     {
      price_level = p;
      type = t;
      status = ZONE_VIRGIN;
      is_user_zone = false;
      was_drawn = false;
      is_broken = false;
      broken_time = 0;

      double zone_height = 0.0;
      if(current_atr > 0.0)
        {
         zone_height = current_atr * 0.5;    // Zone size scales directly with volatility
        }
      else
        {
         zone_height = 20.0 * _Point * 10.0; // Fallback constructor thickness when ATR is unavailable
        }

      top = (type == ZONE_RESISTANCE) ? p : p + zone_height;
      bottom = (type == ZONE_RESISTANCE) ? p - zone_height : p;
      height = top - bottom;

      created = ct;
      source_tf = tf;                      // Part VI new: source supplied at construction
      time_left = 0;                       // Part V: stored anchors initialized later
      time_right = 0;
      last_touch_time = ct;
      consecutive_closes_outside = 0;
      buy_triggered = false;
      sell_triggered = false;
      strength = 1.0;

      zone_score           = 0;
      Current_zone_score   =0.0;
      zone_tier            = "NONE";
      initial_volume_ratio = 1.0;
      departure_velocity   = 0.0;
      touch_count          = 0;
      bounce_count         = 0;
      failure_count        = 0;
      max_reaction_pips    = 0.0;
      resurrection_count   = 0;
      breakout_quality     = "NONE";

      is_pending                 = false;
      consecutive_rejection_closes = 0;
      was_recently_moved = false;

      name = (type == ZONE_SUPPORT ? "S_" : "R_") + IntegerToString((int)tf) + "_" +
             DoubleToString(p, _Digits) + "_" + IntegerToString((long)ct);
     }

   bool              IsPriceNearZone(double price)
     {
      double pipMultiplier = (_Digits == 3 || _Digits == 5) ? 10.0 : 1.0;
      double proximityBuffer = ApproachPips * _Point * pipMultiplier;

      bool isInside = (price >= (bottom - proximityBuffer) && price <= (top + proximityBuffer));
      return isInside;
     }

   color             GetColor(void)
     {
      if(is_broken)
        {
         return clrWhite; // Broken-state color; fill is handled by visual updates
        }
      if(status == ZONE_INACTIVE)
        {
         return clrGray;  // Deactivated states render in neutral gray
        }
      if(type == ZONE_SUPPORT)
        {
         return (status == ZONE_VIRGIN ? clrLimeGreen : clrGreen);
        }

      return (status == ZONE_VIRGIN ? clrRed : clrOrangeRed);
     }
  };

bool   RegisterUserZone(string obj_name);      // Manual registration entry point
void ResolvePendingInteractions(ENUM_TIMEFRAMES tf, double atr);
void MonitorZoneLifecycle(CLogger &log_instance, CArrayObj &zones, ENUM_TIMEFRAMES tf, double atr, double multiplier);
int    AnalyzeZoneCandidate(int pivot_idx, ENUM_ZONE_TYPE type, double p, ENUM_TIMEFRAMES tf, double atr, double &vol_ratio, double &velocity_pips, string &tier);

CZone* GetZoneByName(string obj_name);
bool UpdateZoneCoordinates(string obj_name);
void RemoveZoneByName(string obj_name);
void MergeZones(ENUM_TIMEFRAMES tf, double atr);
bool DetectDynamicZones(ENUM_TIMEFRAMES tf, double atr, bool is_initial_scan);
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);
void UpdateZoneVisuals(bool force_time_extension);

bool UpdateVolatilityCache(const int src_index)
  {
   if(src_index < 0 || src_index >= g_src_count || g_src[src_index].atr_handle == INVALID_HANDLE)
     {

      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;
  }

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;
  }

int SourceIndex(ENUM_TIMEFRAMES tf)
  {
   for(int i = 0; i < g_src_count; i++)
      if(g_src[i].tf == tf)
         return i;
   return -1;
  }

bool IsActiveSource(ENUM_TIMEFRAMES tf)
  {
   return (SourceIndex(tf) >= 0);
  }

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;
  }

void ApplyZoneVisibility(const CZone *z)
  {
   if(z != NULL && ObjectFind(0, z.name) >= 0)
     {
      ObjectSetInteger(0, z.name, OBJPROP_TIMEFRAMES, SourceVisibilityMask(z.source_tf));

      bool is_current_tf = IsActiveSource(z.source_tf) &&
                           z.source_tf == (ENUM_TIMEFRAMES)_Period;
      ObjectSetInteger(0, z.name, OBJPROP_SELECTABLE, is_current_tf);

      if(!is_current_tf)
         ObjectSetInteger(0, z.name, OBJPROP_SELECTED, false);
     }
  }

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);
  }

double SourceCachedAtr(ENUM_TIMEFRAMES tf)
  {
   int idx = SourceIndex(tf);
   return (idx >= 0) ? g_src[idx].cached_atr : 0.0;
  }

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;
  }

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;
  }

void ReleaseSourceHandles(void)
  {
   for(int i = 0; i < MAX_SOURCE_TF; i++)
      ReleaseSourceHandle(i);
  }

string BlacklistKey(ENUM_TIMEFRAMES tf, double price)
  {
   return IntegerToString((int)tf) + "|" + DoubleToString(price, _Digits);
  }

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);
  }

void RemoveManagedChartObjects(void)
  {
   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 && ObjectGetInteger(0, z.name, OBJPROP_TYPE) == OBJ_RECTANGLE)
         ObjectDelete(0, z.name);
      z.was_drawn = false;
     }
  }

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;
  }

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);
     }
  }

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

   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);

   g_src[s].bar1_time = iTime(_Symbol, g_src[s].tf, 1);
   g_src[s].bar0_time = bar0;
   return true;
  }

int OnInit(void)
  {
      // код доступен только после оплаты
   }

void OnTick(void)
  {
      // код доступен только после оплаты
   }

void OnDeinit(const int reason)
  {

   if(g_persist_loaded)
      SavePersistState();

   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++)
     {

      ReleaseSourceHandle(s);
     }

   if(CheckPointer(g_trade) == POINTER_DYNAMIC)
     {
      delete g_trade;
      g_trade = NULL;
     }
   if(CheckPointer(g_strategy) == POINTER_DYNAMIC)
     {
      delete g_strategy;
      g_strategy = NULL;
     }

   logger.Shutdown();

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

CZone* GetZoneByName(string obj_name)
  {
   for(int i = 0; i < active_zones.Total(); i++)
     {
      CZone *z = (CZone*)active_zones.At(i);
      if(z != NULL && z.name == obj_name)
         return z;
     }
   return NULL;
  }

void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
  {

   if(id == CHARTEVENT_OBJECT_CREATE)
     {

      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;

            double z_top = z.top;
            double z_bottom = z.bottom;
            string z_type = EnumToString(z.type);

            string details = StringFormat(">>> Registered user zone: %s | Bounds: %.5f - %.5f", sparam, z_top, z_bottom);
            logger.LogZone("USER", ZE_CREATED, sparam, z_type, z.source_tf, z_top, z_bottom, StringFormat("Strength:%.1f", (double)MinZoneScore), details);
           }
        }
     }

   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)
                 {
                  string details = StringFormat(">>> ZONE MANIPULATION Resized object: %s | New Bounds: %.5f - %.5f", sparam, z.top, z.bottom);
                  logger.LogZone("USER", ZE_MODIFIED, sparam, EnumToString(z.type), z.source_tf, z.top, z.bottom, StringFormat("Strength:%.1f", z.Current_zone_score), details);
                 }
               else
                 {

                  string details = StringFormat(">>> Registered user zone: %s | Bounds: %.5f - %.5f", sparam, z.top, z.bottom);
                  logger.LogZone("USER", ZE_CREATED, sparam, EnumToString(z.type), z.source_tf, z.top, z.bottom, StringFormat("Strength:%.1f", z.Current_zone_score), details);
                 }
              }
            ChartRedraw(0);
           }
        }

      else
         if(id == CHARTEVENT_OBJECT_DELETE)
           {

            if(ObjectFind(0, sparam) >= 0)
               return;

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

            if(!IsActiveSource(z.source_tf))
              {
               ChartRedraw(0);
               return;
              }

            string details = ">>> Deletion Detected user extraction of: " + sparam;
            PrintFormat(">>> [CHART DELETE] Removed from chart: %s | %s", sparam, details);   // the ZE_DELETED transition is logged once, by RemoveZoneByName()

            RemoveZoneByName(sparam);
            ChartRedraw(0);
           }
  }

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;

   if(!IsActiveSource((ENUM_TIMEFRAMES)_Period))
     {
      PrintFormat("[V6][USER] Rectangle '%s' not registered: chart %s is not an active source timeframe. Switch to a configured source timeframe to register a zone.",
                  obj_name, EnumToString((ENUM_TIMEFRAMES)_Period));
      return false;
     }

   int source_index = SourceIndex((ENUM_TIMEFRAMES)_Period);
   if(source_index < 0 || source_index >= g_src_count)
     {
      PrintFormat("[V6][USER] Rectangle '%s' not registered: source context is unavailable.",
                  obj_name);
      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);

   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)
     {
      PrintFormat("[V6][USER] Rectangle '%s' not registered: zone allocation failed.",
                  obj_name);
      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;

   new_zone.zone_score           = MinZoneScore;
   new_zone.Current_zone_score   = MinZoneScore;
   if(MinZoneScore >= 95)
      new_zone.zone_tier = "ELITE";
   else
      if(MinZoneScore >= 80)
         new_zone.zone_tier = "HIGH";
      else
         if(MinZoneScore >= 50)
            new_zone.zone_tier = "MODERATE";
         else
            new_zone.zone_tier = "LOW";

   new_zone.time_left  = (datetime)ObjectGetInteger(0, obj_name, OBJPROP_TIME, 0);   // Part V: capture the user left anchor
   new_zone.time_right = TimeCurrent();                    // Managed right edge

   if(!active_zones.Add(new_zone))
     {
      delete new_zone;
      PrintFormat("[V6][USER] Rectangle '%s' not registered: adding the zone to the tracking array failed.",
                  obj_name);
      return false;
     }

   ObjectSetInteger(0, obj_name, OBJPROP_TIME, 1, TimeCurrent());
   ObjectSetString(0, obj_name, OBJPROP_TEXT, "USER");
   ObjectSetInteger(0, obj_name, OBJPROP_RAY_RIGHT, true);
   ObjectSetInteger(0, obj_name, OBJPROP_BACK, true);
   ObjectSetInteger(0, obj_name, OBJPROP_FILL, true);
   ObjectSetInteger(0, obj_name, OBJPROP_COLOR, new_zone.GetColor());

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

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;
        }
     }

   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;
     }

   if(existing_zone == NULL)
     {

      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;

   if(!existing_zone.is_user_zone)
     {
      existing_zone.is_user_zone = true;
      ObjectSetString(0, existing_zone.name, OBJPROP_TEXT, "USER");

      double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
      existing_zone.type = (existing_zone.price_level > bid) ? ZONE_RESISTANCE : ZONE_SUPPORT;
     }

   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;
  }

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)
           {

            blacklist.Add(BlacklistKey(z.source_tf, z.price_level));   // source-aware identity
           }

         z.was_drawn = false;

         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;

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

         logger.LogZone(z_source,
                        ZE_DELETED,
                        obj_name,
                        z_type,
                        z.source_tf,
                        z_top,
                        z_bottom,
                        "State:CLEANUP",
                        details);

         active_zones.Delete(i);
        }
     }
  }

string PersistFilePath(void)
  {

   return ZP_FOLDER + "\\" + ZP_FILE_PREFIX + _Symbol + ".bin";
  }

void SetupPersistencePath(void)
  {
   FolderCreate("DynamicSR", FILE_COMMON);
   FolderCreate(ZP_FOLDER, FILE_COMMON);
   g_persist.SetPath(PersistFilePath());
  }

void MarkPersistDirty(void)
  {
   g_persist_dirty = true;
  }

void PersistZoneToRecord(const CZone *z, SZonePersist &r)
 

Показано первые 50% кода (символов: 53332)