# MAEA (Moving Average Expert Advisor) Implementation Plan ## Project Overview - **Name**: MAEA - **Type**: MQL4 Expert Advisor for MetaTrader 4 - **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 (3 Base Lines) All EMAs use period 30 with different price sources: - **EMA High**: EMA of High prices - Light Blue color - **EMA Medium**: EMA of Close prices - Yellow color - **EMA Low**: EMA of Low prices - Orange color ### 2. Border Lines (2 Dynamic Lines) Calculated based on the range between EMAs: - **High Border Line**: EMA High + (EMA Medium - EMA Low) - Purple color - **Low Border Line**: EMA Low - (EMA Medium - EMA Low) - Purple color **Example Calculation:** ``` EMA High = 3500 EMA Medium = 3400 EMA Low = 3300 Range = EMA Medium - EMA Low = 3400 - 3300 = 100 High Border = 3500 + 100 = 3600 Low Border = 3300 - 100 = 3200 ``` ### 3. Signal Types #### 3.1 Breakthrough Signal - **Buy Signal**: Close price breaks above EMA High - **Sell Signal**: Close price breaks below EMA Low - **Purpose**: Triggers order opening #### 3.2 Pullback Signal - **Definition**: Price hits a line and closes on the opposite side - **Buy Pullback**: Price moves down to hit any line, then closes above the line - **Sell Pullback**: Price moves up to hit any line, then closes below the line - **Purpose**: Increases lot size when breakthrough occurs in the same direction - **Tracking**: Separate tracking for buy and sell directions, resets when order opens - **Lot Size Impact**: - No pullback before breakthrough = 0.01 lot - Pullback occurred before breakthrough = 0.02 lot ### 4. Order Opening Logic - **Only one order at a time** - **Lot Size**: - 0.01 lot if no pullback occurred before breakthrough - 0.02 lot if at least one pullback occurred before breakthrough in the same direction - **Trigger**: Breakthrough signal only - **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 Low Border Line - **Sell Orders**: SL at High Border Line #### 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 orders allowed - If D1 close < D1 EMA Low: Only sell orders allowed - If D1 close between D1 EMA High and D1 EMA Low: No orders allowed - **Behavior**: Order 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 ```mermaid graph TD A[Start New Bar] --> B[Calculate EMAs] B --> C[Calculate Border Lines] C --> D[Check for Open Orders] D -->|Has Open Order| E[Manage Open Order] D -->|No Open Order| F[Check Pullback Signals] E --> E1[Check Take Profit] E1 -->|TP Reached| E2[Close Order] E1 -->|TP Not Reached| E3[Check Breakeven] E3 -->|Breakeven Reached| E4[Move SL to Entry] E3 -->|Breakeven Not Reached| E5[Check Stop Loss] E5 -->|SL Hit| E2 E5 -->|SL Not Hit| A F --> F1[Close Below EMA High] F1 -->|Yes| F2[Set Pullback Flag] F1 -->|No| F3[Close Below EMA Medium] F3 -->|Yes| F2 F3 -->|No| F4[Close Below EMA Low] F4 -->|Yes| F2 F4 -->|No| F5[Check Breakthrough Signals] F2 --> F5 F5 --> F6[Close Above EMA High] F6 -->|Yes| F7[Open Buy Order] F6 -->|No| F8[Close Below EMA Low] F8 -->|Yes| F9[Open Sell Order] F8 -->|No| A F7 --> F10[Set Lot Size] F10 -->|Pullback| F11[0.02 Lot] F10 -->|No Pullback| F12[0.01 Lot] F11 --> F13[Set SL at Low Border] F12 --> F13 F13 --> F14[Set TP based on USD Target] F14 --> F15[Reset Pullback Flag] F15 --> A F9 --> F16[Set Lot Size] F16 -->|Pullback| F17[0.02 Lot] F16 -->|No Pullback| F18[0.01 Lot] F17 --> F19[Set SL at High Border] F18 --> F19 F19 --> F20[Set TP based on USD Target] F20 --> F21[Reset Pullback Flag] F21 --> A E2 --> F15 ``` ## Implementation Steps ### Phase 1: Project Setup & Git Configuration 1. Create MQL4 project structure 2. Initialize Git repository 3. Configure remote to Gitea server (https://git.moreminimore.com/kunthawat/MAEA) ### Phase 2: Core EA Structure 4. Create [`MAEA.mq4`](MAEA.mq4) with basic EA framework 5. Define all input parameters (EMA period, lot sizes, TP, breakeven, trailing stop, filters, etc.) 6. Set up indicator buffers for 5 visual lines 7. Initialize global variables for state tracking ### Phase 3: Indicator Calculations 8. Implement EMA calculations for High, Medium, Low (period 30) 9. Implement Border Line calculations (High Border = High + Range, Low Border = Low - Range) 10. Add visual indicators with correct colors (Light Blue, Yellow, Orange, Purple) 11. Implement Volume average calculation (20-bar average) ### Phase 4: Signal Detection 12. Implement breakthrough signal detection (price breaks High/Low EMA) 13. Implement pullback signal detection (price hits line and closes on opposite side) 14. Implement separate pullback tracking for buy and sell directions 15. Implement pullback flag reset logic after order opens ### Phase 5: Multiple Timeframe Filter 16. Implement D1 EMA calculations for MTF filter 17. Implement MTF filter logic (D1 > High = buy only, D1 < Low = sell only, between = no trade) 18. Add enable/disable toggle for MTF filter ### Phase 6: Additional Filters 19. Implement volume filter (current volume > 20-bar average) 20. Implement spread filter (current spread <= max spread) 21. Implement news filter (avoid specific hours/days, Thailand timezone) 22. Add enable/disable toggles for news filter ### Phase 7: Order Management 23. Implement order opening logic with all filter checks 24. Implement dynamic lot sizing (0.01 no pullback, 0.02 with pullback) 25. Implement Stop Loss placement at Border Lines 26. Implement Take Profit calculation (convert USD target to pips) 27. Implement Breakeven logic (move SL to entry at X points) 28. Implement Trailing Stop logic (trail by X points after breakeven) 29. Implement single order restriction ### Phase 8: Risk Management 30. Implement max drawdown calculation 31. Implement drawdown protection (stop trading if exceeded) 32. Implement trading resume logic when drawdown is below limit ### Phase 9: Order Monitoring & Management 33. Implement Take Profit checking on each tick 34. Implement Breakeven checking and SL modification 35. Implement Trailing Stop checking and SL modification 36. Implement Stop Loss checking 37. Implement order closure logic ### Phase 10: Testing & Validation 38. Test all EMA and Border Line calculations 39. Test breakthrough and pullback signal detection 40. Test all filters (volume, spread, MTF, news) 41. Test order opening with correct lot sizes 42. Test TP, SL, breakeven, and trailing stop 43. Test drawdown protection 44. Test visual indicators display ### Phase 11: Documentation & Deployment 45. Create comprehensive [`README.md`](README.md) with strategy documentation 46. Add parameter descriptions and usage instructions 47. Add troubleshooting guide 48. Commit initial code to Git 49. Push to Gitea repository 50. Verify repository connection and code availability ## Input Parameters | Parameter | Description | Default Value | |-----------|-------------|---------------| | `EMAPeriod` | EMA period for all lines | 30 | | `LotSizeNormal` | Lot size without pullback | 0.01 | | `LotSizePullback` | Lot size with pullback | 0.02 | | `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 | | `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 Medium | Yellow (clrYellow) | EMA of Close prices | | EMA Low | Orange (clrOrange) | EMA of Low prices | | High Border | Purple (clrPurple) | Upper dynamic border | | Low Border | Purple (clrPurple) | Lower dynamic border | ## Key Considerations 1. **Pullback Detection**: Track price hitting lines and closing on opposite side separately for buy/sell 2. **Pullback Reset**: Reset pullback flag immediately after opening an order 3. **Single Order**: Only one order open at any time 4. **Dynamic SL**: Stop Loss moves with Border Lines as they update 5. **Breakeven**: Only moves SL to entry price, not to profit 6. **TP Calculation**: Convert USD target to pips based on lot size and symbol 7. **Volume Filter**: Only trade when current volume exceeds 20-bar average 8. **MTF Filter**: D1 timeframe acts as trend filter, H1 for entry signals 9. **Spread Filter**: Avoid high spread periods 10. **Timezone**: All time-based filters use Thailand timezone (UTC+7) 11. **Trailing Stop**: Activates after breakeven, trails by specified points 12. **Drawdown Protection**: Stops trading if max drawdown exceeded ## Technical Specifications - **Platform**: MetaTrader 4 - **Language**: MQL4 - **Trading Timeframe**: H1 (recommended) - **Filter Timeframe**: D1 (for MTF filter) - **Currency Pairs**: All pairs (user-selectable) - **Account Types**: Any MT4 account type - **Server Timezone**: Thailand (UTC+7) ## Testing Checklist ### Core Strategy - [ ] EMA calculations verify correctly (High, Medium, Low) - [ ] Border Line calculations verify correctly - [ ] Breakthrough signals trigger correctly - [ ] Pullback signals detect correctly (buy and sell separately) - [ ] Pullback flag resets after order opens - [ ] Lot sizes apply correctly (0.01 vs 0.02) ### Filters - [ ] Volume filter works (20-bar average, current > average) - [ ] Spread filter prevents high spread trades - [ ] MTF filter works correctly (D1 > High = buy only, D1 < Low = sell only, between = no trade) - [ ] MTF filter can be enabled/disabled - [ ] News filter avoids specified times (Thailand timezone) - [ ] News filter can be enabled/disabled ### Order Management - [ ] Stop Loss places at correct Border Lines - [ ] Take Profit closes at correct USD amount - [ ] Breakeven triggers at correct points - [ ] Trailing stop activates after breakeven - [ ] Trailing stop trails by correct distance - [ ] Only one order opens at a time ### 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 5 visual lines on the chart - Pullback tracking is separate for buy and sell directions - Border Lines expand the range beyond the EMAs for wider stops - The strategy is trend-following and works best in trending markets - Multiple filters ensure quality trade entries - All time-based calculations use Thailand timezone (UTC+7) - MTF filter provides higher timeframe trend confirmation - Risk management features protect account from excessive losses