mql5/Experts/Archive/ERMT_7.1_main.mq5
darashikoh efd4c0e156 Analysis:
Let me chronologically analyze this conversation to capture all technical details, code patterns, and architectural decisions.

## Chronological Analysis:

### Section 1: Initial Phase Management Analysis Request
**User Request**: "In this Management EA, we have implemented phase management to protect profits. Check the flow of the phase management, mechanisms for profit protection and what happens when when a position moves from Intitial to Protection and then back to Initial without locking in a profit percentage"

**My Response**:
- Read ERMT_PME_1.2.mq5 main file (too large)
- Read ProfitMaximizer_PME.mqh module
- Identified 6-tier phase system (INITIAL, PROTECTION, ACCUMULATION, MAXIMIZATION, RUNNER, EXTREME)
- Discovered critical vulnerability: positions could retreat from higher phases without maintaining profit locks
- The `protected_profit` was calculated but not enforced with actual stop loss modifications

### Section 2: Design Solution Request
**User Request**: "Suggest modifications to the EA, whilst remaining within the current architecture, to lock in profits using phase management whilst allowing trades to breathe as well"

**My Response**:
- Created comprehensive modification plan (PHASE_PROFIT_LOCK_MODIFICATIONS.md)
- Designed progressive profit locking with minimum guarantees per phase
- 50% breathing room from peak
- Dynamic adjustments for momentum/volatility
- Retreat protection maintaining locks from highest achieved phase

### Section 3: Implementation Request
**User Request**: "Implement the suggested changes"

**My Response**:
- Modified ProfitMaximizer_PME.mqh: Added 17 config parameters, 6 tracker fields, 9 new methods (~250 lines)
- Modified ERMT_PME_1.2.mq5: Added 10 input parameters, enhanced ApplyPhaseManagement(), updated dashboard (~60 lines)
- Implementation included lock calculation, retreat protection, dynamic adjustments

### Section 4: Pre-Compilation Hard Stop Analysis
**User Request**: "Just before we compile, check if there are hard stop losses coded in to the EA and assess when they are triggered"

**My Response**:
- Analyzed all stop loss mechanisms
- Found emergency stops (3× ATR), breakeven stops, trailing stops, account-level stops
- Created HARD_STOP_ANALYSIS.md documenting all mechanisms

### Section 5: First Compilation Errors
**User Report**: Compilation errors including 'protected' reserved keyword and type conversion warning

**My Response**:
- Fixed 'protected' reserved keyword by renaming to 'protected_profit', 'peak_profit', 'retracement_pct'
- Fixed type conversion with explicit cast: `switch((int)deal_reason)`
- Created COMPILATION_FIXES.md

### Section 6: Second Compilation Error (Line 367)
**User Report**: "undeclared identifier ERMT_PME_1.2.mq5 367 13" with multiple syntax errors

**My Response**:
- Identified issue: `PositionModify()` used as standalone function (doesn't exist in MQL5)
- Fixed by using `g_manager.AdjustStopLoss()` method instead
- Created COMPILATION_FIX_LINE367.md

### Section 7: Profit Protection Systems Conflict Analysis
**User Request**: "In this EA, assess whether breakeven enablement conflicts with partial position closure and phase management. Thereafter, assess which method is the best for profit maximisation, protection in the case of retracements"

**My Response**:
- Comprehensive analysis identifying critical conflict at 40pts trigger point
- Breakeven: 8pts fixed lock (20% efficiency)
- Phase locks: 10-14pts adaptive lock (35% efficiency)
- Partials + Phase locks: 70-80% combined efficiency
- Created PROFIT_PROTECTION_ANALYSIS.md recommending to disable breakeven

### Section 8: Code Cleanup Request
**User Request**: "Suggest which code should be commented out but do not delete code"

**My Response**:
- Recommended commenting out breakeven execution in PositionManager
- Suggested preserving code for backward compatibility
- Explained benefits of keeping code vs deleting
- Alternative: conditional compilation approach

### Section 9: Conditional Compilation Implementation
**User Request**: "Implement the cleaner code completion"

**My Response**:
- Added system configuration flags at top of ERMT_PME_1.2.mq5:
  - `#define USE_BREAKEVEN_SYSTEM false`
  - `#define USE_PHASE_LOCKING true`
  - `#define USE_PARTIAL_CLOSURES true`
- Wrapped breakeven configuration in `#if USE_BREAKEVEN_SYSTEM ... #else ... #endif`
- Wrapped breakeven execution in PositionManager
- Added automatic logging of active systems
- Created CONDITIONAL_COMPILATION_GUIDE.md

### Section 10: Configuration Analysis Request
**User Request**: "Before further compilations, assess which variables would benefit from being setup as inputs when initialising the EA. Moreover, demonstrate the difference between the different management strategies and whether volatility adaptation can make use of other methods other than ATR"

**My Response**:
- Comprehensive analysis identifying 100+ hardcoded variables
- Created CONFIGURATION_RECOMMENDATIONS.md with:
  - Risk management variables (Priority HIGH)
  - Trailing stop configuration
  - Partial closure settings
  - Trading style presets (Conservative/Balanced/Aggressive)
  - Input validation requirements
- Created MANAGEMENT_STRATEGIES_COMPARISON.md with:
  - Detailed comparison of 4 management strategies
  - Performance metrics for each strategy
  - Volatility adaptation alternatives (ATR, Bollinger Bands, Std Dev, Range %, Chaikin)
  - Hybrid volatility assessment approach

## Key Technical Details to Preserve:

### Phase Lock System Design:
- 6 phases with progressive locks: 10→200pts
- Breathing room: 50% retracement from peak
- Retreat protection: maintains highest phase lock
- Dynamic adjustments: momentum (±30%), volatility (±30%)

### Configuration Flags:
```mql5
#define USE_BREAKEVEN_SYSTEM false
#define USE_PHASE_LOCKING true
#define USE_PARTIAL_CLOSURES true
```

### Critical File Modifications:
1. ProfitMaximizer_PME.mqh: 17 config params, 6 tracker fields, 9 methods
2. ERMT_PME_1.2.mq5: 10 input params, ApplyPhaseManagement() enhancement
3. PositionManager_PME_Complete.mqh: Conditional compilation wrappers

### Errors Fixed:
1. Reserved keyword 'protected' → renamed to 'protected_profit'
2. Type conversion warning → explicit cast `(int)deal_reason`
3. PositionModify() undefined → use g_manager.AdjustStopLoss()

Summary:
## 1. Primary Request and Intent

The user's requests evolved through several phases:

1. **Initial Analysis**: Analyze phase management flow and identify profit protection gaps when positions retreat from higher phases without locking profits
2. **Design Solution**: Suggest modifications within current architecture to lock profits while allowing trades to breathe
3. **Implementation**: Implement the suggested phase-based profit locking system
4. **Pre-Compilation**: Check for hard-coded stop losses before compilation
5. **Fix Compilation Errors**: Address multiple compilation errors (reserved keywords, type conversions, undefined functions)
6. **Conflict Analysis**: Assess whether breakeven conflicts with partial closures and phase management, determine best method for profit maximization
7. **Code Cleanup**: Suggest which code to comment out (not delete) to resolve conflicts
8. **Clean Implementation**: Implement conditional compilation for cleaner code management
9. **Configuration Analysis**: Identify hardcoded variables that should be exposed as inputs, compare management strategies, analyze volatility adaptation alternatives

## 2. Key Technical Concepts

- **Phase-Based Profit Management**: 6-tier progressive system (INITIAL, PROTECTION, ACCUMULATION, MAXIMIZATION, RUNNER, EXTREME)
- **Progressive Profit Locking**: Minimum locks increase with each phase (10→25→50→100→200 points)
- **Breathing Room**: 50% retracement tolerance from peak profit
- **Retreat Protection**: Maintains locks from highest achieved phase with 20% tightening multiplier
- **Dynamic Lock Adjustments**: Adapts based on momentum (±30%) and volatility (±30%)
- **Conditional Compilation**: Using `#define` flags to enable/disable systems without code deletion
- **MQL5 Trading Functions**: `PositionModify()` doesn't exist as standalone, must use `CTrade.PositionModify()` or manager wrapper
- **Reserved Keywords**: `protected`, `public`, `private` cannot be used as variable names in MQL5
- **Partial Closure Strategy**: Progressive profit-taking at multiple levels (50, 100, 200, 400 points)
- **Volatility Adaptation**: ATR-based (current), alternatives include Bollinger Bands, Std Dev of Returns, Range %, Chaikin Volatility

## 3. Files and Code Sections

### A. ProfitMaximizer_PME.mqh
**Why Important**: Core module implementing phase-based profit locking logic

**Key Modifications**:
- Added 17 configuration parameters for phase-based profit locking
- Added 6 tracking fields to ProfitTracker struct
- Implemented 9 new methods (~250 lines of code)

**Critical Code Snippets**:

```mql5
// Enhanced Configuration Structure (Lines 45-66)
struct ProfitProtectionConfig
{
    // === PHASE-BASED PROFIT LOCKING ===
    bool     use_phase_profit_locks;         // Enable phase-based profit locking
    double   phase_lock_percentage;          // Base % of profit to lock per phase
    bool     progressive_locking;            // Increase lock % with higher phases

    // Phase-Specific Minimum Locks
    double   phase1_min_lock;                // PROTECTION: 10pts
    double   phase2_min_lock;                // ACCUMULATION: 25pts
    double   phase3_min_lock;                // MAXIMIZATION: 50pts
    double   phase4_min_lock;                // RUNNER: 100pts
    double   phase5_min_lock;                // EXTREME: 200pts

    // Dynamic Lock Adjustments
    double   momentum_lock_reduction;        // 0.7 = 30% reduction in strong trends
    double   volatility_lock_increase;       // 1.3 = 30% tighter in high volatility
    double   breathing_room_percentage;      // 50% retracement allowed from peak

    // Phase Transition Lock Behavior
    bool     lock_on_phase_advance;          // Lock profit when advancing phases
    bool     maintain_lock_on_retreat;       // Keep lock when retreating
    double   retreat_lock_multiplier;        // 1.2 = 20% tighter when retreating
};
```

```mql5
// Enhanced Tracker Structure (Lines 92-98)
struct ProfitTracker
{
    // Phase lock tracking
    ENUM_PROFIT_PHASE highest_phase_achieved;  // Highest phase ever reached
    double   locked_profit_minimum;            // Minimum profit locked in
    bool     phase_lock_active;                // Is phase lock currently active
    double   last_lock_price;                  // Last stop price set by phase lock
    datetime last_lock_time;                   // When lock was last updated
    int      phase_retreat_count;              // Number of times retreated from higher phase
};
```

```mql5
// Retreat Protection Logic (Lines 551-571)
else if(new_phase < old_phase)
{
    // Phase retreat detected
    m_trackers[index].phase_retreat_count++;

    if(m_config.maintain_lock_on_retreat)
    {
        // Keep the higher phase's minimum lock
        double higher_phase_lock = GetMinimumPhaseLock(m_trackers[index].highest_phase_achieved);
        if(higher_phase_lock > m_trackers[index].locked_profit_minimum)
        {
            m_trackers[index].locked_profit_minimum = higher_phase_lock;
            m_trackers[index].phase_lock_active = true;
        }

        m_utils.Log(StringFormat("Position #%I64u: Phase retreat - maintaining lock at %.1f pts (from %s phase)",
                    m_trackers[index].ticket,
                    m_trackers[index].locked_profit_minimum,
                    PhaseToString(m_trackers[index].highest_phase_achieved)), LOG_WARNING);
    }
}
```

```mql5
// Phase-Based Stop Calculation (Lines 746-797)
double CalculatePhaseBasedStop(ulong ticket, double current_price, double entry_price)
{
    if(!m_config.use_phase_profit_locks) return 0;

    int index = FindTracker(ticket);
    if(index < 0) return 0;

    ENUM_PROFIT_PHASE phase = m_trackers[index].phase;
    double peak_profit = m_trackers[index].peak_profit;

    // Calculate base protected profit based on phase
    double base_lock = CalculateBasePhaseLock(phase);

    // Apply progressive locking based on peak profit
    double progressive_lock = 0;
    if(m_config.progressive_locking && peak_profit > base_lock)
    {
        double excess_profit = peak_profit - base_lock;
        double lock_percentage = CalculateLockPercentage(phase);
        progressive_lock = excess_profit * (lock_percentage / 100.0);
    }

    // Total locked profit
    double total_locked_profit = base_lock + progressive_lock;

    // Apply breathing room (allow retracement from peak)
    double breathing_room = (peak_profit - total_locked_profit) *
                           (m_config.breathing_room_percentage / 100.0);
    double effective_lock = total_locked_profit - breathing_room;

    // Apply dynamic adjustments
    effective_lock = ApplyDynamicLockAdjustments(index, effective_lock, peak_profit);

    // Convert locked profit to price level
    double stop_price;
    if(is_long)
        stop_price = entry_price + (effective_lock * _Point);
    else
        stop_price = entry_price - (effective_lock * _Point);

    return NormalizeDouble(stop_price, _Digits);
}
```

### B. ERMT_PME_1.2.mq5
**Why Important**: Main EA file, entry point, configuration hub

**Key Modifications**:
- Added system configuration flags (conditional compilation)
- Added 10 input parameters for phase-based profit locking
- Enhanced ApplyPhaseManagement() function to apply phase locks
- Updated dashboard with phase lock statistics

**Critical Code Snippets**:

```mql5
// System Configuration Flags (Lines 24-44)
//+------------------------------------------------------------------+
//| SYSTEM CONFIGURATION FLAGS                                        |
//+------------------------------------------------------------------+
#define USE_BREAKEVEN_SYSTEM false        // DISABLED - Replaced by phase locks
#define USE_PHASE_LOCKING true            // ENABLED - Primary protection system
#define USE_PARTIAL_CLOSURES true         // ENABLED - Complementary to phase locks
```

```mql5
// Phase-Based Profit Locking Inputs (Lines 124-136)
input group "Phase-Based Profit Locking"
input bool     InpUsePhaseProfitLocks = true;          // Enable Phase Profit Locks
input double   InpPhaseLockBreathingRoom = 50;         // Breathing Room from Peak (%)
input bool     InpMaintainLockOnRetreat = true;        // Keep Lock When Retreating
input double   InpRetreatLockMultiplier = 1.2;         // Lock Tightening on Retreat

// Phase Minimum Locks
input double   InpPhase1MinLock = 10;                  // PROTECTION Min Lock (pts)
input double   InpPhase2MinLock = 25;                  // ACCUMULATION Min Lock (pts)
input double   InpPhase3MinLock = 50;                  // MAXIMIZATION Min Lock (pts)
input double   InpPhase4MinLock = 100;                 // RUNNER Min Lock (pts)
input double   InpPhase5MinLock = 200;                 // EXTREME Min Lock (pts)
```

```mql5
// Enhanced ApplyPhaseManagement Function (Lines 325-377)
void ApplyPhaseManagement(ulong ticket)
{
    if(!InpUsePhaseManagement || g_profit_max == NULL) return;

    // Get position info
    if(!PositionSelectByTicket(ticket)) return;

    double current_price = PositionGetDouble(POSITION_PRICE_CURRENT);
    double entry_price = PositionGetDouble(POSITION_PRICE_OPEN);
    double profit_points = (current_price - entry_price) / _Point;

    // For short positions, profit calculation is inverted
    if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
        profit_points = (entry_price - current_price) / _Point;

    // Analyze position and determine phase
    g_profit_max.AnalyzePosition(ticket, current_price, profit_points);

    // Get current phase
    ENUM_PROFIT_PHASE phase = g_profit_max.GetCurrentPhase(ticket);

    // === NEW: Apply phase-based profit lock ===
    double phase_stop_price;
    string lock_reason;

    if(g_profit_max.GetPhaseProtectionStop(ticket, phase_stop_price, lock_reason))
    {
        // Phase lock suggests a stop update
        if(g_manager != NULL && !g_manager.AdjustStopLoss(ticket, phase_stop_price))
        {
            if(g_utils != NULL)
                g_utils.Log(StringFormat("Failed to apply phase lock for #%I64u: %s",
                            ticket, lock_reason), LOG_ERROR);
        }
        else
        {
            if(g_utils != NULL)
                g_utils.Log(StringFormat("Applied phase lock for #%I64u: %s",
                            ticket, lock_reason), LOG_INFO);

            // Sound alert for lock application
            if(InpSoundAlerts) PlaySound("ok.wav");
        }
    }
}
```

```mql5
// Conditional Breakeven Configuration (Lines 68-100)
#if USE_BREAKEVEN_SYSTEM
    input bool     InpBreakevenEnabled = true;
    input double   InpBreakevenTrigger = 40;
    input double   InpBreakevenOffset = 8;
    input bool     InpMultiLevelBE = true;
#else
    // Breakeven DISABLED - Using phase-based profit locking instead
    bool     InpBreakevenEnabled = false;           // DISABLED
    double   InpBreakevenTrigger = 40;              // (Not used)
    double   InpBreakevenOffset = 8;                // (Not used)
    bool     InpMultiLevelBE = false;               // (Not used)
#endif
```

### C. PositionManager_PME_Complete.mqh
**Why Important**: Handles position management, executes stop loss modifications

**Key Modifications**:
- Added configuration flag imports
- Wrapped breakeven execution in conditional compilation
- Wrapped partial closures in conditional compilation
- Added system status logging

**Critical Code Snippets**:

```mql5
// Configuration Flag Imports (Lines 19-34)
//+------------------------------------------------------------------+
//| Import system configuration flags from main EA                   |
//+------------------------------------------------------------------+
#ifndef USE_BREAKEVEN_SYSTEM
    #define USE_BREAKEVEN_SYSTEM false    // Default: DISABLED
#endif

#ifndef USE_PHASE_LOCKING
    #define USE_PHASE_LOCKING true        // Default: ENABLED
#endif

#ifndef USE_PARTIAL_CLOSURES
    #define USE_PARTIAL_CLOSURES true     // Default: ENABLED
#endif
```

```mql5
// Conditional Breakeven Execution (Lines 736-749)
// Breakeven management
#if USE_BREAKEVEN_SYSTEM
    if(m_config.breakeven_enabled && !m_positions[index].breakeven_applied)
    {
        if(CheckBreakevenCondition(index))
        {
            MoveToBreakeven(ticket);
        }
    }
#else
    // Breakeven system DISABLED - Using phase-based profit locking instead
    // To re-enable: Set USE_BREAKEVEN_SYSTEM = true in main EA file
#endif
```

```mql5
// System Status Logging (Lines 324-337)
// Log active profit protection systems
#if !USE_BREAKEVEN_SYSTEM
    m_utils.Log("Breakeven system: DISABLED (using phase-based profit locking)", LOG_INFO);
#else
    m_utils.Log("Breakeven system: ENABLED", LOG_INFO);
#endif

#if USE_PHASE_LOCKING
    m_utils.Log("Phase-based profit locking: ENABLED", LOG_INFO);
#endif

#if USE_PARTIAL_CLOSURES
    m_utils.Log("Partial closures: ENABLED", LOG_INFO);
#endif
```

### D. Documentation Files Created

1. **PHASE_PROFIT_LOCK_MODIFICATIONS.md**: Complete design specification with examples
2. **IMPLEMENTATION_SUMMARY.md**: Implementation details and statistics
3. **HARD_STOP_ANALYSIS.md**: Analysis of all stop loss mechanisms
4. **COMPILATION_FIXES.md**: Documentation of compilation errors fixed
5. **COMPILATION_FIX_LINE367.md**: Specific fix for PositionModify error
6. **PROFIT_PROTECTION_ANALYSIS.md**: 15-page comprehensive analysis comparing all profit protection systems
7. **CONDITIONAL_COMPILATION_GUIDE.md**: Guide for using configuration flags
8. **CONFIGURATION_RECOMMENDATIONS.md**: Analysis of 100+ hardcoded variables with recommendations
9. **MANAGEMENT_STRATEGIES_COMPARISON.md**: Detailed comparison of management strategies and volatility methods

## 4. Errors and Fixes

### Error 1: Reserved Keyword "protected"
**Location**: ERMT_PME_1.2.mq5:985

**Error Message**:
```
'protected' - unexpected token
undeclared identifier
wrong parameters count
```

**Cause**: `protected` is a reserved keyword in MQL5 (access modifier)

**Fix Applied**: Renamed variables in UpdateDashboard() function:
```mql5
// BEFORE:
double protected, peak, retracement;
g_profit_max.GetProtectionStatus(ticket, protected, peak, retracement);

// AFTER:
double protected_profit, peak_profit, retracement_pct;
g_profit_max.GetProtectionStatus(ticket, protected_profit, peak_profit, retracement_pct);
```

**User Feedback**: User reported the error, I fixed it immediately

### Error 2: Type Conversion Warning
**Location**: PositionManager_PME_Complete.mqh:562

**Error Message**:
```
possible loss of data due to type conversion from 'long' to 'int'
```

**Fix Applied**: Added explicit type cast:
```mql5
// BEFORE:
long deal_reason = HistoryDealGetInteger(deal_ticket, DEAL_REASON);
switch(deal_reason)

// AFTER:
long deal_reason = HistoryDealGetInteger(deal_ticket, DEAL_REASON);
switch((int)deal_reason)  // Explicit cast to int
```

### Error 3: Line 367 Undefined Function
**Location**: ERMT_PME_1.2.mq5:367

**Error Messages**:
```
undeclared identifier
',' - unexpected token
'ticket' - some operator expected
'(' - unbalanced left parenthesis
illegal 'else' without matching 'if'
```

**Root Cause**: Used `PositionModify(ticket, phase_stop_price, PositionGetDouble(POSITION_TP))` as if it were a standalone MQL5 function, but it doesn't exist. Position modifications must be done through a CTrade object.

**Fix Applied**: Changed to use PositionManager's wrapper method:
```mql5
// BEFORE (INCORRECT):
if(!PositionModify(ticket, phase_stop_price, PositionGetDouble(POSITION_TP)))

// AFTER (CORRECT):
if(g_manager != NULL && !g_manager.AdjustStopLoss(ticket, phase_stop_price))
```

**Why This Works**:
- `g_manager` is the global `CPositionManager` object
- It has a `CTrade m_trade` member internally
- `AdjustStopLoss()` method properly wraps the `m_trade.PositionModify()` call
- Maintains consistency with EA's architecture

**User Feedback**: User reported "undeclared identifier ERMT_PME_1.2.mq5 367 13" with multiple errors, I analyzed and fixed

## 5. Problem Solving

### Problems Solved:

1. **Profit Protection Gap Identified**: Discovered positions could retreat from PROTECTION to INITIAL phase without any profit locked, losing all gains from the move.

2. **Phase-Based Locking System Designed**: Created comprehensive system with:
   - Progressive minimum locks (10→200pts)
   - Breathing room (50% retracement tolerance)
   - Retreat protection (maintains highest phase lock)
   - Dynamic adjustments (momentum/volatility)

3. **Implementation Completed**: Added ~250 lines to ProfitMaximizer and ~60 lines to main EA with full phase locking functionality.

4. **Compilation Errors Resolved**: Fixed three critical errors (reserved keyword, type conversion, undefined function).

5. **Conflict Resolution**: Identified and resolved conflict between breakeven and phase locks:
   - Both triggered at 40pts
   - Breakeven: 8pts lock (20% efficiency)
   - Phase locks: 10-14pts lock (35% efficiency)
   - Solution: Disabled breakeven using conditional compilation

6. **Code Organization**: Implemented clean conditional compilation system allowing easy enable/disable of systems without code deletion.

7. **Configuration Analysis**: Identified 100+ hardcoded variables that should be exposed as inputs for better user control.

8. **Strategy Comparison**: Provided comprehensive comparison showing Partials + Phase Locks achieve 70-80% efficiency vs 4% for breakeven only.

### Ongoing Considerations:

- Over 100 variables should be exposed as inputs (documented in CONFIGURATION_RECOMMENDATIONS.md)
- Volatility adaptation could be enhanced with multi-method approach (ATR + Bollinger Bands + Std Dev)
- Preset configurations (Conservative/Balanced/Aggressive) could improve user experience

## 6. All User Messages

1. "In this Management EA, we have implemented phase management to protect profits. Check the flow of the phase management, mechanisms for profit protection and what happens when when a position moves from Intitial to Protection and then back to Initial without locking in a profit percentage"

2. "Suggest modifications to the EA, whilst remaining within the current architecture, to lock in profits using phase management whilst allowing trades to breathe as well"

3. "Implement the suggested changes"

4. "Just before we compile, check if there are hard stop losses coded in to the EA and assess when they are triggered"

5. "These are the compilation errors: [list of errors including protected keyword and type conversion]"

6. "undeclared identifier ERMT_PME_1.2.mq5 367 13 [followed by additional line 367 errors]"

7. "In this EA, assess whether breakeven enablement conflicts with partial position closure and phase management. Thereafter, assess which method is the best for profit maximisation, protection in the case of retracements"

8. "Suggest which code should be commented out but do not delete code"

9. "Implement the cleaner code completion"

10. "Before further compilations, assess which variables would benefit from being setup as inputs when initialising the EA. Moreover, demonstrate the difference between the different management strategies and whether volatility adaptation can make use of other methods other than ATR"

## 7. Pending Tasks

No explicit pending tasks. The most recent work (configuration analysis and management strategy comparison) has been completed with two comprehensive documentation files created.

## 8. Current Work

**Immediately Before Summary Request**: The work focused on completing two major analytical documents in response to the user's request to assess configuration variables and compare management strategies.

**Specific Work Completed**:

1. **Created CONFIGURATION_RECOMMENDATIONS.md** (52KB document):
   - Identified 100+ hardcoded variables that should be exposed as inputs
   - Organized into 13 functional groups (Risk Management, Profit Protection, Exit Management, etc.)
   - Created priority tiers (HIGH/MEDIUM/LOW)
   - Designed trading style presets (Ultra Conservative → Very Aggressive)
   - Provided implementation examples with input validation
   - Documented variable interactions and dependencies

2. **Created MANAGEMENT_STRATEGIES_COMPARISON.md** (extensive document):
   - Compared 4 management strategies:
     * Breakeven (4-10% efficiency) - NOT RECOMMENDED
     * Trailing Stops (40-60% efficiency) - Good for trends
     * Partial Closures (40-55% efficiency) - Requires stop management
     * Phase Locks (50-70% efficiency) - Excellent adaptive
     * **Partials + Phase Locks (75-80% efficiency) - OPTIMAL**
   - Analyzed volatility adaptation methods:
     * ATR (current) - Industry standard
     * Bollinger Band Width - Squeeze/expansion detection
     * Standard Deviation of Returns - Statistical precision
     * Intraday Range Percentage - Real-time assessment
     * Chaikin Volatility - Volatility trend
   - Provided hybrid volatility assessment approach
   - Detailed scenario comparisons (strong uptrend, whipsaw, quick reversal)

**Key Files Modified**: None in this section - focused on documentation and analysis

**Key Findings**:
- Risk management variables (InpMaxLossPerTrade, InpMaxDailyLoss) are hardcoded at dangerously high levels (10%, 20%)
- Current system (Partials + Phase Locks with ATR) is already excellent (75-80% efficiency)
- Breakeven should remain disabled (already implemented via conditional compilation)
- Enhancement opportunity: Multi-method volatility assessment for even better adaptation

## 9. Optional Next Step

**Status**: The most recent work is complete. All requested analysis and documentation has been provided.

**If User Wants to Proceed**, the logical next steps based on the analysis would be:

1. **Expose Critical Variables as Inputs** (from CONFIGURATION_RECOMMENDATIONS.md):
   - Priority 1: Risk limits (InpMaxLossPerTrade, InpMaxDailyLoss, InpMaxDrawdown)
   - Priority 2: Trailing parameters (InpTrailStart, InpTrailDistance, InpTrailStep)
   - Priority 3: Partial closure settings (triggers and percentages)

2. **Implement Trading Style Presets**:
   - Add `ENUM_TRADING_STYLE InpTradingStyle` input
   - Auto-configure all settings based on selected style
   - Add input validation

3. **Enhance Volatility Assessment**:
   - Add Bollinger Band Width calculation
   - Implement multi-method consensus approach
   - Add volatility regime detection

**Direct Quote from Recent Work**: The user's last request was: "Before further compilations, assess which variables would benefit from being setup as inputs when initialising the EA. Moreover, demonstrate the difference between the different management strategies and whether volatility adaptation can make use of other methods other than ATR"

This request has been fully completed with:
- CONFIGURATION_RECOMMENDATIONS.md identifying 100+ variables with priority tiers
- MANAGEMENT_STRATEGIES_COMPARISON.md providing detailed strategy comparison and volatility method analysis

**Recommendation**: Wait for user confirmation before proceeding with any code modifications to expose variables as inputs, as this would be a significant change requiring testing and validation..
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.

# Entry Assessment — Implementation Plan (29.10)

## Tier 1: Immediate Optimizations (enable a working EA first)

### 1.1 Complete missing strategy implementations
Priority: CRITICAL • Impact: Enable 3 additional entry modes

- [ ] A) Mean Reversion Strategy (`EntrySystem_Optimised.mqh:1027-1039`)
- Check RSI < 30 (oversold) or RSI > 70 (overbought)
- Verify Bollinger Band touches (price beyond bands)
- Confirm market is RANGING or QUIET
- Enter on reversion to mean (BB middle or key MA)
- Tight stops at extreme, targets at mean

- [ ] B) MA Pullback Strategy (`EntrySystem_Optimised.mqh:1015-1024`)
- Identify primary trend (MA 50 > MA 200)
- Wait for price pullback to MA 20/50
- Confirm momentum resumption (MACD or RSI turn)
- Enter in trend direction with tight stop below pullback low

- [ ] C) Contrarian Strategy (`EntrySystem_Optimised.mqh:1042-1051`)
- Detect extreme readings (RSI < 20 or > 80)
- Stochastic oversold/overbought
- Volume climax detection
- Divergence confirmation (price vs RSI)
- Counter-trend entry with wider stops

### 1.2 Optimize existing strategy parameters
Priority: HIGH • Impact: Increase signal frequency 2–3x without quality loss

| Parameter               | Current | Scalping (M1–M5) | Intraday (M15–H1) | Daily (H4–D1) |
|-------------------------|---------|------------------|-------------------|---------------|
| MinTimeBetweenTrades    | 60 min  | 5–15 min         | 30–60 min         | 120–240 min   |
| MA Fast                 | EMA 20  | EMA 8–12         | EMA 20            | EMA 50        |
| MA Slow                 | EMA 50  | EMA 21–34        | EMA 50            | EMA 200       |
| RSI Period              | 14      | 7–9              | 14                | 21            |
| ADX Threshold           | 25      | 20               | 25                | 30            |
| BB Period               | 20      | 10–15            | 20                | 30            |
| ATR Multiplier (SL)     | 2.0     | 1.5              | 2.0               | 2.5–3.0       |
| Signal Threshold        | 60%     | 70%              | 65%               | 60%           |

### 1.3 Add adaptive timeframe logic
Priority: HIGH • File: `EntrySystem_Optimised.mqh`

```cpp
// ADD NEW METHOD:
void CEntrySystem::AdaptParametersToTimeframe()
{
    int current_period = Period();

    // Scalping timeframes (M1-M5)
    if(current_period <= PERIOD_M5)
    {
        m_config.min_time_between = 10;   // 10 minutes
        m_config.signal_threshold = 70;   // Higher quality required
        // Recreate indicators with faster periods
    }
    // Intraday timeframes (M15-H1)
    else if(current_period <= PERIOD_H1)
    {
        m_config.min_time_between = 30;
        m_config.signal_threshold = 65;
    }
    // Daily timeframes (H4+)
    else
    {
        m_config.min_time_between = 120;
        m_config.signal_threshold = 60;
    }
}
```

## Tier 2: Enhanced signal generation

### 2.1 Enable intra-bar scanning for breakout mode
Priority: MEDIUM • Impact: 3–5x more breakout signals • File: `EntrySystem_Optimised.mqh:296-300`

```cpp
// MODIFY:
// Only check on new bar for most strategies (except breakout)
if(!m_new_bar && m_config.entry_mode != ENTRY_BREAKOUT &&
   m_config.entry_mode != ENTRY_MOMENTUM)  // Add momentum for scalping
{
    return signal;
}
```

### 2.2 Multi-timeframe signal confirmation
Priority: MEDIUM • Impact: Higher quality signals, better win rate

```cpp
bool CEntrySystem::ConfirmWithHigherTimeframe(ENUM_SIGNAL_TYPE signal_type)
{
    // Check 1-2 timeframes higher for trend alignment
    ENUM_TIMEFRAMES htf = GetHigherTimeframe(PERIOD_CURRENT);

    // Simple MA trend check on HTF
    double ma_fast_htf[], ma_slow_htf[];
    // Copy and compare

    if(signal_type == SIGNAL_BUY)
        return (ma_fast_htf[0] > ma_slow_htf[0]);  // HTF uptrend
    else
        return (ma_fast_htf[0] < ma_slow_htf[0]);  // HTF downtrend
}
```

Integration:
- Add HTF filter to `ValidateSignal()`
- Optional bonus to confidence score if HTF aligned

### 2.3 Add market session awareness
Priority: MEDIUM • Impact: Better signal timing, avoid low-liquidity periods

```cpp
enum ENUM_SESSION
{
    SESSION_ASIAN,     // 00:00-09:00 GMT
    SESSION_LONDON,    // 08:00-17:00 GMT
    SESSION_NY,        // 13:00-22:00 GMT
    SESSION_OVERLAP    // London/NY overlap
};
```

Session-driven strategy selection:
- Breakout strategies during overlaps (high volatility)
- Mean reversion during Asian session (low volatility)
- Momentum during London/NY sessions

## Tier 3: Advanced enhancements

### 3.1 Volume profile integration
Priority: LOW • Impact: Identify high-probability zones (Technical Analysis)
- Volume-weighted price zones
- POC (Point of Control) levels
- Value Area High/Low
- Entry at VA boundaries

### 3.2 Smart order flow detection
Priority: LOW • Impact: Institutional trade detection
- Large order detection (volume spikes)
- Bid/Ask imbalance analysis
- Absorption/exhaustion patterns
- Hidden liquidity detection

### 3.3 Correlation-based signal filtering
Priority: MEDIUM • Impact: Avoid correlated entries

```cpp
// Before opening new position:
// 1. Check correlation of new symbol with existing positions
// 2. If correlation > 0.7, reduce position size or skip
// 3. Track symbol pair correlations dynamically
```

## Implementation roadmap

### Phase 1: Foundation (Week 1–2)
- [x] Complete Mean Reversion strategy
- [x] Complete MA Pullback strategy
- [x] Complete Contrarian strategy
- [x] Add adaptive timeframe parameter logic
- [] Test all strategies on M15/H1 independently

### Phase 2: Optimization (Week 3–4)
- [] Implement intra-bar scanning for selected strategies
- [] Add multi-timeframe confirmation system
- [] Optimize parameters per timeframe
- [] Backtest across all timeframes
- [] Compare signal frequency and quality metrics

### Phase 3: Advanced features (Week 5–6)
- [ ] Add market session logic
- [ ] Implement correlation filtering
- [ ] Volume profile analysis (optional)
- [ ] Final optimization and stress testing

## Expected outcomes

### Signal frequency improvements

| Timeframe              | Current  | After Phase 1 | After Phase 2 |
|------------------------|----------|---------------|----------------|
| M1–M5 (Scalping)       | 0.5–2/day| 5–10/day      | 10–20/day      |
| M15–M30 (Intraday)     | 2–8/day  | 6–12/day      | 8–15/day       |
| H1–H4 (Swing)          | 1–5/day  | 3–8/day       | 4–10/day       |
| D1 (Position)          | 1–5/week | 2–7/week      | 3–10/week      |

### Quality metrics targets
- Win Rate: 45–55% (maintain or improve)
- Profit Factor: > 1.5 (target 1.8–2.2)
- Sharpe Ratio: > 1.2
- Max Drawdown: < 20%
- Avg R:R: > 1:1.5 (target 1:2)

## Update TODOs
- [ ] Assess EA signal generation for scalping timeframes
- [ ] Assess EA signal generation for intraday timeframes
- [ ] Assess EA signal generation for daily timeframes
- [ ] Evaluate robustness and filtering mechanisms
- [ ] Create improvement plan document

## Summary & recommendations

### Current state assessment
Your ERMT 7.1 EA is institutionally robust with excellent risk management, but signal generation is optimized primarily for intraday trading (M15–H1).

Strengths:
- Exceptional modular architecture
- Multiple entry strategies with consensus capability
- Sophisticated risk and trade management
- Multi-symbol external trade handling

Weaknesses:
- 3 strategies have incomplete implementations
- Fixed parameters don't adapt to timeframe
- New-bar requirement limits scalping potential
- Conservative time restrictions reduce signal frequency

### Priority recommendation
START WITH TIER 1 (Phase 1):
- Complete the 3 incomplete strategies first
- Add adaptive parameter logic based on timeframe
- Test each strategy independently on M15/H1 (your sweet spot)
- Once working reliably, expand to other timeframes

This approach follows your learning point: "Rework and optimize existing code and modules first enabling a working EA before advancing to new architecture."

### Next steps
- [ ] Implement the missing strategy completions (Mean Reversion, MA Pullback, Contrarian)
- [ ] Add the adaptive timeframe logic to automatically adjust parameters
- [ ] Create a testing framework to evaluate signal frequency and quality
- [ ] Proceed with any other specific improvement from the plan
2025-11-11 17:23:18 +00:00

1784 Zeilen
Kein EOL
60 KiB
MQL5

//+------------------------------------------------------------------+
//| Risk Management Overlay EA v7.1 |
//| Fully Optimized Version |
//| Fixed Multi-Symbol Detection |
//+------------------------------------------------------------------+
#property copyright "Institutional Risk Management System v7.1"
#property version "7.0"
#property strict
#property description "Modular risk management system with advanced monitoring"
//--- Include system modules
#include <Trade/Trade.mqh>
#include "Modules/RiskManager.mqh"
#include "Modules/TradeManager.mqh"
#include "Modules/EntrySystem.mqh"
#include "Modules/TechnicalAnalysis.mqh"
#include "Modules/Dashboard_Enhanced.mqh"
#include "Modules/Utilities.mqh"
#include "Modules/MultiTradeReporter.mqh"
//+------------------------------------------------------------------+
//| INPUT PARAMETERS - GROUPED BY MODULE |
//+------------------------------------------------------------------+
//--- System Configuration
input group "=== SYSTEM CONFIGURATION ==="
input bool SystemEnabled = true; // Enable System
input int TradingMagic = 12345; // EA Magic Number
input bool ManageExternalTrades = true; // Manage External Trades
input int MagicNumberFilter = 0; // External Magic Filter (0=all)
input ENUM_LOG_LEVEL LogLevel = LOG_INFO; // Logging Level
//--- Entry System Parameters
input group "=== ENTRY SYSTEM ==="
input ENUM_ENTRY_MODE EntryMode = ENTRY_MA_CROSS; // Entry System Type
input bool EnableMultipleEntries = false; // Allow Multiple Entries
input int MaxPositions = 3; // Maximum Positions
input double MinTimeBetweenTrades = 60; // Min Minutes Between Trades
//--- Risk Management Parameters
input group "=== RISK MANAGEMENT ==="
input ENUM_POSITION_SIZING SizingMode = PS_RISK_PERCENT; // Position Sizing Mode
input double RiskPercent = 2.5; // Risk Per Trade (%)
input double MaxRiskPercent = 5.0; // Maximum Risk (%)
input double MaxDailyDrawdown = 5.0; // Max Daily Drawdown (%)
input double MaxTotalExposure = 10.0; // Max Total Exposure (%)
input bool UseKellyCriterion = false; // Use Kelly Criterion
input double KellyFraction = 0.25; // Kelly Fraction
input double MinLotSize = 0.01; // Minimum Lot Size
input double MaxLotSize = 10.0; // Maximum Lot Size
//--- Trade Management Parameters
input group "=== TRADE MANAGEMENT ==="
input ENUM_TP_MODE TPMode = TP_ADAPTIVE; // Take Profit Mode
input ENUM_SL_MODE SLMode = SL_ATR; // Stop Loss Mode
input bool EnableBreakeven = true; // Enable Breakeven
input double BreakevenTrigger = 1.0; // Breakeven at X:1
input bool EnableTrailing = true; // Enable Trailing Stop
input double TrailingStart = 1.5; // Start Trailing at X:1
input bool EnablePartialClose = true; // Enable Partial Closes
input string PartialLevels = "1.0:33,2.0:33,3.0:20"; // Partial Close Levels
//--- External Trade Management
input group "=== EXTERNAL TRADE RULES ==="
input bool ForceRiskRules = true; // Force Risk Rules
input bool ForceStopLoss = true; // Force Stop Loss
input bool ForceTakeProfit = true; // Force Take Profit
input bool OverrideExternalSL = false; // Override Existing SL
input bool OverrideExternalTP = false; // Override Existing TP
input double DefaultExternalRisk = 1.0; // Default External Risk (%)
input bool CloseExcessiveRisk = true; // Close Excessive Risk
//--- Technical Analysis Parameters
input group "=== TECHNICAL ANALYSIS ==="
input bool UseSupportResistance = true; // Use S/R Levels
input bool UseFibonacci = true; // Use Fibonacci
input bool UsePivotPoints = true; // Use Pivot Points
input bool UseMarketStructure = true; // Use Market Structure
input bool EnableLogging = true; // Enable Detailed Logging
input int TechnicalLookback = 200; // Technical Lookback Bars
//--- Dashboard Parameters
input group "=== DASHBOARD SETTINGS ==="
input bool ShowDashboard = true; // Show Dashboard
input int DashboardX = 20; // Dashboard X Position
input int DashboardY = 30; // Dashboard Y Position
input color DashboardColor = clrWhiteSmoke; // Dashboard Text Color
input color ProfitColor = clrLime; // Profit Color
input color LossColor = clrRed; // Loss Color
input int UpdateFrequency = 1; // Update Frequency (seconds)
//--- Enhanced Display Settings
input group "=== ENHANCED DISPLAY SETTINGS ==="
input int MaxTradesDisplay = 10; // Maximum Trades to Display
input bool GroupBySource = true; // Group Trades by Source
input bool ShowCorrelation = true; // Show Position Correlation
input color InternalTradeColor = clrAqua; // Internal Trade Color
input color ExternalTradeColor = clrOrange; // External Trade Color
input color WarningColor = clrYellow; // Warning Color
//--- Reporting Options
input group "=== REPORTING OPTIONS ==="
input bool GenerateReports = true; // Generate Periodic Reports
input bool ExportCSV = true; // Export Reports to CSV
input bool DetectEAsOnStartup = true; // Detect All EAs on Startup
input bool AutoDetectSymbols = true; // Auto-Detect Traded Symbols
input bool DebugMode = false; // Enable Debug Mode
//+------------------------------------------------------------------+
//| GLOBAL OBJECTS |
//+------------------------------------------------------------------+
//--- Module instances
CRiskManager *RiskMgr;
CTradeManager *TradeMgr;
CEntrySystem *EntrySys;
CTechnicalAnalysis *TechAnalysis;
CDashboardEnhanced *Dashboard;
CUtilities *Utils;
CMultiTradeReporter *Reporter;
//--- System state
SystemState g_SystemState;
PerformanceMetrics g_Performance;
MarketConditions g_MarketConditions;
//--- Trade tracking
ManagedTrade g_ManagedTrades[];
int g_TotalTrades = 0;
//--- Multi-symbol monitoring
string g_MonitoredSymbols[];
int g_SymbolCount = 0;
//--- Timing variables
datetime g_LastUpdateTime = 0;
datetime g_LastTradeTime = 0;
datetime g_LastReportTime = 0;
datetime g_LastSymbolScan = 0;
datetime g_LastDiagnostic = 0;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- Initialize system state
g_SystemState.is_active = SystemEnabled;
g_SystemState.magic_number = TradingMagic;
g_SystemState.start_balance = AccountInfoDouble(ACCOUNT_BALANCE);
g_SystemState.peak_balance = g_SystemState.start_balance;
g_SystemState.session_start = TimeCurrent();
//--- Create module instances
RiskMgr = new CRiskManager();
TradeMgr = new CTradeManager();
EntrySys = new CEntrySystem();
TechAnalysis = new CTechnicalAnalysis();
Dashboard = new CDashboardEnhanced();
Utils = new CUtilities();
Reporter = new CMultiTradeReporter();
//--- Initialize modules
if(!InitializeModules())
{
Print("Failed to initialize modules");
return(INIT_FAILED);
}
//--- Wait for indicators to be ready
if(MQLInfoInteger(MQL_TESTER))
{
Print("Backtest mode: Waiting for indicators to initialize...");
int required_bars = MathMax(200, TechnicalLookback);
if(Bars(_Symbol, PERIOD_CURRENT) < required_bars)
{
Print("Insufficient bars for indicator calculation. Need ", required_bars,
", have ", Bars(_Symbol, PERIOD_CURRENT));
return(INIT_FAILED);
}
double test_atr = (*TechAnalysis).GetATR(14);
if(test_atr <= 0)
{
Print("ATR indicator not ready. Please ensure sufficient historical data.");
return(INIT_FAILED);
}
Print("Indicators initialized successfully. ATR: ", test_atr);
}
//--- Initialize performance metrics
ZeroMemory(g_Performance);
//--- Initialize managed trades array
ArrayResize(g_ManagedTrades, 0);
ArraySetAsSeries(g_ManagedTrades, false);
//--- Initialize multi-symbol monitoring
if(ManageExternalTrades)
{
InitializeSymbolMonitoring();
//--- Initial detection
if(DetectEAsOnStartup)
{
DetectAllEAs();
}
//--- Initial external trade scan
Print("Performing initial external trade scan...");
CheckForNewExternalTradesEnhanced();
//--- Run diagnostic if in debug mode
if(DebugMode)
{
RunExternalTradeDiagnostics();
}
}
//--- Load existing positions
LoadExistingPositions();
//--- Create dashboard
if(ShowDashboard)
{
(*Dashboard).Create(DashboardX, DashboardY, DashboardColor, ProfitColor, LossColor);
(*Dashboard).Update(g_Performance, g_ManagedTrades, g_MarketConditions);
}
//--- Initialize reporter
if(Reporter != NULL && GenerateReports)
{
(*Reporter).Initialize("Reports");
}
//--- Set timer for periodic updates
EventSetTimer(UpdateFrequency);
//--- Log initialization
(*Utils).Log(LOG_INFO, StringFormat("Risk Management Overlay v7.1 initialized. Balance: %.2f",
g_SystemState.start_balance));
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- Kill timer
EventKillTimer();
//--- Save final report
if(Utils != NULL && GenerateReports)
(*Utils).GenerateReport(g_Performance, g_ManagedTrades);
//--- Cleanup modules
if(Dashboard != NULL && ShowDashboard)
(*Dashboard).Destroy();
//--- Delete module instances
delete Reporter;
delete RiskMgr;
delete TradeMgr;
delete EntrySys;
delete TechAnalysis;
delete Dashboard;
delete Utils;
//--- Log shutdown
Print("Risk Management Overlay shutdown: ", (*Utils).GetUninitReasonText(reason));
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- Check if system is enabled
if(!g_SystemState.is_active || !SystemEnabled)
return;
//--- Check terminal connection
if(!TerminalInfoInteger(TERMINAL_CONNECTED))
return;
//--- Check terminal connection and auto trading
if(Utils != NULL)
{
if(!(*Utils).CheckTerminalConnection())
return;
if(!(*Utils).CheckAutoTrading())
return;
}
//--- Update market conditions
UpdateMarketConditions();
//--- Process existing trades
ProcessManagedTrades();
//--- Check for new external trades (enhanced multi-symbol)
if(ManageExternalTrades)
{
CheckForNewExternalTradesEnhanced();
}
//--- Check entry signals (if enabled)
if(EntryMode != ENTRY_DISABLED)
CheckEntrySignals();
//--- Update dashboard
if(ShowDashboard && TimeCurrent() - g_LastUpdateTime >= UpdateFrequency)
{
(*Dashboard).Update(g_Performance, g_ManagedTrades, g_MarketConditions);
g_LastUpdateTime = TimeCurrent();
}
//--- Periodic tasks
PerformPeriodicTasks();
//--- Debug output if enabled
if(DebugMode)
{
static datetime last_debug = 0;
if(TimeCurrent() - last_debug > 2)
{
string debug = StringFormat("DEBUG: Pos=%d Array=%d Ext=%d",
PositionsTotal(),
ArraySize(g_ManagedTrades),
CountExternalTrades());
Comment(debug);
last_debug = TimeCurrent();
}
}
}
//+------------------------------------------------------------------+
//| Timer function for periodic updates |
//+------------------------------------------------------------------+
void OnTimer()
{
//--- Update dashboard
if(ShowDashboard)
{
(*Dashboard).Update(g_Performance, g_ManagedTrades, g_MarketConditions);
}
//--- Monitor positions
if(DebugMode)
{
MonitorPositions();
}
//--- Periodic EA detection
static datetime last_ea_detect = 0;
if(ManageExternalTrades && TimeCurrent() - last_ea_detect > 300) // Every 5 minutes
{
if(AutoDetectSymbols)
{
DetectTradedSymbols();
}
last_ea_detect = TimeCurrent();
}
}
//+------------------------------------------------------------------+
//| Initialize symbol monitoring list |
//+------------------------------------------------------------------+
void InitializeSymbolMonitoring()
{
if(AutoDetectSymbols)
{
// Auto-detect all symbols with open positions
DetectTradedSymbols();
}
else
{
// Manual symbol list - customize as needed
g_SymbolCount = 10;
ArrayResize(g_MonitoredSymbols, g_SymbolCount);
g_MonitoredSymbols[0] = "EURUSD";
g_MonitoredSymbols[1] = "GBPUSD";
g_MonitoredSymbols[2] = "USDJPY";
g_MonitoredSymbols[3] = "AUDUSD";
g_MonitoredSymbols[4] = "USDCAD";
g_MonitoredSymbols[5] = "NZDUSD";
g_MonitoredSymbols[6] = "USDCHF";
g_MonitoredSymbols[7] = "EURJPY";
g_MonitoredSymbols[8] = "GBPJPY";
g_MonitoredSymbols[9] = "GOLD";
}
Print("Symbol Monitoring initialized with ", g_SymbolCount, " symbols");
}
//+------------------------------------------------------------------+
//| Auto-detect all symbols with positions |
//+------------------------------------------------------------------+
void DetectTradedSymbols()
{
// Clear existing array
ArrayFree(g_MonitoredSymbols);
g_SymbolCount = 0;
// Temporary array to collect unique symbols
string temp_symbols[];
int temp_count = 0;
// Scan all positions
int total_positions = PositionsTotal();
for(int i = 0; i < total_positions; i++)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
string symbol = PositionGetString(POSITION_SYMBOL);
// Check if symbol already in list
bool found = false;
for(int j = 0; j < temp_count; j++)
{
if(temp_symbols[j] == symbol)
{
found = true;
break;
}
}
// Add new symbol
if(!found)
{
ArrayResize(temp_symbols, temp_count + 1);
temp_symbols[temp_count] = symbol;
temp_count++;
}
}
}
// Also add current chart symbol if not already included
bool current_found = false;
for(int i = 0; i < temp_count; i++)
{
if(temp_symbols[i] == _Symbol)
{
current_found = true;
break;
}
}
if(!current_found)
{
ArrayResize(temp_symbols, temp_count + 1);
temp_symbols[temp_count] = _Symbol;
temp_count++;
}
// Copy to global array
g_SymbolCount = temp_count;
ArrayResize(g_MonitoredSymbols, g_SymbolCount);
for(int i = 0; i < g_SymbolCount; i++)
{
g_MonitoredSymbols[i] = temp_symbols[i];
}
// Log detected symbols
if(g_SymbolCount > 0)
{
string symbol_list = "Detected symbols: ";
for(int i = 0; i < g_SymbolCount; i++)
{
symbol_list += g_MonitoredSymbols[i];
if(i < g_SymbolCount - 1) symbol_list += ", ";
}
(*Utils).Log(LOG_INFO, symbol_list);
}
}
//+------------------------------------------------------------------+
//| Enhanced multi-symbol external trade detection |
//+------------------------------------------------------------------+
void CheckForNewExternalTradesEnhanced()
{
static datetime last_symbol_update = 0;
// Update symbol list periodically (every 60 seconds)
if(AutoDetectSymbols && TimeCurrent() - last_symbol_update > 60)
{
DetectTradedSymbols();
last_symbol_update = TimeCurrent();
}
// Scan all positions
int total_positions = PositionsTotal();
int external_trades_found = 0;
int trades_added = 0;
for(int i = 0; i < total_positions; i++)
{
ulong ticket = PositionGetTicket(i);
if(!ticket) continue;
if(PositionSelectByTicket(ticket))
{
// Get position details
string symbol = PositionGetString(POSITION_SYMBOL);
ulong magic = PositionGetInteger(POSITION_MAGIC);
// Skip our own trades
if(magic == TradingMagic)
{
continue;
}
// Check if already managed
if(IsTradeManaged(ticket))
{
continue;
}
// Apply magic number filter
if(MagicNumberFilter != 0 && magic != MagicNumberFilter)
{
continue;
}
external_trades_found++;
// Create managed trade entry
ManagedTrade trade;
if(CreateManagedTradeEnhanced(trade, ticket, symbol))
{
// Mark as external trade
trade.is_external = true;
trade.entry_reason = "External: " + GetEANameFromMagic(magic);
// Apply risk rules if configured
if(ForceRiskRules)
{
(*Utils).Log(LOG_INFO, StringFormat("Applying risk rules to external trade #%d on %s",
ticket, symbol));
(*RiskMgr).EnforceRiskRules(trade, DefaultExternalRisk, CloseExcessiveRisk);
}
// Add to managed trades array
if(AddManagedTrade(trade))
{
trades_added++;
(*Utils).Log(LOG_INFO, StringFormat("Added external trade #%d (%s %.2f lots) from %s to management",
ticket, symbol, trade.volume, GetEANameFromMagic(magic)));
// Apply default stops if needed
if((trade.sl == 0 && ForceStopLoss) || (trade.tp == 0 && ForceTakeProfit))
{
(*Utils).Log(LOG_INFO, "Applying default stops to external trade");
// Get ATR for the specific symbol
double symbol_atr = GetSymbolATR(symbol);
(*TradeMgr).ApplyDefaultStops(trade, symbol_atr);
}
}
}
}
}
if(external_trades_found > 0 || trades_added > 0)
{
(*Utils).Log(LOG_DEBUG, StringFormat("External trade scan complete: Found %d, Added %d new trades",
external_trades_found, trades_added));
}
}
//+------------------------------------------------------------------+
//| Create managed trade with multi-symbol support |
//+------------------------------------------------------------------+
bool CreateManagedTradeEnhanced(ManagedTrade &trade, ulong ticket, string symbol)
{
// Ensure we're working with the correct position
if(!PositionSelectByTicket(ticket))
{
(*Utils).Log(LOG_ERROR, StringFormat("Failed to select position #%d", ticket));
return false;
}
// Verify symbol matches
if(PositionGetString(POSITION_SYMBOL) != symbol)
{
(*Utils).Log(LOG_ERROR, StringFormat("Symbol mismatch for position #%d", ticket));
return false;
}
// Fill trade structure
trade.ticket = ticket;
trade.symbol = symbol;
trade.magic = PositionGetInteger(POSITION_MAGIC);
trade.type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
trade.volume = PositionGetDouble(POSITION_VOLUME);
trade.current_volume = trade.volume;
trade.open_price = PositionGetDouble(POSITION_PRICE_OPEN);
trade.open_time = (datetime)PositionGetInteger(POSITION_TIME);
trade.sl = PositionGetDouble(POSITION_SL);
trade.tp = PositionGetDouble(POSITION_TP);
trade.profit = PositionGetDouble(POSITION_PROFIT);
trade.swap = PositionGetDouble(POSITION_SWAP);
trade.comment = PositionGetString(POSITION_COMMENT);
// Get commission from deals
trade.commission = (*Utils).CalculatePositionCommission(ticket);
// Calculate risk metrics for the specific symbol
if(trade.sl > 0)
{
double tick_value = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_VALUE);
double tick_size = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE);
double stop_distance;
if(trade.type == POSITION_TYPE_BUY)
stop_distance = trade.open_price - trade.sl;
else
stop_distance = trade.sl - trade.open_price;
if(stop_distance > 0 && tick_size > 0)
{
double potential_loss = (stop_distance / tick_size) * tick_value * trade.volume;
trade.risk_amount = potential_loss;
trade.risk_percent = (potential_loss / AccountInfoDouble(ACCOUNT_BALANCE)) * 100;
}
}
else
{
// No stop loss - use default risk calculation
trade.risk_amount = 0;
trade.risk_percent = DefaultExternalRisk;
}
// Calculate current metrics
double current_price = (trade.type == POSITION_TYPE_BUY) ?
SymbolInfoDouble(symbol, SYMBOL_BID) :
SymbolInfoDouble(symbol, SYMBOL_ASK);
// Calculate R-multiple
if(trade.risk_amount > 0)
{
double current_pl = trade.profit + trade.swap + trade.commission;
trade.r_multiple = current_pl / trade.risk_amount;
}
else
{
trade.r_multiple = 0;
}
// Calculate MAE/MFE (simplified for initial creation)
trade.mae = 0;
trade.mfe = 0;
// Management flags
trade.is_managed = true;
trade.is_external = true;
trade.be_activated = false;
trade.trailing_activated = false;
trade.partial_count = 0;
// Time tracking
trade.bars_in_trade = 0;
trade.management_start = TimeCurrent();
return true;
}
//+------------------------------------------------------------------+
//| Get ATR for specific symbol |
//+------------------------------------------------------------------+
double GetSymbolATR(string symbol, int period = 14)
{
int atr_handle = iATR(symbol, PERIOD_CURRENT, period);
if(atr_handle == INVALID_HANDLE)
{
(*Utils).Log(LOG_ERROR, "Failed to create ATR handle for " + symbol);
return 50 * SymbolInfoDouble(symbol, SYMBOL_POINT); // Default fallback
}
double atr_buffer[1];
if(CopyBuffer(atr_handle, 0, 0, 1, atr_buffer) > 0 && atr_buffer[0] > 0)
{
IndicatorRelease(atr_handle);
return atr_buffer[0];
}
IndicatorRelease(atr_handle);
// Fallback calculation
double sum = 0;
for(int i = 1; i <= period; i++)
{
double high = iHigh(symbol, PERIOD_CURRENT, i);
double low = iLow(symbol, PERIOD_CURRENT, i);
double close_prev = iClose(symbol, PERIOD_CURRENT, i + 1);
if(high > 0 && low > 0 && close_prev > 0)
{
double tr = MathMax(high - low, MathMax(MathAbs(high - close_prev), MathAbs(low - close_prev)));
sum += tr;
}
}
return (sum > 0) ? sum / period : 50 * SymbolInfoDouble(symbol, SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Count external trades in array |
//+------------------------------------------------------------------+
int CountExternalTrades()
{
int count = 0;
for(int i = 0; i < ArraySize(g_ManagedTrades); i++)
{
if(g_ManagedTrades[i].is_external)
count++;
}
return count;
}
//+------------------------------------------------------------------+
//| Monitor positions (debug function) |
//+------------------------------------------------------------------+
void MonitorPositions()
{
static datetime last_check = 0;
static int last_total = -1;
// Check every 5 seconds
if(TimeCurrent() - last_check < 5) return;
last_check = TimeCurrent();
int total = PositionsTotal();
// Only print if changed
if(total != last_total)
{
last_total = total;
string summary = StringFormat("\n[POSITION MONITOR] Total: %d | Managed Array: %d | ",
total, ArraySize(g_ManagedTrades));
// Count by type
int own = 0, ext = 0, managed_ext = 0;
for(int i = 0; i < total; i++)
{
if(PositionSelectByTicket(PositionGetTicket(i)))
{
ulong magic = PositionGetInteger(POSITION_MAGIC);
if(magic == TradingMagic)
own++;
else
{
ext++;
if(IsTradeManaged(PositionGetTicket(i)))
managed_ext++;
}
}
}
summary += StringFormat("Own: %d | External: %d (Managed: %d)",
own, ext, managed_ext);
Print(summary);
// If external trades exist but aren't managed, run diagnostic
if(ext > 0 && managed_ext == 0 && ManageExternalTrades)
{
Print("⚠️ External trades not being managed! Running diagnostic...");
RunExternalTradeDiagnostics();
}
}
}
//+------------------------------------------------------------------+
//| Run external trade diagnostics |
//+------------------------------------------------------------------+
void RunExternalTradeDiagnostics()
{
Print("\n========== EXTERNAL TRADE DETECTION DIAGNOSTICS ==========");
Print("Timestamp: ", TimeToString(TimeCurrent()));
Print("Running from: ", _Symbol, " ", EnumToString((ENUM_TIMEFRAMES)_Period));
//--- 1. Check EA Settings
Print("\n[1] EA CONFIGURATION CHECK:");
Print(" SystemEnabled: ", SystemEnabled ? "YES" : "NO");
Print(" ManageExternalTrades: ", ManageExternalTrades ? "ENABLED" : "DISABLED");
Print(" MagicNumberFilter: ", MagicNumberFilter, (MagicNumberFilter == 0) ? " (All external trades)" : " (Specific magic only)");
Print(" TradingMagic (Own): ", TradingMagic);
Print(" ForceRiskRules: ", ForceRiskRules ? "YES" : "NO");
Print(" DefaultExternalRisk: ", DoubleToString(DefaultExternalRisk, 2), "%");
Print(" AutoDetectSymbols: ", AutoDetectSymbols ? "YES" : "NO");
//--- 2. Scan all open positions
Print("\n[2] POSITION SCAN:");
int total_positions = PositionsTotal();
Print(" Total positions in terminal: ", total_positions);
if(total_positions == 0)
{
Print(" ⚠️ NO OPEN POSITIONS FOUND!");
Print(" Make sure other EAs have open trades.");
return;
}
//--- Categorize positions
int own_trades = 0;
int external_trades = 0;
int filtered_trades = 0;
int managed_trades = 0;
Print("\n[3] POSITION DETAILS:");
for(int i = 0; i < total_positions; i++)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0)
{
Print(" Error getting ticket at index ", i);
continue;
}
if(!PositionSelectByTicket(ticket))
{
Print(" Error selecting position ", ticket);
continue;
}
string symbol = PositionGetString(POSITION_SYMBOL);
ulong magic = PositionGetInteger(POSITION_MAGIC);
double volume = PositionGetDouble(POSITION_VOLUME);
string type = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? "BUY" : "SELL";
bool is_managed = IsTradeManaged(ticket);
Print("\n Position #", ticket, ":");
Print(" - Symbol: ", symbol);
Print(" - Type: ", type);
Print(" - Volume: ", DoubleToString(volume, 2));
Print(" - Magic: ", magic, " (", GetEANameFromMagic(magic), ")");
// Determine status
if(magic == TradingMagic)
{
own_trades++;
Print(" - Status: OWN TRADE (will skip)");
}
else if(MagicNumberFilter != 0 && magic != MagicNumberFilter)
{
filtered_trades++;
Print(" - Status: FILTERED OUT (magic doesn't match filter ", MagicNumberFilter, ")");
}
else if(is_managed)
{
managed_trades++;
Print(" - Status: ALREADY MANAGED ✓");
}
else
{
external_trades++;
Print(" - Status: EXTERNAL TRADE - SHOULD BE ADDED! ⚠️");
if(!ManageExternalTrades)
{
Print(" → ISSUE: ManageExternalTrades is DISABLED!");
}
}
}
//--- 4. Summary
Print("\n[4] SUMMARY:");
Print(" Own trades: ", own_trades);
Print(" External trades (eligible): ", external_trades);
Print(" Filtered out: ", filtered_trades);
Print(" Already managed: ", managed_trades);
//--- 5. Check managed trades array
Print("\n[5] MANAGED TRADES ARRAY:");
int array_size = ArraySize(g_ManagedTrades);
Print(" Size of g_ManagedTrades: ", array_size);
if(array_size > 0)
{
int internal_count = 0;
int external_count = 0;
for(int i = 0; i < array_size; i++)
{
if(g_ManagedTrades[i].is_external)
external_count++;
else
internal_count++;
Print(" Trade[", i, "]: #", g_ManagedTrades[i].ticket,
" ", g_ManagedTrades[i].symbol,
" Magic: ", g_ManagedTrades[i].magic,
" External: ", g_ManagedTrades[i].is_external ? "YES" : "NO",
" Valid: ", (g_ManagedTrades[i].ticket > 0) ? "YES" : "NO");
}
Print(" Internal trades in array: ", internal_count);
Print(" External trades in array: ", external_count);
}
else
{
Print(" ⚠️ Managed trades array is EMPTY!");
}
//--- 6. Symbol monitoring
Print("\n[6] SYMBOL MONITORING:");
Print(" Monitored symbols: ", g_SymbolCount);
for(int i = 0; i < g_SymbolCount; i++)
{
Print(" - ", g_MonitoredSymbols[i]);
}
//--- 7. Dashboard check
Print("\n[7] DASHBOARD STATUS:");
Print(" ShowDashboard: ", ShowDashboard ? "ENABLED" : "DISABLED");
Print(" Dashboard pointer: ", (Dashboard != NULL) ? "VALID" : "NULL");
//--- 8. Recommendations
Print("\n[8] DIAGNOSTIC RECOMMENDATIONS:");
if(!SystemEnabled)
{
Print(" ❌ CRITICAL: SystemEnabled is FALSE - EA is disabled!");
}
if(!ManageExternalTrades)
{
Print(" ❌ CRITICAL: Enable ManageExternalTrades to detect external trades!");
}
if(external_trades > 0 && external_count == 0)
{
Print(" ❌ ISSUE: External trades exist but none in managed array!");
Print(" → Verify CheckForNewExternalTradesEnhanced() is being called in OnTick()");
Print(" → Check if AddManagedTrade() function is working correctly");
Print(" → Ensure CreateManagedTradeEnhanced() is creating valid trade objects");
}
if(MagicNumberFilter != 0 && filtered_trades > 0)
{
Print(" ⚠️ WARNING: ", filtered_trades, " trades filtered out by MagicNumberFilter");
Print(" → Set MagicNumberFilter = 0 to manage ALL external trades");
}
if(array_size == 0 && (own_trades > 0 || external_trades > 0))
{
Print(" ❌ CRITICAL: Managed trades array is empty but trades exist!");
Print(" → Check array initialization in OnInit()");
Print(" → Verify ProcessManagedTrades() isn't clearing the array");
}
Print("\n========== END OF DIAGNOSTICS ==========\n");
}
//+------------------------------------------------------------------+
//| Add managed trade to array with validation |
//+------------------------------------------------------------------+
bool AddManagedTrade(ManagedTrade &trade)
{
// Validate trade
if(trade.ticket == 0)
{
(*Utils).Log(LOG_ERROR, "Cannot add trade with ticket 0");
return false;
}
// Check if already exists
if(IsTradeManaged(trade.ticket))
{
(*Utils).Log(LOG_WARNING, StringFormat("Trade #%d already managed", trade.ticket));
return false;
}
// Add to array
int size = ArraySize(g_ManagedTrades);
if(ArrayResize(g_ManagedTrades, size + 1) < 0)
{
(*Utils).Log(LOG_ERROR, "Failed to resize managed trades array");
return false;
}
g_ManagedTrades[size] = trade;
g_TotalTrades++;
(*Utils).Log(LOG_DEBUG, StringFormat("Added trade #%d to position %d in array",
trade.ticket, size));
return true;
}
//+------------------------------------------------------------------+
//| Create managed trade structure (for compatibility) |
//+------------------------------------------------------------------+
bool CreateManagedTrade(ManagedTrade &trade, ulong ticket)
{
if(!PositionSelectByTicket(ticket))
return false;
string symbol = PositionGetString(POSITION_SYMBOL);
return CreateManagedTradeEnhanced(trade, ticket, symbol);
}
//+------------------------------------------------------------------+
//| Initialize all modules |
//+------------------------------------------------------------------+
bool InitializeModules()
{
//--- Initialize Risk Manager
RiskManagerConfig riskConfig;
riskConfig.sizing_mode = SizingMode;
riskConfig.risk_percent = RiskPercent;
riskConfig.max_risk_percent = MaxRiskPercent;
riskConfig.max_daily_dd = MaxDailyDrawdown;
riskConfig.max_exposure = MaxTotalExposure;
riskConfig.use_kelly = UseKellyCriterion;
riskConfig.kelly_fraction = KellyFraction;
riskConfig.min_lot_size = MinLotSize;
riskConfig.max_lot_size = MaxLotSize;
if(!(*RiskMgr).Initialize(riskConfig))
return false;
//--- Initialize Trade Manager
TradeManagerConfig tradeConfig;
tradeConfig.tp_mode = TPMode;
tradeConfig.sl_mode = SLMode;
tradeConfig.enable_breakeven = EnableBreakeven;
tradeConfig.breakeven_trigger = BreakevenTrigger;
tradeConfig.enable_trailing = EnableTrailing;
tradeConfig.trailing_start = TrailingStart;
tradeConfig.enable_partial = EnablePartialClose;
tradeConfig.partial_levels = PartialLevels;
tradeConfig.force_sl = ForceStopLoss;
tradeConfig.force_tp = ForceTakeProfit;
tradeConfig.override_sl = OverrideExternalSL;
tradeConfig.override_tp = OverrideExternalTP;
if(!(*TradeMgr).Initialize(tradeConfig, TradingMagic))
return false;
//--- Initialize Entry System
EntrySystemConfig entryConfig;
entryConfig.entry_mode = EntryMode;
entryConfig.max_positions = MaxPositions;
entryConfig.min_time_between = MinTimeBetweenTrades;
entryConfig.allow_multiple = EnableMultipleEntries;
if(!(*EntrySys).Initialize(entryConfig))
return false;
//--- Initialize Technical Analysis
TechnicalConfig techConfig;
techConfig.use_sr = UseSupportResistance;
techConfig.use_fib = UseFibonacci;
techConfig.use_pivot = UsePivotPoints;
techConfig.use_structure = UseMarketStructure;
techConfig.lookback = TechnicalLookback;
if(!(*TechAnalysis).Initialize(techConfig))
return false;
//--- Initialize Utilities
if(!(*Utils).Initialize(LogLevel))
return false;
return true;
}
//+------------------------------------------------------------------+
//| Load existing positions into management system |
//+------------------------------------------------------------------+
void LoadExistingPositions()
{
int total = PositionsTotal();
int loaded = 0;
for(int i = 0; i < total; i++)
{
ulong ticket = PositionGetTicket(i);
if(!PositionSelectByTicket(ticket))
continue;
string symbol = PositionGetString(POSITION_SYMBOL);
ulong magic = PositionGetInteger(POSITION_MAGIC);
bool should_manage = false;
//--- Check if we should manage this position
if(magic == TradingMagic)
{
should_manage = true;
}
else if(ManageExternalTrades && (MagicNumberFilter == 0 || magic == MagicNumberFilter))
{
should_manage = true;
}
if(should_manage && !IsTradeManaged(ticket))
{
ManagedTrade trade;
if(CreateManagedTradeEnhanced(trade, ticket, symbol))
{
if(magic != TradingMagic)
trade.is_external = true;
if(AddManagedTrade(trade))
{
loaded++;
(*Utils).Log(LOG_INFO, StringFormat("Loaded position #%d (%s) into management",
ticket, symbol));
}
}
}
}
if(loaded > 0)
{
(*Utils).Log(LOG_INFO, StringFormat("Loaded %d existing positions", loaded));
}
}
//+------------------------------------------------------------------+
//| Update market conditions |
//+------------------------------------------------------------------+
void UpdateMarketConditions()
{
// Get fresh market analysis
g_MarketConditions = (*TechAnalysis).AnalyzeMarket();
// Additional validation and fallback
if(g_MarketConditions.volatility <= 0)
{
Print("UpdateMarketConditions: Invalid volatility from TechAnalysis, calculating fallback");
// Direct ATR calculation
double atr = (*TechAnalysis).GetATR(14);
if(atr > 0)
{
g_MarketConditions.volatility = atr;
Print("UpdateMarketConditions: Set volatility to ", atr);
}
else
{
// Emergency fallback
double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
g_MarketConditions.volatility = price * 0.001; // 0.1% of price
Print("UpdateMarketConditions: Using emergency volatility: ", g_MarketConditions.volatility);
}
}
g_MarketConditions.spread = (double)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
//--- Update risk manager with market conditions
(*RiskMgr).UpdateMarketConditions(g_MarketConditions);
}
//+------------------------------------------------------------------+
//| Process all managed trades |
//+------------------------------------------------------------------+
void ProcessManagedTrades()
{
for(int i = ArraySize(g_ManagedTrades) - 1; i >= 0; i--)
{
//--- Check if position still exists
if(!PositionSelectByTicket(g_ManagedTrades[i].ticket))
{
//--- Position closed, update performance
UpdatePerformanceMetrics(g_ManagedTrades[i]);
//--- Save to history if external
if(g_ManagedTrades[i].is_external)
{
(*Utils).SaveTradeHistory(g_ManagedTrades[i]);
}
RemoveManagedTrade(i);
continue;
}
//--- Update trade information
UpdateTradeInfo(g_ManagedTrades[i]);
//--- Apply risk management
(*RiskMgr).ValidateAndAdjustRisk(g_ManagedTrades[i]);
//--- Apply trade management
(*TradeMgr).ManageTrade(g_ManagedTrades[i], g_MarketConditions);
}
}
//+------------------------------------------------------------------+
//| Check entry signals |
//+------------------------------------------------------------------+
void CheckEntrySignals()
{
//--- Check position limits
if(ArraySize(g_ManagedTrades) >= MaxPositions)
{
if(EnableLogging)
(*Utils).Log(LOG_DEBUG, "Max positions reached");
return;
}
//--- Check time restriction
if(TimeCurrent() - g_LastTradeTime < MinTimeBetweenTrades * 60)
{
if(EnableLogging)
(*Utils).Log(LOG_DEBUG, "Time restriction active");
return;
}
//--- Ensure valid market conditions
if(g_MarketConditions.volatility <= 0)
{
UpdateMarketConditions();
}
//--- Get entry signal
EntrySignal signal = (*EntrySys).CheckSignal(g_MarketConditions);
if(signal.signal_type != SIGNAL_NONE)
{
// Additional safety check
if(signal.stop_loss_distance <= 0)
{
(*Utils).Log(LOG_ERROR, StringFormat("Zero stop distance detected! Signal: %s",
signal.comment));
// Emergency fallback
double emergency_stop = 50 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
signal.stop_loss_distance = emergency_stop;
signal.take_profit_distance = emergency_stop * 2;
(*Utils).Log(LOG_WARNING, StringFormat("Applied emergency stop: %.5f", emergency_stop));
}
//--- Calculate position size
double lotSize = (*RiskMgr).CalculatePositionSize(signal.stop_loss_distance);
if(lotSize > 0 && (*RiskMgr).ValidateNewPosition(lotSize, signal.stop_loss_distance))
{
//--- Prepare trade request
TradeRequest request;
request.symbol = _Symbol;
request.volume = lotSize;
request.type = (signal.signal_type == SIGNAL_BUY) ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;
request.sl_distance = signal.stop_loss_distance;
request.tp_distance = signal.take_profit_distance;
request.comment = signal.comment;
//--- Execute trade
ulong ticket = (*TradeMgr).OpenPosition(request);
if(ticket > 0)
{
g_LastTradeTime = TimeCurrent();
//--- Add to managed trades
ManagedTrade trade;
if(CreateManagedTrade(trade, ticket))
{
trade.entry_reason = signal.comment;
trade.entry_signal = signal;
trade.is_external = false;
if(AddManagedTrade(trade))
{
(*Utils).Log(LOG_INFO, StringFormat("Opened %s position #%d, Lots: %.2f, Risk: %.2f%%",
(signal.signal_type == SIGNAL_BUY) ? "BUY" : "SELL",
ticket, lotSize, RiskPercent));
}
}
}
}
}
}
//+------------------------------------------------------------------+
//| Perform periodic maintenance tasks |
//+------------------------------------------------------------------+
void PerformPeriodicTasks()
{
//--- Daily reset check
MqlDateTime current_time;
TimeToStruct(TimeCurrent(), current_time);
static int last_day = -1;
if(current_time.day != last_day)
{
last_day = current_time.day;
ResetDailyMetrics();
}
//--- Generate periodic reports
if(GenerateReports && TimeCurrent() - g_LastReportTime > 3600) // Hourly
{
(*Utils).GenerateReport(g_Performance, g_ManagedTrades);
if(Reporter != NULL)
{
(*Reporter).GenerateFullReport(g_ManagedTrades, g_Performance);
}
g_LastReportTime = TimeCurrent();
}
//--- Check for news events
if((*Utils).IsNewsTime())
{
g_MarketConditions.news_event = true;
}
}
//+------------------------------------------------------------------+
//| Remove trade from managed array |
//+------------------------------------------------------------------+
void RemoveManagedTrade(int index)
{
int size = ArraySize(g_ManagedTrades);
if(index < 0 || index >= size)
return;
for(int i = index; i < size - 1; i++)
{
g_ManagedTrades[i] = g_ManagedTrades[i + 1];
}
ArrayResize(g_ManagedTrades, size - 1);
}
//+------------------------------------------------------------------+
//| Check if trade is already managed |
//+------------------------------------------------------------------+
bool IsTradeManaged(ulong ticket)
{
for(int i = 0; i < ArraySize(g_ManagedTrades); i++)
{
if(g_ManagedTrades[i].ticket == ticket)
return true;
}
return false;
}
//+------------------------------------------------------------------+
//| Update trade information |
//+------------------------------------------------------------------+
void UpdateTradeInfo(ManagedTrade &trade)
{
if(!PositionSelectByTicket(trade.ticket))
return;
trade.current_volume = PositionGetDouble(POSITION_VOLUME);
trade.sl = PositionGetDouble(POSITION_SL);
trade.tp = PositionGetDouble(POSITION_TP);
trade.profit = PositionGetDouble(POSITION_PROFIT);
trade.commission = (*Utils).CalculatePositionCommission(trade.ticket);
trade.swap = PositionGetDouble(POSITION_SWAP);
//--- Update max profit/drawdown
double total_profit = trade.profit + trade.commission + trade.swap;
if(total_profit > trade.max_profit)
trade.max_profit = total_profit;
if(total_profit < trade.max_drawdown)
trade.max_drawdown = total_profit;
//--- Update R-multiple
if(trade.risk_amount > 0)
{
trade.r_multiple = total_profit / trade.risk_amount;
}
}
//+------------------------------------------------------------------+
//| Update performance metrics |
//+------------------------------------------------------------------+
void UpdatePerformanceMetrics(ManagedTrade &trade)
{
double final_profit = trade.profit + trade.commission + trade.swap;
//--- Update counts
g_Performance.total_trades++;
if(final_profit > 0)
{
g_Performance.winning_trades++;
g_Performance.gross_profit += final_profit;
g_Performance.consecutive_wins++;
g_Performance.consecutive_losses = 0;
}
else
{
g_Performance.losing_trades++;
g_Performance.gross_loss += MathAbs(final_profit);
g_Performance.consecutive_losses++;
g_Performance.consecutive_wins = 0;
}
//--- Update max consecutive
if(g_Performance.consecutive_wins > g_Performance.max_consecutive_wins)
g_Performance.max_consecutive_wins = g_Performance.consecutive_wins;
if(g_Performance.consecutive_losses > g_Performance.max_consecutive_losses)
g_Performance.max_consecutive_losses = g_Performance.consecutive_losses;
//--- Update profit factor and win rate
if(g_Performance.gross_loss > 0)
g_Performance.profit_factor = g_Performance.gross_profit / g_Performance.gross_loss;
else
g_Performance.profit_factor = (g_Performance.gross_profit > 0) ? 999.99 : 0;
g_Performance.win_rate = (g_Performance.total_trades > 0) ?
(double)g_Performance.winning_trades / g_Performance.total_trades * 100 : 0;
//--- Update drawdown
double current_balance = AccountInfoDouble(ACCOUNT_BALANCE);
if(current_balance > g_SystemState.peak_balance)
g_SystemState.peak_balance = current_balance;
double drawdown = (g_SystemState.peak_balance - current_balance) / g_SystemState.peak_balance * 100;
if(drawdown > g_Performance.max_drawdown_percent)
g_Performance.max_drawdown_percent = drawdown;
//--- Update net profit
g_Performance.net_profit = g_Performance.gross_profit - g_Performance.gross_loss;
//--- Update expectancy
if(g_Performance.total_trades > 0)
g_Performance.expectancy = g_Performance.net_profit / g_Performance.total_trades;
//--- Update average win/loss
if(g_Performance.winning_trades > 0)
g_Performance.avg_win = g_Performance.gross_profit / g_Performance.winning_trades;
if(g_Performance.losing_trades > 0)
g_Performance.avg_loss = g_Performance.gross_loss / g_Performance.losing_trades;
//--- Update daily metrics
g_Performance.daily_trades++;
g_Performance.daily_profit += final_profit;
}
//+------------------------------------------------------------------+
//| Reset daily metrics |
//+------------------------------------------------------------------+
void ResetDailyMetrics()
{
g_Performance.daily_profit = 0;
g_Performance.daily_trades = 0;
g_Performance.daily_volume = 0;
(*Utils).Log(LOG_INFO, "Daily metrics reset");
}
//+------------------------------------------------------------------+
//| Trade transaction event |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction& trans,
const MqlTradeRequest& request,
const MqlTradeResult& result)
{
//--- Handle trade events
if(trans.type == TRADE_TRANSACTION_DEAL_ADD)
{
if(trans.deal_type == DEAL_TYPE_BUY || trans.deal_type == DEAL_TYPE_SELL)
{
(*Utils).Log(LOG_DEBUG, StringFormat("New deal: #%d, Volume: %.2f",
trans.deal, trans.volume));
}
}
}
//+------------------------------------------------------------------+
//| Chart event handler |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- Handle keyboard shortcuts for debugging
if(id == CHARTEVENT_KEYDOWN)
{
if(lparam == 'D' || lparam == 'd') // D key
{
RunExternalTradeDiagnostics();
}
else if(lparam == 'R' || lparam == 'r') // R key
{
Print("Forcing external trade refresh...");
CheckForNewExternalTradesEnhanced();
}
else if(lparam == 'T' || lparam == 't') // T key
{
(*Utils).GenerateReport(g_Performance, g_ManagedTrades);
}
}
}
//+------------------------------------------------------------------+
//| EA Detection and Monitoring Functions |
//+------------------------------------------------------------------+
struct EAInfo
{
string symbol;
long magic_number;
string ea_name;
int trade_count;
double total_volume;
double total_risk;
double total_profit;
};
//+------------------------------------------------------------------+
//| Detect all EAs running on the account |
//+------------------------------------------------------------------+
void DetectAllEAs()
{
Print("=== DETECTING ALL EXPERT ADVISORS ===");
EAInfo detected_eas[];
int ea_count = 0;
// Scan all open positions
int total_positions = PositionsTotal();
for(int i = 0; i < total_positions; i++)
{
if(PositionSelectByTicket(PositionGetTicket(i)))
{
string symbol = PositionGetString(POSITION_SYMBOL);
long magic = PositionGetInteger(POSITION_MAGIC);
double volume = PositionGetDouble(POSITION_VOLUME);
double profit = PositionGetDouble(POSITION_PROFIT);
// Check if this magic number already recorded
bool found = false;
int index = -1;
for(int j = 0; j < ea_count; j++)
{
if(detected_eas[j].magic_number == magic &&
detected_eas[j].symbol == symbol)
{
found = true;
index = j;
break;
}
}
// Add new EA or update existing
if(!found)
{
ArrayResize(detected_eas, ea_count + 1);
detected_eas[ea_count].symbol = symbol;
detected_eas[ea_count].magic_number = magic;
detected_eas[ea_count].ea_name = GetEANameFromMagic(magic);
detected_eas[ea_count].trade_count = 1;
detected_eas[ea_count].total_volume = volume;
detected_eas[ea_count].total_profit = profit;
detected_eas[ea_count].total_risk = CalculatePositionRisk(PositionGetTicket(i));
ea_count++;
}
else
{
detected_eas[index].trade_count++;
detected_eas[index].total_volume += volume;
detected_eas[index].total_profit += profit;
detected_eas[index].total_risk += CalculatePositionRisk(PositionGetTicket(i));
}
}
}
// Display results
Print("\n╔════════════════════════════════════════════════════════╗");
Print("║ DETECTED EXPERT ADVISORS ║");
Print("╚════════════════════════════════════════════════════════╝");
if(ea_count == 0)
{
Print("No active EA trades detected.");
}
else
{
// Sort by magic number
for(int i = 0; i < ea_count - 1; i++)
{
for(int j = i + 1; j < ea_count; j++)
{
if(detected_eas[i].magic_number > detected_eas[j].magic_number)
{
EAInfo temp = detected_eas[i];
detected_eas[i] = detected_eas[j];
detected_eas[j] = temp;
}
}
}
// Display each EA
for(int i = 0; i < ea_count; i++)
{
Print("\n┌─────────────────────────────────────────────────────────┐");
Print("│ EA #", (i+1), ": ", detected_eas[i].ea_name,
" (Magic: ", detected_eas[i].magic_number, ")");
Print("├─────────────────────────────────────────────────────────┤");
Print("│ Symbol: ", detected_eas[i].symbol);
Print("│ Active Trades: ", detected_eas[i].trade_count);
Print("│ Total Volume: ", DoubleToString(detected_eas[i].total_volume, 2), " lots");
Print("│ Total Risk: ", DoubleToString(detected_eas[i].total_risk, 2), "%");
Print("│ Current P/L: $", DoubleToString(detected_eas[i].total_profit, 2));
Print("└─────────────────────────────────────────────────────────┘");
}
}
// Configuration suggestions
Print("\n╔════════════════════════════════════════════════════════╗");
Print("║ CONFIGURATION SUGGESTIONS ║");
Print("╚════════════════════════════════════════════════════════╝");
if(ea_count > 0)
{
Print("\nTo manage specific EAs, use these MagicNumberFilter values:");
for(int i = 0; i < ea_count; i++)
{
if(detected_eas[i].magic_number != 0) // Skip manual trades
{
Print("- For ", detected_eas[i].ea_name, ": MagicNumberFilter = ",
detected_eas[i].magic_number);
}
}
Print("\nTo manage ALL external trades: MagicNumberFilter = 0");
}
// Risk warnings
double total_risk = 0;
for(int i = 0; i < ea_count; i++)
{
total_risk += detected_eas[i].total_risk;
}
if(total_risk > 5.0)
{
Print("\n⚠️ WARNING: Total risk across all EAs: ",
DoubleToString(total_risk, 2), "%");
Print("Consider reducing position sizes or number of EAs.");
}
}
//+------------------------------------------------------------------+
//| Get EA name from magic number |
//+------------------------------------------------------------------+
string GetEANameFromMagic(long magic)
{
// Add your known EA magic numbers here
switch((int)magic)
{
case 0: return "Manual Trading";
case 12345: return "Risk Manager EA";
case 55555: return "Commercial EA";
case 77777: return "Scalper EA";
case 88888: return "Grid EA";
case 99999: return "Martingale EA";
// Magic number ranges
default:
{
if(magic >= 10000 && magic < 20000)
return StringFormat("External EA (%d)", magic);
else if(magic >= 20000 && magic < 30000)
return StringFormat("Signal Service (%d)", magic);
else if(magic >= 30000 && magic < 40000)
return StringFormat("Copy Trader (%d)", magic);
else if(magic >= 80000 && magic < 90000)
return StringFormat("PAMM/MAM (%d)", magic);
else
return StringFormat("Unknown EA (%d)", magic);
}
}
}
//+------------------------------------------------------------------+
//| Calculate position risk percentage |
//+------------------------------------------------------------------+
double CalculatePositionRisk(ulong ticket)
{
if(!PositionSelectByTicket(ticket))
return 0;
string symbol = PositionGetString(POSITION_SYMBOL);
double sl = PositionGetDouble(POSITION_SL);
double open_price = PositionGetDouble(POSITION_PRICE_OPEN);
double volume = PositionGetDouble(POSITION_VOLUME);
ENUM_POSITION_TYPE type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
if(sl == 0) return 0; // No stop loss
double stop_distance;
if(type == POSITION_TYPE_BUY)
stop_distance = open_price - sl;
else
stop_distance = sl - open_price;
if(stop_distance <= 0) return 0;
double tick_value = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_VALUE);
double tick_size = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE);
if(tick_size <= 0) return 0;
double potential_loss = (stop_distance / tick_size) * tick_value * volume;
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
return (balance > 0) ? (potential_loss / balance) * 100 : 0;
}
//+------------------------------------------------------------------+
//| Create EA summary dashboard label |
//+------------------------------------------------------------------+
void CreateEASummaryDashboard()
{
string summary = "═══ EA SUMMARY ═══\n";
int total_positions = PositionsTotal();
long magic_numbers[];
int magic_count = 0;
// Collect unique magic numbers
for(int i = 0; i < total_positions; i++)
{
if(PositionSelectByTicket(PositionGetTicket(i)))
{
long magic = PositionGetInteger(POSITION_MAGIC);
bool found = false;
for(int j = 0; j < magic_count; j++)
{
if(magic_numbers[j] == magic)
{
found = true;
break;
}
}
if(!found)
{
ArrayResize(magic_numbers, magic_count + 1);
magic_numbers[magic_count] = magic;
magic_count++;
}
}
}
// Build summary
for(int i = 0; i < magic_count; i++)
{
int count = 0;
double profit = 0;
for(int j = 0; j < total_positions; j++)
{
if(PositionSelectByTicket(PositionGetTicket(j)))
{
if(PositionGetInteger(POSITION_MAGIC) == magic_numbers[i])
{
count++;
profit += PositionGetDouble(POSITION_PROFIT);
}
}
}
summary += GetEANameFromMagic(magic_numbers[i]) + ": " +
IntegerToString(count) + " trades, P/L: $" +
DoubleToString(profit, 2) + "\n";
}
// Display on chart
Comment(summary);
}
//+------------------------------------------------------------------+