commit 7c7c118c5f5ea485c68cb5b25d8c1689294802e0 Author: Kunthawat Greethong Date: Fri Jan 2 11:13:52 2026 +0700 Initial commit: MAEA Expert Advisor v1.00 - Implemented complete trend-following strategy with EMA-based signals - Added 5 visual indicator lines (3 EMAs + 2 Border Lines) - Implemented breakthrough and pullback signal detection - Added dynamic lot sizing (0.01/0.02 based on pullback) - Implemented comprehensive filters: * Volume filter (20-bar average) * Spread filter (max 30 points) * Multiple Timeframe filter (H1 trading, D1 trend confirmation) * News filter (Thailand timezone) - Added advanced risk management: * Take Profit in USD * Stop Loss at Border Lines * Breakeven (100 points) * Trailing Stop (100 points) * Max drawdown protection (10%) - Created comprehensive documentation - Connected to Gitea repository diff --git a/MAEA.mq4 b/MAEA.mq4 new file mode 100644 index 0000000..da24601 --- /dev/null +++ b/MAEA.mq4 @@ -0,0 +1,775 @@ +//+------------------------------------------------------------------+ +//| MAEA.mq4 | +//| Moving Average Expert Advisor | +//| Advanced Trend-Following Strategy | +//+------------------------------------------------------------------+ +#property copyright "MAEA" +#property link "https://git.moreminimore.com/kunthawat/MAEA" +#property version "1.00" +#property strict +#property indicator_chart_window + +//--- Indicator buffers +#property indicator_buffers 5 +#property indicator_plots 5 + +//--- Plot settings for EMA High +#property indicator_label1 "EMA High" +#property indicator_type1 DRAW_LINE +#property indicator_color1 clrLightBlue +#property indicator_style1 STYLE_SOLID +#property indicator_width1 2 + +//--- Plot settings for EMA Medium +#property indicator_label2 "EMA Medium" +#property indicator_type2 DRAW_LINE +#property indicator_color2 clrYellow +#property indicator_style2 STYLE_SOLID +#property indicator_width2 2 + +//--- Plot settings for EMA Low +#property indicator_label3 "EMA Low" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrOrange +#property indicator_style3 STYLE_SOLID +#property indicator_width3 2 + +//--- Plot settings for High Border +#property indicator_label4 "High Border" +#property indicator_type4 DRAW_LINE +#property indicator_color4 clrPurple +#property indicator_style4 STYLE_DASH +#property indicator_width4 1 + +//--- Plot settings for Low Border +#property indicator_label5 "Low Border" +#property indicator_type5 DRAW_LINE +#property indicator_color5 clrPurple +#property indicator_style5 STYLE_DASH +#property indicator_width5 1 + +//+------------------------------------------------------------------+ +//| Input Parameters | +//+------------------------------------------------------------------+ +input string Section1 = "=== EMA Settings ==="; +input int EMAPeriod = 30; // EMA Period for all lines + +input string Section2 = "=== Lot Settings ==="; +input double LotSizeNormal = 0.01; // Lot size without pullback +input double LotSizePullback = 0.02; // Lot size with pullback + +input string Section3 = "=== Risk Management ==="; +input double TakeProfitUSD = 5.0; // Take Profit target in USD +input int BreakevenPoints = 100; // Points to trigger breakeven +input int TrailingStopPoints = 100; // Trailing stop distance +input double MaxDrawdownPercent = 10.0;// Max drawdown percentage + +input string Section4 = "=== Filters ==="; +input int MaxSpread = 30; // Maximum allowed spread in points +input int VolumePeriod = 20; // Period for volume average +input bool UseMTFFilter = true; // Enable MTF filter +input bool UseNewsFilter = true; // Enable news filter +input string NewsAvoidHours = "14,15,20,21"; // Hours to avoid (Thailand time) +input string NewsAvoidDays = "1,5"; // Days to avoid (Monday=1, Friday=5) + +input string Section5 = "=== General ==="; +input int MagicNumber = 12345; // EA unique identifier + +//+------------------------------------------------------------------+ +//| Global Variables | +//+------------------------------------------------------------------+ +// Indicator buffers +double EMAHighBuffer[]; +double EMAMediumBuffer[]; +double EMALowBuffer[]; +double HighBorderBuffer[]; +double LowBorderBuffer[]; + +// EMA handles +int EMAHighHandle; +int EMAMediumHandle; +int EMALowHandle; + +// D1 EMA handles for MTF filter +int D1_EMAHighHandle; +int D1_EMAMediumHandle; +int D1_EMALowHandle; + +// State tracking +bool PullbackBuy = false; +bool PullbackSell = false; +bool BreakevenTriggered = false; +double OrderOpenPrice = 0; +double OrderStopLoss = 0; +double OrderTakeProfit = 0; +int OrderTicket = 0; + +// Drawdown tracking +double AccountEquityPeak = 0; + +// Previous bar values for signal detection +double PrevClose = 0; +double PrevEMAHigh = 0; +double PrevEMAMedium = 0; +double PrevEMALow = 0; + +// News filter arrays +int AvoidHoursArray[]; +int AvoidDaysArray[]; + +//+------------------------------------------------------------------+ +//| Custom indicator initialization function | +//+------------------------------------------------------------------+ +int OnInit() +{ + // Set indicator buffers + SetIndexBuffer(0, EMAHighBuffer); + SetIndexBuffer(1, EMAMediumBuffer); + SetIndexBuffer(2, EMALowBuffer); + SetIndexBuffer(3, HighBorderBuffer); + SetIndexBuffer(4, LowBorderBuffer); + + // Set indicator labels + PlotIndexSetString(0, PLOT_LABEL, "EMA High"); + PlotIndexSetString(1, PLOT_LABEL, "EMA Medium"); + PlotIndexSetString(2, PLOT_LABEL, "EMA Low"); + PlotIndexSetString(3, PLOT_LABEL, "High Border"); + PlotIndexSetString(4, PLOT_LABEL, "Low Border"); + + // Initialize EMA handles + EMAHighHandle = iMA(Symbol(), PERIOD_CURRENT, EMAPeriod, 0, MODE_EMA, PRICE_HIGH); + EMAMediumHandle = iMA(Symbol(), PERIOD_CURRENT, EMAPeriod, 0, MODE_EMA, PRICE_CLOSE); + EMALowHandle = iMA(Symbol(), PERIOD_CURRENT, EMAPeriod, 0, MODE_EMA, PRICE_LOW); + + // Initialize D1 EMA handles for MTF filter + D1_EMAHighHandle = iMA(Symbol(), PERIOD_D1, EMAPeriod, 0, MODE_EMA, PRICE_HIGH); + D1_EMAMediumHandle = iMA(Symbol(), PERIOD_D1, EMAPeriod, 0, MODE_EMA, PRICE_CLOSE); + D1_EMALowHandle = iMA(Symbol(), PERIOD_D1, EMAPeriod, 0, MODE_EMA, PRICE_LOW); + + // Check handles + if(EMAHighHandle == INVALID_HANDLE || EMAMediumHandle == INVALID_HANDLE || EMALowHandle == INVALID_HANDLE) + { + Print("Error creating EMA handles"); + return(INIT_FAILED); + } + + if(UseMTFFilter && (D1_EMAHighHandle == INVALID_HANDLE || D1_EMAMediumHandle == INVALID_HANDLE || D1_EMALowHandle == INVALID_HANDLE)) + { + Print("Error creating D1 EMA handles"); + return(INIT_FAILED); + } + + // Parse news filter arrays + ParseNewsFilterArrays(); + + // Initialize account equity peak + AccountEquityPeak = AccountEquity(); + + Print("MAEA initialized successfully"); + return(INIT_SUCCEEDED); +} + +//+------------------------------------------------------------------+ +//| Custom indicator deinitialization function | +//+------------------------------------------------------------------+ +void OnDeinit(const int reason) +{ + // Release indicator handles + if(EMAHighHandle != INVALID_HANDLE) IndicatorRelease(EMAHighHandle); + if(EMAMediumHandle != INVALID_HANDLE) IndicatorRelease(EMAMediumHandle); + if(EMALowHandle != INVALID_HANDLE) IndicatorRelease(EMALowHandle); + if(D1_EMAHighHandle != INVALID_HANDLE) IndicatorRelease(D1_EMAHighHandle); + if(D1_EMAMediumHandle != INVALID_HANDLE) IndicatorRelease(D1_EMAMediumHandle); + if(D1_EMALowHandle != INVALID_HANDLE) IndicatorRelease(D1_EMALowHandle); + + Print("MAEA deinitialized"); +} + +//+------------------------------------------------------------------+ +//| Custom indicator iteration function | +//+------------------------------------------------------------------+ +int OnCalculate(const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[]) +{ + // Check for minimum bars + if(rates_total < EMAPeriod + 1) return(0); + + // Set arrays as series + ArraySetAsSeries(EMAHighBuffer, false); + ArraySetAsSeries(EMAMediumBuffer, false); + ArraySetAsSeries(EMALowBuffer, false); + ArraySetAsSeries(HighBorderBuffer, false); + ArraySetAsSeries(LowBorderBuffer, false); + + // Calculate start position + int start; + if(prev_calculated == 0) + { + start = EMAPeriod; + // Initialize buffers + for(int i = 0; i < start; i++) + { + EMAHighBuffer[i] = 0; + EMAMediumBuffer[i] = 0; + EMALowBuffer[i] = 0; + HighBorderBuffer[i] = 0; + LowBorderBuffer[i] = 0; + } + } + else + { + start = prev_calculated - 1; + } + + // Calculate EMA values and border lines + for(int i = start; i < rates_total; i++) + { + // Get EMA values + double emaHigh = GetEMAValue(EMAHighHandle, i); + double emaMedium = GetEMAValue(EMAMediumHandle, i); + double emaLow = GetEMAValue(EMALowHandle, i); + + // Calculate range + double range = emaMedium - emaLow; + + // Calculate border lines + double highBorder = emaHigh + range; + double lowBorder = emaLow - range; + + // Store values in buffers + EMAHighBuffer[i] = emaHigh; + EMAMediumBuffer[i] = emaMedium; + EMALowBuffer[i] = emaLow; + HighBorderBuffer[i] = highBorder; + LowBorderBuffer[i] = lowBorder; + } + + // Only process trading logic on new bar + static datetime lastBarTime = 0; + if(time[rates_total - 1] != lastBarTime) + { + lastBarTime = time[rates_total - 1]; + + // Update previous bar values + int lastBar = rates_total - 1; + int prevBar = rates_total - 2; + + if(prevBar >= EMAPeriod) + { + PrevClose = close[prevBar]; + PrevEMAHigh = EMAHighBuffer[prevBar]; + PrevEMAMedium = EMAMediumBuffer[prevBar]; + PrevEMALow = EMALowBuffer[prevBar]; + + // Process trading logic + ProcessTradingLogic(rates_total, time, open, high, low, close, tick_volume, spread); + } + } + + // Manage open orders on every tick + ManageOpenOrders(); + + return(rates_total); +} + +//+------------------------------------------------------------------+ +//| Get EMA value from handle | +//+------------------------------------------------------------------+ +double GetEMAValue(int handle, int shift) +{ + double value[]; + ArraySetAsSeries(value, true); + CopyBuffer(handle, 0, shift, 1, value); + return(value[0]); +} + +//+------------------------------------------------------------------+ +//| Parse news filter arrays | +//+------------------------------------------------------------------+ +void ParseNewsFilterArrays() +{ + // Parse hours + string hoursStr = NewsAvoidHours; + ArrayResize(AvoidHoursArray, 0); + while(hoursStr != "") + { + int pos = StringFind(hoursStr, ","); + string hourStr; + if(pos >= 0) + { + hourStr = StringSubstr(hoursStr, 0, pos); + hoursStr = StringSubstr(hoursStr, pos + 1); + } + else + { + hourStr = hoursStr; + hoursStr = ""; + } + StringTrimLeft(hourStr); + StringTrimRight(hourStr); + if(hourStr != "") + { + int hour = (int)StringToInteger(hourStr); + int size = ArraySize(AvoidHoursArray); + ArrayResize(AvoidHoursArray, size + 1); + AvoidHoursArray[size] = hour; + } + } + + // Parse days + string daysStr = NewsAvoidDays; + ArrayResize(AvoidDaysArray, 0); + while(daysStr != "") + { + int pos = StringFind(daysStr, ","); + string dayStr; + if(pos >= 0) + { + dayStr = StringSubstr(daysStr, 0, pos); + daysStr = StringSubstr(daysStr, pos + 1); + } + else + { + dayStr = daysStr; + daysStr = ""; + } + StringTrimLeft(dayStr); + StringTrimRight(dayStr); + if(dayStr != "") + { + int day = (int)StringToInteger(dayStr); + int size = ArraySize(AvoidDaysArray); + ArrayResize(AvoidDaysArray, size + 1); + AvoidDaysArray[size] = day; + } + } +} + +//+------------------------------------------------------------------+ +//| Process trading logic | +//+------------------------------------------------------------------+ +void ProcessTradingLogic(const int rates_total, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const int &spread[]) +{ + // Check if we have an open order + if(HasOpenOrder()) return; + + // Check drawdown + if(!CheckDrawdown()) return; + + // Check news filter + if(UseNewsFilter && !CheckNewsFilter(time[rates_total - 1])) return; + + // Check spread filter + if(spread[rates_total - 1] > MaxSpread) return; + + // Check volume filter + if(!CheckVolumeFilter(tick_volume, rates_total)) return; + + // Check MTF filter + if(UseMTFFilter && !CheckMTFFilter()) return; + + // Get current values + int lastBar = rates_total - 1; + double currentClose = close[lastBar]; + double currentEMAHigh = EMAHighBuffer[lastBar]; + double currentEMALow = EMALowBuffer[lastBar]; + + // Detect pullback signals + DetectPullbackSignals(currentClose, currentEMAHigh, PrevEMAHigh, currentEMALow, PrevEMALow, PrevEMAMedium); + + // Detect breakthrough signals + if(DetectBreakthroughBuy(currentClose, currentEMAHigh, PrevClose, PrevEMAHigh)) + { + OpenBuyOrder(); + } + else if(DetectBreakthroughSell(currentClose, currentEMALow, PrevClose, PrevEMALow)) + { + OpenSellOrder(); + } +} + +//+------------------------------------------------------------------+ +//| Detect pullback signals | +//+------------------------------------------------------------------+ +void DetectPullbackSignals(double currentClose, double currentEMAHigh, double prevEMAHigh, + double currentEMALow, double prevEMALow, double prevEMAMedium) +{ + // Buy pullback: price moved down to hit a line, then closed above it + if(PrevClose < prevEMAMedium && currentClose > currentEMALow) + { + PullbackBuy = true; + } + else if(PrevClose < prevEMALow && currentClose > currentEMALow) + { + PullbackBuy = true; + } + else if(PrevClose < prevEMAHigh && currentClose > currentEMAHigh) + { + PullbackBuy = true; + } + + // Sell pullback: price moved up to hit a line, then closed below it + if(PrevClose > prevEMAMedium && currentClose < currentEMAHigh) + { + PullbackSell = true; + } + else if(PrevClose > prevEMAHigh && currentClose < currentEMAHigh) + { + PullbackSell = true; + } + else if(PrevClose > prevEMALow && currentClose < currentEMALow) + { + PullbackSell = true; + } +} + +//+------------------------------------------------------------------+ +//| Detect breakthrough buy signal | +//+------------------------------------------------------------------+ +bool DetectBreakthroughBuy(double currentClose, double currentEMAHigh, double prevClose, double prevEMAHigh) +{ + return (prevClose <= prevEMAHigh && currentClose > currentEMAHigh); +} + +//+------------------------------------------------------------------+ +//| Detect breakthrough sell signal | +//+------------------------------------------------------------------+ +bool DetectBreakthroughSell(double currentClose, double currentEMALow, double prevClose, double prevEMALow) +{ + return (prevClose >= prevEMALow && currentClose < currentEMALow); +} + +//+------------------------------------------------------------------+ +//| Check volume filter | +//+------------------------------------------------------------------+ +bool CheckVolumeFilter(const long &tick_volume[], int rates_total) +{ + if(rates_total < VolumePeriod + 1) return false; + + // Calculate average volume + double avgVolume = 0; + for(int i = rates_total - VolumePeriod - 1; i < rates_total - 1; i++) + { + avgVolume += tick_volume[i]; + } + avgVolume /= VolumePeriod; + + // Check if current volume is above average + return (tick_volume[rates_total - 1] > avgVolume); +} + +//+------------------------------------------------------------------+ +//| Check MTF filter | +//+------------------------------------------------------------------+ +bool CheckMTFFilter() +{ + double d1Close = iClose(Symbol(), PERIOD_D1, 0); + double d1EMAHigh = GetEMAValue(D1_EMAHighHandle, 0); + double d1EMALow = GetEMAValue(D1_EMALowHandle, 0); + + if(d1Close > d1EMAHigh) + { + // Only buy orders allowed + return true; + } + else if(d1Close < d1EMALow) + { + // Only sell orders allowed + return true; + } + else + { + // Price between lines - no orders allowed + return false; + } +} + +//+------------------------------------------------------------------+ +//| Check news filter | +//+------------------------------------------------------------------+ +bool CheckNewsFilter(datetime currentTime) +{ + MqlDateTime timeStruct; + TimeToStruct(currentTime, timeStruct); + + // Convert to Thailand timezone (UTC+7) + // MT4 server time is usually UTC, so add 7 hours + int thailandHour = (timeStruct.hour + 7) % 24; + int thailandDay = timeStruct.day_of_week; + + // Check if current hour is in avoid list + for(int i = 0; i < ArraySize(AvoidHoursArray); i++) + { + if(thailandHour == AvoidHoursArray[i]) + { + return false; + } + } + + // Check if current day is in avoid list + for(int i = 0; i < ArraySize(AvoidDaysArray); i++) + { + if(thailandDay == AvoidDaysArray[i]) + { + return false; + } + } + + return true; +} + +//+------------------------------------------------------------------+ +//| Check drawdown | +//+------------------------------------------------------------------+ +bool CheckDrawdown() +{ + double currentEquity = AccountEquity(); + + // Update peak equity + if(currentEquity > AccountEquityPeak) + { + AccountEquityPeak = currentEquity; + } + + // Calculate drawdown percentage + double drawdownPercent = ((AccountEquityPeak - currentEquity) / AccountEquityPeak) * 100; + + // Check if drawdown exceeds limit + if(drawdownPercent >= MaxDrawdownPercent) + { + return false; + } + + return true; +} + +//+------------------------------------------------------------------+ +//| Open buy order | +//+------------------------------------------------------------------+ +void OpenBuyOrder() +{ + double lotSize = PullbackBuy ? LotSizePullback : LotSizeNormal; + double stopLoss = LowBorderBuffer[ArraySize(LowBorderBuffer) - 1]; + double takeProfit = CalculateTakeProfit(lotSize, OP_BUY); + + OrderTicket = OrderSend(Symbol(), OP_BUY, lotSize, Ask, 3, stopLoss, takeProfit, "MAEA Buy", MagicNumber, 0, clrBlue); + + if(OrderTicket > 0) + { + OrderOpenPrice = Ask; + OrderStopLoss = stopLoss; + OrderTakeProfit = takeProfit; + BreakevenTriggered = false; + + // Reset pullback flags + PullbackBuy = false; + PullbackSell = false; + + Print("Buy order opened: Ticket=", OrderTicket, " Price=", Ask, " SL=", stopLoss, " TP=", takeProfit); + } + else + { + Print("Error opening buy order: ", GetLastError()); + } +} + +//+------------------------------------------------------------------+ +//| Open sell order | +//+------------------------------------------------------------------+ +void OpenSellOrder() +{ + double lotSize = PullbackSell ? LotSizePullback : LotSizeNormal; + double stopLoss = HighBorderBuffer[ArraySize(HighBorderBuffer) - 1]; + double takeProfit = CalculateTakeProfit(lotSize, OP_SELL); + + OrderTicket = OrderSend(Symbol(), OP_SELL, lotSize, Bid, 3, stopLoss, takeProfit, "MAEA Sell", MagicNumber, 0, clrRed); + + if(OrderTicket > 0) + { + OrderOpenPrice = Bid; + OrderStopLoss = stopLoss; + OrderTakeProfit = takeProfit; + BreakevenTriggered = false; + + // Reset pullback flags + PullbackBuy = false; + PullbackSell = false; + + Print("Sell order opened: Ticket=", OrderTicket, " Price=", Bid, " SL=", stopLoss, " TP=", takeProfit); + } + else + { + Print("Error opening sell order: ", GetLastError()); + } +} + +//+------------------------------------------------------------------+ +//| Calculate take profit in pips from USD target | +//+------------------------------------------------------------------+ +double CalculateTakeProfit(double lotSize, int orderType) +{ + double tickValue = MarketInfo(Symbol(), MODE_TICKVALUE); + double tickSize = MarketInfo(Symbol(), MODE_TICKSIZE); + double pipValue = tickValue / tickSize * Point; + + double profitInPips = TakeProfitUSD / (lotSize * pipValue); + double profitInPrice = profitInPips * Point; + + if(orderType == OP_BUY) + { + return Ask + profitInPrice; + } + else + { + return Bid - profitInPrice; + } +} + +//+------------------------------------------------------------------+ +//| Check if we have an open order | +//+------------------------------------------------------------------+ +bool HasOpenOrder() +{ + if(OrderTicket == 0) return false; + + if(OrderSelect(OrderTicket, SELECT_BY_TICKET)) + { + if(OrderCloseTime() == 0) + { + return true; + } + else + { + OrderTicket = 0; + return false; + } + } + else + { + OrderTicket = 0; + return false; + } +} + +//+------------------------------------------------------------------+ +//| Manage open orders | +//+------------------------------------------------------------------+ +void ManageOpenOrders() +{ + if(!HasOpenOrder()) return; + + if(!OrderSelect(OrderTicket, SELECT_BY_TICKET)) return; + + double currentPrice = OrderType() == OP_BUY ? Bid : Ask; + double currentProfit = OrderProfit(); + double openPrice = OrderOpenPrice(); + + // Check take profit + if(currentProfit >= TakeProfitUSD) + { + CloseOrder(); + return; + } + + // Check stop loss + if(OrderType() == OP_BUY && currentPrice <= OrderStopLoss()) + { + CloseOrder(); + return; + } + else if(OrderType() == OP_SELL && currentPrice >= OrderStopLoss()) + { + CloseOrder(); + return; + } + + // Calculate profit in points + double profitPoints = 0; + if(OrderType() == OP_BUY) + { + profitPoints = (currentPrice - openPrice) / Point; + } + else + { + profitPoints = (openPrice - currentPrice) / Point; + } + + // Check breakeven + if(!BreakevenTriggered && profitPoints >= BreakevenPoints) + { + double newSL = openPrice; + if(OrderModify(OrderTicket, openPrice, newSL, OrderTakeProfit(), 0, clrNONE)) + { + BreakevenTriggered = true; + OrderStopLoss = newSL; + Print("Breakeven triggered: SL moved to ", newSL); + } + } + + // Check trailing stop + if(BreakevenTriggered && profitPoints >= BreakevenPoints + TrailingStopPoints) + { + double newSL; + if(OrderType() == OP_BUY) + { + newSL = currentPrice - TrailingStopPoints * Point; + if(newSL > OrderStopLoss()) + { + if(OrderModify(OrderTicket, openPrice, newSL, OrderTakeProfit(), 0, clrNONE)) + { + OrderStopLoss = newSL; + Print("Trailing stop: SL moved to ", newSL); + } + } + } + else + { + newSL = currentPrice + TrailingStopPoints * Point; + if(newSL < OrderStopLoss()) + { + if(OrderModify(OrderTicket, openPrice, newSL, OrderTakeProfit(), 0, clrNONE)) + { + OrderStopLoss = newSL; + Print("Trailing stop: SL moved to ", newSL); + } + } + } + } +} + +//+------------------------------------------------------------------+ +//| Close order | +//+------------------------------------------------------------------+ +void CloseOrder() +{ + if(OrderSelect(OrderTicket, SELECT_BY_TICKET)) + { + double closePrice = OrderType() == OP_BUY ? Bid : Ask; + if(OrderClose(OrderTicket, OrderLots(), closePrice, 3, clrNONE)) + { + Print("Order closed: Ticket=", OrderTicket, " Profit=", OrderProfit()); + OrderTicket = 0; + BreakevenTriggered = false; + } + else + { + Print("Error closing order: ", GetLastError()); + } + } +} +//+------------------------------------------------------------------+ \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..e17d200 --- /dev/null +++ b/README.md @@ -0,0 +1,345 @@ +# MAEA - Moving Average Expert Advisor + +Advanced trend-following Expert Advisor for MetaTrader 4 with sophisticated filtering and risk management features. + +## 📋 Table of Contents + +- [Overview](#overview) +- [Features](#features) +- [Strategy Details](#strategy-details) +- [Installation](#installation) +- [Parameters](#parameters) +- [Usage](#usage) +- [Visual Indicators](#visual-indicators) +- [Risk Management](#risk-management) +- [Troubleshooting](#troubleshooting) +- [Disclaimer](#disclaimer) + +## 🎯 Overview + +MAEA is a sophisticated trading robot that uses Exponential Moving Averages (EMAs) with dynamic border lines to identify trend-following opportunities. The EA includes multiple filters to ensure high-quality trade entries and comprehensive risk management to protect your account. + +**Repository:** https://git.moreminimore.com/kunthawat/MAEA +**Platform:** MetaTrader 4 +**Language:** MQL4 +**Timezone:** Thailand (UTC+7) + +## ✨ Features + +### Core Strategy +- **5 Visual Indicator Lines:** 3 EMA lines + 2 dynamic Border Lines +- **Breakthrough Signals:** Entry when price breaks through EMA High/Low +- **Pullback Signals:** Enhanced lot sizing after pullback detection +- **Dynamic Lot Sizing:** 0.01 or 0.02 lots based on market behavior +- **Single Order Management:** Prevents over-trading + +### Advanced Filters +- **Volume Filter:** Trade only when volume exceeds 20-bar average +- **Spread Filter:** Avoid high spread periods (max 30 points) +- **Multiple Timeframe Filter:** D1 trend confirmation (optional) +- **News Filter:** Avoid specific hours/days (Thailand timezone, optional) + +### Risk Management +- **Take Profit:** Target in USD (default $5) +- **Stop Loss:** At dynamic Border Lines +- **Breakeven:** Move SL to entry at 100 points profit +- **Trailing Stop:** Trail by 100 points after breakeven +- **Max Drawdown Protection:** Stop trading at 10% drawdown + +## 📊 Strategy Details + +### Indicator System + +#### EMA Lines (3 Base Lines) +All EMAs use period 30 with different price sources: + +1. **EMA High** (Light Blue) - EMA of High prices +2. **EMA Medium** (Yellow) - EMA of Close prices +3. **EMA Low** (Orange) - EMA of Low prices + +#### Border Lines (2 Dynamic Lines) +Calculated based on the range between EMAs: + +1. **High Border** (Purple) = EMA High + (EMA Medium - EMA Low) +2. **Low Border** (Purple) = EMA Low - (EMA Medium - EMA Low) + +**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 +``` + +### Signal Types + +#### 1. Breakthrough Signal +- **Buy Signal:** Close price breaks above EMA High +- **Sell Signal:** Close price breaks below EMA Low +- **Purpose:** Triggers order opening + +#### 2. Pullback Signal +- **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 same direction +- **Tracking:** Separate for buy and sell directions + +### Order Management +- **Single Order:** Only one order at a time +- **Dynamic Lot Sizing:** + - 0.01 lot (no pullback before breakthrough) + - 0.02 lot (pullback occurred before breakthrough) +- **Stop Loss:** At Border Lines (Low Border for buys, High Border for sells) +- **Take Profit:** Target in USD (default $5) +- **Breakeven:** Move SL to entry at X points profit (default 100) +- **Trailing Stop:** Trail by X points after breakeven (default 100) + +## 🚀 Installation + +1. **Download the EA:** + - Clone the repository: `git clone https://git.moreminimore.com/kunthawat/MAEA.git` + - Or download [`MAEA.mq4`](MAEA.mq4) directly + +2. **Copy to MT4:** + - Navigate to your MT4 data folder + - Go to `MQL4/Indicators` or `MQL4/Experts` + - Copy [`MAEA.mq4`](MAEA.mq4) to that folder + +3. **Compile in MetaEditor:** + - Open MetaEditor (press F4 in MT4) + - Open [`MAEA.mq4`](MAEA.mq4) + - Press F7 to compile + - Ensure no compilation errors + +4. **Attach to Chart:** + - Open MT4 + - Drag MAEA from Navigator to your chart + - Recommended timeframe: H1 + - Configure parameters as needed + +5. **Enable Auto Trading:** + - Click "Auto Trading" button in MT4 toolbar + - Ensure EA is allowed to trade in Tools → Options → Expert Advisors + +## ⚙️ Parameters + +### EMA Settings +| Parameter | Default | Description | +|-----------|---------|-------------| +| `EMAPeriod` | 30 | EMA period for all lines | + +### Lot Settings +| Parameter | Default | Description | +|-----------|---------|-------------| +| `LotSizeNormal` | 0.01 | Lot size without pullback | +| `LotSizePullback` | 0.02 | Lot size with pullback | + +### Risk Management +| Parameter | Default | Description | +|-----------|---------|-------------| +| `TakeProfitUSD` | 5.0 | Take profit target in USD | +| `BreakevenPoints` | 100 | Points to trigger breakeven | +| `TrailingStopPoints` | 100 | Trailing stop distance | +| `MaxDrawdownPercent` | 10.0 | Maximum drawdown percentage | + +### Filters +| Parameter | Default | Description | +|-----------|---------|-------------| +| `MaxSpread` | 30 | Maximum allowed spread in points | +| `VolumePeriod` | 20 | Period for volume average | +| `UseMTFFilter` | true | Enable MTF filter | +| `UseNewsFilter` | true | Enable news filter | +| `NewsAvoidHours` | "14,15,20,21" | Hours to avoid (Thailand time) | +| `NewsAvoidDays` | "1,5" | Days to avoid (Monday=1, Friday=5) | + +### General +| Parameter | Default | Description | +|-----------|---------|-------------| +| `MagicNumber` | 12345 | EA unique identifier | + +## 📖 Usage + +### Basic Setup +1. Attach MAEA to an H1 chart +2. Adjust parameters according to your risk tolerance +3. Enable Auto Trading +4. Monitor the EA's performance + +### Recommended Timeframes +- **Trading Timeframe:** H1 (recommended) +- **Filter Timeframe:** D1 (for MTF filter) + +### Currency Pairs +- Works on all major currency pairs +- Best performance on trending pairs (EURUSD, GBPUSD, USDJPY) + +### Account Types +- Compatible with any MT4 account type +- Ensure sufficient margin for lot sizes + +## 🎨 Visual Indicators + +The EA displays 5 lines on your chart: + +| Line | Color | Style | Description | +|------|-------|-------|-------------| +| EMA High | Light Blue | Solid | EMA of High prices | +| EMA Medium | Yellow | Solid | EMA of Close prices | +| EMA Low | Orange | Solid | EMA of Low prices | +| High Border | Purple | Dashed | Upper dynamic border | +| Low Border | Purple | Dashed | Lower dynamic border | + +### Reading the Indicators +- **Price above all lines:** Strong uptrend +- **Price below all lines:** Strong downtrend +- **Price between lines:** Consolidation/ranging +- **Border Lines:** Dynamic support/resistance levels + +## 🛡️ Risk Management + +### Take Profit +- Closes order when profit reaches target amount in USD +- Automatically calculated based on lot size and symbol + +### Stop Loss +- **Buy Orders:** SL at Low Border Line +- **Sell Orders:** SL at High Border Line +- Moves dynamically as Border Lines update + +### Breakeven +- Triggered when profit reaches specified points (default 100) +- Moves Stop Loss to breakeven (entry price) +- Protects profits while allowing room for trend continuation + +### Trailing Stop +- Activates after breakeven is reached +- Trails Stop Loss by specified points (default 100) +- Locks in profits as trend continues + +### Drawdown Protection +- Calculates drawdown percentage from peak equity +- Stops trading if drawdown exceeds limit (default 10%) +- Resumes trading when drawdown is below limit + +## 🔧 Troubleshooting + +### EA Not Opening Orders + +**Problem:** EA is attached but not opening any orders + +**Solutions:** +1. Check if Auto Trading is enabled (green button in MT4 toolbar) +2. Verify EA is allowed in Tools → Options → Expert Advisors +3. Check if filters are too restrictive: + - Reduce `MaxSpread` if spread is too high + - Disable `UseMTFFilter` temporarily + - Disable `UseNewsFilter` temporarily +4. Verify account has sufficient margin +5. Check Experts tab for error messages + +### Compilation Errors + +**Problem:** EA fails to compile in MetaEditor + +**Solutions:** +1. Ensure you're using MT4 (not MT5) +2. Check for missing brackets or semicolons +3. Verify all function names are spelled correctly +4. Update MetaEditor to latest version + +### Incorrect Indicator Display + +**Problem:** Lines not displaying correctly on chart + +**Solutions:** +1. Ensure sufficient historical data (at least 50 bars) +2. Check if `EMAPeriod` is too high for available data +3. Refresh chart (right-click → Refresh) +4. Reattach EA to chart + +### Orders Closing Prematurely + +**Problem:** Orders closing too early or not reaching TP + +**Solutions:** +1. Check if `TakeProfitUSD` is too low +2. Verify `MaxDrawdownPercent` is not too restrictive +3. Check if spread is causing SL hits +4. Review trade logs for closure reasons + +### Drawdown Protection Triggering + +**Problem:** EA stops trading due to drawdown + +**Solutions:** +1. Increase `MaxDrawdownPercent` if too conservative +2. Wait for equity to recover above threshold +3. Review trading strategy and risk settings +4. Consider reducing lot sizes + +### Timezone Issues + +**Problem:** News filter not working at expected times + +**Solutions:** +1. Verify your MT4 server timezone +2. Adjust `NewsAvoidHours` accordingly +3. Thailand timezone is UTC+7 +4. Test with different hour values + +### Performance Issues + +**Problem:** EA slow or causing MT4 lag + +**Solutions:** +1. Reduce `EMAPeriod` for faster calculations +2. Disable MTF filter if not needed +3. Close unnecessary charts and indicators +4. Check MT4 and computer performance + +## 📝 Best Practices + +1. **Start Small:** Begin with minimum lot sizes and conservative settings +2. **Test Thoroughly:** Use demo account before live trading +3. **Monitor Regularly:** Check EA performance and adjust as needed +4. **Keep Records:** Track trades and analyze performance +5. **Stay Informed:** Be aware of market conditions and news events +6. **Use Stop Loss:** Never disable risk management features +7. **Diversify:** Don't rely on a single EA or strategy + +## ⚠️ Disclaimer + +**IMPORTANT NOTICE:** + +Trading Forex and CFDs involves significant risk of loss and may not be suitable for all investors. MAEA is provided as-is without any warranty or guarantee of performance. + +- Past performance is not indicative of future results +- Always trade with money you can afford to lose +- Test thoroughly on demo accounts before live trading +- The authors are not responsible for any financial losses +- Use at your own risk + +**By using MAEA, you acknowledge that:** +- You understand the risks involved in trading +- You are solely responsible for your trading decisions +- You will not hold the authors liable for any losses +- You have read and understood this disclaimer + +## 📞 Support + +For issues, questions, or contributions: +- **Repository:** https://git.moreminimore.com/kunthawat/MAEA +- **Issues:** Report bugs or request features via repository issues + +## 📄 License + +This project is provided for educational and research purposes. Use responsibly and in accordance with your broker's terms of service. + +--- + +**Version:** 1.00 +**Last Updated:** 2026-01-02 +**Timezone:** Thailand (UTC+7) \ No newline at end of file diff --git a/plans/MAEA-implementation-plan.md b/plans/MAEA-implementation-plan.md new file mode 100644 index 0000000..b054508 --- /dev/null +++ b/plans/MAEA-implementation-plan.md @@ -0,0 +1,342 @@ +# 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 \ No newline at end of file diff --git a/plans/MAEA-summary.md b/plans/MAEA-summary.md new file mode 100644 index 0000000..45a0525 --- /dev/null +++ b/plans/MAEA-summary.md @@ -0,0 +1,196 @@ +# MAEA Project Summary + +## Project Overview +**MAEA (Moving Average Expert Advisor)** - An advanced trend-following trading robot for MetaTrader 4 with sophisticated filtering and risk management features. + +**Repository:** https://git.moreminimore.com/kunthawat/MAEA +**Timezone:** Thailand (UTC+7) + +## Core Strategy + +### Indicator System (5 Visual Lines) +1. **EMA High** (Light Blue) - EMA of High prices, period 30 +2. **EMA Medium** (Yellow) - EMA of Close prices, period 30 +3. **EMA Low** (Orange) - EMA of Low prices, period 30 +4. **High Border** (Purple) - EMA High + (EMA Medium - EMA Low) +5. **Low Border** (Purple) - EMA Low - (EMA Medium - EMA Low) + +### Signal Types + +#### 1. Breakthrough Signal +- **Buy:** Close price breaks above EMA High +- **Sell:** Close price breaks below EMA Low +- **Purpose:** Triggers order opening + +#### 2. Pullback Signal +- **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 same direction +- **Tracking:** Separate for buy and sell directions + +### Order Management +- **Single Order:** Only one order at a time +- **Dynamic Lot Sizing:** + - 0.01 lot (no pullback before breakthrough) + - 0.02 lot (pullback occurred before breakthrough) +- **Stop Loss:** At Border Lines (Low Border for buys, High Border for sells) +- **Take Profit:** Target in USD (default $5) +- **Breakeven:** Move SL to entry at X points profit (default 100) +- **Trailing Stop:** Trail by X points after breakeven (default 100) + +## Advanced Filters + +### 1. Volume Filter +- Calculate 20-bar volume average +- Trade only when current volume > average +- Ensures sufficient market activity + +### 2. Spread Filter +- Maximum allowed spread: 30 points +- Prevents trading during high spread periods + +### 3. Multiple Timeframe (MTF) Filter (Optional) +- **Trading Timeframe:** H1 +- **Filter Timeframe:** D1 +- **Logic:** + - D1 close > D1 EMA High: Only buy orders allowed + - D1 close < D1 EMA Low: Only sell orders allowed + - D1 close between: No orders allowed +- Can be enabled/disabled + +### 4. News Filter (Optional) +- Avoid specific hours (default: 14, 15, 20, 21) +- Avoid specific days (default: 1, 5) +- All times in Thailand timezone (UTC+7) +- Can be enabled/disabled + +### 5. Risk Management +- **Max Drawdown:** Percentage-based protection (default 10%) +- Stops trading if drawdown exceeds limit +- Resumes trading when drawdown is below limit + +## Implementation Phases + +### Phase 1: Project Setup & Git Configuration (3 tasks) +- Create MQL4 project structure +- Initialize Git repository +- Configure remote to Gitea server + +### Phase 2: Core EA Structure (4 tasks) +- Create MAEA.mq4 with basic framework +- Define all input parameters +- Set up indicator buffers +- Initialize global variables + +### Phase 3: Indicator Calculations (4 tasks) +- Implement EMA calculations (High, Medium, Low) +- Implement Border Line calculations +- Add visual indicators with colors +- Implement Volume average calculation + +### Phase 4: Signal Detection (4 tasks) +- Implement breakthrough signal detection +- Implement pullback signal detection +- Implement separate pullback tracking +- Implement pullback flag reset logic + +### Phase 5: Multiple Timeframe Filter (3 tasks) +- Implement D1 EMA calculations +- Implement MTF filter logic +- Add enable/disable toggle + +### Phase 6: Additional Filters (4 tasks) +- Implement volume filter +- Implement spread filter +- Implement news filter (Thailand timezone) +- Add enable/disable toggle for news filter + +### Phase 7: Order Management (7 tasks) +- Implement order opening with all filters +- Implement dynamic lot sizing +- Implement Stop Loss placement +- Implement Take Profit calculation +- Implement Breakeven logic +- Implement Trailing Stop logic +- Implement single order restriction + +### Phase 8: Risk Management (3 tasks) +- Implement max drawdown calculation +- Implement drawdown protection +- Implement trading resume logic + +### Phase 9: Order Monitoring & Management (5 tasks) +- Implement Take Profit checking +- Implement Breakeven checking and SL modification +- Implement Trailing Stop checking and SL modification +- Implement Stop Loss checking +- Implement order closure logic + +### Phase 10: Testing & Validation (7 tasks) +- Test all EMA and Border Line calculations +- Test breakthrough and pullback signals +- Test all filters +- Test order opening with correct lot sizes +- Test TP, SL, breakeven, and trailing stop +- Test drawdown protection +- Test visual indicators display + +### Phase 11: Documentation & Deployment (5 tasks) +- Create comprehensive README.md +- Add parameter descriptions and usage instructions +- Add troubleshooting guide +- Commit initial code to Git +- Push to Gitea repository and verify + +## Total Tasks: 50 + +## Key Features Summary + +✅ **Advanced Trend Following:** EMA-based with dynamic border lines +✅ **Smart Signal Detection:** Breakthrough and pullback signals with separate tracking +✅ **Dynamic Lot Sizing:** 0.01 or 0.02 based on market behavior +✅ **Comprehensive Filters:** Volume, spread, MTF, news, and drawdown protection +✅ **Risk Management:** TP in USD, SL at borders, breakeven, trailing stop +✅ **Visual Indicators:** 5 colored lines for easy analysis +✅ **Flexible Configuration:** All features can be enabled/disabled +✅ **Single Order Management:** Prevents over-trading +✅ **Timezone Aware:** Thailand timezone (UTC+7) for all time-based features + +## Default Parameters + +| Parameter | Value | Description | +|-----------|-------|-------------| +| EMA Period | 30 | Period for all EMAs | +| Lot Size (Normal) | 0.01 | Lot without pullback | +| Lot Size (Pullback) | 0.02 | Lot with pullback | +| Take Profit | $5 | Target profit in USD | +| Breakeven Points | 100 | Points to trigger breakeven | +| Trailing Stop Points | 100 | Trail distance after breakeven | +| Max Spread | 30 points | Maximum allowed spread | +| Volume Period | 20 | Bars for volume average | +| Max Drawdown | 10% | Maximum drawdown percentage | +| MTF Filter | true | Enable/disable MTF filter | +| News Filter | true | Enable/disable news filter | + +## Technical Specifications + +- **Platform:** MetaTrader 4 +- **Language:** MQL4 +- **Trading Timeframe:** H1 (recommended) +- **Filter Timeframe:** D1 (for MTF) +- **Currency Pairs:** All pairs (user-selectable) +- **Account Types:** Any MT4 account +- **Server Timezone:** Thailand (UTC+7) + +## Next Steps + +The implementation plan is complete and ready for execution. All 50 tasks have been clearly defined and organized into 11 logical phases. The plan includes: + +1. ✅ Detailed strategy documentation +2. ✅ Visual flow diagram +3. ✅ Complete implementation steps +4. ✅ Input parameters table +5. ✅ Testing checklist +6. ✅ Technical specifications + +**Ready to proceed with implementation in Code mode.** \ No newline at end of file