XAUUSD H1 6 months RSIReversalProEA optimized result. 15 wins, 1 loss.
//+------------------------------------------------------------------+
//| RSIReversalPro.mq5 |
//| Copyright 2025, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.05"
#property strict
#ifndef SYMBOL_VOLUME_DIGITS
#define SYMBOL_VOLUME_DIGITS 71
#endif
#include
input double InpRisk = 2.0; // Maximum Risk in percentage
input int InpStopLoss = 505; // Stop Loss in points
input int InpTakeProfit = 5000; // Take Profit in points
input long InpMagicNumber = 550; // Unique number
input int InpRSIPeriod = 12; // RSI period
input ENUM_APPLIED_PRICE InpRSIAP = PRICE_MEDIAN; // RSI Applied price
input double InpRSIOBLevel = 99.0; // RSI over bought level
input double InpRSIOSLevel = 15.0; // RSI over sold level
//---
int handle=0;
bool hedging=false;
CTrade trade;
double RSI[],DecreaseFactor=3.0;
MqlRates ratesBuffer[];
//+------------------------------------------------------------------+
//| Calculate optimal lot size |
//+------------------------------------------------------------------+
double TradeSizeOptimized(void)
{
int leverage=0;
double price=0.0;
double margin=0.0;
//--- select lot size
if(!SymbolInfoDouble(_Symbol,SYMBOL_ASK,price))
return(0.0);
if(!OrderCalcMargin(ORDER_TYPE_BUY,_Symbol,1.0,price,margin))
return(0.0);
if(margin<=0.0)
return(0.0);
long volumeDigits;
if(!SymbolInfoInteger(_Symbol, SYMBOL_VOLUME_DIGITS, volumeDigits))
{
Print("Failed to get SYMBOL_VOLUME_DIGITS: ", GetLastError());
volumeDigits = 2;
}
int lotDigits=(int)volumeDigits;
if(lotDigits < 0 || lotDigits > 9)
{
Print("Invalid SYMBOL_VOLUME_DIGITS: ", lotDigits, ", using default 2");
lotDigits = 2;
}
leverage=(int)AccountInfoInteger(ACCOUNT_LEVERAGE)/2;
double lot=NormalizeDouble(AccountInfoDouble(ACCOUNT_MARGIN_FREE)*InpRisk/10000/margin*leverage,lotDigits);
//--- calculate number of losses orders without a break
if(DecreaseFactor>0)
{
//--- select history for access
HistorySelect(0,TimeCurrent());
//---
int orders=HistoryDealsTotal(); // total history deals
int losses=0; // number of losses orders without a break
for(int i=orders-1;i>=0;i--)
{
ulong ticket=HistoryDealGetTicket(i);
if(ticket==0)
{
Print("HistoryDealGetTicket failed, no trade history");
break;
}
//--- check symbol
if(HistoryDealGetString(ticket,DEAL_SYMBOL)!=_Symbol)
continue;
//--- check Expert Magic number
if(HistoryDealGetInteger(ticket,DEAL_MAGIC)!=InpMagicNumber)
continue;
//--- check profit
double profit=HistoryDealGetDouble(ticket,DEAL_PROFIT);
if(profit>0.0)
break;
if(profit losses++;
}
//---
if(losses>2)
lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,lotDigits);
}
//--- normalize and check limits
double stepvol=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
lot=stepvol*NormalizeDouble(lot/stepvol,lotDigits);
double minvol=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
if(lot lot=minvol;
double maxvol=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
if(lot>maxvol)
lot=maxvol;
//--- return trading volume
return(lot);
}
//+------------------------------------------------------------------+
//| Check for open position conditions |
//+------------------------------------------------------------------+
void CheckForOpen(void)
{
double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(_Symbol,SYMBOL_DIGITS);
//--- go trading only on ticks
if(CopyRates(_Symbol,_Period,0,2,ratesBuffer)!=2)
{
Print("CopyRates of ",_Symbol," failed, no history");
return;
}
if(ratesBuffer[1].tick_volume return;
//--- get current RSI value
if(CopyBuffer(handle,0,0,2,RSI)!=2)
{
Print("CopyBuffer from iRSI failed, no data");
return;
}
//--- check signals
ENUM_ORDER_TYPE signal=WRONG_VALUE;
if(RSI[1] < InpRSIOBLevel && RSI[0]>InpRSIOBLevel)
signal=ORDER_TYPE_SELL; // sell conditions
else
{
if(RSI[1] > InpRSIOBLevel && RSI[0] < InpRSIOSLevel)
signal=ORDER_TYPE_BUY; // buy conditions
}
//--- additional checking
if(signal!=WRONG_VALUE)
{
double price = SymbolInfoDouble(_Symbol, signal == ORDER_TYPE_SELL ? SYMBOL_BID : SYMBOL_ASK);
double sl = signal == ORDER_TYPE_BUY ? price - InpStopLoss * point : price + InpStopLoss * point;
double tp = signal == ORDER_TYPE_BUY ? price + InpTakeProfit * point : price - InpTakeProfit * point;
if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && Bars(_Symbol,_Period)>100)
trade.PositionOpen(_Symbol,signal,TradeSizeOptimized(),
SymbolInfoDouble(_Symbol,signal==ORDER_TYPE_SELL ? SYMBOL_BID:SYMBOL_ASK),
sl,tp,"RSIReversalProEA");
}
//---
}
//+------------------------------------------------------------------+
//| Check for close position conditions |
//+------------------------------------------------------------------+
void CheckForClose(void)
{
//--- go trading only for first ticks of new bar
if(CopyRates(_Symbol,_Period,0,2,ratesBuffer)!=2)
{
Print("CopyRates of ",_Symbol," failed, no history");
return;
}
if(ratesBuffer[1].tick_volume>1)
return;
//--- get current RSI value
double ma[1];
if(CopyBuffer(handle,0,0,2,RSI)!=2)
{
Print("CopyBuffer from iMA failed, no data");
return;
}
//--- positions already selected before
bool signal=false;
long type=PositionGetInteger(POSITION_TYPE);
if(type==(long)POSITION_TYPE_BUY && RSI[1] < InpRSIOBLevel && RSI[0]>InpRSIOBLevel)
signal=true;
if(type==(long)POSITION_TYPE_SELL && RSI[1] > InpRSIOSLevel && RSI[0] signal=true;
//--- additional checking
if(signal)
{
if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && Bars(_Symbol,_Period)>100)
trade.PositionClose(_Symbol,0);
}
//---
}
//+------------------------------------------------------------------+
//| Position select depending on netting or hedging |
//+------------------------------------------------------------------+
bool SelectPosition()
{
bool res=false;
//--- check position in Hedging mode
if(hedging)
{
uint total=PositionsTotal();
for(uint i=0; i {
string position_symbol=PositionGetSymbol(i);
if(_Symbol==position_symbol && InpMagicNumber==PositionGetInteger(POSITION_MAGIC))
{
res=true;
break;
}
}
}
//--- check position in Netting mode
else
{
if(!PositionSelect(_Symbol))
return(false);
else
return(PositionGetInteger(POSITION_MAGIC)==InpMagicNumber); //---check Magic number
}
//--- result for Hedging mode
return(res);
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit(void)
{
//--- prepare trade class to control positions if hedging mode is active
hedging=((ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGIN_MODE)==ACCOUNT_MARGIN_MODE_RETAIL_HEDGING);
trade.SetExpertMagicNumber(InpMagicNumber);
trade.SetMarginMode();
trade.SetTypeFillingBySymbol(Symbol());
//--- Moving Average indicator
if(INVALID_HANDLE==(handle=iRSI(_Symbol,_Period,InpRSIPeriod,InpRSIAP)))
{
printf("Error creating RSI indicator, please check inputs");
return(INIT_PARAMETERS_INCORRECT);
}
ArraySetAsSeries(ratesBuffer,true);
ArraySetAsSeries(RSI,true);
//--- ok
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick(void)
{
//---
if(SelectPosition())
CheckForClose();
else
CheckForOpen();
//---
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
if(handle!=INVALID_HANDLE)
IndicatorRelease(handle);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| RSIReversalPro.mq5 |
//| Copyright 2025, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.05"
#property strict
#ifndef SYMBOL_VOLUME_DIGITS
#define SYMBOL_VOLUME_DIGITS 71
#endif
#include
input double InpRisk = 2.0; // Maximum Risk in percentage
input int InpStopLoss = 505; // Stop Loss in points
input int InpTakeProfit = 5000; // Take Profit in points
input long InpMagicNumber = 550; // Unique number
input int InpRSIPeriod = 12; // RSI period
input ENUM_APPLIED_PRICE InpRSIAP = PRICE_MEDIAN; // RSI Applied price
input double InpRSIOBLevel = 99.0; // RSI over bought level
input double InpRSIOSLevel = 15.0; // RSI over sold level
//---
int handle=0;
bool hedging=false;
CTrade trade;
double RSI[],DecreaseFactor=3.0;
MqlRates ratesBuffer[];
//+------------------------------------------------------------------+
//| Calculate optimal lot size |
//+------------------------------------------------------------------+
double TradeSizeOptimized(void)
{
int leverage=0;
double price=0.0;
double margin=0.0;
//--- select lot size
if(!SymbolInfoDouble(_Symbol,SYMBOL_ASK,price))
return(0.0);
if(!OrderCalcMargin(ORDER_TYPE_BUY,_Symbol,1.0,price,margin))
return(0.0);
if(margin<=0.0)
return(0.0);
long volumeDigits;
if(!SymbolInfoInteger(_Symbol, SYMBOL_VOLUME_DIGITS, volumeDigits))
{
Print("Failed to get SYMBOL_VOLUME_DIGITS: ", GetLastError());
volumeDigits = 2;
}
int lotDigits=(int)volumeDigits;
if(lotDigits < 0 || lotDigits > 9)
{
Print("Invalid SYMBOL_VOLUME_DIGITS: ", lotDigits, ", using default 2");
lotDigits = 2;
}
leverage=(int)AccountInfoInteger(ACCOUNT_LEVERAGE)/2;
double lot=NormalizeDouble(AccountInfoDouble(ACCOUNT_MARGIN_FREE)*InpRisk/10000/margin*leverage,lotDigits);
//--- calculate number of losses orders without a break
if(DecreaseFactor>0)
{
//--- select history for access
HistorySelect(0,TimeCurrent());
//---
int orders=HistoryDealsTotal(); // total history deals
int losses=0; // number of losses orders without a break
for(int i=orders-1;i>=0;i--)
{
ulong ticket=HistoryDealGetTicket(i);
if(ticket==0)
{
Print("HistoryDealGetTicket failed, no trade history");
break;
}
//--- check symbol
if(HistoryDealGetString(ticket,DEAL_SYMBOL)!=_Symbol)
continue;
//--- check Expert Magic number
if(HistoryDealGetInteger(ticket,DEAL_MAGIC)!=InpMagicNumber)
continue;
//--- check profit
double profit=HistoryDealGetDouble(ticket,DEAL_PROFIT);
if(profit>0.0)
break;
if(profit losses++;
}
//---
if(losses>2)
lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,lotDigits);
}
//--- normalize and check limits
double stepvol=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
lot=stepvol*NormalizeDouble(lot/stepvol,lotDigits);
double minvol=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
if(lot lot=minvol;
double maxvol=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
if(lot>maxvol)
lot=maxvol;
//--- return trading volume
return(lot);
}
//+------------------------------------------------------------------+
//| Check for open position conditions |
//+------------------------------------------------------------------+
void CheckForOpen(void)
{
double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(_Symbol,SYMBOL_DIGITS);
//--- go trading only on ticks
if(CopyRates(_Symbol,_Period,0,2,ratesBuffer)!=2)
{
Print("CopyRates of ",_Symbol," failed, no history");
return;
}
if(ratesBuffer[1].tick_volume return;
//--- get current RSI value
if(CopyBuffer(handle,0,0,2,RSI)!=2)
{
Print("CopyBuffer from iRSI failed, no data");
return;
}
//--- check signals
ENUM_ORDER_TYPE signal=WRONG_VALUE;
if(RSI[1] < InpRSIOBLevel && RSI[0]>InpRSIOBLevel)
signal=ORDER_TYPE_SELL; // sell conditions
else
{
if(RSI[1] > InpRSIOBLevel && RSI[0] < InpRSIOSLevel)
signal=ORDER_TYPE_BUY; // buy conditions
}
//--- additional checking
if(signal!=WRONG_VALUE)
{
double price = SymbolInfoDouble(_Symbol, signal == ORDER_TYPE_SELL ? SYMBOL_BID : SYMBOL_ASK);
double sl = signal == ORDER_TYPE_BUY ? price - InpStopLoss * point : price + InpStopLoss * point;
double tp = signal == ORDER_TYPE_BUY ? price + InpTakeProfit * point : price - InpTakeProfit * point;
if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && Bars(_Symbol,_Period)>100)
trade.PositionOpen(_Symbol,signal,TradeSizeOptimized(),
SymbolInfoDouble(_Symbol,signal==ORDER_TYPE_SELL ? SYMBOL_BID:SYMBOL_ASK),
sl,tp,"RSIReversalProEA");
}
//---
}
//+------------------------------------------------------------------+
//| Check for close position conditions |
//+------------------------------------------------------------------+
void CheckForClose(void)
{
//--- go trading only for first ticks of new bar
if(CopyRates(_Symbol,_Period,0,2,ratesBuffer)!=2)
{
Print("CopyRates of ",_Symbol," failed, no history");
return;
}
if(ratesBuffer[1].tick_volume>1)
return;
//--- get current RSI value
double ma[1];
if(CopyBuffer(handle,0,0,2,RSI)!=2)
{
Print("CopyBuffer from iMA failed, no data");
return;
}
//--- positions already selected before
bool signal=false;
long type=PositionGetInteger(POSITION_TYPE);
if(type==(long)POSITION_TYPE_BUY && RSI[1] < InpRSIOBLevel && RSI[0]>InpRSIOBLevel)
signal=true;
if(type==(long)POSITION_TYPE_SELL && RSI[1] > InpRSIOSLevel && RSI[0] signal=true;
//--- additional checking
if(signal)
{
if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && Bars(_Symbol,_Period)>100)
trade.PositionClose(_Symbol,0);
}
//---
}
//+------------------------------------------------------------------+
//| Position select depending on netting or hedging |
//+------------------------------------------------------------------+
bool SelectPosition()
{
bool res=false;
//--- check position in Hedging mode
if(hedging)
{
uint total=PositionsTotal();
for(uint i=0; i {
string position_symbol=PositionGetSymbol(i);
if(_Symbol==position_symbol && InpMagicNumber==PositionGetInteger(POSITION_MAGIC))
{
res=true;
break;
}
}
}
//--- check position in Netting mode
else
{
if(!PositionSelect(_Symbol))
return(false);
else
return(PositionGetInteger(POSITION_MAGIC)==InpMagicNumber); //---check Magic number
}
//--- result for Hedging mode
return(res);
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit(void)
{
//--- prepare trade class to control positions if hedging mode is active
hedging=((ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGIN_MODE)==ACCOUNT_MARGIN_MODE_RETAIL_HEDGING);
trade.SetExpertMagicNumber(InpMagicNumber);
trade.SetMarginMode();
trade.SetTypeFillingBySymbol(Symbol());
//--- Moving Average indicator
if(INVALID_HANDLE==(handle=iRSI(_Symbol,_Period,InpRSIPeriod,InpRSIAP)))
{
printf("Error creating RSI indicator, please check inputs");
return(INIT_PARAMETERS_INCORRECT);
}
ArraySetAsSeries(ratesBuffer,true);
ArraySetAsSeries(RSI,true);
//--- ok
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick(void)
{
//---
if(SelectPosition())
CheckForClose();
else
CheckForOpen();
//---
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
if(handle!=INVALID_HANDLE)
IndicatorRelease(handle);
}
//+------------------------------------------------------------------+

