//+… · 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 Mistral AI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Added to archive Nov 19, 2026
ID 01m7tp9wjq0c61vnne2gv92ec6Source & license Imported from Arena Expert 5K (source ). Imported records earn no Research Points.
Upstream record: 999f53e6-dfae-481e-bbda-009857e3f379:b
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 MQL5 Expert Advisor (EA), you need to ensure that the EA is designed to work with the Strategy Tester in MetaTrader 5. The Strategy Tester allows you to simulate the performance of your EA over historical data. Below are the steps and modifications you need to make to enable backtesting:
Ensure Proper Initialization and Deinitialization : The OnInit and OnDeinit functions should handle the initialization and cleanup of indicators and other resources properly.
Use Strategy Tester Functions : Utilize functions like OnTester and OnTesterInit to handle backtesting-specific logic.
Handle Historical Data : Ensure that the EA can handle historical data correctly, especially if it relies on indicators that need a certain amount of historical data to function properly.
Logging and Debugging : Add logging to help debug issues during backtesting.
Here is the modified code with backtesting capabilities added:
mql5 Copy code
//+------------------------------------------------------------------+
//| 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
//--- 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;
};
TradeStats stats;
//+------------------------------------------------------------------+
//| 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);
//--- 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);
PrintTradeStats();
}
//+------------------------------------------------------------------+
//| 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);
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;
}
return true;
}
//+------------------------------------------------------------------+
//| 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]);
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];
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);
if(lotSize <= 0)
return;
//--- 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);
if(lotSize <= 0)
return;
//--- 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);
//--- 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;
return lotSize;
}
//+------------------------------------------------------------------+
//| 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;
case 1: // SL_PERCENTAGE
slDistance = entryPrice * InpSLPercentage / 100.0;
break;
case 2: // SL_FIXED
slDistance = InpSLPoints * _Point;
break;
}
return slDistance;
}
//+------------------------------------------------------------------+
//| 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);
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;
return true;
}
//+------------------------------------------------------------------+
//| 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++;
}
}
}
return 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++;
}
}
}
return 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;
if(newSL > currentSL && newSL < currentPrice)
{
trade.PositionModify(ticket, newSL, positionInfo.TakeProfit());
}
}
else
{
double newSL = currentPrice + atrValue * InpSLATRMult;
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;
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;
}
}
//+------------------------------------------------------------------+
//| OnTester function |
//+------------------------------------------------------------------+
void OnTester()
{
//--- Update statistics during backtesting
UpdateStats();
}
//+------------------------------------------------------------------+
//| OnTesterInit function |
//+------------------------------------------------------------------+
void OnTesterInit()
{
//--- Initialize statistics for backtesting
InitializeStats();
}
Explanation of Changes:
OnTester and OnTesterInit Functions : These functions are added to handle backtesting-specific logic. OnTesterInit initializes the statistics, and OnTester updates the statistics during the backtest.
Logging and Debugging : Added Print statements to help debug issues during backtesting.
Historical Data Handling : Ensured that the EA can handle historical data correctly, especially for indicators that need a certain amount of historical data.
Strategy Tester Functions : Utilized OnTester and OnTesterInit to handle backtesting-specific logic.
With these changes, your EA should be ready for backtesting in the MetaTrader 5 Strategy Tester. You can now run the backtest to simulate the performance of your EA over historical data.
Show full message · 836 lines Copy first response