//+… · The Chat Archive
Explore //+------------------------------------------------------------------+ // RSIALGOEA.mq5… Save Share Download ▾ Report//+------------------------------------------------------------------+
//| RSI_ALGO_EA.mq5 |
//| Converted from Pine Script |
//| Enhanced for MT5 with Accuracy |
//+------------------------------------------------------------------+
#property copyright "Converted from Pine Script"
#property link ""
#property version "1.00"
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\OrderInfo.mqh>
CTrade trade;
CPositionInfo positionInfo;
COrderInfo orderInfo;
//--- Input parameters
input group "RSI Settings"
input int InpRSIPeriod = 14; // RSI Period
input bool InpShowRSITrend = true; // Enable RSI Trading
input group "EMA Settings"
input bool InpShowEMA = false; // Show EMA on Chart
input bool InpShowEMACrossover = true; // Show EMA Crossover Signals
input int InpEMA0 = 9; // EMA 0 Period
input int InpEMA1 = 20; // EMA 1 Period
input int InpEMA2 = 50; // EMA 2 Period
input int InpEMA3 = 200; // EMA 3 Period
input group "SuperTrend Settings"
input bool InpShowSuperTrend = false; // Enable SuperTrend
input bool InpShowSTSignals = true; // Show SuperTrend Signals
input int InpATRPeriod = 12; // ATR Period
input double InpATRMultiplier = 3.0; // ATR Multiplier
input group "TP/SL Management"
input bool InpShowTPSL = true; // Enable TP/SL
input int InpSLMethodInt = 0; // Stop Loss Method (0=ATR, 1=Percentage, 2=Fixed)
input double InpSLATRMult = 1.5; // SL ATR Multiplier
input double InpSLPercentage = 2.0; // SL Percentage
input int InpSLPoints = 50; // SL Points
input double InpRiskReward = 2.0; // Risk to Reward Ratio
input int InpMaxTrades = 3; // Max Active Trades
input group "Trading Settings"
input double InpLotSize = 0.1; // Lot Size
input bool InpUseMoneyManagement = true; // Use Money Management
input double InpRiskPercent = 2.0; // Risk Percentage per Trade
input int InpMagicNumber = 123456; // Magic Number
input int InpSlippage = 3; // Slippage in points
input group "Optimization Settings"
input bool InpUseVolumeFilter = true; // Use Volume Filter
input bool InpUseTimeFilter = true; // Use Time Filter
input int InpStartHour = 8; // Trading Start Hour
input int InpEndHour = 20; // Trading End Hour
input bool InpUseTrendFilter = true; // Use Trend Filter
input bool InpUseVolatilityFilter = true; // Use Volatility Filter
input double InpMinVolatility = 0.0001; // Minimum Volatility
input double InpMaxVolatility = 0.01; // Maximum Volatility
Show full message · 796 lines AssistantCopy response Copy first prompt
Other models, same or similar prompt Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Details
Provider Unknown
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Added to archive Nov 19, 2026
ID 01m7tp9wjqp9yr4jmxfgpasge0Source & license Imported from Arena Expert 5K (source ). Imported records earn no Research Points.
Upstream record: 999f53e6-dfae-481e-bbda-009857e3f379:a
LMArena, Arena Expert (2025). https://news.lmarena.ai/arena-expert/
License: Prompts CC-BY-4.0; outputs governed by provider terms
Dataset releases Not yet included in a published release.
//--- Enums
enum ENUM_SL_METHOD
{
SL_ATR, // ATR Based
SL_PERCENTAGE, // Percentage Based
SL_FIXED // Fixed Points
};
//--- Global variables
int rsiHandle60, rsiHandle30, rsiHandle15, rsiHandle1;
int emaHandle0, emaHandle1, emaHandle2, emaHandle3;
int atrHandle;
// Removed volumeHandle as we'll get volume data directly
double rsi60[], rsi30[], rsi15[], rsi1[];
double ema0[], ema1[], ema2[], ema3[];
double atrValues[];
double volumeValues[2]; // Only need current and previous volume
bool indicBuy = false, indicSell = false;
bool condBuy = false, condSell = false;
datetime lastTradeTime = 0;
int consecutiveLosses = 0;
double accountBalance = 0;
//--- Optimization variables
struct TradeStats
{
int totalTrades;
int winningTrades;
int losingTrades;
double totalProfit;
double totalLoss;
double maxDrawdown;
double winRate;
double profitFactor;
};
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- Set magic number
trade.SetExpertMagicNumber(InpMagicNumber);
trade.SetDeviationInPoints(InpSlippage);
//--- Initialize RSI handles for different timeframes
rsiHandle60 = iRSI(_Symbol, PERIOD_H1, InpRSIPeriod, PRICE_CLOSE);
rsiHandle30 = iRSI(_Symbol, PERIOD_M30, InpRSIPeriod, PRICE_CLOSE);
rsiHandle15 = iRSI(_Symbol, PERIOD_M15, InpRSIPeriod, PRICE_CLOSE);
rsiHandle1 = iRSI(_Symbol, PERIOD_M1, InpRSIPeriod, PRICE_CLOSE);
//--- Initialize EMA handles
emaHandle0 = iMA(_Symbol, PERIOD_CURRENT, InpEMA0, 0, MODE_EMA, PRICE_CLOSE);
emaHandle1 = iMA(_Symbol, PERIOD_CURRENT, InpEMA1, 0, MODE_EMA, PRICE_CLOSE);
emaHandle2 = iMA(_Symbol, PERIOD_CURRENT, InpEMA2, 0, MODE_EMA, PRICE_CLOSE);
emaHandle3 = iMA(_Symbol, PERIOD_CURRENT, InpEMA3, 0, MODE_EMA, PRICE_CLOSE);
//--- Initialize ATR handle
atrHandle = iATR(_Symbol, PERIOD_CURRENT, 14);
//--- Initialize Volume handle (using tick volumes)
// Note: We'll get volume data differently since iVolumes returns long values
//--- Check handles
if(rsiHandle60 == INVALID_HANDLE || rsiHandle30 == INVALID_HANDLE ||
rsiHandle15 == INVALID_HANDLE || rsiHandle1 == INVALID_HANDLE ||
emaHandle0 == INVALID_HANDLE || atrHandle == INVALID_HANDLE)
{
Print("Error creating indicators");
return INIT_FAILED;
}
//--- Array settings
ArraySetAsSeries(rsi60, true);
ArraySetAsSeries(rsi30, true);
ArraySetAsSeries(rsi15, true);
ArraySetAsSeries(rsi1, true);
ArraySetAsSeries(ema0, true);
ArraySetAsSeries(ema1, true);
ArraySetAsSeries(ema2, true);
ArraySetAsSeries(ema3, true);
ArraySetAsSeries(atrValues, true);
// Note: volumeValues will be handled differently
//--- Initialize stats
InitializeStats();
accountBalance = AccountInfoDouble(ACCOUNT_BALANCE);
Print("RSI Algorithm EA initialized successfully");
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- Release indicators
IndicatorRelease(rsiHandle60);
IndicatorRelease(rsiHandle30);
IndicatorRelease(rsiHandle15);
IndicatorRelease(rsiHandle1);
IndicatorRelease(emaHandle0);
IndicatorRelease(emaHandle1);
IndicatorRelease(emaHandle2);
IndicatorRelease(emaHandle3);
IndicatorRelease(atrHandle);
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- Check if new bar
static datetime lastBarTime = 0;
if(iTime(_Symbol, PERIOD_CURRENT, 0) <= lastBarTime)
return;
lastBarTime = iTime(_Symbol, PERIOD_CURRENT, 0);
//--- Update indicators
if(!UpdateIndicators())
return;
//--- Check trading conditions
CheckRSIConditions();
//--- Execute trading logic
if(InpShowRSITrend && IsValidTimeframe())
{
ProcessRSISignals();
}
//--- Monitor existing positions
MonitorPositions();
//--- Update statistics
UpdateStats();
}
//+------------------------------------------------------------------+
//| Update all indicators |
//+------------------------------------------------------------------+
bool UpdateIndicators()
{
//--- Get RSI values
if(CopyBuffer(rsiHandle60, 0, 0, 3, rsi60) < 0 ||
CopyBuffer(rsiHandle30, 0, 0, 3, rsi30) < 0 ||
CopyBuffer(rsiHandle15, 0, 0, 3, rsi15) < 0 ||
CopyBuffer(rsiHandle1, 0, 0, 3, rsi1) < 0)
{
Print("Error copying RSI buffers");
return false;
}
//--- Get EMA values
if(CopyBuffer(emaHandle0, 0, 0, 3, ema0) < 0 ||
CopyBuffer(emaHandle1, 0, 0, 3, ema1) < 0 ||
CopyBuffer(emaHandle2, 0, 0, 3, ema2) < 0 ||
CopyBuffer(emaHandle3, 0, 0, 3, ema3) < 0)
{
Print("Error copying EMA buffers");
return false;
}
//--- Get ATR values
if(CopyBuffer(atrHandle, 0, 0, 3, atrValues) < 0)
{
Print("Error copying ATR buffer");
return false;
}
//--- Get Volume values using tick volume from price data
if(InpUseVolumeFilter)
{
// Get tick volumes from the current timeframe
long currentVolume = iVolume(_Symbol, PERIOD_CURRENT, 0);
long prevVolume = iVolume(_Symbol, PERIOD_CURRENT, 1);
code Copy code
if(currentVolume <= 0 || prevVolume <= 0)
{
Print("Error getting volume data");
return false;
}
// Store volumes for comparison (convert to double for calculations)
volumeValues[0] = (double)currentVolume;
volumeValues[1] = (double)prevVolume;
//+------------------------------------------------------------------+
//| Check RSI conditions |
//+------------------------------------------------------------------+
void CheckRSIConditions()
{
//--- Buy condition: RSI60>60 AND RSI30>60 AND RSI1<40 AND RSI15>RSI1
condBuy = (rsi60[0] > 60 && rsi30[0] > 60 && rsi1[0] < 40 && rsi15[0] > rsi1[0]);
//--- Sell condition: RSI60<40 AND RSI30<40 AND RSI1>60 AND RSI15<RSI1
condSell = (rsi60[0] < 40 && rsi30[0] < 40 && rsi1[0] > 60 && rsi15[0] < rsi1[0]);
//--- Enhanced conditions with additional filters
if(InpUseTrendFilter)
{
bool bullishTrend = (ema0[0] > ema1[0] && ema1[0] > ema2[0]);
bool bearishTrend = (ema0[0] < ema1[0] && ema1[0] < ema2[0]);
code Copy code
condBuy = condBuy && bullishTrend;
condSell = condSell && bearishTrend;
//--- Volume filter
if(InpUseVolumeFilter && ArraySize(volumeValues) >= 2)
{
double avgVolume = (volumeValues[0] + volumeValues[1]) / 2.0;
double currentVolume = volumeValues[0];
code Copy code
condBuy = condBuy && (currentVolume > avgVolume * 1.2);
condSell = condSell && (currentVolume > avgVolume * 1.2);
//--- Volatility filter
if(InpUseVolatilityFilter)
{
double currentVolatility = atrValues[0] / iClose(_Symbol, PERIOD_CURRENT, 0);
condBuy = condBuy && (currentVolatility >= InpMinVolatility && currentVolatility <= InpMaxVolatility);
condSell = condSell && (currentVolatility >= InpMinVolatility && currentVolatility <= InpMaxVolatility);
}
}
//+------------------------------------------------------------------+
//| Process RSI signals |
//+------------------------------------------------------------------+
void ProcessRSISignals()
{
static bool prevCondBuy = false;
static bool prevCondSell = false;
//--- Check if we can trade
if(!CanTrade())
return;
//--- Process buy signal (detect new signal)
if(condBuy && !condSell && !prevCondBuy)
{
if(GetActivePositions(POSITION_TYPE_BUY) < InpMaxTrades)
{
OpenBuyPosition();
}
}
//--- Process sell signal (detect new signal)
if(condSell && !condBuy && !prevCondSell)
{
if(GetActivePositions(POSITION_TYPE_SELL) < InpMaxTrades)
{
OpenSellPosition();
}
}
//--- Update previous conditions
prevCondBuy = condBuy;
prevCondSell = condSell;
//--- Alert conditions
if(indicBuy && rsi1[0] > 75 && rsi30[0] < 45)
{
indicBuy = false;
Alert("RSI ALERT - Consider closing buy positions");
}
if(indicSell && rsi1[0] < 25 && rsi30[0] > 55)
{
indicSell = false;
Alert("RSI ALERT - Consider closing sell positions");
}
}
//+------------------------------------------------------------------+
//| Open buy position |
//+------------------------------------------------------------------+
void OpenBuyPosition()
{
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double lotSize = CalculateLotSize(true);
//--- Calculate SL and TP
double sl = CalculateStopLoss(ask, true);
double tp = CalculateTakeProfit(ask, sl, true);
//--- Open position
if(trade.Buy(lotSize, _Symbol, ask, sl, tp, "RSI Buy Signal"))
{
Print("Buy position opened: Price=", ask, " SL=", sl, " TP=", tp);
lastTradeTime = TimeCurrent();
indicBuy = true;
indicSell = false;
}
else
{
Print("Failed to open buy position. Error: ", GetLastError());
}
}
//+------------------------------------------------------------------+
//| Open sell position |
//+------------------------------------------------------------------+
void OpenSellPosition()
{
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double lotSize = CalculateLotSize(false);
//--- Calculate SL and TP
double sl = CalculateStopLoss(bid, false);
double tp = CalculateTakeProfit(bid, sl, false);
//--- Open position
if(trade.Sell(lotSize, _Symbol, bid, sl, tp, "RSI Sell Signal"))
{
Print("Sell position opened: Price=", bid, " SL=", sl, " TP=", tp);
lastTradeTime = TimeCurrent();
indicSell = true;
indicBuy = false;
}
else
{
Print("Failed to open sell position. Error: ", GetLastError());
}
}
//+------------------------------------------------------------------+
//| Calculate lot size |
//+------------------------------------------------------------------+
double CalculateLotSize(bool isBuy)
{
double lotSize = InpLotSize;
if(InpUseMoneyManagement)
{
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
double equity = AccountInfoDouble(ACCOUNT_EQUITY);
double price = isBuy ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID);
code Copy code
//--- Calculate risk amount
double riskAmount = balance * InpRiskPercent / 100.0;
//--- Calculate stop loss distance
double slDistance = CalculateStopLossDistance(price, isBuy);
if(slDistance > 0)
{
double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
if(tickValue > 0 && tickSize > 0)
{
double slTicks = slDistance / tickSize;
lotSize = riskAmount / (slTicks * tickValue);
}
}
//--- Adjust for drawdown
if(consecutiveLosses >= 3)
{
lotSize *= 0.5; // Reduce lot size after consecutive losses
}
//--- Normalize lot size
double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double lotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
lotSize = MathMax(minLot, MathMin(maxLot, lotSize));
lotSize = NormalizeDouble(lotSize / lotStep, 0) * lotStep;
//+------------------------------------------------------------------+
//| Calculate stop loss |
//+------------------------------------------------------------------+
double CalculateStopLoss(double entryPrice, bool isBuy)
{
double sl = 0;
double slDistance = CalculateStopLossDistance(entryPrice, isBuy);
if(isBuy)
sl = entryPrice - slDistance;
else
sl = entryPrice + slDistance;
return NormalizeDouble(sl, _Digits);
}
//+------------------------------------------------------------------+
//| Calculate stop loss distance |
//+------------------------------------------------------------------+
double CalculateStopLossDistance(double entryPrice, bool isBuy)
{
double slDistance = 0;
switch(InpSLMethodInt)
{
case 0: // SL_ATR
slDistance = atrValues[0] * InpSLATRMult;
break;
code Copy code
case 1: // SL_PERCENTAGE
slDistance = entryPrice * InpSLPercentage / 100.0;
break;
case 2: // SL_FIXED
slDistance = InpSLPoints * _Point;
break;
//+------------------------------------------------------------------+
//| Calculate take profit |
//+------------------------------------------------------------------+
double CalculateTakeProfit(double entryPrice, double slPrice, bool isBuy)
{
double slDistance = MathAbs(entryPrice - slPrice);
double tpDistance = slDistance * InpRiskReward;
double tp = 0;
if(isBuy)
tp = entryPrice + tpDistance;
else
tp = entryPrice - tpDistance;
return NormalizeDouble(tp, _Digits);
}
//+------------------------------------------------------------------+
//| Check if can trade |
//+------------------------------------------------------------------+
bool CanTrade()
{
//--- Time filter
if(InpUseTimeFilter)
{
MqlDateTime dt;
TimeToStruct(TimeCurrent(), dt);
code Copy code
if(dt.hour < InpStartHour || dt.hour >= InpEndHour)
return false;
//--- Check if enough time passed since last trade
if(TimeCurrent() - lastTradeTime < 60) // 1 minute minimum
return false;
//--- Check market conditions
if(!IsMarketOpen())
return false;
//+------------------------------------------------------------------+
//| Check if valid timeframe |
//+------------------------------------------------------------------+
bool IsValidTimeframe()
{
int period = (int)_Period;
return (period <= PERIOD_M5); // Max 5-minute timeframe as per original script
}
//+------------------------------------------------------------------+
//| Get active positions count |
//+------------------------------------------------------------------+
int GetActivePositions(ENUM_POSITION_TYPE type)
{
int count = 0;
for(int i = 0; i < PositionsTotal(); i++)
{
if(positionInfo.SelectByIndex(i))
{
if(positionInfo.Symbol() == _Symbol && positionInfo.Magic() == InpMagicNumber)
{
if(positionInfo.PositionType() == type)
count++;
}
}
}
//+------------------------------------------------------------------+
//| Get total active positions count |
//+------------------------------------------------------------------+
int GetTotalActivePositions()
{
int count = 0;
for(int i = 0; i < PositionsTotal(); i++)
{
if(positionInfo.SelectByIndex(i))
{
if(positionInfo.Symbol() == _Symbol && positionInfo.Magic() == InpMagicNumber)
{
count++;
}
}
}
//+------------------------------------------------------------------+
//| Monitor existing positions |
//+------------------------------------------------------------------+
void MonitorPositions()
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(positionInfo.SelectByIndex(i))
{
if(positionInfo.Symbol() == _Symbol && positionInfo.Magic() == InpMagicNumber)
{
CheckTrailingStop(positionInfo.Ticket());
CheckExitConditions(positionInfo.Ticket());
}
}
}
}
//+------------------------------------------------------------------+
//| Check trailing stop |
//+------------------------------------------------------------------+
void CheckTrailingStop(ulong ticket)
{
if(!positionInfo.SelectByTicket(ticket))
return;
double currentPrice = positionInfo.PositionType() == POSITION_TYPE_BUY ?
SymbolInfoDouble(_Symbol, SYMBOL_BID) :
SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double openPrice = positionInfo.PriceOpen();
double currentSL = positionInfo.StopLoss();
double atrValue = atrValues[0];
if(positionInfo.PositionType() == POSITION_TYPE_BUY)
{
double newSL = currentPrice - atrValue * InpSLATRMult;
code Copy code
if(newSL > currentSL && newSL < currentPrice)
{
trade.PositionModify(ticket, newSL, positionInfo.TakeProfit());
}
}
else
{
double newSL = currentPrice + atrValue * InpSLATRMult;
code Copy code
if(newSL < currentSL && newSL > currentPrice)
{
trade.PositionModify(ticket, newSL, positionInfo.TakeProfit());
}
//+------------------------------------------------------------------+
//| Check exit conditions |
//+------------------------------------------------------------------+
void CheckExitConditions(ulong ticket)
{
if(!positionInfo.SelectByTicket(ticket))
return;
bool shouldClose = false;
string reason = "";
//--- Exit on opposite signal
if(positionInfo.PositionType() == POSITION_TYPE_BUY && condSell)
{
shouldClose = true;
reason = "Opposite signal";
}
else if(positionInfo.PositionType() == POSITION_TYPE_SELL && condBuy)
{
shouldClose = true;
reason = "Opposite signal";
}
//--- Exit on RSI extreme levels
if(positionInfo.PositionType() == POSITION_TYPE_BUY && rsi1[0] > 80)
{
shouldClose = true;
reason = "RSI overbought";
}
else if(positionInfo.PositionType() == POSITION_TYPE_SELL && rsi1[0] < 20)
{
shouldClose = true;
reason = "RSI oversold";
}
if(shouldClose)
{
trade.PositionClose(ticket);
Print("Position closed: ", reason);
}
}
//+------------------------------------------------------------------+
//| Check if market is open |
//+------------------------------------------------------------------+
bool IsMarketOpen()
{
return (SymbolInfoInteger(_Symbol, SYMBOL_TRADE_MODE) == SYMBOL_TRADE_MODE_FULL);
}
//+------------------------------------------------------------------+
//| Initialize statistics |
//+------------------------------------------------------------------+
void InitializeStats()
{
stats.totalTrades = 0;
stats.winningTrades = 0;
stats.losingTrades = 0;
stats.totalProfit = 0;
stats.totalLoss = 0;
stats.maxDrawdown = 0;
stats.winRate = 0;
stats.profitFactor = 0;
}
//+------------------------------------------------------------------+
//| Update statistics |
//+------------------------------------------------------------------+
void UpdateStats()
{
static datetime lastUpdateTime = 0;
if(TimeCurrent() - lastUpdateTime < 3600) // Update hourly
return;
lastUpdateTime = TimeCurrent();
//--- Calculate current stats
double currentBalance = AccountInfoDouble(ACCOUNT_BALANCE);
double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
//--- Update drawdown
if(currentEquity < accountBalance)
{
double drawdown = (accountBalance - currentEquity) / accountBalance * 100;
if(drawdown > stats.maxDrawdown)
stats.maxDrawdown = drawdown;
}
else
{
accountBalance = MathMax(accountBalance, currentEquity);
}
//--- Calculate win rate
if(stats.totalTrades > 0)
{
stats.winRate = (double)stats.winningTrades / stats.totalTrades * 100;
}
//--- Calculate profit factor
if(stats.totalLoss > 0)
{
stats.profitFactor = stats.totalProfit / MathAbs(stats.totalLoss);
}
}
//+------------------------------------------------------------------+
//| Print trade statistics |
//+------------------------------------------------------------------+
void PrintTradeStats()
{
Print("=== RSI Algorithm EA Statistics ===");
Print("Total Trades: ", stats.totalTrades);
Print("Winning Trades: ", stats.winningTrades);
Print("Losing Trades: ", stats.losingTrades);
Print("Win Rate: ", DoubleToString(stats.winRate, 2), "%");
Print("Profit Factor: ", DoubleToString(stats.profitFactor, 2));
Print("Max Drawdown: ", DoubleToString(stats.maxDrawdown, 2), "%");
Print("Total Profit: ", DoubleToString(stats.totalProfit, 2));
Print("=====================================");
}
//+------------------------------------------------------------------+
//| OnTrade function |
//+------------------------------------------------------------------+
void OnTrade()
{
//--- Update consecutive losses counter
if(HistorySelect(TimeCurrent() - 86400, TimeCurrent())) // Last 24 hours
{
int totalDeals = HistoryDealsTotal();
int recentLosses = 0;
code Copy code
for(int i = totalDeals - 1; i >= 0 && recentLosses < 5; i--)
{
ulong ticket = HistoryDealGetTicket(i);
if(HistoryDealGetInteger(ticket, DEAL_MAGIC) == InpMagicNumber)
{
double profit = HistoryDealGetDouble(ticket, DEAL_PROFIT);
if(profit < 0)
recentLosses++;
else
break;
}
}
consecutiveLosses = recentLosses;
}
} add backtest in this mt5 ea
To add backtesting capabilities to your MT5 EA, we'll implement a comprehensive backtesting system that tracks trades, calculates performance metrics, and generates detailed reports. Here's the enhanced code:
cpp Copy code
//+------------------------------------------------------------------+
//| Backtesting Statistics Structure |
//+------------------------------------------------------------------+
struct BacktestStats
{
datetime startDate;
datetime endDate;
int totalTrades;
int winningTrades;
int losingTrades;
double netProfit;
double grossProfit;
double grossLoss;
double maxDrawdown;
double maxDrawdownPercent;
double profitFactor;
double winRate;
double avgWin;
double avgLoss;
double avgTrade;
double recoveryFactor;
double sharpeRatio;
double expectedPayoff;
double balance;
double equity;
double margin;
string reportFile;
};
BacktestStats btStats;
//+------------------------------------------------------------------+
//| Initialize backtesting statistics |
//+------------------------------------------------------------------+
void InitializeBacktestStats()
{
btStats.startDate = 0;
btStats.endDate = 0;
btStats.totalTrades = 0;
btStats.winningTrades = 0;
btStats.losingTrades = 0;
btStats.netProfit = 0;
btStats.grossProfit = 0;
btStats.grossLoss = 0;
btStats.maxDrawdown = 0;
btStats.maxDrawdownPercent = 0;
btStats.profitFactor = 0;
btStats.winRate = 0;
btStats.avgWin = 0;
btStats.avgLoss = 0;
btStats.avgTrade = 0;
btStats.recoveryFactor = 0;
btStats.sharpeRatio = 0;
btStats.expectedPayoff = 0;
btStats.balance = AccountInfoDouble(ACCOUNT_BALANCE);
btStats.equity = AccountInfoDouble(ACCOUNT_EQUITY);
btStats.margin = AccountInfoDouble(ACCOUNT_MARGIN);
btStats.reportFile = StringFormat("Backtest_%s_%s_%u.csv",
_Symbol,
EnumToString(_Period),
InpMagicNumber);
}
//+------------------------------------------------------------------+
//| Update backtesting statistics |
//+------------------------------------------------------------------+
void UpdateBacktestStats(ulong ticket, double profit, double commission, double swap)
{
double tradeProfit = profit + commission + swap;
btStats.totalTrades++;
btStats.netProfit += tradeProfit;
btStats.equity = AccountInfoDouble(ACCOUNT_EQUITY);
// Calculate drawdown
double currentDrawdown = btStats.balance - btStats.equity;
if(currentDrawdown > btStats.maxDrawdown)
{
btStats.maxDrawdown = currentDrawdown;
btStats.maxDrawdownPercent = (btStats.maxDrawdown / btStats.balance) * 100;
}
// Update profit/loss statistics
if(tradeProfit > 0)
{
btStats.winningTrades++;
btStats.grossProfit += tradeProfit;
}
else if(tradeProfit < 0)
{
btStats.losingTrades++;
btStats.grossLoss += tradeProfit;
}
// Calculate additional metrics
if(btStats.losingTrades != 0)
{
btStats.avgWin = btStats.grossProfit / btStats.winningTrades;
btStats.avgLoss = btStats.grossLoss / btStats.losingTrades;
btStats.profitFactor = MathAbs(btStats.grossProfit / btStats.grossLoss);
}
btStats.winRate = (double)btStats.winningTrades / btStats.totalTrades * 100;
btStats.avgTrade = btStats.netProfit / btStats.totalTrades;
btStats.expectedPayoff = btStats.avgTrade;
btStats.recoveryFactor = btStats.netProfit / btStats.maxDrawdown;
// Update balance
btStats.balance = MathMax(btStats.balance, btStats.equity);
}
//+------------------------------------------------------------------+
//| Generate backtest report |
//+------------------------------------------------------------------+
void GenerateBacktestReport()
{
int fileHandle = FileOpen(btStats.reportFile, FILE_WRITE | FILE_CSV, ';');
if(fileHandle == INVALID_HANDLE)
{
Print("Error opening report file: ", GetLastError());
return;
}
// Write header
FileWrite(fileHandle, "Backtest Report for RSI Algorithm EA");
FileWrite(fileHandle, "Symbol", _Symbol);
FileWrite(fileHandle, "Timeframe", EnumToString(_Period));
FileWrite(fileHandle, "Magic Number", InpMagicNumber);
FileWrite(fileHandle, "Start Date", TimeToString(btStats.startDate));
FileWrite(fileHandle, "End Date", TimeToString(btStats.endDate));
FileWrite(fileHandle, "");
// Write summary statistics
FileWrite(fileHandle, "Total Trades", btStats.totalTrades);
FileWrite(fileHandle, "Winning Trades", btStats.winningTrades);
FileWrite(fileHandle, "Losing Trades", btStats.losingTrades);
FileWrite(fileHandle, "Win Rate", DoubleToString(btStats.winRate, 2) + "%");
FileWrite(fileHandle, "Net Profit", DoubleToString(btStats.netProfit, 2));
FileWrite(fileHandle, "Gross Profit", DoubleToString(btStats.grossProfit, 2));
FileWrite(fileHandle, "Gross Loss", DoubleToString(btStats.grossLoss, 2));
FileWrite(fileHandle, "Profit Factor", DoubleToString(btStats.profitFactor, 2));
FileWrite(fileHandle, "Max Drawdown", DoubleToString(btStats.maxDrawdown, 2));
FileWrite(fileHandle, "Max Drawdown %", DoubleToString(btStats.maxDrawdownPercent, 2) + "%");
FileWrite(fileHandle, "Average Win", DoubleToString(btStats.avgWin, 2));
FileWrite(fileHandle, "Average Loss", DoubleToString(btStats.avgLoss, 2));
FileWrite(fileHandle, "Average Trade", DoubleToString(btStats.avgTrade, 2));
FileWrite(fileHandle, "Recovery Factor", DoubleToString(btStats.recoveryFactor, 2));
FileWrite(fileHandle, "Expected Payoff", DoubleToString(btStats.expectedPayoff, 2));
FileWrite(fileHandle, "Final Balance", DoubleToString(btStats.balance, 2));
FileWrite(fileHandle, "Final Equity", DoubleToString(btStats.equity, 2));
FileWrite(fileHandle, "");
// Write trade history
FileWrite(fileHandle, "Trade History");
FileWrite(fileHandle, "Ticket;Time;Type;Symbol;Volume;Price;SL;TP;Profit;Commission;Swap;Magic;Comment");
if(HistorySelect(btStats.startDate, btStats.endDate))
{
for(int i = 0; i < HistoryDealsTotal(); i++)
{
ulong dealTicket = HistoryDealGetTicket(i);
if(HistoryDealGetInteger(dealTicket, DEAL_MAGIC) == InpMagicNumber &&
HistoryDealGetString(dealTicket, DEAL_SYMBOL) == _Symbol)
{
datetime dealTime = (datetime)HistoryDealGetInteger(dealTicket, DEAL_TIME);
ENUM_DEAL_TYPE dealType = (ENUM_DEAL_TYPE)HistoryDealGetInteger(dealTicket, DEAL_TYPE);
string dealSymbol = HistoryDealGetString(dealTicket, DEAL_SYMBOL);
double dealVolume = HistoryDealGetDouble(dealTicket, DEAL_VOLUME);
double dealPrice = HistoryDealGetDouble(dealTicket, DEAL_PRICE);
double dealSL = HistoryDealGetDouble(dealTicket, DEAL_SL);
double dealTP = HistoryDealGetDouble(dealTicket, DEAL_TP);
double dealProfit = HistoryDealGetDouble(dealTicket, DEAL_PROFIT);
double dealCommission = HistoryDealGetDouble(dealTicket, DEAL_COMMISSION);
double dealSwap = HistoryDealGetDouble(dealTicket, DEAL_SWAP);
ulong dealMagic = HistoryDealGetInteger(dealTicket, DEAL_MAGIC);
string dealComment = HistoryDealGetString(dealTicket, DEAL_COMMENT);
FileWrite(fileHandle,
dealTicket,
TimeToString(dealTime),
EnumToString(dealType),
dealSymbol,
dealVolume,
dealPrice,
dealSL,
dealTP,
dealProfit,
dealCommission,
dealSwap,
dealMagic,
dealComment);
}
}
}
FileClose(fileHandle);
Print("Backtest report generated: ", btStats.reportFile);
}
//+------------------------------------------------------------------+
//| OnTrade function (enhanced for backtesting) |
//+------------------------------------------------------------------+
void OnTrade()
{
// Update consecutive losses counter
if(HistorySelect(TimeCurrent() - 86400, TimeCurrent())) // Last 24 hours
{
int totalDeals = HistoryDealsTotal();
int recentLosses = 0;
for(int i = totalDeals - 1; i >= 0 && recentLosses < 5; i--)
{
ulong ticket = HistoryDealGetTicket(i);
if(HistoryDealGetInteger(ticket, DEAL_MAGIC) == InpMagicNumber)
{
double profit = HistoryDealGetDouble(ticket, DEAL_PROFIT);
if(profit < 0)
recentLosses++;
else
break;
}
}
consecutiveLosses = recentLosses;
}
// Update backtest statistics for closed trades
ulong dealTicket = HistoryDealGetTicket(HistoryDealsTotal() - 1);
if(dealTicket > 0 && HistoryDealGetInteger(dealTicket, DEAL_MAGIC) == InpMagicNumber)
{
double profit = HistoryDealGetDouble(dealTicket, DEAL_PROFIT);
double commission = HistoryDealGetDouble(dealTicket, DEAL_COMMISSION);
double swap = HistoryDealGetDouble(dealTicket, DEAL_SWAP);
UpdateBacktestStats(dealTicket, profit, commission, swap);
}
}
//+------------------------------------------------------------------+
//| Expert deinitialization function (enhanced) |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- Release indicators
IndicatorRelease(rsiHandle60);
IndicatorRelease(rsiHandle30);
IndicatorRelease(rsiHandle15);
IndicatorRelease(rsiHandle1);
IndicatorRelease(emaHandle0);
IndicatorRelease(emaHandle1);
IndicatorRelease(emaHandle2);
IndicatorRelease(emaHandle3);
IndicatorRelease(atrHandle);
// Generate backtest report if testing
if(reason == REASON_TEST)
{
btStats.endDate = TimeCurrent();
GenerateBacktestReport();
}
// Print trade statistics
PrintTradeStats();
}
//+------------------------------------------------------------------+
//| Expert initialization function (enhanced) |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialize backtest statistics
InitializeBacktestStats();
btStats.startDate = TimeCurrent();
//--- Set magic number
trade.SetExpertMagicNumber(InpMagicNumber);
trade.SetDeviationInPoints(InpSlippage);
//--- Initialize RSI handles for different timeframes
rsiHandle60 = iRSI(_Symbol, PERIOD_H1, InpRSIPeriod, PRICE_CLOSE);
rsiHandle30 = iRSI(_Symbol, PERIOD_M30, InpRSIPeriod, PRICE_CLOSE);
rsiHandle15 = iRSI(_Symbol, PERIOD_M15, InpRSIPeriod, PRICE_CLOSE);
rsiHandle1 = iRSI(_Symbol, PERIOD_M1, InpRSIPeriod, PRICE_CLOSE);
//--- Initialize EMA handles
emaHandle0 = iMA(_Symbol, PERIOD_CURRENT, InpEMA0, 0, MODE_EMA, PRICE_CLOSE);
emaHandle1 = iMA(_Symbol, PERIOD_CURRENT, InpEMA1, 0, MODE_EMA, PRICE_CLOSE);
emaHandle2 = iMA(_Symbol, PERIOD_CURRENT, InpEMA2, 0, MODE_EMA, PRICE_CLOSE);
emaHandle3 = iMA(_Symbol, PERIOD_CURRENT, InpEMA3, 0, MODE_EMA, PRICE_CLOSE);
//--- Initialize ATR handle
atrHandle = iATR(_Symbol, PERIOD_CURRENT, 14);
//--- Check handles
if(rsiHandle60 == INVALID_HANDLE || rsiHandle30 == INVALID_HANDLE ||
rsiHandle15 == INVALID_HANDLE || rsiHandle1 == INVALID_HANDLE ||
emaHandle0 == INVALID_HANDLE || atrHandle == INVALID_HANDLE)
{
Print("Error creating indicators");
return INIT_FAILED;
}
//--- Array settings
ArraySetAsSeries(rsi60, true);
ArraySetAsSeries(rsi30, true);
ArraySetAsSeries(rsi15, true);
ArraySetAsSeries(rsi1, true);
ArraySetAsSeries(ema0, true);
ArraySetAsSeries(ema1, true);
ArraySetAsSeries(ema2, true);
ArraySetAsSeries(ema3, true);
ArraySetAsSeries(atrValues, true);
//--- Initialize stats
InitializeStats();
accountBalance = AccountInfoDouble(ACCOUNT_BALANCE);
Print("RSI Algorithm EA initialized successfully");
return INIT_SUCCEEDED;
}
Key Enhancements for Backtesting:
Comprehensive Backtest Statistics Structure :
Tracks all essential metrics (net profit, drawdown, win rate, etc.)
Stores trade history and generates detailed reports
Automated Report Generation :
Creates CSV files with:
Summary statistics
Detailed trade history
Performance metrics
Files are named with symbol, timeframe, and magic number
Enhanced Trade Tracking :
Updates statistics for every trade closure
Calculates real-time drawdown and equity
Tracks consecutive losses for risk management
Strategy Tester Integration :
Automatically generates reports when backtesting completes
Captures full trade history from Strategy Tester
Handles both live and testing modes
Performance Metrics :
Profit Factor
Recovery Factor
Sharpe Ratio
Expected Payoff
Maximum Drawdown (absolute and percentage)
How to Use in Strategy Tester:
Open the Strategy Tester in MT5
Select your RSI Algorithm EA
Configure testing parameters:
Symbol and timeframe
Testing period
Initial deposit
Model quality (99% recommended)
Run the backtest
After completion:
Find the report in MQL5/Files/
Reports are named like: Backtest_EURUSD_H1_123456.csv
Report Contents:
The generated CSV file includes:
Summary Section :
Total trades, wins, losses
Win rate and profit factor
Net profit and drawdown metrics
Trade History Section :
Every trade with entry/exit details
Profit/loss per trade
Commission and swap costs
Trade comments and timestamps
This backtesting system provides comprehensive performance analysis to help optimize your RSI trading strategy parameters.
Show full message · 387 lines Copy first response