Migrate MAEA Expert Advisor from MetaTrader 4 to MetaTrader 5 platform with significant strategy simplification and architectural improvements. Key changes: - Platform: MQL4 → MQL5 - Indicators: Reduced from 5 lines (3 EMAs + 2 borders) to 2 EMAs with zone fill - Strategy: Removed pullback signals and dynamic lot sizing - Lot sizing: Changed from dynamic (0.01/0.02) to fixed 0.01 lot - Stop loss: Changed from Border Lines to opposite EMA (Buy: EMA Low, Sell: EMA High) - Signal logic: Added opposite signal close for reversal protection - New filter: Added minimum zone width filter (100 points) - Documentation: Updated implementation plans and project summary - New files: Added AGENTS.md, MAEA_Indicator.mq5, and opencode.jsonc BREAKING CHANGE: Complete rewrite from MQL4 to MQL5 with simplified strategy. Previous MAEA.mq4 and README.md deleted. New implementation requires MetaTrader 5.
14 KiB
14 KiB
MAEA (Moving Average Expert Advisor) Implementation Plan
Project Overview
- Name: MAEA
- Type: MQL5 Expert Advisor for MetaTrader 5
- Strategy: Advanced trend-following with EMA-based signals, multiple filters, and risk management
- Repository: https://git.moreminimore.com/kunthawat/MAEA
- Timezone: Thailand (UTC+7)
Strategy Details
1. EMA Lines (2 Base Lines)
All EMAs use period 30 with different price sources:
- EMA High: EMA of High prices - Light Blue color
- EMA Low: EMA of Low prices - Orange color
2. EMA Zone (Visual Area)
- Zone Definition: The area between EMA High and EMA Low
- Visual: Light yellow transparent fill between EMA High and EMA Low
3. Signal Type
3.1 Breakthrough Signal
- Buy Signal: Close price breaks above EMA High (zone breakout upward)
- Sell Signal: Close price breaks below EMA Low (zone breakout downward)
- Purpose: Triggers position opening/closing
- Logic:
- Previous close must be inside zone (between EMA High and EMA Low)
- Current close must be outside zone
- For buy: previous_close <= EMA_High AND current_close > EMA_High
- For sell: previous_close >= EMA_Low AND current_close < EMA_Low
3.2 Opposite Signal Close
- Close Buy Position: When sell signal occurs (price breaks below EMA Low)
- Close Sell Position: When buy signal occurs (price breaks above EMA High)
- Priority: Opposite signal closes existing position immediately before opening new one
4. Order Opening Logic
- Only one position at a time
- Lot Size: Fixed 0.01 lot for all trades
- Trigger: Breakthrough signal only
- Minimum Zone Width: Zone must be at least 100 points before trading
- Filters Applied:
- Volume filter must pass
- Spread filter must pass
- MTF filter must pass (if enabled)
- News filter must pass (if enabled)
5. Risk Management
5.1 Take Profit
- Target specified in USD (e.g., $5)
- Closes order when profit reaches target amount
5.2 Stop Loss
- Buy Orders: SL at EMA Low
- Sell Orders: SL at EMA High
5.3 Breakeven
- Triggered when profit reaches specified number of points (e.g., 100 points)
- Moves Stop Loss to breakeven (entry price)
5.4 Trailing Stop
- Starts after breakeven is reached
- Trails Stop Loss by specified number of points from current price
- Default: 100 points trail distance
Additional Filters and Features
6. Volume Filter
- Calculation: Average volume of last 20 bars
- Condition: Trade only when current volume > average volume
- Purpose: Ensures sufficient market activity
7. Multiple Timeframe (MTF) Filter
- Timeframes: H1 (trading) and D1 (filter)
- Status: Optional feature (can be turned on/off)
- D1 Filter Logic:
- If D1 close > D1 EMA High: Only buy positions allowed (bullish trend)
- If D1 close < D1 EMA Low: Only sell positions allowed (bearish trend)
- If D1 close between D1 EMA High and D1 EMA Low: No positions allowed (no clear trend)
- Behavior: Position opens immediately when filter condition is met
8. Spread Filter
- Purpose: Avoid trading during high spread periods
- Condition: Only open orders when current spread <= maximum allowed spread
- Default: 30 points
9. Risk Management
- Max Drawdown: Maximum percentage drawdown allowed
- Behavior: Stop trading if drawdown exceeds limit
- Recovery: Resume trading when drawdown is below limit
10. News Filter
- Purpose: Avoid trading during high-impact news events
- Implementation: Avoid specific times (e.g., NFP, FOMC releases)
- Timezone: Thailand (UTC+7) - all times must be converted accordingly
- Flexibility: User can configure multiple time ranges to avoid
Strategy Flow Diagram
graph TD
A[Start New Bar] --> B[Calculate EMA High/Low]
B --> C[Fill Zone Between EMAs]
C --> D[Check for Open Positions]
D -->|Has Open Position| E[Check Opposite Signal]
D -->|No Open Position| F[Check Breakthrough Signals]
E --> E1{Opposite Signal?}
E1 -->|Buy open, Sell signal| E2[Close Buy Position]
E1 -->|Sell open, Buy signal| E3[Close Sell Position]
E1 -->|No opposite signal| E4[Manage Position Risks]
E2 --> A
E3 --> A
E4 --> E5[Check Take Profit]
E5 -->|TP Reached| E6[Close Position]
E5 -->|TP Not Reached| E7[Check Breakeven]
E7 -->|Breakeven Reached| E8[Move SL to Entry]
E7 -->|Breakeven Not Reached| E9[Check SL Hit]
E9 -->|SL Hit| E6
E9 -->|SL Not Hit| A
E6 --> A
F --> F1{Previous Close Inside Zone?}
F1 -->|No| A
F1 -->|Yes| F2{Zone Width >= 100 points?}
F2 -->|No| A
F2 -->|Yes| F3{Current Close Direction}
F3 -->|Close > EMA High| F4[Check Filters]
F3 -->|Close < EMA Low| F5[Check Filters]
F3 -->|Still Inside| A
F4 --> F6{Volume OK? Spread OK? MTF OK? News OK?}
F5 --> F6
F6 -->|All Pass| F7[Open Buy Position]
F6 -->|Any Fail| A
F7 --> F8[Set SL at EMA Low]
F8 --> F9[Set TP based on USD Target]
F9 --> A
F5 --> F10{Volume OK? Spread OK? MTF OK? News OK?}
F10 -->|All Pass| F11[Open Sell Position]
F10 -->|Any Fail| A
F11 --> F12[Set SL at EMA High]
F12 --> F13[Set TP based on USD Target]
F13 --> A
Implementation Steps
Phase 1: Project Setup & Git Configuration
- Create MQL5 project structure
- Initialize Git repository
- Configure remote to Gitea server (https://git.moreminimore.com/kunthawat/MAEA)
Phase 2: Core EA Structure
- Create
MAEA.mq5with basic EA framework - Define all input parameters (EMA period, lot size, TP, breakeven, trailing stop, filters, etc.)
- Set up indicator buffers for 2 EMA lines + zone fill (3 buffers total)
- Initialize global variables for state tracking
Phase 3: Indicator Calculations
- Implement EMA calculations for High and Low (period 30)
- Implement zone fill between EMA High and EMA Low (transparent light yellow)
- Add visual indicators with correct colors (Light Blue for EMA High, Orange for EMA Low)
- Implement Volume average calculation (20-bar average)
Phase 4: Signal Detection
- Implement breakthrough signal detection
- Check if previous close was inside zone
- Check if current close broke above EMA High or below EMA Low
- Implement opposite signal detection and position closing
- If buy position open and sell signal occurs: close buy
- If sell position open and buy signal occurs: close sell
- Implement minimum zone width check (100 points)
- Implement single position check
Phase 5: Multiple Timeframe Filter
- Implement D1 EMA calculations for MTF filter
- Implement MTF filter logic (D1 > High = buy only, D1 < Low = sell only, between = no trade)
- Add enable/disable toggle for MTF filter
Phase 6: Additional Filters
- Implement volume filter (current volume > 20-bar average)
- Implement spread filter (current spread <= max spread)
- Implement news filter (avoid specific hours/days, Thailand timezone)
- Add enable/disable toggles for news filter
Phase 7: Order Management
- Implement position opening logic with all filter checks
- Implement fixed lot sizing (0.01 lot)
- Implement Stop Loss placement at opposite EMA
- Buy: SL at EMA Low
- Sell: SL at EMA High
- Implement Take Profit calculation (convert USD target to pips)
- Implement Breakeven logic (move SL to entry at X points)
- Implement Trailing Stop logic (trail by X points after breakeven)
- Implement single position restriction (use PositionsTotal())
Phase 8: Risk Management
- Implement max drawdown calculation
- Implement drawdown protection (stop trading if exceeded)
- Implement trading resume logic when drawdown is below limit
Phase 9: Order Monitoring & Management
- Implement opposite signal checking on each tick
- If opposite signal detected, close existing position immediately
- Implement Take Profit checking on each tick
- Implement Breakeven checking and SL modification
- Implement Trailing Stop checking and SL modification
- Implement Stop Loss checking
- Implement position closure logic
Phase 10: Testing & Validation
- Test EMA High and Low calculations
- Test zone fill visualization (transparent yellow)
- Test breakthrough signal detection
- Verify breakout requires previous close inside zone
- Test all filters (volume, spread, MTF, news)
- Test position opening with fixed 0.01 lot
- Test TP, SL (at opposite EMA), breakeven, and trailing stop
- Test drawdown protection
- Test visual indicators display
Phase 11: Documentation & Deployment
- Create comprehensive
README.mdwith strategy documentation - Add parameter descriptions and usage instructions
- Add troubleshooting guide
- Commit initial code to Git
- Push to Gitea repository
- Verify repository connection and code availability
Input Parameters
| Parameter | Description | Default Value |
|---|---|---|
EMAPeriod |
EMA period for both lines | 30 |
LotSize |
Fixed lot size | 0.01 |
TakeProfitUSD |
Take profit target in USD | 5.0 |
BreakevenPoints |
Points to trigger breakeven | 100 |
TrailingStopPoints |
Points for trailing stop distance | 100 |
MagicNumber |
EA unique identifier | 12345 |
MaxSpread |
Maximum allowed spread in points | 30 |
VolumePeriod |
Period for volume average calculation | 20 |
MinZoneWidthPoints |
Minimum zone width to trade (points) | 100 |
MaxDrawdownPercent |
Maximum drawdown percentage | 10.0 |
UseMTFFilter |
Enable/disable MTF filter | true |
UseNewsFilter |
Enable/disable news filter | true |
NewsAvoidHours |
Hours to avoid (comma-separated) | 14,15,20,21 |
NewsAvoidDays |
Days to avoid (comma-separated) | 1,5 |
Visual Indicators
| Line | Color | Description |
|---|---|---|
| EMA High | Light Blue (clrLightBlue) | EMA of High prices |
| EMA Low | Orange (clrOrange) | EMA of Low prices |
| Zone Fill | Light Yellow (transparent) | Area between EMA High and EMA Low |
Key Considerations
- Breakthrough Detection: Previous close must be inside zone, current close outside zone
- Opposite Signal Close: Close existing position when opposite breakthrough signal occurs
- Minimum Zone Width: Zone must be at least 100 points wide before trading
- Single Position: Only one position open at any time (MT5 uses positions, not orders)
- SL at Opposite EMA: Buy SL at EMA Low, Sell SL at EMA High
- Fixed Lot Size: Always 0.01 lot regardless of market conditions
- Breakeven: Only moves SL to entry price, not to profit
- TP Calculation: Convert USD target to pips based on lot size and symbol
- Volume Filter: Only trade when current volume exceeds 20-bar average
- MTF Filter: D1 price position relative to zone determines allowed direction
- Spread Filter: Avoid high spread periods
- Timezone: All time-based filters use Thailand timezone (UTC+7)
- Trailing Stop: Activates after breakeven, trails by specified points
- Drawdown Protection: Stops trading if max drawdown exceeded
- Zone Visualization: Light yellow transparent fill between EMA High and EMA Low
Technical Specifications
- Platform: MetaTrader 5
- Language: MQL5
- Trading Timeframe: H1 (recommended)
- Filter Timeframe: D1 (for MTF filter)
- Currency Pairs: All pairs (user-selectable)
- Account Types: Any MT5 account type
- Server Timezone: Thailand (UTC+7)
Testing Checklist
Core Strategy
- EMA calculations verify correctly (High and Low)
- Zone fill displays correctly (light yellow, transparent)
- Zone width calculation verify correctly (in points)
- Minimum zone width filter works (100 points minimum)
- Breakthrough signals trigger correctly
- Previous close inside zone check
- Buy signal: close > EMA High
- Sell signal: close < EMA Low
- Opposite signal detection works
- Buy position closes when sell signal occurs
- Sell position closes when buy signal occurs
Filters
- Volume filter works (20-bar average, current > average)
- Spread filter prevents high spread trades
- MTF filter works correctly
- D1 close > EMA High: buy only
- D1 close < EMA Low: sell only
- D1 close between: no trade
- MTF filter can be enabled/disabled
- Min zone width filter works (100 points minimum)
- News filter avoids specified times (Thailand timezone)
- News filter can be enabled/disabled
Order Management
- Stop Loss places at opposite EMA (Buy: EMA Low, Sell: EMA High)
- Take Profit closes at correct USD amount
- Breakeven triggers at correct points
- Trailing stop activates after breakeven
- Trailing stop trails by correct distance
- Opposite signal closes existing position immediately
- Only one position opens at a time
- Fixed lot size always 0.01
Risk Management
- Max drawdown protection works
- Trading stops when drawdown exceeds limit
- Trading resumes when drawdown is below limit
Visual & Technical
- Visual indicators display with correct colors
- Git repository connects to Gitea successfully
- Code compiles without errors
- EA runs without runtime errors
Notes
- The strategy uses 2 EMA lines with a filled zone between them
- No pullback tracking or dynamic lot sizing - simplified approach
- Fixed lot size: 0.01 for all trades
- Positions close when opposite signal occurs (reversal protection)
- Minimum zone width of 100 points ensures meaningful setups
- The strategy is trend-following and works best in trending markets
- Breakthrough signals require price to be inside zone before breaking out
- Multiple filters ensure quality trade entries
- All time-based calculations use Thailand timezone (UTC+7)
- MTF filter matches price position relative to D1 zone
- Risk management features protect account from excessive losses
- Zone fill uses light yellow color with transparency for better visibility