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.
6.0 KiB
6.0 KiB
MAEA Development Guidelines
Build and Test Commands
Compilation
- Use MetaEditor (MT5 built-in editor) to compile the EA
- Press F7 or click Compile button in MetaEditor
- Check "Errors" tab in Toolbox for compilation issues
- All MQL5 files must compile with 0 errors before testing
Testing
- Use MT5 Strategy Tester (Ctrl+T or View → Strategy Tester)
- Select "MAEA" from Expert Advisor dropdown
- Set testing parameters:
- Symbol: Desired currency pair
- Model: "Every tick" for accurate testing
- Period: H1 (recommended timeframe)
- Spread: Use current or specify fixed value
- Run single test: Click Start button in Strategy Tester
- Run optimization: Enable Genetic Algorithm or slow complete algorithm
- Optimization criteria: Balance, Profit Factor, Drawdown, or Sharpe Ratio
Key Testing Scenarios
- Test EMA calculations accuracy by comparing with manual calculations
- Test breakthrough signals on historical data
- Test pullback detection on ranging markets
- Test all filters individually (enable one at a time)
- Test risk management (TP, SL, breakeven, trailing stop)
- Test max drawdown protection with aggressive parameters
Code Style Guidelines
File Naming and Organization
- EA file:
MAEA.mq5(root directory) - Use #include for external functions if needed
- Keep single file structure preferred for portability
Naming Conventions
- Input parameters: PascalCase (e.g.,
EMAPeriod,LotSizeNormal,TakeProfitUSD) - Global variables: g_PascalCase (e.g.,
g_EMAHighBuffer,g_PullbackBuyDetected) - Local variables: camelCase (e.g.,
currentClose,signalDetected) - Functions: PascalCase (e.g.,
CalculateEMA(),CheckFilters(),OpenOrder()) - Constants: UPPER_CASE with underscore prefix (e.g.,
_MAX_ORDERS,_DEFAULT_TP)
Imports and Includes
- MQL5 standard headers:
(Required for MT5 position management and indicator handling)
#include <Trade\Trade.mqh> #include <Indicators\Indicators.mqh> #include <Arrays\ArrayDouble.mqh> - Use MT5 standard functions and objects:
- CTrade class for position operations
- Indicator handles via iMA()
- Position operations: PositionSelect(), PositionGetSymbol()
- Use <Trade\Trade.mqh> as it's essential for MT5 trading operations
Code Formatting
- Indentation: 4 spaces (no tabs)
- Braces: K&R style (opening brace on same line)
- Line length: Max 120 characters
- Blank line between functions
- Comment section headers like
// === INDICATOR CALCULATIONS ===
Variable Types
- Use explicit types, not auto
- Integer counts:
int - Prices and averages:
double - Boolean flags:
bool - Time values:
datetime - Array buffers:
double[] - String values:
string
Error Handling
- Always check return values for:
- CTrade.OrderOpen() - check return value
- CTrade.PositionModify() - check return value
- CTrade.PositionClose() - check return value
- Indicator handle creation - check if handle != INVALID_HANDLE
- ObjectCreate() - check return value
- Use GetLastError() after failed operations
- Log errors using Print() or Alert() for critical issues
- Example:
CTrade trade; trade.SetExpertMagicNumber(MagicNumber); if(!trade.Buy(lotSize, Symbol(), price, sl, tp)) { int err = GetLastError(); Print("OrderOpen failed. Error: ", err, " - ", ErrorDescription(err)); return; }
Input Parameters Structure
- Group related parameters together
- Use clear, descriptive comments
- Example format:
// === EMA SETTINGS === input int EMAPeriod = 30; // EMA period for all indicator lines // === RISK MANAGEMENT === input double TakeProfitUSD = 5.0; // Take profit target in USD input int BreakevenPoints = 100; // Points to trigger breakeven // === FILTERS === input bool UseMTFFilter = true; // Enable MTF filter input int MaxSpread = 30; // Maximum spread in points
Function Design
- Keep functions focused and under 40 lines if possible
- Use descriptive parameter names
- Return meaningful values (bool for success/failure when applicable)
- Document complex logic with inline comments
- Separate calculation logic from trading logic
Timezone Handling
- All time-based logic uses Thailand timezone (UTC+7)
- Use TimeGMT() + 25200 seconds for Thailand time
- Convert server time to Thailand time for news filter checks
- Document timezone conversions explicitly in code
Testing Best Practices
- Use MT5 Strategy Tester with "Every tick" model
- Test on multiple currency pairs (EURUSD, GBPUSD, XAUUSD)
- Test on different timeframes (M15, H1, H4)
- Verify indicators by visual inspection in tester
- Check both profitable and losing scenarios
- Validate filter logic by comparing tester results with expected behavior
- Paper trade on demo account before live trading
Safety Constraints
- Never change code to bypass risk management
- Test all parameter changes in Strategy Tester first
- Ensure only one position can be open at a time (MT5 uses positions, not orders)
- Drawdown protection must be always active
- Stop Loss must always be set when opening positions
- Verify position count using PositionsTotal() and filter by MagicNumber
Code Comments
- Comment complex calculations (especially EMA and Border Line formulas)
- Document edge cases and special conditions
- Include formula explanations:
// Border Line = EMA High + (EMA Medium - EMA Low) - No excessive comments for obvious code
Trading Logic Organization
- Typical entry points: OnTick() (per tick) or OnNewBar() (on new candle)
- Structure: Indicators → Filters → Signals → Orders → Risk Management
- Use state variables to track:
- Pullback detection (buy and sell separately)
- Current drawdown
- Last bar time for new bar detection
- Order tracking for management
Git Practices
- Commit after implementing each phase from the implementation plan
- Commit message format: "Phase X: Title - Brief description"
- Verify compilation before committing
- Test major features before committing
- Pull latest changes before starting new work