Live vs Demo EA

 

Anyone fancy taking a look at this EA , when back tested in strategy on the 1m chart XAUUSD with TP 100 , the results are amazing, however in live I cant get it to be profitable? 

here's the  script : 

//+------------------------------------------------------------------+

//| Expert Advisor: FractalRSI_EA.mq4                                |

//| Strategy: 3 SMMA + Fractals + RSI + Engulfing + Range Filter     |

//| Scalping logic implemented per confirmed rules                   |

//| Copyright: John Caunt 28021985                                   |

//+------------------------------------------------------------------+

#property strict



#include <MovingAverages.mqh>



input double Lot = 0.01;

input double RiskPercent = 1.0;

input double TakeProfitPips = 10;

input int Slippage = 3;

input int MagicNumber = 12345;

input string SymbolSuffix = "";

input bool EnableTelegram = false;

input string TelegramBotToken = "";

input string TelegramChatID = "";

input double MaxLossGBP = 0;



string ActualSymbol;

bool tradingDisabled = false;

double initialBalance = 0;

double pip;

datetime lastDayCheck = 0;

datetime lastWeekCheck = 0;

double DailyPnL = 0;

double WeeklyPnL = 0;



bool SendTelegram(string message) {

   if (!EnableTelegram || StringLen(TelegramBotToken) == 0 || StringLen(TelegramChatID) == 0) return false;

   string url = "https://api.telegram.org/bot" + TelegramBotToken + "/sendMessage";

   string payload = "chat_id=" + TelegramChatID + "&text=" + message;

   uchar post[];

   uchar result[];

   StringToCharArray(payload, post);

   string result_headers = "";

   int res = WebRequest("POST", url, "application/x-www-form-urlencoded", 5000, post, result, result_headers);

   if (res != 200) Print("Telegram send failed: ", GetLastError());

   return (res == 200);

}



int OnInit() {

   initialBalance = AccountBalance();

   tradingDisabled = false;

   SendTelegram("📥 FractalRSI_EA attached to chart.");

   ActualSymbol = Symbol();

   int suffixLen = StringLen(SymbolSuffix);

   if (suffixLen > 0 && StringFind(Symbol(), SymbolSuffix) != -1)

      ActualSymbol = StringSubstr(Symbol(), 0, StringLen(Symbol()) - suffixLen);

   pip = (Digits == 5 || Digits == 3) ? Point * 10 : Point;

   Print("FractalRSI_EA initialized with pip value: ", pip);

   return(INIT_SUCCEEDED);

}



bool HasOpenTrade(int type) {

   for (int i = 0; i < OrdersTotal(); i++) {

      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {

         if (OrderSymbol() == ActualSymbol + SymbolSuffix && OrderMagicNumber() == MagicNumber && OrderType() == type)

            return true;

      }

   }

   return false;

}



double CalculateLotSize(double entryPrice, double stopLoss) {

   double tickValue = MarketInfo(Symbol(), MODE_TICKVALUE);

   double tickSize = MarketInfo(Symbol(), MODE_TICKSIZE);

   if (tickSize == 0 || tickValue == 0 || stopLoss == entryPrice || RiskPercent <= 0) return Lot;

   double riskAmount = AccountBalance() * RiskPercent / 100;

   double pipsRisk = MathAbs(entryPrice - stopLoss) / tickSize;

   double lotSize = NormalizeDouble(riskAmount / (pipsRisk * tickValue), 2);

   double minLot = MarketInfo(Symbol(), MODE_MINLOT);

   double maxLot = MarketInfo(Symbol(), MODE_MAXLOT);

   double lotStep = MarketInfo(Symbol(), MODE_LOTSTEP);

   lotSize = MathMax(minLot, MathMin(maxLot, lotSize));

   lotSize = NormalizeDouble(lotSize / lotStep, 0) * lotStep;

   return lotSize;

}



bool IsMarketOpen() {

   datetime now = TimeCurrent();

   int weekday = TimeDayOfWeek(now);

   int hour = TimeHour(now);

   return !(weekday == 6 || weekday == 0 || (weekday == 5 && hour >= 21) || (weekday == 0 && hour < 1));

}



void CloseAllTrades() {

   for (int i = OrdersTotal() - 1; i >= 0; i--) {

      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {

         if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber) {

            if (OrderType() == OP_BUY && !OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, clrRed))

               Print("Failed to close BUY #", OrderTicket(), " Error: ", GetLastError());

            if (OrderType() == OP_SELL && !OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, clrRed))

               Print("Failed to close SELL #", OrderTicket(), " Error: ", GetLastError());

         }

      }

   }

}



void OnTick() {

   if (MaxLossGBP > 0 && (initialBalance - AccountBalance()) >= MaxLossGBP) {

      if (!tradingDisabled) {

         SendTelegram("🛑 Max GBP loss reached. Trading disabled until EA is manually reset.");

         tradingDisabled = true;

      }

      return;

   }



   datetime now = TimeCurrent();

   datetime dayStart = StrToTime(TimeToString(now, TIME_DATE));

   datetime weekStart = now - (TimeDayOfWeek(now) * 86400);



   if (lastDayCheck < dayStart) {

      SendTelegram("📊 Daily PnL: " + DoubleToString(DailyPnL, 2));

      DailyPnL = 0;

      lastDayCheck = dayStart;

   }

   if (lastWeekCheck < weekStart) {

      SendTelegram("📈 Weekly PnL: " + DoubleToString(WeeklyPnL, 2));

      WeeklyPnL = 0;

      lastWeekCheck = weekStart;

   }



   if (!IsTradeAllowed() || !IsMarketOpen() || tradingDisabled) return;



   if (TimeDayOfWeek(now) == 5 && TimeHour(now) >= 20) {

      CloseAllTrades();

      return;

   }



   int shift = 1;

   double close1 = Close[shift];

   double close2 = Close[shift + 1];

   double open1 = Open[shift];

   double smma60 = iMA(NULL, 0, 60, 0, MODE_SMMA, PRICE_CLOSE, shift);

   double smma100 = iMA(NULL, 0, 100, 0, MODE_SMMA, PRICE_CLOSE, shift);

   double smma200 = iMA(NULL, 0, 200, 0, MODE_SMMA, PRICE_CLOSE, shift);

   double rsi = iRSI(NULL, 0, 14, PRICE_CLOSE, shift);



   double range = High[shift] - Low[shift];

   double median = 0;

   for (int i = 1; i <= 50; i++) median += High[i] - Low[i];

   median /= 50;

   if (range > 2 * median) return;



   bool fractalUp = High[shift] > High[shift + 1] && High[shift] > High[shift - 1];

   bool fractalDown = Low[shift] < Low[shift + 1] && Low[shift] < Low[shift - 1];

   bool bearishEngulf = open1 > close2 && close1 < close2;

   bool bullishEngulf = open1 < close2 && close1 > close2;



   double entryPrice, sl, tp;



   if (close1 < smma60 && close1 < smma100 && close1 < smma200 && rsi < 50 && fractalUp && bearishEngulf) {

      if (!HasOpenTrade(OP_SELL)) {

         entryPrice = Bid;

         tp = entryPrice - TakeProfitPips * pip;

         sl = High[shift + 1] + 0.02;

         if (MathAbs(entryPrice - sl) > 5 * pip)

            OpenTrade(OP_SELL, entryPrice, sl, tp);

      }

   } else if (close1 > smma60 && close1 > smma100 && close1 > smma200 && rsi > 50 && fractalDown && bullishEngulf) {

      if (!HasOpenTrade(OP_BUY)) {

         entryPrice = Ask;

         tp = entryPrice + TakeProfitPips * pip;

         sl = Low[shift + 1] - 0.02;

         if (MathAbs(entryPrice - sl) > 5 * pip)

            OpenTrade(OP_BUY, entryPrice, sl, tp);

      }

   }

}



void OpenTrade(int type, double price, double sl, double tp) {

   double lotSize = RiskPercent > 0 ? CalculateLotSize(price, sl) : Lot;

   string comment = "FractalRSI_EA";

   color orderColor = (type == OP_BUY) ? clrGreen : clrRed;

   int ticket = OrderSend(ActualSymbol + SymbolSuffix, type, lotSize, price, Slippage, sl, tp, comment, MagicNumber, 0, orderColor);

   if (ticket < 0) {

      int error = GetLastError();

      Print("OrderSend failed with error #", error);

      Print("Parameters: Type=", type, ", Lot=", lotSize, ", Price=", price, ", SL=", sl, ", TP=", tp);

   } else {

      double profit = tp - price;

      DailyPnL += profit;

      WeeklyPnL += profit;

      Print("Order #", ticket, " opened successfully. Type=", type, ", Lot=", lotSize, ", Price=", price, ", SL=", sl, ", TP=", tp);

   }

}



void OnDeinit(const int reason) {

   SendTelegram("📤 FractalRSI_EA removed from chart.");

   Print("FractalRSI_EA deinitialized, reason: ", reason);

}

//+------------------------------------------------------------------+


 
johnca85:

Anyone fancy taking a look at this EA , when back tested in strategy on the 1m chart XAUUSD with TP 100 , the results are amazing, however in live I cant get it to be profitable? 

here's the  script : 


Backtested on real ticks?
 
johnca85:
when back tested in strategy on the 1m chart XAUUSD with TP 100 , the results are amazing, however in live I cant get it to be profitable?

MT4?
there is something well-known which is related to MT4:

Forum on trading, automated trading systems and testing trading strategies

entry price in ea backtesting different from live trades why

Sergey Golubev, 2021.12.08 18:53

Entry price in live trading may be different from the backtesting results in the following cases:

  • your EA is for MT4 (and it is almost always different; if not so it is the subject to the discussion on the way to the following: "which special technique do you use to be the same ...");
  • bug in your code;
  • martingale/hedging - it depends on the many factors, such as the following: number of ticks used, time/hours/min to be started to trade, data quality provided, and some more.
  • more.

Testing trading strategies on real ticks and the explanation is on this post


Many traders are converting their EAs to MT5 (from MT4/mql4 to MT5/mql5) just to backtest EAs with "every tick based on real ticks" to use the broker's data to backtest EA.
 
Vasile Verdes #:
Backtested on real ticks?
tick 97 percent 
 
Sergey Golubev #:

MT4?
there is something well-known which is related to MT4:


Many traders are converting their EAs to MT5 (from MT4/mql4 to MT5/mql5) just to backtest EAs with "every tick based on real ticks" to use the broker's data to backtest EA.
Yes MT4, I'm happy to share the bot I'm not precious about it, id rather a community profit. I have tired different settings running parameter runs for days , I'm at a loss really. i wonder i had optomised it
 
johnca85 #:
Yes MT4, I'm happy to share the bot I'm not precious about it, id rather a community profit. I have tired different settings running parameter runs for days , I'm at a loss really. i wonder i had optomised it

In MT4: the performance in backtesting should not be same with real trading. If it is same so the EA is using D1 or W1 timeframe to get several trades only in a half a year (just to confirm the conclusions of the technical analysis for example) or the coder used some special coding technique to be the same.
Because it should not be the same by default.

In MT5: the performance of backtesting with "every tick based on real ticks" should be same with real trading (in most fo the cases).

----------------