# Optimised Wilders Trend Following AutoAdjusting VixControlled Expert Advisor
## Overview
The Optimised Wilders Trend Following AutoAdjusting VixControlled Expert Advisor is an advanced trading system for MetaTrader 5 that implements a sophisticated trend following strategy based on Welles Wilder's concepts, enhanced with modern risk management techniques. This EA combines multiple innovative features to adapt to changing market conditions while maintaining strict risk control parameters.
## Application and Optimization
The Optimised Wilders Trend Following EA requires careful optimization for each specific financial instrument (underlier) as market behaviors can vary significantly across different assets. Using the MetaTrader Strategy Tester is essential to fine-tune the EA parameters for optimal performance on each instrument.
### Optimization Process
Each underlier might respond differently to market conditions and parameter settings. It's crucial to conduct thorough backtesting with historical data that represents various market conditions. Here's a detailed approach to optimizing the EA:
1. **AutoAdjusting ACC Feature Testing**:
- Test with AutoAdjustAcc = true vs. false
- When enabled, experiment with different AtrHigherTimeframe settings (H1, H4, H12, D1)
- Optimize the AutoAdjustPeriod parameter (range: 100-300)
- Adjust AtrRefreshPeriod to find the optimal refresh frequency for your instrument
2. **Higher ATR Value Optimization**:
- Test different ATR calculation periods
- Instruments with higher volatility may require longer ATR periods to smooth out noise
- Lower volatility instruments might benefit from shorter ATR periods for more responsive signals
3. **Fixed ACC Parameter Testing**:
- With AutoAdjust OFF, test a range of fixed ACC values (typically between 5.0-15.0)
- More volatile instruments generally perform better with lower ACC values
- Less volatile instruments may require higher ACC values for effective trend following
- Create optimization matrices with different ACC values against different timeframes
4. **StopLoss Configuration Testing**:
- Test with UseStopLoss = true vs. false
- When enabled, optimize the AF_MIN and AF_MAX parameters
- Adjust K_Smooth parameter (range: 2.0-7.0) to find the optimal sigmoid steepness
- For instruments with frequent gap movements, test different StopLevelBuffer values
5. **VIX Control Level Optimization**:
- Test with UseVixFilter = true vs. false
- Optimize the VixMinimumLevel parameter (typically between 15.0-25.0)
- Different asset classes may require different VIX thresholds:
* Equity indices might perform better with higher VIX thresholds (19.0-22.0)
* Forex pairs might need lower thresholds (16.0-19.0)
* Commodities may require custom thresholds based on their correlation with VIX
### Optimization Tips
- **Use Forward Testing**: After backtesting, always validate your optimized parameters with forward testing or out-of-sample data
- **Avoid Over-Optimization**: Focus on parameter ranges rather than exact values to avoid curve-fitting
- **Consider Market Regimes**: Test your settings across different market regimes (trending, ranging, volatile, calm)
- **Balance Performance Metrics**: Don't optimize solely for profit - consider drawdown, Sharpe ratio, and win rate
- **Instrument Correlation**: For portfolio trading, consider how parameters perform across correlated instruments
### Recommended Optimization Workflow
1. Start with default parameters and run a baseline test
2. Perform single-parameter optimization for the most critical parameters (ACC, VixMinimumLevel)
3. Run multi-parameter optimization with narrow ranges around the best single-parameter results
4. Validate results with out-of-sample testing
5. Periodically re-optimize as market conditions evolve
By thoroughly optimizing these key parameters for each specific underlier, traders can significantly enhance the performance of the Optimised Wilders Trend Following EA across different market conditions.
## Core Strategy
At its core, the EA uses a trend following approach based on the Stop-And-Reverse (SAR) principle. The system tracks significant price levels and calculates dynamic reversal points using Average True Range (ATR) to determine market volatility. The EA maintains a position in the market at all times (either long or short) and switches direction when price crosses the calculated SAR level.
## Auto Adjusting Feature
One of the most powerful aspects of this Expert Advisor is its Auto Adjusting Acceleration Factor (ACC) feature. This innovative mechanism allows the EA to dynamically adapt to changing market conditions across different timeframes.
### How the Auto Adjusting Feature Works:
1. **Timeframe Correlation Analysis**: The EA calculates the ATR (Average True Range) on two different timeframes:
- A higher timeframe (configurable, default is H12)
- The M1 (1-minute) timeframe
2. **Ratio-Based Adjustment**: The system calculates the ratio between these two ATR values:
```
pendingACC = ATRHigher / ATRM1
```
This ratio represents the relative volatility between the timeframes and becomes the new Acceleration Factor.
3. **Intelligent Application**: The calculated ACC value is not applied immediately but stored as a "pending" update that takes effect only when a position change occurs. This ensures smooth transitions between different volatility regimes.
4. **Validation and Fallback**: The system includes comprehensive validation to ensure the calculated ACC value is reasonable. If any issues are detected (division by zero, invalid values), the EA falls back to the initial ACC value.
5. **Periodic Recalculation**: The ACC value is recalculated periodically (configurable, default is hourly) to ensure it remains relevant to current market conditions.
This auto-adjusting mechanism allows the EA to:
- Use wider stops in volatile markets
- Use tighter stops in calmer markets
- Automatically adapt to changing market conditions without manual intervention
- Optimize risk management across different market phases
## VIX Control Feature
The VIX Control feature adds another layer of market awareness by incorporating volatility index data into the trading decision process.
### How the VIX Control Works:
1. **Market Volatility Assessment**: The EA monitors the VIX (Volatility Index) level from a specified symbol and timeframe.
2. **Minimum Threshold Filter**: New positions are only opened when the VIX level is above a configurable minimum threshold (default is 19.0).
3. **Risk Management Integration**: This feature acts as a market filter that prevents the EA from entering new positions during periods of low volatility, which often correspond to choppy, directionless markets.
4. **Configurable Parameters**: Users can:
- Enable/disable the VIX filter
- Adjust the minimum VIX level threshold
- Specify the VIX symbol name and timeframe to use
The VIX Control feature significantly improves the EA's performance by:
- Avoiding trading during unfavorable market conditions
- Reducing the number of false signals in low-volatility environments
- Focusing trading activity on periods with higher directional movement potential
- Adding a macroeconomic dimension to the trading strategy
## Advanced Trade Management
The EA implements sophisticated trade management techniques to optimize performance and minimize risk:
### Dynamic Stop Loss Management
1. **Adaptive Acceleration Factor (AFX)**: The EA uses a sigmoid-based transition function to calculate an adaptive acceleration factor that adjusts the stop loss distance based on price movement:
```
AFX = CalculateAFX(currentPrice, SIC_SNAP, ATR_SNAP, currentACC, AF_MIN, AF_MAX, FLIP, K_Smooth)
```
2. **Bound-Based Stop Loss Adjustment**: The system implements upper and lower bounds based on the ATR and tracks when these bounds are breached:
```
upperBound = SIC_SNAP + ATR_SNAP * currentACC
lowerBound = SIC_SNAP - ATR_SNAP * currentACC
```
Once a bound is breached, the stop loss is adjusted using a different algorithm to lock in profits.
3. **Trailing Stop Logic**: For long positions, the stop loss is continuously raised as the price moves favorably. For short positions, the stop loss is continuously lowered.
4. **Position Modification Management**: The EA includes sophisticated logic for position modifications:
- Cooldown periods between modification attempts
- Tracking of consecutive modification failures
- Fallback to more conservative stop loss values when needed
- Validation of stop loss levels against minimum distance requirements
### Risk Management Checks
The EA implements multiple risk management checks:
1. **Position Sizing**: Position size is calculated based on:
- Account balance
- User-defined risk percentage
- Current market volatility (ATR)
- Symbol-specific parameters (tick size, tick value, lot step)
2. **Margin Requirements**: Before opening a position, the EA verifies:
- Required margin for the trade
- Available free margin (with a 10% buffer)
- Rejection of trades with insufficient margin
3. **Stop Level Validation**: The system ensures stop loss levels are valid:
- Checks against minimum stop level requirements
- Adds configurable buffer to minimum stop level
- Implements waiting mechanism for market to move if stop level is too close
- Adjusts stop loss automatically if market doesn't move enough
4. **Two-Step Order Placement**: Optionally uses a two-step order placement process:
- First places the order without stop loss
- After a configurable delay, adds the stop loss
- This helps avoid issues with brokers rejecting orders with tight stop losses
5. **Slippage Control**: Configurable maximum allowed slippage in points
### Memory and Resource Management
The EA includes features for efficient operation:
1. **Memory Monitoring**: Optional monitoring of memory usage with configurable logging intervals
2. **Indicator Handle Management**: Efficient creation and release of indicator handles
3. **Optimized Calculations**: Heavy calculations (like AFX) are only performed when needed
## Technical Implementation Details
### Key Components:
1. **ATR Calculation**: Smoothed Average True Range calcu
ation with configurable alpha factor
2. **SIC (Significant Close)**: Tracks significant price levels based on position direction
3. **SAR (Stop-And-Reverse)**: Dynamic calculation of reversal points
4. **AFX Calculation**: Sigmoid-based adaptive acceleration factor
5. **Position Management**: Comprehensive position tracking and modification
### Error Handling:
1. **Division by Zero Protection**: Multiple checks to prevent division by zero errors
2. **Parameter Validation**: Extensive validation of calculated values
3. **Retry Mechanisms**: Retry logic for indicator buffer copying
4. **Fallback Values**: Default values used when calculations fail
## Conclusion
The Optimised Wilders Trend Following AutoAdjusting VixControlled Expert Advisor represents a sophisticated trading system that combines classic trend following principles with modern adaptive techniques. The Auto Adjusting feature and VIX Control mechanism provide significant advantages in adapting to changing market conditions, while the comprehensive trade management system ensures disciplined risk control.
This EA is particularly well-suited for traders who:
- Trade across multiple timeframes
- Seek a system that adapts to changing market conditions
- Want to incorporate volatility awareness into their trading
- Require sophisticated risk management
- Prefer a fully automated trading solution
By combining these advanced features, the EA aims to deliver consistent performance across various market conditions while maintaining strict risk management parameters.