CHANGES:
- InitializeM5BarCountingMode(): Replace hardcoded boolean overrides with
input-driven values (InpBreakevenEnabled, InpPartialEnabled,
InpTrailingMethod, InpTrailDistance, InpTrailStep, InpAdaptiveTrailing)
- ConfigureContrarianMode(): Update preset to respect global inputs instead
of hardcoded values
- ApplyM5ContrarianManagement() - Phase 1: Add m_config.breakeven_enabled
check before executing BE
- ApplyM5ContrarianManagement() - Phase 2: Add m_config.breakeven_enabled
check and wrap partials in if(m_config.partial_enabled) block
- Remove undeclared config.use_technical_exits field reference
BEHAVIOR:
- M5 mode now respects global enable/disable flags set in EA inputs
- Delayed breakeven and trailing delays preserved (InpMinBarsBeforeBE,
InpMinBarsBeforeTrail remain M5-specific)
- Graduated stop-loss (3.5→2.5→2.0 ATR) and phase-based management unchanged
- Test reports now accurately reflect enabled/disabled features
FIXES:
- Configuration now matches tester report flags
- User can disable BE or partials in M5 mode via global inputs
- Prevents undefined behavior from conflicting hardcoded vs input values
CRITICAL FIX:
- MoveToBreakeven() now validates against broker stop level before modification
- Prevents "Invalid stops" error causing infinite retry spam
- Marks breakeven_applied=true even on failed modify to stop retries
RELATED FIXES:
- Disabled analyzer cleanup in OnDeinit to prevent error 506 pointer access crash
- Analyzer GenerateAnalysisReport() file I/O unsafe during shutdown
- TODO: Refactor analyzer report generation to be shutdown-safe
Changes to PositionManager_PME_Complete.mqh:
- Lines 854-876: Added ValidateStopLoss() check in MoveToBreakeven()
- Failsafe: Mark BE attempted even if modify fails post-validation
- Prevents tick-spam when BE trigger met but SL too close to market price
Changes to ERMT_PME_2.1_M5.mq5:
- Lines 893-906: Commented out g_analyzer cleanup block in OnDeinit()
- Temporary disable pending shutdown-safe refactor
Testing:
- Before: "failed modify #7... [Invalid stops]" spam, backtest hangs
- After: Clean execution, BE either succeeds or silently skips
- Parametric optimization now completes successfully
Dependencies: Requires M5 v2.1 changes from previous commit
BREAKING CHANGES:
- M5 mode now enforces all v2.1 delayed BE/trailing parameters
- Graduated stop system replaces legacy disaster stop when enabled
- Max bars limit now triggers hard position close
Changes to PositionManager_PME_Complete.mqh:
1. Max Bars Hard Close Enforcement
- Added check for m_m5_config.max_bars at start of ApplyM5ContrarianManagement()
- Forces EXIT_TIME close when position age exceeds configured limit (300 bars)
- Prevents indefinite position holding in extended phases
2. Graduated Stop-Loss System
- Implements ATR-based phase-progressive stops:
* Phase 1 (0-60 bars): 3.5 ATR wide initial protection
* Phase 2 (60-180 bars): 2.5 ATR tightened stop
* Phase 3 (180+ bars): 2.0 ATR mature stop
- Replaces legacy disaster stop when m_config.use_graduated_stops enabled
- Falls back to disaster stop (150pt @ -100pt) if graduated stops disabled
- Updates m_positions[].current_sl after successful modification
3. Delayed Breakeven Enforcement (v2.1)
- Respects m_config.breakeven_min_bars (20 bars minimum age)
- Respects m_config.breakeven_min_profit_bars (5 consecutive profit bars)
- Applied to both Phase 1 fast BE (25pts) and Phase 2 maturity BE (30pts)
- Logs bar count and consecutive profit bars on activation
4. Delayed Trailing Enforcement (v2.1)
- Respects m_config.trail_min_bars (40 bars minimum age)
- Applied to percentage trail in Phase 2 (30%/40% based on reversal speed)
- Sets trail_activated flag and increments m_metrics.trails_activated
- Logs activation with percentage and bar count
5. M5 Trailing Helper Metric Sync
- Created ApplyM5PercentageTrail() with current_sl sync
- Created ApplyM5PointsTrail() with current_sl sync
- Created ApplyM5DynamicTrail() with current_sl sync
- Standard helpers (ApplyPercentageTrail, etc.) preserved for non-M5 use
- M5 contrarian management now calls M5-specific versions exclusively
- Fixes metric/state desync between MT5 server and in-memory position tracking
Architecture:
- M5 mode continues to bypass standard management path (intentional isolation)
- Standard trailing/technical/time-exit engines remain unused in M5 mode
- Configuration separation maintained: ManagementConfig for standard + v2.1 fields, M5Config for contrarian-specific
- No changes to main EA file (ERMT_PME_2.1_M5.mq5)
Compatibility:
- No breaking changes to standard (non-M5) management path
- Existing M5 backtest results remain valid (behavior refinement only)
- All v2.1 configuration fields now honored in M5 runtime
BREAKING CHANGES:
- EA is no longer management-only when InpEnableEntries=true
- New CTrade dependency added
- New magic number 77777 used for automated entries
NEW FEATURES:
- Toggleable bar-counting entry system (3/5/7 consecutive opposite bars)
* Detects N consecutive bearish/bullish bars followed by reversal
* Long entry: After N bearish bars, current bar closes bullish
* Short entry: After N bullish bars, current bar closes bearish
- Auto lot sizing based on account risk percentage
- Fixed stop-loss and R:R-based take profit
- Entry cooldown period (minimum bars between entries)
- Fully integrated with existing position management system
IMPLEMENTATION:
- DetectBarCountingEntry(): Scans for consecutive opposite bars pattern
- ExecuteEntry(): Places market orders with risk management
- Integrated into OnTick() with new bar detection
- CTrade setup with magic number, deviation, and filling mode
- Ent
Implements comprehensive risk management solutions specifically designed for
contrarian bar-counting entries that require time to develop.
## Solution 1: Graduated Stop-Loss System
- **Dynamic ATR-based stops** that widen during development phases
* 0-60 bars (0-5hrs): 3.5 ATR - Wide protection for reversal development
* 60-180 bars (5-15hrs): 2.5 ATR - Medium after trend confirmation
* 180+ bars (15+hrs): 2.0 ATR - Standard for matured positions
- **Configurable via inputs**: InpUseGraduatedStops, InpInitialStopATR, etc.
- **Prevents premature stop-outs** during normal contrarian drawdown
## Solution 2: Delayed Breakeven with Maturity Check
- **Time-aware breakeven** requires BOTH profit AND minimum trade age
* Minimum 20 bars (1.5 hours) before applying BE
* Requires 5 consecutive profitable bars for stability
- **Prevents premature locking** during initial volatility
- **Configurable via inputs**: InpUseDelayedBreakeven, InpMinBarsBeforeBE
## Additional Enhancements
### Delayed Trailing System
- Waits 40+ bars (3.3 hours) AND 60+ points before trailing
- Gives reversals time to fully develop
- Prevents whipsaw stop-outs on deep retracements
### Reversal Speed Tracking Dashboard
- **Real-time metrics** for reversal performance:
* Fast reversals (<1hr): Green indicator
* Normal reversals (1-5hr): Yellow indicator
* Slow reversals (>5hr): Orange indicator
* Failed reversals: Red indicator
- **Average bars to profit** tracking
- **Fast reversal efficiency** percentage with color coding
### ConfigureContrarianMode() Helper Function
- **One-click contrarian preset** for easy setup
- Pre-configured optimal settings for bar-counting strategies
- Can be called programmatically for automated setup
## Technical Details
- **File size**: 116KB (added 26KB of new functionality)
- **Lines of code**: 1449 (added 261 lines)
- **Backwards compatible**: All new features can be disabled
- **Dashboard enhanced**: New reversal speed section when enabled
## Input Parameters Added
- Graduated Stop-Loss: 5 new parameters
- Delayed Breakeven: 4 new parameters
- Delayed Trailing: 3 new parameters
- Reversal Speed Tracking: 4 new parameters
## Configuration Recommendations
For contrarian M5 strategies:
- Enable all three systems (Graduated Stops, Delayed BE, Delayed Trail)
- Show reversal metrics for performance insight
- Use disaster stops as ultimate safety net (100/150pts)
- Progressive partials: 35/70/110/150pts (85% total closed)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Solution 1: Phase locks guarantee minimum profit for highest phase achieved. Adaptive trailing manages dynamic protection above that floor. Partial closures realize profits progressively. Together, they work in harmony instead of conflict.
EMRT 7x
Critical – Spread filter always rejects signals (EntrySystem_Optimised.mqh:L858-L882; ERMT_7.1_ERMT-ML.mq5:L1290-L1305) The validator compares market.spread (set to the raw point count from SYMBOL_SPREAD) against stop distances expressed in price units. Typical FX spreads (e.g. 18 points) dwarf an ATR-derived stop such as 0.0024, so every candidate fails the 20%-of-stop check. Until the spread is normalised (e.g. market.spread * _Point) or the stop distances are converted to points, the EA cannot emit any live entry orders.
Medium – Technical context is largely empty (TechnicalAnalysis_Optimised.mqh:L38-L119; EntrySystem_Optimised.mqh:L1005-L1030) Market snapshots never populate sr_levels, Fibonacci, pivots, or market-structure data—the ana
- Created two new INI files for optimization:
- ERMT_7.1_ERMT-ML.EURUSD.M5.20251001_20251102.210.ini
- ERMT_7.1_ERMT-ML.EURUSD.M5.20251001_20251111.210.ini
- Each file includes detailed configuration settings for the trading strategy, including system configuration, entry system, risk management, trade management, technical analysis, dashboard settings, and reporting options.
- The profiles are set for the period from October 1, 2025, to November 2, 2025, and November 1, 2025, respectively.