MQL4/.github/instructions/mt4-ea-implementation-plan.md
Rahul Dhangar 669ecde7b7 Initial commit: Documentation and MT4 EA Phases 1-3 complete
- Added comprehensive MQ4/MQ5 comparison documentation (60+ pages)
- Added MT4 EA implementation plan and tracking documents (60+ pages)
- Phase 1: Core infrastructure with input parameters and data structures
- Phase 2: Bar detection system for H4, M30, M15 timeframes
- Phase 3: Pattern detection logic (Regular/Irregular Buy/Sell patterns)
- Reference files: FINAL_H4_ZONES.mq4, MultiTimeframeZoneEA.mq5, Strategy.md
2025-11-04 01:38:41 +05:30

1100 lines
33 KiB
Markdown

# Implementation Plan: Multi-Timeframe Zone EA for MT4
**Document Version:** 1.0
**Date:** November 4, 2025
**Target Platform:** MetaTrader 4
**Language:** MQL4 (legacy compatibility)
**Strategy Source:** Strategy.md
**Reference Code:** FINAL_H4_ZONES.mq4
---
## Executive Summary
This document outlines the step-by-step implementation plan for creating a **Multi-Timeframe Zone Expert Advisor** for MetaTrader 4. The EA will implement a three-level confirmation strategy (H4 → M30 → M15) with automated trade execution, building upon the proven zone detection logic from `FINAL_H4_ZONES.mq4`.
**Key Objectives:**
1. Detect zones on H4 timeframe with reversal tracking
2. Confirm with M30 zones when price pulls back
3. Execute trades on M15 zone confirmations
4. Manage full trade lifecycle (entry, SL, TP, closure)
5. Maintain MT4 compatibility (no MQL5 constructs)
---
## Phase 1: Requirements Analysis
### 1.1 Strategy Requirements Breakdown
#### H4 Level (Primary Zone Detection)
```
REQUIREMENTS:
├─► Pattern Detection (4 types)
│ ├─► Regular Engulfing Buy
│ ├─► Irregular Engulfing Buy
│ ├─► Regular Engulfing Sell
│ └─► Irregular Engulfing Sell
├─► Zone Lifecycle Management
│ ├─► Create: Draw dashed rectangle
│ ├─► Break Detection: H4 close beyond zone
│ ├─► Reversal: Change direction + solid style
│ └─► Delete: Second break removes zone
└─► Monitoring State
├─► Track active zones
├─► Detect price entry into zones
└─► Trigger M30 monitoring
```
#### M30 Level (Confirmation)
```
REQUIREMENTS:
├─► Conditional Activation
│ └─► Only when price enters H4 zone
├─► Pattern Detection
│ ├─► Same 4 patterns as H4
│ ├─► Must match H4 direction
│ └─► Only check NEW bars after entry
├─► Zone Management
│ ├─► Create M30 zone on pattern match
│ ├─► One-break deletion (no reversal)
│ └─► Stop searching after break
└─► State Tracking
├─► Link to parent H4 zone
├─► Monitor for price entry
└─► Trigger M15 search
```
#### M15 Level (Entry Execution)
```
REQUIREMENTS:
├─► Conditional Activation
│ └─► Only when price enters M30 zone
├─► Pattern Detection
│ ├─► Same 4 patterns
│ ├─► Must match H4/M30 direction
│ └─► Only check NEW bars after entry
├─► Trade Execution
│ ├─► Buy: Limit at M15 High, SL at M15 Low
│ ├─► Sell: Limit at M15 Low, SL at M15 High
│ └─► One trade per M15 zone
└─► Order Management
├─► Place pending limit order
├─► Calculate TP from inputs
└─► Monitor order status
```
### 1.2 MT4 Constraints & Considerations
**Language Limitations:**
- ❌ No classes/objects (use structs and functions)
- ❌ No `CTrade` library (use `OrderSend()` directly)
- ❌ No `MqlRates[]` structures (use `iOpen/iClose/iHigh/iLow`)
- ❌ No dynamic arrays of complex types (use parallel arrays)
- ✅ Structs are allowed
- ✅ Global functions and variables
- ✅ Arrays with fixed or resizable simple types
**API Differences:**
- `OrderSend()` for all order types (no separate functions)
- `OrderSelect()` + `OrderModify()` for management
- Different magic number handling
- No position concept (only orders/trades)
### 1.3 Input Parameters (From Strategy.md)
```mql4
// Core Trading Parameters
input double LotSize = 0.01; // Fixed lot size for all trades
input int StopLossPips = 30; // SL distance in pips from entry
input int TakeProfitPips = 60; // TP distance in pips from entry
input int MagicNumber = 123456; // Unique EA identifier
input int Slippage = 3; // Max slippage in pips
// Zone Detection Parameters
input int RecentBarsToCheck = 10; // Bars to scan for patterns
// Display Parameters
input color BuyZoneColor = Lime; // Color for buy zones
input color SellZoneColor = Red; // Color for sell zones
input bool ShowM30Zones = true; // Display M30 zones
input bool ShowM15Zones = true; // Display M15 zones
input bool EnableDebugLogs = false; // Print debug messages
```
---
## Phase 2: Data Structure Design
### 2.1 Zone Storage Strategy
Since MT4 doesn't support dynamic arrays of structs reliably, we'll use **parallel arrays** (proven approach from FINAL_H4_ZONES.mq4):
```mql4
// Maximum zones per timeframe
#define MAX_H4_ZONES 50
#define MAX_M30_ZONES 100
#define MAX_M15_ZONES 200
// H4 Zone Data
double h4_ZoneHighs[MAX_H4_ZONES];
double h4_ZoneLows[MAX_H4_ZONES];
datetime h4_ZoneTimes[MAX_H4_ZONES];
bool h4_ZoneIsReversed[MAX_H4_ZONES];
string h4_ZoneTypes[MAX_H4_ZONES]; // "Buy", "Sell", "ReversalBuy", "ReversalSell"
bool h4_ZoneMonitoringM30[MAX_H4_ZONES]; // Is this zone monitoring M30?
datetime h4_M30MonitorStart[MAX_H4_ZONES]; // When did M30 monitoring start?
int h4_M30ChildIndex[MAX_H4_ZONES]; // Index of child M30 zone (-1 if none)
bool h4_ZoneActive[MAX_H4_ZONES]; // Is zone still active?
int h4_ZoneCount = 0; // Current H4 zone count
// M30 Zone Data
double m30_ZoneHighs[MAX_M30_ZONES];
double m30_ZoneLows[MAX_M30_ZONES];
datetime m30_ZoneTimes[MAX_M30_ZONES];
string m30_ZoneTypes[MAX_M30_ZONES]; // "Buy" or "Sell"
int m30_ParentH4Index[MAX_M30_ZONES]; // Link to parent H4 zone
bool m30_ZoneMonitoringM15[MAX_M30_ZONES];
datetime m30_M15MonitorStart[MAX_M30_ZONES];
int m30_M15ChildIndex[MAX_M30_ZONES]; // Index of child M15 zone
bool m30_ZoneActive[MAX_M30_ZONES];
int m30_ZoneCount = 0;
// M15 Zone Data
double m15_ZoneHighs[MAX_M15_ZONES];
double m15_ZoneLows[MAX_M15_ZONES];
datetime m15_ZoneTimes[MAX_M15_ZONES];
string m15_ZoneTypes[MAX_M15_ZONES];
int m15_ParentM30Index[MAX_M15_ZONES]; // Link to parent M30 zone
int m15_OrderTicket[MAX_M15_ZONES]; // Order ticket number
bool m15_OrderPlaced[MAX_M15_ZONES];
bool m15_ZoneActive[MAX_M15_ZONES];
int m15_ZoneCount = 0;
// Bar tracking for each timeframe
datetime lastH4BarTime = 0;
datetime lastM30BarTime = 0;
datetime lastM15BarTime = 0;
```
**Rationale:**
- Parallel arrays avoid struct array issues in MT4
- Each timeframe has independent storage
- Parent-child relationships via index references
- Active flags for lifecycle management
- Proven pattern from FINAL_H4_ZONES.mq4
### 2.2 Helper Structures (Limited Use)
```mql4
// Only for temporary data passing, not for storage
struct PatternInfo {
bool found;
string type; // "Buy" or "Sell"
double high;
double low;
datetime time;
int anchorIndex;
};
```
---
## Phase 3: Architecture Overview
### 3.1 Function Hierarchy
```
OnInit()
├─► InitializeArrays()
└─► CreateInfoPanel()
OnTick()
├─► CheckNewBars()
│ ├─► IsNewH4Bar()
│ ├─► IsNewM30Bar()
│ └─► IsNewM15Bar()
├─► ProcessH4()
│ ├─► DetectH4Patterns()
│ │ ├─► IsRegularBuy(i)
│ │ ├─► IsIrregularBuy(i)
│ │ ├─► IsRegularSell(i)
│ │ └─► IsIrregularSell(i)
│ ├─► CreateH4Zone(type, index)
│ └─► CheckH4Breaks()
│ ├─► DetectBreak(zoneIndex)
│ ├─► ReverseZone(zoneIndex)
│ └─► DeleteZone(zoneIndex)
├─► ProcessM30()
│ ├─► CheckPriceInH4Zones()
│ │ └─► StartM30Monitoring(h4Index)
│ ├─► DetectM30Patterns(h4Index)
│ │ └─► (Same 4 pattern functions)
│ ├─► CreateM30Zone(h4Index, type)
│ └─► CheckM30Breaks()
│ └─► DeleteM30Zone(m30Index)
├─► ProcessM15()
│ ├─► CheckPriceInM30Zones()
│ │ └─► StartM15Monitoring(m30Index)
│ ├─► DetectM15Patterns(m30Index)
│ ├─► CreateM15Zone(m30Index, type)
│ └─► PlacePendingOrder(m15Index)
│ ├─► CalculateOrderPrices()
│ └─► OrderSend()
├─► MonitorOrders()
│ ├─► CheckOrderStatus(ticket)
│ └─► ManageOpenTrades()
└─► UpdateDisplay()
├─► UpdateH4Zones()
├─► UpdateM30Zones()
├─► UpdateM15Zones()
└─► UpdateInfoPanel()
OnDeinit()
├─► CloseAllOrders()
└─► DeleteAllObjects()
```
### 3.2 Modular Design (Without Classes)
**Pattern Detection Module:**
```mql4
// Pattern detection functions (timeframe-agnostic)
bool IsRegularBuy(ENUM_TIMEFRAMES tf, int index);
bool IsIrregularBuy(ENUM_TIMEFRAMES tf, int index);
bool IsRegularSell(ENUM_TIMEFRAMES tf, int index);
bool IsIrregularSell(ENUM_TIMEFRAMES tf, int index);
PatternInfo DetectPattern(ENUM_TIMEFRAMES tf, string direction, int startIndex);
```
**Zone Management Module:**
```mql4
// H4 zone functions
int CreateH4Zone(string type, int barIndex);
void UpdateH4Zone(int zoneIndex);
bool CheckH4Break(int zoneIndex);
void ReverseH4Zone(int zoneIndex);
void DeleteH4Zone(int zoneIndex);
void DrawH4Zone(int zoneIndex);
// M30 zone functions
int CreateM30Zone(int h4ParentIndex, string type, int barIndex);
bool CheckM30Break(int zoneIndex);
void DeleteM30Zone(int zoneIndex);
void DrawM30Zone(int zoneIndex);
// M15 zone functions
int CreateM15Zone(int m30ParentIndex, string type, int barIndex);
void DrawM15Zone(int zoneIndex);
```
**Trade Management Module:**
```mql4
// Order execution
int PlacePendingOrder(int m15ZoneIndex);
bool ModifyOrder(int ticket, double sl, double tp);
void MonitorPendingOrders();
void CloseTradeIfNeeded(int ticket);
// Helper functions
double CalculateStopLoss(string type, double entryPrice);
double CalculateTakeProfit(string type, double entryPrice);
double NormalizeLots(double lots);
double NormalizePrice(double price);
```
**State Management Module:**
```mql4
// Price monitoring
bool IsPriceInZone(double price, double high, double low);
void CheckH4ZoneEntries();
void CheckM30ZoneEntries();
// Bar detection
bool IsNewBar(ENUM_TIMEFRAMES tf);
datetime GetLastBarTime(ENUM_TIMEFRAMES tf);
```
**Display Module:**
```mql4
// Visual updates
void DrawZoneRectangle(string name, datetime startTime, double high, double low,
color zoneColor, int style);
void UpdateZoneEnd(string name, datetime endTime);
void UpdateZoneStyle(string name, color newColor, int newStyle);
void DeleteZoneObjects(string baseName);
// Info panel
void CreateInfoPanel();
void UpdateInfoPanel();
string GetPanelText();
```
---
## Phase 4: Implementation Steps
### Step 1: Core Infrastructure (Foundation)
**Files to Create:**
- `MultiTimeframeZoneEA_MT4.mq4` (main EA file)
**Tasks:**
1. Define all global variables and arrays
2. Implement `OnInit()`:
- Initialize arrays to zero/default values
- Set up bar time trackers
- Create info panel placeholder
3. Implement `OnDeinit()`:
- Delete all chart objects
- Close any open orders (optional based on strategy)
4. Implement basic `OnTick()` skeleton
5. Add input parameters with validation
**Testing:** Compile successfully, attach to chart, verify no errors
---
### Step 2: Bar Detection System
**Tasks:**
1. Implement `IsNewBar()` function:
```mql4
bool IsNewBar(ENUM_TIMEFRAMES tf) {
datetime currentBar = iTime(Symbol(), tf, 0);
datetime lastBar = GetLastBarTime(tf);
if (currentBar != lastBar) {
SetLastBarTime(tf, currentBar);
return true;
}
return false;
}
```
2. Implement bar time getters/setters for H4, M30, M15
3. Add debug logging for bar detection
**Testing:** Attach to chart, verify correct bar detection on all timeframes
---
### Step 3: Pattern Detection (Port from MQ4 Indicator)
**Tasks:**
1. Copy and adapt pattern functions from `FINAL_H4_ZONES.mq4`:
- `IsRegularBuy()`
- `IsIrregularBuy()`
- `IsRegularSell()`
- `IsIrregularSell()`
2. Make them work with any timeframe (add `ENUM_TIMEFRAMES` parameter)
3. Create wrapper function `DetectPattern()` that tries all 4 patterns
4. Add comprehensive logging for detected patterns
**Testing:**
- Run on H4 chart, verify patterns detected correctly
- Compare with original FINAL_H4_ZONES.mq4 output
- Test on M30 and M15 timeframes
---
### Step 4: H4 Zone Management
**Tasks:**
1. Implement `CreateH4Zone()`:
- Add to arrays at next available index
- Draw dashed rectangle
- Initialize monitoring flags
2. Implement `DrawH4Zone()`:
- Use `ObjectCreate()` with `OBJ_RECTANGLE`
- Set color, style, ray right
3. Implement `CheckH4Breaks()`:
- Loop all active H4 zones
- Check if H4 close broke zone
- Call `ReverseH4Zone()` or `DeleteH4Zone()`
4. Implement zone lifecycle functions:
- `ReverseH4Zone()`: Flip direction, change style to solid
- `DeleteH4Zone()`: Remove objects, mark inactive
**Testing:**
- Verify zones draw correctly
- Test break detection (manual chart manipulation)
- Verify reversals change style
- Verify second break deletes zone
---
### Step 5: M30 Monitoring & Zone Creation
**Tasks:**
1. Implement `CheckH4ZoneEntries()`:
```mql4
void CheckH4ZoneEntries() {
double currentPrice = (Bid + Ask) / 2;
for (int i = 0; i < h4_ZoneCount; i++) {
if (!h4_ZoneActive[i]) continue;
if (h4_ZoneMonitoringM30[i]) continue; // Already monitoring
if (h4_M30ChildIndex[i] >= 0) continue; // Already has child
if (IsPriceInZone(currentPrice, h4_ZoneHighs[i], h4_ZoneLows[i])) {
h4_ZoneMonitoringM30[i] = true;
h4_M30MonitorStart[i] = iTime(Symbol(), PERIOD_M30, 0);
LogEvent("H4 Zone entered, starting M30 monitoring");
}
}
}
```
2. Implement `ProcessM30()`:
- For each H4 zone monitoring M30
- Only check bars AFTER monitor start time
- Detect pattern matching H4 direction
- Create M30 zone on match
3. Implement `CreateM30Zone()`:
- Link to parent H4 zone
- Draw zone on chart
4. Implement `CheckM30Breaks()`:
- One break = immediate deletion
- No reversal logic
**Testing:**
- Verify M30 monitoring starts when price enters H4 zone
- Verify only new bars checked (not historical)
- Verify M30 zone created correctly
- Verify break deletes M30 zone
---
### Step 6: M15 Entry & Order Placement
**Tasks:**
1. Implement `CheckM30ZoneEntries()`:
- Similar to H4 logic
- Start M15 monitoring when price enters M30 zone
2. Implement `ProcessM15()`:
- Detect M15 pattern matching direction
- Create M15 zone
- Immediately place pending order
3. Implement `PlacePendingOrder()`:
```mql4
int PlacePendingOrder(int m15Index) {
string type = m15_ZoneTypes[m15Index];
double entryPrice, sl, tp;
int orderType;
if (type == "Buy") {
entryPrice = m15_ZoneHighs[m15Index];
sl = m15_ZoneLows[m15Index] - (StopLossPips * Point);
tp = entryPrice + (TakeProfitPips * Point);
orderType = OP_BUYLIMIT;
} else {
entryPrice = m15_ZoneLows[m15Index];
sl = m15_ZoneHighs[m15Index] + (StopLossPips * Point);
tp = entryPrice - (TakeProfitPips * Point);
orderType = OP_SELLLIMIT;
}
entryPrice = NormalizeDouble(entryPrice, Digits);
sl = NormalizeDouble(sl, Digits);
tp = NormalizeDouble(tp, Digits);
int ticket = OrderSend(Symbol(), orderType, LotSize, entryPrice,
Slippage, sl, tp, "MTZ_EA", MagicNumber, 0, clrNONE);
if (ticket > 0) {
m15_OrderTicket[m15Index] = ticket;
m15_OrderPlaced[m15Index] = true;
LogEvent("Order placed: Ticket " + IntegerToString(ticket));
return ticket;
} else {
LogEvent("Order failed: " + GetLastError());
return -1;
}
}
```
4. Implement order calculation helpers:
- `NormalizePrice()`: Round to symbol digits
- `NormalizeLots()`: Round to lot step
- `CalculateStopLoss()`: From strategy rules
- `CalculateTakeProfit()`: From input parameters
**Testing:**
- Verify M15 zone created correctly
- Verify pending order placed immediately
- Verify order prices are correct (entry, SL, TP)
- Test order placement failure handling
---
### Step 7: Order Monitoring & Management
**Tasks:**
1. Implement `MonitorPendingOrders()`:
```mql4
void MonitorPendingOrders() {
for (int i = 0; i < m15_ZoneCount; i++) {
if (!m15_OrderPlaced[i]) continue;
int ticket = m15_OrderTicket[i];
if (!OrderSelect(ticket, SELECT_BY_TICKET)) continue;
// Check if order filled
if (OrderType() == OP_BUY || OrderType() == OP_SELL) {
LogEvent("Order filled: Ticket " + IntegerToString(ticket));
// Trade is now active, manage via normal trade management
}
// Check if order was deleted/cancelled
if (OrderCloseTime() > 0) {
m15_OrderPlaced[i] = false;
LogEvent("Order closed/cancelled: Ticket " + IntegerToString(ticket));
}
}
}
```
2. Implement optional trade management:
- Trailing stop (if desired)
- Breakeven move (if desired)
- Partial close (if desired)
3. Add order cleanup on zone breaks:
- If H4 zone breaks, cancel related M15 orders
- If M30 zone breaks, cancel child M15 order
**Testing:**
- Verify order status tracked correctly
- Test order fill detection
- Test order cancellation on zone breaks
---
### Step 8: Visual Display System
**Tasks:**
1. Implement zone drawing functions:
```mql4
void DrawZone(string name, datetime startTime, double high, double low,
color zoneColor, int style, string label) {
if (ObjectFind(name) >= 0) {
ObjectMove(name, 1, TimeCurrent(), low); // Update end time
} else {
ObjectCreate(name, OBJ_RECTANGLE, 0, startTime, high, TimeCurrent(), low);
ObjectSet(name, OBJPROP_COLOR, zoneColor);
ObjectSet(name, OBJPROP_STYLE, style);
ObjectSet(name, OBJPROP_WIDTH, 1);
ObjectSet(name, OBJPROP_BACK, false);
ObjectSet(name, OBJPROP_RAY, true);
ObjectSetText(name, label);
}
}
```
2. Implement info panel:
- Show active zone counts (H4, M30, M15)
- Show monitoring status
- Show active orders
- Show account info (balance, equity, P&L)
3. Update all zones on each tick (extend end time)
**Testing:**
- Verify zones visible on all timeframes
- Verify colors and styles correct
- Test zone updates (reversals, deletions)
- Verify info panel accuracy
---
### Step 9: Error Handling & Validation
**Tasks:**
1. Add array bounds checking:
```mql4
int CreateH4Zone(string type, int barIndex) {
if (h4_ZoneCount >= MAX_H4_ZONES) {
LogEvent("ERROR: H4 zone limit reached!");
return -1;
}
// ... rest of function
}
```
2. Add order validation:
- Check free margin before OrderSend
- Validate lot size is within limits
- Verify prices are within allowed distance
3. Add error logging:
- Log all OrderSend failures with error codes
- Log zone creation failures
- Log invalid states
4. Add input parameter validation in `OnInit()`:
- LotSize > 0
- StopLossPips > 0
- TakeProfitPips > 0
**Testing:**
- Test with insufficient margin
- Test with invalid lot sizes
- Test array limit reached
- Verify error messages clear
---
### Step 10: Testing & Optimization
**Tasks:**
1. **Strategy Tester Validation:**
- Run on H4 chart with visual mode
- Verify all three timeframe levels work
- Check order placement accuracy
- Review trade results
2. **Edge Case Testing:**
- Multiple H4 zones active simultaneously
- Rapid zone reversals
- Orders pending when zone breaks
- High volatility scenarios
3. **Performance Optimization:**
- Minimize chart object operations
- Optimize loop iterations
- Cache frequently used values
4. **Code Cleanup:**
- Add comprehensive comments
- Organize functions logically
- Remove debug code (or make conditional)
**Testing:**
- Backtest on 3+ months of data
- Visual mode to verify logic
- Compare with manual trading expectations
---
## Phase 5: Critical Implementation Notes
### 5.1 MT4-Specific Considerations
**Order Types:**
```mql4
// Buy Limit = buy when price comes DOWN to level
OP_BUYLIMIT // Entry below current price
OP_SELLLIMIT // Entry above current price
// BUT: Strategy says "place limit at zone high/low"
// If price is INSIDE zone, we need:
// - Buy: Entry at HIGH (price must go up) = BUY STOP
// - Sell: Entry at LOW (price must go down) = SELL STOP
// CORRECTION FOR STRATEGY:
if (type == "Buy") {
orderType = OP_BUYSTOP; // Entry above current price
} else {
orderType = OP_SELLSTOP; // Entry below current price
}
```
**Price Normalization:**
```mql4
double NormalizePrice(double price) {
return NormalizeDouble(price, Digits);
}
double NormalizeLots(double lots) {
double minLot = MarketInfo(Symbol(), MODE_MINLOT);
double maxLot = MarketInfo(Symbol(), MODE_MAXLOT);
double lotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
lots = MathMax(lots, minLot);
lots = MathMin(lots, maxLot);
lots = NormalizeDouble(lots / lotStep, 0) * lotStep;
return lots;
}
```
**Point vs Pips:**
```mql4
double PipsToPoints(int pips) {
if (Digits == 3 || Digits == 5) {
return pips * 10 * Point; // 5-digit broker
}
return pips * Point; // 4-digit broker
}
```
### 5.2 Strategy Interpretation Clarifications
**"Place limit order" Correction:**
- Strategy says "Buy Limit at High" and "Sell Limit at Low"
- This is incorrect for limit orders (limit buys below price, sells above)
- **CORRECTED:** Use **Buy Stop** at High and **Sell Stop** at Low
- This matches the strategy intent (breakout entry)
**"Stop Loss at zone boundary":**
- Strategy says SL at opposite zone boundary
- Additional buffer from `StopLossPips` input
- **Implementation:** SL = zone boundary ± (StopLossPips × Point)
**"Only monitor new bars":**
- Critical for M30 and M15 levels
- Track `M30MonitorStart` and `M15MonitorStart` times
- Only check bars with `time >= monitorStartTime`
### 5.3 Debugging Strategy
**Enable Comprehensive Logging:**
```mql4
void LogEvent(string message) {
if (EnableDebugLogs) {
Print(TimeToString(TimeCurrent(), TIME_DATE|TIME_MINUTES), " | ", message);
}
}
// Usage throughout code:
LogEvent("H4: Buy pattern detected at bar " + IntegerToString(i));
LogEvent("M30: Monitoring started for H4 zone #" + IntegerToString(h4Index));
LogEvent("M15: Order placed - Ticket: " + IntegerToString(ticket));
```
**Visual Debugging:**
- Use different colors for each zone level
- Add text labels showing zone info
- Display monitoring status on chart
---
## Phase 6: File Structure & Organization
### 6.1 Main EA File Structure
```mql4
//+------------------------------------------------------------------+
//| MultiTimeframeZoneEA_MT4.mq4 |
//| _Thivyam Trading |
//| Version: 1.0 |
//+------------------------------------------------------------------+
#property copyright "_Thivyam Trading Systems"
#property link "https://www.rahuldhangar.com"
#property version "1.00"
#property strict
//+------------------------------------------------------------------+
//| INPUT PARAMETERS |
//+------------------------------------------------------------------+
// [All inputs here]
//+------------------------------------------------------------------+
//| GLOBAL CONSTANTS |
//+------------------------------------------------------------------+
#define MAX_H4_ZONES 50
#define MAX_M30_ZONES 100
#define MAX_M15_ZONES 200
//+------------------------------------------------------------------+
//| GLOBAL VARIABLES - H4 ZONES |
//+------------------------------------------------------------------+
// [All H4 arrays]
//+------------------------------------------------------------------+
//| GLOBAL VARIABLES - M30 ZONES |
//+------------------------------------------------------------------+
// [All M30 arrays]
//+------------------------------------------------------------------+
//| GLOBAL VARIABLES - M15 ZONES |
//+------------------------------------------------------------------+
// [All M15 arrays]
//+------------------------------------------------------------------+
//| GLOBAL VARIABLES - STATE TRACKING |
//+------------------------------------------------------------------+
// [Bar times, etc.]
//+------------------------------------------------------------------+
//| INITIALIZATION |
//+------------------------------------------------------------------+
int OnInit() { }
//+------------------------------------------------------------------+
//| DEINITIALIZATION |
//+------------------------------------------------------------------+
void OnDeinit(const int reason) { }
//+------------------------------------------------------------------+
//| MAIN TICK HANDLER |
//+------------------------------------------------------------------+
void OnTick() { }
//+------------------------------------------------------------------+
//| SECTION: BAR DETECTION |
//+------------------------------------------------------------------+
// [Bar detection functions]
//+------------------------------------------------------------------+
//| SECTION: PATTERN DETECTION |
//+------------------------------------------------------------------+
// [Pattern functions]
//+------------------------------------------------------------------+
//| SECTION: H4 ZONE MANAGEMENT |
//+------------------------------------------------------------------+
// [H4 functions]
//+------------------------------------------------------------------+
//| SECTION: M30 ZONE MANAGEMENT |
//+------------------------------------------------------------------+
// [M30 functions]
//+------------------------------------------------------------------+
//| SECTION: M15 ZONE MANAGEMENT |
//+------------------------------------------------------------------+
// [M15 functions]
//+------------------------------------------------------------------+
//| SECTION: TRADE EXECUTION |
//+------------------------------------------------------------------+
// [Order functions]
//+------------------------------------------------------------------+
//| SECTION: VISUAL DISPLAY |
//+------------------------------------------------------------------+
// [Drawing functions]
//+------------------------------------------------------------------+
//| SECTION: UTILITY FUNCTIONS |
//+------------------------------------------------------------------+
// [Helpers]
```
### 6.2 File Location
```
MQL4/
└── Experts/
└── _Thivyam/
└── MultiTimeframeZone/
└── MultiTimeframeZoneEA_MT4.mq4
```
---
## Phase 7: Testing Checklist
### 7.1 Unit Testing (Per Phase)
- [ ] **Phase 2:** Bar detection works on all timeframes
- [ ] **Phase 3:** Patterns detected correctly vs indicator
- [ ] **Phase 4:** H4 zones create, reverse, delete properly
- [ ] **Phase 5:** M30 monitoring starts on H4 entry
- [ ] **Phase 5:** M30 zones created correctly
- [ ] **Phase 6:** M15 monitoring starts on M30 entry
- [ ] **Phase 6:** M15 zones created correctly
- [ ] **Phase 6:** Orders placed with correct parameters
- [ ] **Phase 7:** Orders monitored and managed
- [ ] **Phase 8:** All zones visible and accurate
### 7.2 Integration Testing
- [ ] Full H4 → M30 → M15 cascade works
- [ ] Multiple concurrent H4 zones handled
- [ ] Zone breaks cancel related orders
- [ ] Reversals don't affect existing M30/M15 zones
- [ ] Orders placed only once per M15 zone
### 7.3 Strategy Tester Scenarios
**Test Case 1: Simple Buy Setup**
1. H4 buy pattern detected
2. Price pulls back into H4 zone
3. M30 buy pattern forms
4. Price pulls back into M30 zone
5. M15 buy pattern forms
6. Order placed at M15 high
7. Order fills and hits TP
**Test Case 2: H4 Reversal**
1. H4 buy zone created
2. H4 zone breaks (no M30 child yet)
3. Zone reverses to sell
4. New sell M30 zone detected
**Test Case 3: Multiple Concurrent Zones**
1. Multiple H4 zones active
2. Each monitoring independently
3. M30 zones link to correct parents
4. Orders placed correctly for each
**Test Case 4: Zone Break Cascade**
1. Full H4 → M30 → M15 setup
2. Order pending
3. H4 zone breaks
4. Verify order cancelled
### 7.4 Visual Verification
- [ ] H4 zones visible on H4, M30, M15 charts
- [ ] M30 zones visible on M30, M15 charts
- [ ] M15 zones visible on M15 chart
- [ ] Colors correct (buy=lime, sell=red)
- [ ] Styles correct (dashed → solid on reversal)
- [ ] Info panel shows accurate data
---
## Phase 8: Risk Considerations
### 8.1 Known Limitations
1. **Array Size Limits:**
- Max 50 H4 zones (should be sufficient)
- Max 100 M30 zones
- Max 200 M15 zones
- Risk: If limits reached, new zones won't create
2. **Order Execution:**
- No slippage protection beyond input parameter
- No re-quote handling
- Market conditions may prevent order placement
3. **No Position Sizing:**
- Fixed lot size only
- No dynamic risk management
- User must calculate appropriate lot size
4. **No Trade Management:**
- No trailing stop
- No breakeven
- No partial close
- Only initial SL/TP
### 8.2 Safety Features
1. **Magic Number Filtering:**
- EA only manages its own orders
- Won't interfere with other EAs/manual trades
2. **One Trade Per Zone:**
- Flag prevents duplicate orders
- Prevents over-trading
3. **Input Validation:**
- Check all inputs in OnInit
- Prevent invalid parameter combinations
4. **Error Logging:**
- All failures logged to Journal
- Helps diagnose issues
---
## Phase 9: Future Enhancements (Post-MVP)
### 9.1 Potential Improvements
1. **Dynamic Position Sizing:**
- Add risk % input
- Calculate lots based on SL distance
2. **Advanced Trade Management:**
- Trailing stop option
- Breakeven move option
- Partial close at 1R, 2R, etc.
3. **Multi-Symbol Support:**
- Run on multiple charts simultaneously
- Centralized order management
4. **Session Filters:**
- Only trade during specific hours
- Avoid news times
5. **Pattern Filters:**
- Minimum zone size
- Maximum zone age
- Trend confirmation
### 9.2 Code Improvements
1. **Separate Include Files:**
- Break into multiple .mqh files
- Easier maintenance
- Reusable components
2. **Configuration File:**
- External settings
- Easier testing/optimization
3. **Performance Optimization:**
- Reduce redundant calculations
- Cache symbol info
- Optimize loops
---
## Phase 10: Success Criteria
### 10.1 Functional Requirements
- ✅ Detects all 4 pattern types on H4
- ✅ Creates H4 zones with correct lifecycle
- ✅ Monitors M30 when price enters H4 zone
- ✅ Creates M30 zones matching H4 direction
- ✅ Monitors M15 when price enters M30 zone
- ✅ Creates M15 zones matching M30 direction
- ✅ Places pending orders at M15 zone boundaries
- ✅ Sets correct SL and TP
- ✅ Manages order lifecycle
- ✅ Cancels orders when parent zones break
- ✅ Handles zone reversals correctly
### 10.2 Quality Requirements
- ✅ Compiles without errors or warnings
- ✅ No runtime errors in Strategy Tester
- ✅ All zones visible and accurate
- ✅ Orders placed with correct parameters
- ✅ Backtest results match expectations
- ✅ Code is readable and documented
- ✅ Debug logs are comprehensive
### 10.3 Performance Requirements
- ✅ OnTick executes in < 10ms average
- ✅ No memory leaks (stable over days)
- ✅ Handles 50+ concurrent zones
- ✅ Works on 4 and 5-digit brokers
---
## Conclusion
This implementation plan provides a comprehensive roadmap for creating the Multi-Timeframe Zone EA for MT4. The phased approach ensures:
1. **Solid Foundation:** Core infrastructure first
2. **Incremental Testing:** Each phase validated before proceeding
3. **MT4 Compatibility:** No MQL5 constructs used
4. **Strategy Compliance:** Follows Strategy.md requirements
5. **Maintainability:** Clear organization and documentation
**Estimated Development Time:** 20-30 hours
- Phase 1-2: 2 hours
- Phase 3-4: 4 hours
- Phase 5-6: 6 hours
- Phase 7-8: 4 hours
- Phase 9-10: 4 hours
- Testing: 4-10 hours
**Next Steps:**
1. Review and approve this plan
2. Begin Phase 1 implementation
3. Test each phase thoroughly
4. Proceed to next phase only when previous is validated
5. Final integration testing
6. Deploy to demo account for live validation
---
**Document Status:** Ready for Implementation
**Approval Required:** Yes
**Risk Level:** Medium (new codebase, complex logic)
**Recommended Approach:** Phased development with continuous testing
---
**End of Implementation Plan**