Trend Execution Engine
- Experts
- Alex Amuyunzu Raymond
- Versione: 1.0
- Attivazioni: 5
Trend Execution Engine - Professional Multi-Strategy Expert Advisor for MetaTrader 5
The Trend Execution Engine is a comprehensive algorithmic trading system engineered for MetaTrader 5 that represents the culmination of advanced technical analysis, robust risk management principles, and sophisticated software architecture. This Expert Advisor is not a simple indicator-based system but rather a fully-integrated trading platform that combines multiple independent strategy modules operating simultaneously across different timeframes, instruments, and market conditions to provide diversified exposure and optimized risk distribution.
Architectural Foundation and System Design:
At its core, the Trend Execution Engine employs a modular, object-oriented architecture that separates strategy logic, risk management, and execution layers into discrete, maintainable components. Each strategy operates as an independent instance with its own magic number identifier, allowing multiple configurations to run concurrently on the same chart or across different instruments without position conflicts or signal interference. This architectural approach ensures that Strategy 2 and Strategy 3 can pursue different market opportunities simultaneously while maintaining complete operational independence.
The system is built using the SimpleAVStrategy class framework, a proprietary implementation that encapsulates all necessary functionality including indicator management, signal generation, position tracking, risk calculation, and execution logic. Each strategy instance maintains its own state variables, indicator handles, and historical data, ensuring that modifications to one strategy's parameters or behavior have no impact on other running strategies. This isolation is critical for backtesting, optimization, and live trading scenarios where different market conditions may favor different strategy configurations.
Technical Indicator Framework and Signal Generation:
The signal generation mechanism relies on a sophisticated combination of trend-following and momentum-based technical indicators, each serving a specific purpose in the overall decision-making process. The Exponential Moving Average serves as the primary trend filter, with the system analyzing price position relative to this dynamic level to determine the prevailing market bias. When price trades below the EMA, the system interprets this as a bullish trend condition, while price above the EMA indicates bearish sentiment. This counter-intuitive logic is intentional and reflects the mean-reversion characteristics embedded in the strategy design.
The Parabolic SAR indicator provides directional confirmation and acts as a dynamic support and resistance level that adapts to changing volatility and momentum conditions. For long entries, the SAR must be positioned below the recent price lows, confirming upward momentum. For short entries, the SAR must be above recent highs, confirming downward pressure. This dual confirmation requirement significantly reduces false signals that often plague single-indicator systems.
The MACD oscillator implementation is custom-built using separate fast and slow moving averages rather than relying on built-in indicator functions. This approach provides greater flexibility in moving average type selection, allowing traders to choose between Simple Moving Average and Exponential Moving Average calculations for both the oscillator and signal line components. The system monitors for histogram crossovers, specifically watching for the MACD line to cross above the signal line for bullish signals and below for bearish signals. This momentum confirmation ensures that entries occur during periods of increasing directional pressure rather than exhaustion phases.
Conditional Moving Average Technology:
A distinguishing feature of the Trend Execution Engine is its implementation of conditional moving averages, which update only when specific market conditions are satisfied. Unlike traditional moving averages that recalculate with every new price bar, conditional averages maintain their previous values until triggering conditions are met. This creates more stable reference levels that are less susceptible to whipsaw movements and false breakouts. The conditional EMA and conditional SMA structures use accumulated arrays and specialized update logic to achieve this behavior, providing more reliable trend identification in volatile markets.
Comprehensive Risk Management System:
Risk management is not an afterthought but rather a foundational component integrated into every aspect of the EA's operation. The system employs a multi-layered approach to capital preservation that begins with position sizing and extends through stop loss placement, take profit calculation, trailing stop management, and maximum exposure limits.
Position sizing is handled through dynamic lot calculation that considers both the trader's desired risk level and the actual margin requirements imposed by the broker. The CalculateSafeLot function queries the account's free margin, calculates the margin required for the intended position size, and automatically scales down the lot size if insufficient margin is available. This adaptive behavior prevents trade rejection due to margin insufficiency while allowing the EA to continue operating even after drawdown periods have reduced available capital. The system uses a conservative approach, limiting margin usage to 70 percent of available free margin to maintain a safety buffer for adverse price movements.
Volume normalization ensures that all position sizes conform to broker-specific requirements including minimum lot size, maximum lot size, and lot step increments. The NormalizeLot function retrieves these parameters directly from the symbol specification and rounds the calculated lot size to the nearest valid increment. This prevents the common "Invalid volume" errors that plague many automated trading systems when transitioning between demo and live accounts or when trading instruments with different contract specifications.
Stop Loss and Take Profit Calculation Methods:
The EA supports two distinct methodologies for setting protective stops and profit targets, each suited to different trading styles and market conditions. The Risk-Reward ratio method bases stops on recent price extremes, specifically using the lowest low over a configurable lookback period for long positions and the highest high for short positions. Take profit levels are then calculated as a multiple of the stop loss distance, creating a systematic reward-to-risk relationship. This approach automatically adapts to current market volatility, placing wider stops during volatile periods and tighter stops during calm conditions.
The Percentage method sets stops and targets as fixed percentage distances from the entry price, providing predictable risk levels regardless of recent price action. This approach is preferred by traders who want consistent dollar risk per trade and works well in markets with stable volatility characteristics. Both methods include stop level validation that ensures calculated levels meet broker-imposed minimum distance requirements, automatically adjusting stops that would otherwise be rejected as too close to market price.
Trailing Stop Implementation:
The trailing stop mechanism operates independently for each strategy and position direction, continuously monitoring price movement to lock in profits as favorable trends develop. For long positions, the system tracks the highest high achieved since position entry. When a new high is established, the stop loss is raised by the difference between the new high and the previous high, effectively moving the stop loss upward without ever moving it downward. This ratcheting behavior ensures that locked-in profits can never be given back due to stop adjustment.
For short positions, the inverse logic applies, tracking the lowest low and adjusting the stop loss downward as new lows are achieved. The trailing mechanism only activates when explicitly enabled through the UseTrail parameter, giving traders the option to use fixed stops if they prefer. All stop modifications are executed through proper position modification commands, ensuring broker compliance and audit trail completeness.
Time-Based Session Management:
Recognition that not all trading hours are equal led to the development of comprehensive session filtering functionality. The EA allows traders to define specific time windows during which trade entries are permitted and separate windows during which positions should be closed regardless of technical conditions. Entry sessions are typically aligned with high-liquidity periods when spreads are tight and price action is directional, such as the London-New York overlap for forex pairs.
Exit sessions provide a mechanism to flatten positions before low-liquidity periods, weekends, or major news events that could cause gapping or slippage. The session filter uses a simple hour-minute format specification and compares current time against the defined windows on every strategy execution cycle. This time-based risk management is particularly valuable for intraday strategies that should not hold positions overnight or for avoiding the unpredictable price movements that often occur during Asian session hours in forex markets.
Higher Timeframe Trend Confirmation:
The optional higher timeframe analysis feature adds an additional layer of trend confirmation by requiring price to be favorably positioned relative to a moving average calculated on a longer timeframe. For example, a strategy operating on the one-hour chart might require price to be above a 500-period moving average on the four-hour chart before permitting long entries. This multi-timeframe alignment ensures that trades are placed in the direction of the dominant trend rather than against it.
The higher timeframe moving average is independently configurable in terms of period length, moving average type, and timeframe selection. When enabled, the system queries the higher timeframe indicator on every signal evaluation and only proceeds with entries when the price-to-moving-average relationship confirms the intended trade direction. This filtering mechanism significantly reduces counter-trend signals and improves the overall win rate by focusing execution on high-probability setups.
Pyramiding and Position Scaling:
Pyramiding capability allows the EA to add to winning positions as trends develop, scaling exposure in the direction of confirmed momentum. Each strategy maintains a configurable maximum pyramiding count that limits the total number of positions that can be opened in one direction. Position tracking is handled through magic number filtering, with the system querying all open positions, counting those belonging to the current strategy, and comparing against the pyramiding limit before attempting additional entries.
The pyramiding feature is particularly powerful in strongly trending markets where initial positions quickly move into profit and additional entries can be added at favorable prices. The system treats each pyramided position independently with its own stop loss and take profit levels, though the trailing stop mechanism operates on the collective position by adjusting stops for all related trades simultaneously when new highs or lows are achieved.
Buy-Only Mode and Signal Conversion:
Recognizing that many traders prefer to focus exclusively on long positions, particularly in equity indices or other instruments with long-term upward bias, the EA includes a buy-only mode that converts all short signals into long signals. When this mode is active and the system generates a sell signal based on technical conditions, it interprets this as an opportunity to enter long rather than actually executing a short trade.
This signal conversion logic is based on the observation that in many markets, periods of technical weakness represent buying opportunities rather than shorting opportunities. The conversion happens at the signal generation level, ensuring that all downstream risk management, position sizing, and execution logic operates identically whether the signal originated as a natural long signal or a converted short signal. This feature provides psychological comfort to traders uncomfortable with short selling while still allowing the EA to respond to all market conditions.
Broker Compatibility and Order Execution:
Extensive broker compatibility features ensure the EA functions correctly across different broker implementations, account types, and trading platforms. The system automatically detects whether the account operates in netting or hedging mode and adjusts position management logic accordingly. Stop level validation queries the broker's minimum stop distance requirements and automatically adjusts any stops that would otherwise violate these constraints.
Margin calculation uses the OrderCalcMargin function to query exact margin requirements for specific order sizes before execution, eliminating guesswork and ensuring accurate position sizing even when trading exotic pairs or CFDs with complex margin calculations. Price normalization uses the symbol-specific digit count to ensure all price levels are formatted correctly, preventing rejection due to precision errors.
The execution engine uses the CTrade class from the MQL5 standard library, providing robust order placement with built-in retry logic and error handling. All trades are tagged with descriptive comment fields and magic numbers that enable position filtering and strategy attribution in multi-EA environments.
Strategy Parameter Configuration:
Each strategy module exposes over forty input parameters that control every aspect of its behavior. Timeframe selection determines the chart period on which the strategy operates, with support for anything from one-minute to daily charts. Lot size can be set as a fixed value or could be modified in the code to support percentage-of-equity calculations for true dynamic position sizing.
Stop loss configuration includes the choice between Risk-Reward and Percentage methods, the lookback period for recent high-low calculations, the risk-reward multiple for target placement, and the percentage values for percentage-based calculations. Trailing stop activation is a simple boolean toggle, allowing strategies to be tested with and without trailing functionality.
Pyramiding limits, session time windows, higher timeframe filter settings, and all technical indicator parameters including Parabolic SAR acceleration factors, EMA periods, MACD fast and slow periods, and signal line smoothing are fully customizable. This granular control allows the EA to be adapted to different market conditions, trading styles, and risk tolerances without code modification.
Performance Optimization and Execution Efficiency:
The EA is optimized for computational efficiency, recognizing that excessive processing can cause execution delays and missed opportunities. Indicator handles are created once during initialization and reused throughout the EA's lifecycle rather than being recreated on every tick. Bar-based execution logic ensures that strategy evaluation only occurs when new price bars are formed, avoiding redundant calculations on every price tick.
Array operations use MQL5's native functions with proper series ordering to ensure compatibility with indicator buffer copying. Memory allocation is handled carefully to prevent leaks, with dynamic arrays being resized only when necessary and released during deinitialization. The system maintains minimal state variables, storing only essential information required for trailing stop calculations and position tracking.
Backtesting and Optimization Capabilities:
The EA is fully compatible with MetaTrader 5's Strategy Tester, supporting both single-pass backtests and multi-parameter optimization runs. The modular architecture allows each strategy to be tested independently by disabling others, facilitating isolated performance analysis. Historical tick data can be used for maximum accuracy, or faster one-minute OHLC testing can be employed for preliminary parameter exploration.
Optimization can target any input parameter or combination of parameters, with the genetic algorithm mode allowing efficient exploration of large parameter spaces. The system produces standard MT5 performance reports including equity curves, drawdown analysis, profit factor calculations, trade distribution statistics, and monthly/annual performance breakdowns. Custom metrics can be added through the OnTester function if specialized evaluation criteria are required.
Expected Trading Characteristics:
The Trend Execution Engine is designed as a medium-frequency trend-following system rather than a high-frequency scalping or grid trading approach. Trade frequency varies significantly based on timeframe selection and market conditions but typically ranges from several trades per week on lower timeframes to several per month on higher timeframes. The system is intentionally selective, prioritizing quality setups over quantity of trades.
Win rate expectations fall in the 55 to 70 percent range depending on parameter configuration and market conditions, with the risk-reward framework ensuring that average winning trades exceed average losing trades. Maximum drawdown is typically controlled through position sizing and stop loss discipline, with expected drawdown in the 15 to 25 percent range during normal operation and potentially higher during extended ranging periods.
The EA performs best in trending market conditions where directional moves persist long enough for trailing stops to lock in meaningful profits. Performance typically suffers during prolonged ranging or highly volatile whipsaw conditions, though the time session filters and higher timeframe confirmation help mitigate exposure to these unfavorable periods. Different strategy configurations may exhibit uncorrelated performance, providing portfolio-level diversification when multiple strategies are deployed simultaneously.
Capital Requirements and Account Recommendations:
Minimum capital requirements vary by instrument and broker margin requirements. For standard forex pairs with typical 1:100 or 1:500 leverage, a minimum account balance of $1,000 is recommended for conservative position sizing. For commodities like gold or instruments with higher margin requirements, $5,000 or more may be necessary to withstand normal drawdown while maintaining adequate position sizes.
The dynamic lot sizing feature allows the EA to adapt to available capital, automatically reducing position sizes after losses and potentially increasing them after wins if lot sizes are recalculated based on current equity. A Virtual Private Server is strongly recommended for uninterrupted operation, particularly if running multiple strategies or trading during non-business hours. Network latency and execution speed become increasingly important as timeframe decreases, with VPS hosting near broker servers providing optimal conditions.
Installation and Configuration Process:
Installation follows standard MetaTrader 5 EA procedures. The source code file should be placed in the Experts directory of the MT5 data folder and compiled through the MetaEditor application. Any compilation errors should be reviewed and resolved, though the provided code is tested and should compile without modification on standard MT5 builds.
Configuration begins by attaching the EA to a chart of the desired symbol and timeframe. The Expert Advisor properties panel provides access to all input parameters, organized into logical groups for Strategy 2 and Strategy 3. Initial configuration should focus on enabling or disabling each strategy, setting appropriate lot sizes for the account balance, and configuring time sessions to match the trader's preferred trading hours.
Risk parameters including stop loss method, risk-reward ratios, and trailing stop activation should be set based on backtesting results and personal risk tolerance. Technical indicator parameters can typically remain at default values initially, with optimization performed after observing baseline performance. The magic number for each strategy should be unique and not conflict with any other EAs running on the account.
Monitoring and Maintenance Requirements:
While the EA operates autonomously once configured, regular monitoring is essential for optimal performance. Daily review of open positions, equity curve progression, and drawdown levels helps identify any unexpected behavior or parameter drift. Weekly analysis of trade statistics including win rate, average win-to-loss ratio, and profit factor provides insight into whether current market conditions favor the strategy configuration.
Monthly comprehensive reviews should include comparison of actual performance against backtested expectations, evaluation of whether parameter adjustments are warranted based on changing market conditions, and verification that broker execution quality remains acceptable. The EA includes detailed logging through Print statements that can be reviewed in the Experts tab of the MT5 terminal, providing transparency into decision-making and execution.
Parameter adjustments should be made cautiously and preferably based on additional backtesting rather than curve-fitting to recent performance. Market conditions evolve, and strategies that perform well in trending periods may underperform in ranging periods, making it important to evaluate performance over complete market cycles rather than short time windows.
Risk Disclosure and Realistic Expectations:
The Trend Execution Engine is a sophisticated trading tool but not a guaranteed profit generator. All trading involves substantial risk of loss, and automated systems can lose money just as discretionary trading can. Past performance, whether in backtesting or live trading, does not guarantee future results. Market conditions change, and strategies that worked historically may not work in future environments.
The EA should be thoroughly tested on demo accounts before live deployment, with testing periods covering at least several weeks and ideally including both trending and ranging market conditions. Initial live trading should use minimum position sizes until consistent performance is verified in real market conditions with actual broker execution. Risk per trade should be limited to levels that allow the strategy to withstand expected drawdown without depleting account capital.
No trading system wins on every trade, and losing streaks are a normal part of algorithmic trading. The key to long-term success is maintaining disciplined risk management, avoiding over-leverage, and allowing the statistical edge to play out over a sufficient sample size of trades. Traders should never risk capital they cannot afford to lose and should maintain realistic expectations about potential returns.
Technical Support and Development Roadmap:
The Trend Execution Engine is provided with complete source code, enabling full transparency into all trading logic, risk management protocols, and execution mechanisms. This open-source approach allows experienced programmers to review, modify, or extend functionality as needed. Commented code explains the purpose of key functions and complex logic sections, facilitating understanding and customization.
Yunzuh Trading Systems provides technical support for installation issues, compilation errors, and clarification of EA functionality. Support does not extend to trading advice, parameter selection for specific instruments, or guaranteed performance levels. Updates may be released periodically to address compatibility issues with new MT5 builds, incorporate user feedback, or add requested features.
