Gold L1 Trend Filtering
- Experts
- Version: 1.0
- Activations: 20
Gold L1 Trend Filtering is a trend-following Expert Advisor built on the L1 piecewise-linear trend filter -- a noise-reducing mathematical technique that separates genuine price trends from random market fluctuations. The EA identifies clean directional regimes and enters trades only when multiple timeframes confirm the same bias, resulting in high-conviction setups with reduced false signals.
This EA is designed for traders who value disciplined, rules-based execution over discretionary guessing. It handles every aspect of trade management automatically -- from entry and position sizing to trailing stops, partial profit-taking, and account protection.
How It Works
The core engine applies a piecewise-linear L1 filter to price data, producing a smooth trend estimate that adapts to changing market conditions. Unlike simple moving averages, the L1 filter preserves sharp trend transitions while removing intra-bar noise, allowing the EA to detect regime changes (uptrend, downtrend, or sideways) with precision.
When a new directional regime is detected, the EA confirms the signal across M15, H1, and H4 timeframes before committing capital. An RSI momentum filter provides additional protection against entering overbought or oversold conditions.
Key Features
- L1 piecewise-linear trend filter with volatility-adaptive lambda adjustment
- Multi-timeframe regime confirmation across M15, H1, and H4
- RSI momentum filter to avoid overbought and oversold entries
- Five position sizing methods: Fixed Fractional, ATR-Adjusted, Fractional Kelly, Value at Risk (VaR), and Anti-Martingale
- Dynamic signal scoring that scales lot size proportionally to signal strength
- ATR-based stop loss and take profit with full tick-size price normalization
- Trailing stop with ATR-based or fixed-point distance
- Breakeven protection after a configurable profit threshold
- Partial profit taking at customizable profit levels
- Equity target auto-liquidation to lock in session gains
- Optional session exit to close all positions before market close
- Economic calendar news filter that pauses trading around high-impact events
- Virtual stop loss and take profit system to shield levels from broker visibility
- Execution camouflage with randomized lot sizes and entry delays
- Broker defense shields including trailing drawdown guard, margin spike detection, and execution quality logging
- Maximum daily loss limiter with automatic position liquidation
- Correlation-aware exposure reduction for multi-symbol portfolios
- On-chart dashboard with real-time status, regime, ATR, positions, and daily P&L
- Multi-level hedging mode with three-tier lot allocation (scalp, core, runner) for hedging accounts
- Walk-forward out-of-sample cutoff date for rigorous backtesting discipline
- Exponential backoff retry logic for recoverable execution errors
- Comes with pre-optimized .set files for XAUUSD, EURUSD, GBPUSD, and USDJPY
Recommended Symbols and Timeframes
The EA performs best on XAUUSD (Gold) and major Forex pairs. Pre-configured .set files are provided for XAUUSD, EURUSD, GBPUSD, and USDJPY. The default operating timeframe is M5 or M15, with higher timeframes (H1, H4) used automatically for multi-timeframe confirmation.
Account Requirements
- Minimum recommended balance: 500 f o r F o r e x p a i r s , 500forForexpairs,1000 for Gold
- Works on both hedging and netting accounts
- Hedging accounts unlock the multi-level order feature (three-tier split trades)
- A VPS with low latency to your broker is recommended for optimal execution
Input Parameters
- Trend Filter and Regime
- Base L1 Trend Lambda -- Controls the smoothing intensity of the L1 filter. Higher values produce a smoother trend line with fewer regime changes. Default: 1.0.
- Lookback Bars -- Number of historical bars used to compute the L1 trend filter. Default: 200.
- Lambda Relative -- When enabled, the lambda parameter is scaled relative to the price series, making it consistent across different instruments. Default: true.
- Slope Threshold -- Minimum absolute slope value required to classify price movement as a directional trend rather than sideways. Default: 0.0001.
- Volatility-Adaptive Lambda -- Automatically adjusts the L1 lambda based on the ratio of current ATR to a baseline ATR, increasing smoothing during high volatility and decreasing it during calm markets. Default: true.
- Lambda ATR Baseline Period -- The lookback period used to calculate the baseline ATR for adaptive lambda scaling. Default: 50.
- Reversal Mode -- When enabled, the EA immediately opens an opposite trade after a regime change without waiting for a sideways-to-directional transition. Default: false.
- Risk and Position Sizing
- Position Sizing Method -- Selects the lot calculation algorithm. Options: Standard Risk Percent, ATR-Adjusted, Fractional Kelly, Value at Risk (VaR), Anti-Martingale. Default: Standard Risk Percent.
- Kelly Fraction -- Fraction of the full Kelly Criterion to apply (0.1 to 1.0). Only active when Fractional Kelly mode is selected. Default: 0.5.
- Volatility Baseline Period -- Number of bars used to calculate the average ATR for volatility-adjusted position sizing. Default: 50.
- VaR Confidence Level -- Confidence level for the Value at Risk calculation. Typical values: 0.95 or 0.99. Default: 0.95.
- VaR Lookback Days -- Number of daily returns used to estimate portfolio volatility for VaR. Default: 21.
- Max Total Exposure -- Maximum combined lot size across all open positions. Set to 0 to disable. Default: 0.
- Anti-Martingale Win Bonus -- Percentage increase in risk for each consecutive winning trade when Anti-Martingale mode is selected. Default: 25%.
- Correlation Check -- When enabled, halves the risk allocation if highly correlated positions are already open. Default: true.
- Max Drawdown Percent -- If the current drawdown exceeds this threshold, lot sizes are automatically trimmed to 10% of normal. Default: 20%.
- Walk-Forward OOS Cutoff -- Stops all trading after this date when running in the Strategy Tester, supporting walk-forward out-of-sample analysis. Default: 2026.01.01.
- Risk Per Trade -- Percentage of account balance risked on each trade. Default: 1.0%.
- ATR Period -- Period for the Average True Range indicator used in stop loss and take profit calculation. Default: 14.
- ATR Multiplier for Stop Loss -- Multiplier applied to ATR to determine the stop loss distance. Default: 1.5.
- ATR Multiplier for Take Profit -- Multiplier applied to ATR to determine the take profit distance. Default: 3.0.
- Max Daily Loss Percent -- Maximum allowed daily loss as a percentage of account balance. All positions are closed if this limit is breached. Default: 5.0%.
- Enable Max Daily Loss -- Activates the daily loss limiter. Default: true.
- Max Concurrent Positions -- Maximum number of positions the EA will hold simultaneously on the same symbol. Default: 1.
- Max ATR as Percent of Price -- If ATR exceeds this percentage of the current price, new trades are blocked to avoid extreme volatility conditions. Set to 0 to disable. Default: 2.0%.
- Advanced Money Management
- Dynamic Signal Scoring -- When enabled, the EA calculates a quality score (0-100) for each setup and scales the lot size proportionally. Default: true.
- Minimum Signal Score -- Setups scoring below this threshold are rejected entirely. Default: 60.
- Multi-Level Orders (Hedging Only) -- Splits each trade into three tiers: a scalp tier, a core tier, and a runner tier, each with its own take profit target. Only available on hedging accounts. Default: false.
- Tier 1 Percent (Scalp) -- Percentage of the total lot allocated to the first tier, which closes at half the normal TP distance. Default: 50%.
- Tier 2 Percent (Core) -- Percentage of the total lot allocated to the second tier, which closes at the standard TP distance. Default: 30%.
- Tier 3 Percent (Runner) -- Percentage of the total lot allocated to the third tier, which runs without a take profit and is managed by the trailing stop. Default: 20%.
- Trade Management
- Virtual SL/TP (Broker Defense) -- When enabled, stop loss and take profit levels are managed internally rather than being sent to the broker, preventing stop hunting. Default: true.
- Trailing Stop Broker Sync Step -- Minimum distance (in points) the trailing stop must move before the EA sends an update to the broker. Reduces modification spam. Default: 50.
- Trade Pacing Cooldown -- Minimum waiting period (in minutes) between closing one position and opening the next. Prevents whipsaw overtrading. Default: 15.
- Max Trades Per Day -- Maximum number of new trades allowed per calendar day. Set to 0 to disable. Default: 5.
- Enable Trailing Stop -- Activates the trailing stop module. Default: true.
- Trailing Start (Points) -- Profit distance (in points) required before the trailing stop activates. Default: 50.
- Trailing Start ATR Multiplier -- If set above 0, overrides the fixed trailing start with an ATR-based value. Default: 1.5.
- Trailing Step (Points) -- Distance between the trailing stop and the current price. Default: 10.
- Trailing ATR Multiplier -- If set above 0, overrides the fixed trailing step with an ATR-based distance. Default: 2.0.
- Breakeven Points -- After reaching this profit distance (in points), the stop loss is moved to the entry price. Default: 30.
- Exit on Opposite Regime -- When enabled, closes existing positions immediately if the trend regime reverses, regardless of stop loss. Default: false.
- Operational and Limits
- Max Slippage -- Maximum acceptable slippage in points. Default: 30.
- Max Allowed Spread -- If the current spread exceeds this value (in points), no new trades are opened. Default: 30.
- Enable Trading Hours -- Restricts trading to a specific window of server hours. Default: false.
- Start Hour -- Server hour when trading is permitted to begin. Default: 8.
- End Hour -- Server hour when trading must stop. Default: 20.
- Enable Trading -- Master switch to enable or disable all trading activity. Default: true.
- Calibration Trade for Validator -- Ensures the EA places at least one trade during Strategy Tester validation runs. Default: true.
- Magic Number -- Unique identifier for this EA instance. Allows multiple EAs to run independently on the same account. Default: 1001.
- Trade Comment -- Text comment attached to each trade for identification in the account history. Default: GoldL1Trend.
- MTF Confirmation
- Enable H1 MTF Confirmation -- When enabled, the EA requires that M15, H1, and H4 timeframes all agree on the trend direction before entering a trade. Default: true.
- Momentum Filter
- Enable RSI Momentum Filter -- When enabled, the EA skips buy signals when RSI is overbought and sell signals when RSI is oversold. Default: true.
- RSI Period -- Lookback period for the Relative Strength Index. Default: 14.
- RSI Overbought Level -- RSI value above which buy signals are suppressed. Default: 70.
- RSI Oversold Level -- RSI value below which sell signals are suppressed. Default: 30.
- News Filter
- Enable Economic Calendar News Filter -- Pauses all trading activity around high-impact economic news events detected via the built-in MQL5 Economic Calendar. Default: true.
- Country Code -- The country code used to filter relevant news events (e.g., US, EU). Default: US.
- Minutes Before News -- How many minutes before a high-impact event to stop opening new trades. Default: 30.
- Minutes After News -- How many minutes after a high-impact event to resume trading. Default: 30.
- Equity Target
- Close at Equity Target -- When enabled, all positions are closed when the combined floating profit reaches a specified percentage of account balance. Default: true.
- Target Profit Percent -- The profit threshold as a percentage of account balance. Default: 2.0%.
- Partial Profit
- Enable Partial Profit Taking -- When enabled, the EA closes a portion of the position after reaching a configurable profit level. Default: false.
- Partial Close Percent -- The percentage of position volume to close when the partial profit trigger is hit. Default: 50%.
- Partial Profit Trigger (Points) -- Profit distance in points that triggers the partial close. Set to 0 to use the Trailing Start value instead. Default: 0.
- Session Exit
- Close at End of Day -- When enabled, all positions are closed at a specified time each day. Default: false.
- Close Hour -- Server hour for the session exit. Default: 23.
- Close Minute -- Server minute for the session exit. Default: 45.
- Broker Defenses
- Max Trailing Drawdown -- If the equity drops by this percentage from its peak, all positions are immediately liquidated and trading is paused until the next day. Default: 15%.
- Detect High Margin Requirements -- When enabled, the EA blocks new trades if it detects the broker has artificially spiked margin requirements. Default: true.
- HMR Trigger Multiplier -- The threshold above which a margin increase is flagged as abnormal. Default: 1.5x.
- Randomize Execution -- Adds small random variations to lot sizes (within 10%) and introduces random delays (0-400ms) before order execution, making the EA's trading pattern less predictable to broker algorithms. Default: true.
- Log Execution Details -- Records every trade execution to a CSV file (ExecutionLog.csv) with precise fill prices, slippage, spread, and latency data for post-trade analysis. Default: true.
Support
For questions, feedback, or configuration assistance, please use the Comments section on this product page or contact me directly via MQL5 private message.
