This commit is contained in:
zhutoutoutousan
2026-01-05 07:02:00 +01:00
parent 5b44e14211
commit ee170ac827
35 changed files with 3 additions and 3 deletions
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 239 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 250 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 233 KiB

@@ -1,586 +0,0 @@
//+------------------------------------------------------------------+
//| RSIFollowReverseEMACrossOver.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
// Input Parameters
input group "General Settings"
input ENUM_TIMEFRAMES InpTimeframe = PERIOD_CURRENT; // Trading Timeframe
input double InpLotSize = 0.01; // Lot Size
input int InpMagicNumberRSIFollow = 1001; // Magic Number RSI Follow
input int InpMagicNumberRSIReverse = 1002;// Magic Number RSI Reverse
input int InpMagicNumberEMACross = 1003; // Magic Number EMA Cross
input group "Strategy Switches"
input bool InpEnableRSIFollow = true; // Enable RSI Follow Strategy
input bool InpEnableRSIReverse = true; // Enable RSI Reverse Strategy
input bool InpEnableEMACross = true; // Enable EMA Cross Strategy
input bool InpEnableStrategyLock = false; // Enable Strategy Lock
input double InpLockProfitThreshold = 120.0; // Lock Profit Threshold (pips)
input bool InpCloseOppositeTrades = true; // Close Opposite Trades When Profiting
input group "RSI Follow Strategy"
input int InpRSIPeriod = 49; // RSI Period
input int InpRSIOverbought = 81; // RSI Overbought Level
input int InpRSIOversold = 41; // RSI Oversold Level
input int InpRSIExitLevel = 48; // RSI Exit Level
input int InpRSIFollowStartHour = 24; // RSI Follow Start Hour (0-23)
input int InpRSIFollowEndHour = 8; // RSI Follow End Hour (0-23)
input bool InpRSIFollowCloseOutsideHours = false; // Close trades outside trading hours
input group "RSI Reverse Strategy"
input int InpRSIReversePeriod = 159; // RSI Period
input int InpRSIReverseOverbought = 51; // RSI Overbought Level
input int InpRSIReverseOversold = 49; // RSI Oversold Level
input int InpRSIReverseCrossLevel = 54; // RSI Cross Level
input int InpRSIReverseExitLevel = 49; // RSI Exit Level
input int InpRSIReverseStartHour = 12; // RSI Reverse Start Hour (0-23)
input int InpRSIReverseEndHour = 22; // RSI Reverse End Hour (0-23)
input bool InpRSIReverseCloseOutsideHours = false; // Close trades outside trading hours
input int InpRSIReverseCooldownBars = 11; // RSI Reverse Cooldown (bars)
input bool InpRSIReverseCooldownOnLoss = true; // Apply cooldown only on loss
input group "EMA Cross Strategy"
input int InpEMAPeriod = 175; // EMA Period
input int InpEMACrossStartHour = 22; // EMA Cross Start Hour (0-23)
input int InpEMACrossEndHour = 12; // EMA Cross End Hour (0-23)
input bool InpEMACrossCloseOutsideHours = false; // Close trades outside trading hours
input bool InpUseEMADistanceEntry = true; // Use EMA Distance Entry
input double InpEMADistancePips = 8440.0; // EMA Distance Threshold (pips)
input int InpEMADistancePeriod = 30; // EMA Distance Period (bars)
// Global Variables
int rsiHandle;
int rsiReverseHandle;
int emaHandle;
bool rsiOverbought = false;
bool rsiOversold = false;
bool rsiReverseOverbought = false;
bool rsiReverseOversold = false;
CTrade trade;
CPositionInfo positionInfo;
bool emaCrossBuySignal = false;
bool emaCrossSellSignal = false;
int emaCrossSignalBar = 0;
datetime lastBarTime = 0;
datetime rsiReverseLastCloseTime = 0;
bool rsiReverseInCooldown = false;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialize indicators
rsiHandle = iRSI(_Symbol, InpTimeframe, InpRSIPeriod, PRICE_CLOSE);
rsiReverseHandle = iRSI(_Symbol, InpTimeframe, InpRSIReversePeriod, PRICE_CLOSE);
emaHandle = iMA(_Symbol, InpTimeframe, InpEMAPeriod, 0, MODE_EMA, PRICE_CLOSE);
if(rsiHandle == INVALID_HANDLE || rsiReverseHandle == INVALID_HANDLE || emaHandle == INVALID_HANDLE)
{
Print("Error creating indicators");
return INIT_FAILED;
}
// Initialize trade settings
trade.SetExpertMagicNumber(InpMagicNumberRSIFollow);
trade.SetMarginMode();
trade.SetTypeFillingBySymbol(_Symbol);
trade.SetDeviationInPoints(10);
// Initialize last bar time
datetime time[];
if(CopyTime(_Symbol, InpTimeframe, 0, 1, time) > 0)
{
lastBarTime = time[0];
}
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Check if new bar has formed |
//+------------------------------------------------------------------+
bool IsNewBar()
{
datetime time[];
if(CopyTime(_Symbol, InpTimeframe, 0, 1, time) > 0)
{
if(time[0] != lastBarTime)
{
lastBarTime = time[0];
return true;
}
}
return false;
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Release indicator handles
IndicatorRelease(rsiHandle);
IndicatorRelease(rsiReverseHandle);
IndicatorRelease(emaHandle);
}
//+------------------------------------------------------------------+
//| Check if current time is within trading hours |
//+------------------------------------------------------------------+
bool IsWithinTradingHours(int startHour, int endHour)
{
MqlDateTime currentTime;
TimeToStruct(TimeCurrent(), currentTime);
if(startHour <= endHour)
{
return (currentTime.hour >= startHour && currentTime.hour < endHour);
}
else
{
return (currentTime.hour >= startHour || currentTime.hour < endHour);
}
}
//+------------------------------------------------------------------+
//| Check if position exists for given magic number |
//+------------------------------------------------------------------+
bool HasPosition(int magic)
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(positionInfo.SelectByIndex(i))
{
if(positionInfo.Magic() == magic)
return true;
}
}
return false;
}
//+------------------------------------------------------------------+
//| Check if any strategy has profitable position |
//+------------------------------------------------------------------+
bool HasProfitablePosition(int excludeMagic)
{
bool hasProfitable = false;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(positionInfo.SelectByIndex(i))
{
if(positionInfo.Magic() != excludeMagic)
{
double profit = positionInfo.Profit();
if(profit > InpLockProfitThreshold * _Point)
{
hasProfitable = true;
// If enabled, close opposite trades
if(InpCloseOppositeTrades)
{
// Check if this is an opposite trade to the excluded magic number
if((excludeMagic == InpMagicNumberRSIFollow && positionInfo.Magic() == InpMagicNumberRSIReverse) ||
(excludeMagic == InpMagicNumberRSIReverse && positionInfo.Magic() == InpMagicNumberRSIFollow) ||
(excludeMagic == InpMagicNumberEMACross && (positionInfo.Magic() == InpMagicNumberRSIReverse || positionInfo.Magic() == InpMagicNumberRSIFollow)) ||
((excludeMagic == InpMagicNumberRSIFollow || excludeMagic == InpMagicNumberRSIReverse) && positionInfo.Magic() == InpMagicNumberEMACross))
{
ClosePosition(positionInfo.Magic());
}
}
}
}
}
}
return hasProfitable;
}
//+------------------------------------------------------------------+
//| Check for RSI Follow Strategy signals |
//+------------------------------------------------------------------+
void CheckRSIFollowStrategy()
{
// Check if within trading hours
if(!IsWithinTradingHours(InpRSIFollowStartHour, InpRSIFollowEndHour))
{
if(InpRSIFollowCloseOutsideHours)
{
if(HasPosition(InpMagicNumberRSIFollow))
{
ClosePosition(InpMagicNumberRSIFollow);
}
}
return;
}
// Check strategy lock
if(InpEnableStrategyLock && HasProfitablePosition(InpMagicNumberRSIFollow))
return;
double rsi[];
ArraySetAsSeries(rsi, true);
CopyBuffer(rsiHandle, 0, 0, 3, rsi);
if(ArraySize(rsi) < 3) return;
// Check for overbought condition
if(rsi[1] > InpRSIOverbought)
rsiOverbought = true;
else if(rsi[1] < InpRSIOversold)
rsiOversold = true;
// Check for entry signals
if(rsiOverbought && rsi[1] < rsi[0] && rsi[1] < InpRSIExitLevel)
{
// Sell signal
if(!HasPosition(InpMagicNumberRSIFollow))
{
trade.SetExpertMagicNumber(InpMagicNumberRSIFollow);
trade.Sell(InpLotSize, _Symbol, 0, 0, 0, "RSI Follow");
}
rsiOverbought = false;
}
else if(rsiOversold && rsi[1] > rsi[0] && rsi[1] > InpRSIExitLevel)
{
// Buy signal
if(!HasPosition(InpMagicNumberRSIFollow))
{
trade.SetExpertMagicNumber(InpMagicNumberRSIFollow);
trade.Buy(InpLotSize, _Symbol, 0, 0, 0, "RSI Follow");
}
rsiOversold = false;
}
}
//+------------------------------------------------------------------+
//| Check if RSI Reverse is in cooldown |
//+------------------------------------------------------------------+
bool IsRSIReverseInCooldown()
{
if(InpRSIReverseCooldownBars <= 0)
return false;
if(!rsiReverseInCooldown)
return false;
datetime time[];
if(CopyTime(_Symbol, InpTimeframe, 0, 1, time) > 0)
{
datetime currentBarTime = time[0];
datetime cooldownEndTime = rsiReverseLastCloseTime + InpRSIReverseCooldownBars * PeriodSeconds(InpTimeframe);
if(currentBarTime >= cooldownEndTime)
{
rsiReverseInCooldown = false;
return false;
}
}
return true;
}
//+------------------------------------------------------------------+
//| Check for RSI Reverse Strategy signals |
//+------------------------------------------------------------------+
void CheckRSIReverseStrategy()
{
// Check if within trading hours
if(!IsWithinTradingHours(InpRSIReverseStartHour, InpRSIReverseEndHour))
{
if(InpRSIReverseCloseOutsideHours)
{
if(HasPosition(InpMagicNumberRSIReverse))
{
ClosePosition(InpMagicNumberRSIReverse);
}
}
return;
}
// Check strategy lock
if(InpEnableStrategyLock && HasProfitablePosition(InpMagicNumberRSIReverse))
return;
// Check cooldown
if(IsRSIReverseInCooldown())
return;
double rsi[];
ArraySetAsSeries(rsi, true);
CopyBuffer(rsiReverseHandle, 0, 0, 3, rsi);
if(ArraySize(rsi) < 3) return;
// Check for overbought/oversold conditions
if(rsi[1] > InpRSIReverseOverbought)
rsiReverseOverbought = true;
else if(rsi[1] < InpRSIReverseOversold)
rsiReverseOversold = true;
// Check for entry signals
if(rsiReverseOverbought && rsi[1] < InpRSIReverseCrossLevel)
{
// Sell signal
if(!HasPosition(InpMagicNumberRSIReverse))
{
trade.SetExpertMagicNumber(InpMagicNumberRSIReverse);
trade.Sell(InpLotSize, _Symbol, 0, 0, 0, "RSI Reverse");
}
rsiReverseOverbought = false;
}
else if(rsiReverseOversold && rsi[1] > InpRSIReverseCrossLevel)
{
// Buy signal
if(!HasPosition(InpMagicNumberRSIReverse))
{
trade.SetExpertMagicNumber(InpMagicNumberRSIReverse);
trade.Buy(InpLotSize, _Symbol, 0, 0, 0, "RSI Reverse");
}
rsiReverseOversold = false;
}
}
//+------------------------------------------------------------------+
//| Check for EMA Cross Strategy signals |
//+------------------------------------------------------------------+
void CheckEMACrossStrategy()
{
// Check if within trading hours
if(!IsWithinTradingHours(InpEMACrossStartHour, InpEMACrossEndHour))
{
if(InpEMACrossCloseOutsideHours)
{
if(HasPosition(InpMagicNumberEMACross))
{
ClosePosition(InpMagicNumberEMACross);
}
}
return;
}
// Check strategy lock
if(InpEnableStrategyLock && HasProfitablePosition(InpMagicNumberEMACross))
return;
double ema[], close[];
ArraySetAsSeries(ema, true);
ArraySetAsSeries(close, true);
CopyBuffer(emaHandle, 0, 0, InpEMADistancePeriod + 2, ema);
CopyClose(_Symbol, InpTimeframe, 0, InpEMADistancePeriod + 2, close);
if(ArraySize(ema) < InpEMADistancePeriod + 2 || ArraySize(close) < InpEMADistancePeriod + 2) return;
// Check for cross signals
if(ema[1] < close[1] && ema[0] > close[0])
{
// Buy cross signal
emaCrossBuySignal = true;
emaCrossSellSignal = false;
emaCrossSignalBar = 0;
}
else if(ema[1] > close[1] && ema[0] < close[0])
{
// Sell cross signal
emaCrossSellSignal = true;
emaCrossBuySignal = false;
emaCrossSignalBar = 0;
}
// Check for distance entry conditions
if(InpUseEMADistanceEntry)
{
if(emaCrossBuySignal)
{
// Check if price has moved above EMA by the required distance for the required period
bool distanceConditionMet = true;
for(int i = 0; i < InpEMADistancePeriod; i++)
{
double distance = (close[i] - ema[i]) / _Point;
if(distance < InpEMADistancePips)
{
distanceConditionMet = false;
break;
}
}
if(distanceConditionMet && !HasPosition(InpMagicNumberEMACross))
{
trade.SetExpertMagicNumber(InpMagicNumberEMACross);
trade.Buy(InpLotSize, _Symbol, 0, 0, 0, "EMA Cross Distance");
emaCrossBuySignal = false;
}
}
else if(emaCrossSellSignal)
{
// Check if price has moved below EMA by the required distance for the required period
bool distanceConditionMet = true;
for(int i = 0; i < InpEMADistancePeriod; i++)
{
double distance = (ema[i] - close[i]) / _Point;
if(distance < InpEMADistancePips)
{
distanceConditionMet = false;
break;
}
}
if(distanceConditionMet && !HasPosition(InpMagicNumberEMACross))
{
trade.SetExpertMagicNumber(InpMagicNumberEMACross);
trade.Sell(InpLotSize, _Symbol, 0, 0, 0, "EMA Cross Distance");
emaCrossSellSignal = false;
}
}
}
else
{
// Original cross entry logic
if(ema[1] < close[1] && ema[0] > close[0])
{
// Buy signal
if(!HasPosition(InpMagicNumberEMACross))
{
trade.SetExpertMagicNumber(InpMagicNumberEMACross);
trade.Buy(InpLotSize, _Symbol, 0, 0, 0, "EMA Cross");
}
}
else if(ema[1] > close[1] && ema[0] < close[0])
{
// Sell signal
if(!HasPosition(InpMagicNumberEMACross))
{
trade.SetExpertMagicNumber(InpMagicNumberEMACross);
trade.Sell(InpLotSize, _Symbol, 0, 0, 0, "EMA Cross");
}
}
}
// Increment signal bar counter
if(emaCrossBuySignal || emaCrossSellSignal)
{
emaCrossSignalBar++;
// Reset signals if they're too old (optional, can be removed if not needed)
if(emaCrossSignalBar > InpEMADistancePeriod * 2)
{
emaCrossBuySignal = false;
emaCrossSellSignal = false;
}
}
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Only process on new bar
if(!IsNewBar())
return;
// Check for new signals
if(InpEnableRSIFollow)
CheckRSIFollowStrategy();
if(InpEnableRSIReverse)
CheckRSIReverseStrategy();
if(InpEnableEMACross)
CheckEMACrossStrategy();
// Check for exit conditions
CheckExitConditions();
}
//+------------------------------------------------------------------+
//| Check exit conditions for all strategies |
//+------------------------------------------------------------------+
void CheckExitConditions()
{
double rsi[], rsiReverse[], ema[], close[];
ArraySetAsSeries(rsi, true);
ArraySetAsSeries(rsiReverse, true);
ArraySetAsSeries(ema, true);
ArraySetAsSeries(close, true);
if(InpEnableRSIFollow)
{
CopyBuffer(rsiHandle, 0, 0, 1, rsi);
// Check RSI Follow exit conditions
if(HasPosition(InpMagicNumberRSIFollow))
{
if((positionInfo.PositionType() == POSITION_TYPE_BUY && rsi[0] < InpRSIExitLevel) ||
(positionInfo.PositionType() == POSITION_TYPE_SELL && rsi[0] > InpRSIExitLevel))
{
ClosePosition(InpMagicNumberRSIFollow);
}
}
}
if(InpEnableRSIReverse)
{
CopyBuffer(rsiReverseHandle, 0, 0, 1, rsiReverse);
// Check RSI Reverse exit conditions
if(HasPosition(InpMagicNumberRSIReverse))
{
if((positionInfo.PositionType() == POSITION_TYPE_BUY && rsiReverse[0] < InpRSIReverseExitLevel) ||
(positionInfo.PositionType() == POSITION_TYPE_SELL && rsiReverse[0] > InpRSIReverseExitLevel))
{
ClosePosition(InpMagicNumberRSIReverse);
}
}
}
if(InpEnableEMACross)
{
CopyBuffer(emaHandle, 0, 0, 2, ema);
CopyClose(_Symbol, InpTimeframe, 0, 2, close);
// Check EMA Cross exit conditions
if(HasPosition(InpMagicNumberEMACross))
{
if((positionInfo.PositionType() == POSITION_TYPE_BUY && ema[0] > close[0]) ||
(positionInfo.PositionType() == POSITION_TYPE_SELL && ema[0] < close[0]))
{
ClosePosition(InpMagicNumberEMACross);
}
}
}
}
//+------------------------------------------------------------------+
//| Close position by magic number |
//+------------------------------------------------------------------+
void ClosePosition(int magic)
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(positionInfo.SelectByIndex(i))
{
if(positionInfo.Magic() == magic)
{
// Check if this is RSI Reverse position and update cooldown
if(magic == InpMagicNumberRSIReverse)
{
datetime time[];
if(CopyTime(_Symbol, InpTimeframe, 0, 1, time) > 0)
{
rsiReverseLastCloseTime = time[0];
// Only enter cooldown if it's a loss or if cooldown on loss is disabled
if(!InpRSIReverseCooldownOnLoss || positionInfo.Profit() < 0)
{
rsiReverseInCooldown = true;
}
}
}
trade.PositionClose(positionInfo.Ticket());
break;
}
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 242 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 280 KiB

@@ -1,539 +0,0 @@
//+------------------------------------------------------------------+
//| SimpleRSIReversalAUDUSD.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
// Include trade class
#include <Trade\Trade.mqh>
// Input parameters
input int RSIPeriod = 28; // RSI period
input double OverboughtLevel = 68; // Overbought level
input double OversoldLevel = 30; // Oversold level
input int TakeProfitPips = 175; // Take profit in pips
input int StopLossPips = 5; // Stop loss in pips
input double MaxLotSize = 0.2; // Maximum lot size
input int MaxSpread = 1000; // Maximum allowed spread in pips
input int MaxDuration = 340; // Maximum trade duration in hours
input bool UseStopLoss = false; // Use stop loss
input bool UseTakeProfit = false; // Use take profit
input bool UseRSIExit = true; // Use RSI for exit
input double RSIExitLevel = 48; // RSI level to exit (50 = neutral)
input bool CloseOutsideSession = true; // Close trades outside Asian session
input color PanelBackground = clrBlack; // Panel background color
input color PanelText = clrWhite; // Panel text color
input int PanelX = 10; // Panel X position
input int PanelY = 20; // Panel Y position
// Global variables
CTrade trade;
int rsiHandle;
bool isPositionOpen = false;
double positionOpenPrice = 0;
datetime positionOpenTime = 0;
ENUM_POSITION_TYPE lastPositionType = POSITION_TYPE_BUY;
bool sessionCloseAttempted = false; // Track if we've attempted to close positions for current session
// RSI crossover variables
double rsiCurrent = 0;
double rsiPrevious = 0;
double rsiPrevious2 = 0;
bool rsiCrossedOverbought = false;
bool rsiCrossedOversold = false;
bool rsiCrossedExitLevel = false;
// Panel objects
string panelName = "RSIPanel";
int panelWidth = 200;
int panelHeight = 200;
int labelHeight = 20;
int labelSpacing = 5;
// Session times (UTC)
const int AsianSessionStart = 0; // 00:00 UTC
const int AsianSessionEnd = 8; // 08:00 UTC
//+------------------------------------------------------------------+
//| Create panel |
//+------------------------------------------------------------------+
void CreatePanel()
{
// Create panel background
ObjectCreate(0, panelName, OBJ_RECTANGLE_LABEL, 0, 0, 0);
ObjectSetInteger(0, panelName, OBJPROP_XDISTANCE, PanelX);
ObjectSetInteger(0, panelName, OBJPROP_YDISTANCE, PanelY);
ObjectSetInteger(0, panelName, OBJPROP_XSIZE, panelWidth);
ObjectSetInteger(0, panelName, OBJPROP_YSIZE, panelHeight);
ObjectSetInteger(0, panelName, OBJPROP_BGCOLOR, PanelBackground);
ObjectSetInteger(0, panelName, OBJPROP_BORDER_TYPE, BORDER_FLAT);
ObjectSetInteger(0, panelName, OBJPROP_CORNER, CORNER_LEFT_UPPER);
ObjectSetInteger(0, panelName, OBJPROP_COLOR, PanelText);
ObjectSetInteger(0, panelName, OBJPROP_STYLE, STYLE_SOLID);
ObjectSetInteger(0, panelName, OBJPROP_WIDTH, 1);
ObjectSetInteger(0, panelName, OBJPROP_BACK, false);
ObjectSetInteger(0, panelName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, panelName, OBJPROP_SELECTED, false);
ObjectSetInteger(0, panelName, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, panelName, OBJPROP_ZORDER, 0);
// Create title label
ObjectCreate(0, panelName + "Title", OBJ_LABEL, 0, 0, 0);
ObjectSetInteger(0, panelName + "Title", OBJPROP_XDISTANCE, PanelX + 5);
ObjectSetInteger(0, panelName + "Title", OBJPROP_YDISTANCE, PanelY + 5);
ObjectSetInteger(0, panelName + "Title", OBJPROP_CORNER, CORNER_LEFT_UPPER);
ObjectSetString(0, panelName + "Title", OBJPROP_TEXT, "RSI Reversal");
ObjectSetInteger(0, panelName + "Title", OBJPROP_COLOR, PanelText);
ObjectSetInteger(0, panelName + "Title", OBJPROP_FONTSIZE, 10);
// Create score labels
CreateScoreLabel("RSI", "RSI: ", 0);
CreateScoreLabel("Position", "Position: ", 1);
CreateScoreLabel("Spread", "Spread: ", 2);
CreateScoreLabel("Session", "Session: ", 3);
CreateScoreLabel("SL", "Stop Loss: ", 4);
CreateScoreLabel("TP", "Take Profit: ", 5);
CreateScoreLabel("Cross", "Cross: ", 6);
}
//+------------------------------------------------------------------+
//| Create score label |
//+------------------------------------------------------------------+
void CreateScoreLabel(string name, string text, int index)
{
ObjectCreate(0, panelName + name, OBJ_LABEL, 0, 0, 0);
ObjectSetInteger(0, panelName + name, OBJPROP_XDISTANCE, PanelX + 5);
ObjectSetInteger(0, panelName + name, OBJPROP_YDISTANCE, PanelY + 30 + index * (labelHeight + labelSpacing));
ObjectSetInteger(0, panelName + name, OBJPROP_CORNER, CORNER_LEFT_UPPER);
ObjectSetString(0, panelName + name, OBJPROP_TEXT, text);
ObjectSetInteger(0, panelName + name, OBJPROP_COLOR, PanelText);
ObjectSetInteger(0, panelName + name, OBJPROP_FONTSIZE, 8);
}
//+------------------------------------------------------------------+
//| Update panel values |
//+------------------------------------------------------------------+
void UpdatePanel(double rsi, string position, int spread, string session, double sl, double tp, string crossInfo)
{
ObjectSetString(0, panelName + "RSI", OBJPROP_TEXT, "RSI: " + DoubleToString(rsi, 2));
ObjectSetString(0, panelName + "Position", OBJPROP_TEXT, "Position: " + position);
ObjectSetString(0, panelName + "Spread", OBJPROP_TEXT, "Spread: " + IntegerToString(spread) + " pips");
ObjectSetString(0, panelName + "Session", OBJPROP_TEXT, "Session: " + session);
ObjectSetString(0, panelName + "SL", OBJPROP_TEXT, "Stop Loss: " + IntegerToString(StopLossPips) + " pips");
ObjectSetString(0, panelName + "TP", OBJPROP_TEXT, "Take Profit: " + IntegerToString(TakeProfitPips) + " pips");
ObjectSetString(0, panelName + "Cross", OBJPROP_TEXT, "Cross: " + crossInfo);
}
//+------------------------------------------------------------------+
//| Check if current time is in Asian session |
//+------------------------------------------------------------------+
bool IsAsianSession()
{
datetime currentTime = TimeCurrent();
MqlDateTime timeStruct;
TimeToStruct(currentTime, timeStruct);
return (timeStruct.hour >= AsianSessionStart && timeStruct.hour < AsianSessionEnd);
}
//+------------------------------------------------------------------+
//| Get current session name |
//+------------------------------------------------------------------+
string GetCurrentSession()
{
datetime currentTime = TimeCurrent();
MqlDateTime timeStruct;
TimeToStruct(currentTime, timeStruct);
if(timeStruct.hour >= AsianSessionStart && timeStruct.hour < AsianSessionEnd)
return "Asian";
else if(timeStruct.hour >= 8 && timeStruct.hour < 16)
return "London";
else if(timeStruct.hour >= 13 && timeStruct.hour < 21)
return "New York";
else
return "Other";
}
//+------------------------------------------------------------------+
//| Check if trading is allowed |
//+------------------------------------------------------------------+
bool IsTradingAllowed()
{
// Check if market is open
if(!SymbolInfoInteger(_Symbol, SYMBOL_TRADE_MODE) == SYMBOL_TRADE_MODE_FULL)
{
return false;
}
// Check if we have enough money
if(AccountInfoDouble(ACCOUNT_MARGIN_FREE) <= 0)
{
return false;
}
return true;
}
//+------------------------------------------------------------------+
//| Check RSI crossover conditions |
//+------------------------------------------------------------------+
void CheckRSICrossover()
{
// Reset crossover flags
rsiCrossedOverbought = false;
rsiCrossedOversold = false;
rsiCrossedExitLevel = false;
// Check for overbought crossover (RSI crosses above overbought level)
if(rsiPrevious < OverboughtLevel && rsiCurrent >= OverboughtLevel)
{
rsiCrossedOverbought = true;
}
// Check for oversold crossover (RSI crosses below oversold level)
if(rsiPrevious > OversoldLevel && rsiCurrent <= OversoldLevel)
{
rsiCrossedOversold = true;
}
// Check for exit level crossover
if(rsiPrevious < RSIExitLevel && rsiCurrent >= RSIExitLevel)
{
rsiCrossedExitLevel = true;
}
else if(rsiPrevious > RSIExitLevel && rsiCurrent <= RSIExitLevel)
{
rsiCrossedExitLevel = true;
}
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialize RSI indicator
rsiHandle = iRSI(_Symbol, PERIOD_M15, RSIPeriod, PRICE_CLOSE);
if(rsiHandle == INVALID_HANDLE)
{
return(INIT_FAILED);
}
// Wait a bit for the indicator to be ready
Sleep(100);
// Initialize RSI values with retry logic
double rsi[];
ArraySetAsSeries(rsi, true);
int retryCount = 0;
bool rsiInitialized = false;
while(retryCount < 10 && !rsiInitialized)
{
int copied = CopyBuffer(rsiHandle, 0, 0, 3, rsi);
if(copied >= 3)
{
rsiCurrent = rsi[0];
rsiPrevious = rsi[1];
rsiPrevious2 = rsi[2];
rsiInitialized = true;
}
else
{
retryCount++;
Sleep(100);
}
}
if(!rsiInitialized)
{
// Don't fail initialization, just set default values
rsiCurrent = 50.0;
rsiPrevious = 50.0;
rsiPrevious2 = 50.0;
}
// Create panel
CreatePanel();
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Release indicator handles
IndicatorRelease(rsiHandle);
// Remove panel objects
ObjectsDeleteAll(0, panelName);
}
//+------------------------------------------------------------------+
//| Close all trades for the current symbol |
//+------------------------------------------------------------------+
bool CloseAllTrades(string reason = "")
{
bool allClosed = true;
int totalPositions = PositionsTotal();
if(totalPositions == 0)
return true;
// Check if there are any positions with our magic number
bool hasOurPositions = false;
for(int i = 0; i < totalPositions; i++)
{
if(PositionGetSymbol(i) == _Symbol && PositionGetInteger(POSITION_MAGIC) == 123456)
{
hasOurPositions = true;
break;
}
}
for(int i = totalPositions - 1; i >= 0; i--)
{
if(PositionGetSymbol(i) == _Symbol)
{
// Try to close position with retry logic
int retryCount = 0;
bool positionClosed = false;
while(retryCount < 3 && !positionClosed)
{
if(trade.PositionClose(_Symbol))
{
isPositionOpen = false;
positionClosed = true;
}
else
{
int error = GetLastError();
// If error is 4756 (Trade disabled), wait longer before retry
if(error == 4756)
{
Sleep(5000); // Wait 5 seconds before retry
retryCount++;
}
else
{
// For other errors, break the loop
break;
}
}
}
if(!positionClosed)
{
allClosed = false;
}
}
}
return allClosed;
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check if trading is allowed
if(!IsTradingAllowed())
{
return;
}
// Check if we're in Asian session
if(!IsAsianSession())
{
// Close all positions if outside Asian session and CloseOutsideSession is true
if(CloseOutsideSession && !sessionCloseAttempted)
{
CloseAllTrades("Outside Asian session");
sessionCloseAttempted = true;
}
return;
}
else
{
// Reset the session close attempt flag when we enter Asian session
sessionCloseAttempted = false;
}
// Get current spread
double spread = SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID);
int spreadInPips = (int)(spread / _Point);
// Check if spread is too high
if(spreadInPips > MaxSpread)
{
return;
}
// Get RSI values from bar data
double rsi[];
ArraySetAsSeries(rsi, true);
int copied = CopyBuffer(rsiHandle, 0, 0, 3, rsi);
if(copied < 3)
{
return;
}
// Update RSI values
rsiPrevious2 = rsiPrevious;
rsiPrevious = rsiCurrent;
rsiCurrent = rsi[0];
// Validate RSI values
if(rsiCurrent == 0 || rsiPrevious == 0)
{
return;
}
// Check for RSI crossovers
CheckRSICrossover();
// Get current prices
double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
// Get position status
string positionStatus = "None";
for(int i = 0; i < PositionsTotal(); i++)
{
if(PositionGetSymbol(i) == _Symbol)
{
ENUM_POSITION_TYPE posType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
positionStatus = (posType == POSITION_TYPE_BUY) ? "Long" : "Short";
break;
}
}
// Calculate stop loss and take profit levels
double sl = 0;
double tp = 0;
// Prepare crossover info for panel
string crossInfo = "None";
if(rsiCrossedOverbought) crossInfo = "Overbought";
else if(rsiCrossedOversold) crossInfo = "Oversold";
else if(rsiCrossedExitLevel) crossInfo = "Exit";
// Update panel
UpdatePanel(rsiCurrent, positionStatus, spreadInPips, GetCurrentSession(), sl, tp, crossInfo);
// Check for open position
bool hasOpenPosition = false;
for(int i = 0; i < PositionsTotal(); i++)
{
if(PositionGetSymbol(i) == _Symbol)
{
hasOpenPosition = true;
// Get position details
double positionProfit = PositionGetDouble(POSITION_PROFIT);
double positionVolume = PositionGetDouble(POSITION_VOLUME);
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
ENUM_POSITION_TYPE posType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
// Check for RSI exit if enabled
if(UseRSIExit && rsiCrossedExitLevel)
{
bool shouldExit = false;
// For long positions, exit when RSI crosses above exit level
if(posType == POSITION_TYPE_BUY && rsiCurrent >= RSIExitLevel && rsiPrevious < RSIExitLevel)
{
shouldExit = true;
}
// For short positions, exit when RSI crosses below exit level
else if(posType == POSITION_TYPE_SELL && rsiCurrent <= RSIExitLevel && rsiPrevious > RSIExitLevel)
{
shouldExit = true;
}
if(shouldExit)
{
CloseAllTrades("RSI Exit Crossover");
return;
}
}
// Check for timeout
if(TimeCurrent() - positionOpenTime > MaxDuration * 3600)
{
CloseAllTrades("Timeout");
return;
}
break;
}
}
// If no position is open, look for entry signals based on RSI crossover
if(!hasOpenPosition)
{
// Place buy order if RSI crosses below oversold level (oversold crossover)
if(rsiCrossedOversold)
{
double sl = UseStopLoss ? currentBid - StopLossPips * _Point : 0;
double tp = UseTakeProfit ? currentBid + TakeProfitPips * _Point : 0;
if(UseStopLoss && sl >= currentBid)
return;
if(UseTakeProfit && tp <= currentBid)
return;
// Set trade parameters
trade.SetDeviationInPoints(3);
trade.SetTypeFilling(ORDER_FILLING_IOC);
trade.SetExpertMagicNumber(123456);
// Place buy order using CTrade
if(trade.Buy(MaxLotSize, _Symbol, currentAsk, sl, tp, "RSI Oversold Crossover Buy"))
{
isPositionOpen = true;
positionOpenPrice = currentAsk;
positionOpenTime = TimeCurrent();
lastPositionType = POSITION_TYPE_BUY;
}
}
// Place sell order if RSI crosses above overbought level (overbought crossover)
else if(rsiCrossedOverbought)
{
double sl = UseStopLoss ? currentAsk + StopLossPips * _Point : 0;
double tp = UseTakeProfit ? currentAsk - TakeProfitPips * _Point : 0;
if(UseStopLoss && sl <= currentAsk)
return;
if(UseTakeProfit && tp >= currentAsk)
return;
// Set trade parameters
trade.SetDeviationInPoints(3);
trade.SetTypeFilling(ORDER_FILLING_IOC);
trade.SetExpertMagicNumber(123456);
// Place sell order using CTrade
if(trade.Sell(MaxLotSize, _Symbol, currentBid, sl, tp, "RSI Overbought Crossover Sell"))
{
isPositionOpen = true;
positionOpenPrice = currentBid;
positionOpenTime = TimeCurrent();
lastPositionType = POSITION_TYPE_SELL;
}
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 241 KiB

@@ -1,539 +0,0 @@
//+------------------------------------------------------------------+
//| SimpleRSIReversalAUDUSD.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
// Include trade class
#include <Trade\Trade.mqh>
// Input parameters
input int RSIPeriod = 28; // RSI period
input double OverboughtLevel = 60; // Overbought level
input double OversoldLevel = 8; // Oversold level
input int TakeProfitPips = 175; // Take profit in pips
input int StopLossPips = 5; // Stop loss in pips
input double MaxLotSize = 0.1; // Maximum lot size
input int MaxSpread = 1000; // Maximum allowed spread in pips
input int MaxDuration = 270; // Maximum trade duration in hours
input bool UseStopLoss = false; // Use stop loss
input bool UseTakeProfit = false; // Use take profit
input bool UseRSIExit = true; // Use RSI for exit
input double RSIExitLevel = 55; // RSI level to exit (50 = neutral)
input bool CloseOutsideSession = false; // Close trades outside Asian session
input color PanelBackground = clrBlack; // Panel background color
input color PanelText = clrWhite; // Panel text color
input int PanelX = 10; // Panel X position
input int PanelY = 20; // Panel Y position
// Global variables
CTrade trade;
int rsiHandle;
bool isPositionOpen = false;
double positionOpenPrice = 0;
datetime positionOpenTime = 0;
ENUM_POSITION_TYPE lastPositionType = POSITION_TYPE_BUY;
bool sessionCloseAttempted = false; // Track if we've attempted to close positions for current session
// RSI crossover variables
double rsiCurrent = 0;
double rsiPrevious = 0;
double rsiPrevious2 = 0;
bool rsiCrossedOverbought = false;
bool rsiCrossedOversold = false;
bool rsiCrossedExitLevel = false;
// Panel objects
string panelName = "RSIPanel";
int panelWidth = 200;
int panelHeight = 200;
int labelHeight = 20;
int labelSpacing = 5;
// Session times (UTC)
const int AsianSessionStart = 0; // 00:00 UTC
const int AsianSessionEnd = 8; // 08:00 UTC
//+------------------------------------------------------------------+
//| Create panel |
//+------------------------------------------------------------------+
void CreatePanel()
{
// Create panel background
ObjectCreate(0, panelName, OBJ_RECTANGLE_LABEL, 0, 0, 0);
ObjectSetInteger(0, panelName, OBJPROP_XDISTANCE, PanelX);
ObjectSetInteger(0, panelName, OBJPROP_YDISTANCE, PanelY);
ObjectSetInteger(0, panelName, OBJPROP_XSIZE, panelWidth);
ObjectSetInteger(0, panelName, OBJPROP_YSIZE, panelHeight);
ObjectSetInteger(0, panelName, OBJPROP_BGCOLOR, PanelBackground);
ObjectSetInteger(0, panelName, OBJPROP_BORDER_TYPE, BORDER_FLAT);
ObjectSetInteger(0, panelName, OBJPROP_CORNER, CORNER_LEFT_UPPER);
ObjectSetInteger(0, panelName, OBJPROP_COLOR, PanelText);
ObjectSetInteger(0, panelName, OBJPROP_STYLE, STYLE_SOLID);
ObjectSetInteger(0, panelName, OBJPROP_WIDTH, 1);
ObjectSetInteger(0, panelName, OBJPROP_BACK, false);
ObjectSetInteger(0, panelName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, panelName, OBJPROP_SELECTED, false);
ObjectSetInteger(0, panelName, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, panelName, OBJPROP_ZORDER, 0);
// Create title label
ObjectCreate(0, panelName + "Title", OBJ_LABEL, 0, 0, 0);
ObjectSetInteger(0, panelName + "Title", OBJPROP_XDISTANCE, PanelX + 5);
ObjectSetInteger(0, panelName + "Title", OBJPROP_YDISTANCE, PanelY + 5);
ObjectSetInteger(0, panelName + "Title", OBJPROP_CORNER, CORNER_LEFT_UPPER);
ObjectSetString(0, panelName + "Title", OBJPROP_TEXT, "RSI Reversal");
ObjectSetInteger(0, panelName + "Title", OBJPROP_COLOR, PanelText);
ObjectSetInteger(0, panelName + "Title", OBJPROP_FONTSIZE, 10);
// Create score labels
CreateScoreLabel("RSI", "RSI: ", 0);
CreateScoreLabel("Position", "Position: ", 1);
CreateScoreLabel("Spread", "Spread: ", 2);
CreateScoreLabel("Session", "Session: ", 3);
CreateScoreLabel("SL", "Stop Loss: ", 4);
CreateScoreLabel("TP", "Take Profit: ", 5);
CreateScoreLabel("Cross", "Cross: ", 6);
}
//+------------------------------------------------------------------+
//| Create score label |
//+------------------------------------------------------------------+
void CreateScoreLabel(string name, string text, int index)
{
ObjectCreate(0, panelName + name, OBJ_LABEL, 0, 0, 0);
ObjectSetInteger(0, panelName + name, OBJPROP_XDISTANCE, PanelX + 5);
ObjectSetInteger(0, panelName + name, OBJPROP_YDISTANCE, PanelY + 30 + index * (labelHeight + labelSpacing));
ObjectSetInteger(0, panelName + name, OBJPROP_CORNER, CORNER_LEFT_UPPER);
ObjectSetString(0, panelName + name, OBJPROP_TEXT, text);
ObjectSetInteger(0, panelName + name, OBJPROP_COLOR, PanelText);
ObjectSetInteger(0, panelName + name, OBJPROP_FONTSIZE, 8);
}
//+------------------------------------------------------------------+
//| Update panel values |
//+------------------------------------------------------------------+
void UpdatePanel(double rsi, string position, int spread, string session, double sl, double tp, string crossInfo)
{
ObjectSetString(0, panelName + "RSI", OBJPROP_TEXT, "RSI: " + DoubleToString(rsi, 2));
ObjectSetString(0, panelName + "Position", OBJPROP_TEXT, "Position: " + position);
ObjectSetString(0, panelName + "Spread", OBJPROP_TEXT, "Spread: " + IntegerToString(spread) + " pips");
ObjectSetString(0, panelName + "Session", OBJPROP_TEXT, "Session: " + session);
ObjectSetString(0, panelName + "SL", OBJPROP_TEXT, "Stop Loss: " + IntegerToString(StopLossPips) + " pips");
ObjectSetString(0, panelName + "TP", OBJPROP_TEXT, "Take Profit: " + IntegerToString(TakeProfitPips) + " pips");
ObjectSetString(0, panelName + "Cross", OBJPROP_TEXT, "Cross: " + crossInfo);
}
//+------------------------------------------------------------------+
//| Check if current time is in Asian session |
//+------------------------------------------------------------------+
bool IsAsianSession()
{
datetime currentTime = TimeCurrent();
MqlDateTime timeStruct;
TimeToStruct(currentTime, timeStruct);
return (timeStruct.hour >= AsianSessionStart && timeStruct.hour < AsianSessionEnd);
}
//+------------------------------------------------------------------+
//| Get current session name |
//+------------------------------------------------------------------+
string GetCurrentSession()
{
datetime currentTime = TimeCurrent();
MqlDateTime timeStruct;
TimeToStruct(currentTime, timeStruct);
if(timeStruct.hour >= AsianSessionStart && timeStruct.hour < AsianSessionEnd)
return "Asian";
else if(timeStruct.hour >= 8 && timeStruct.hour < 16)
return "London";
else if(timeStruct.hour >= 13 && timeStruct.hour < 21)
return "New York";
else
return "Other";
}
//+------------------------------------------------------------------+
//| Check if trading is allowed |
//+------------------------------------------------------------------+
bool IsTradingAllowed()
{
// Check if market is open
if(!SymbolInfoInteger(_Symbol, SYMBOL_TRADE_MODE) == SYMBOL_TRADE_MODE_FULL)
{
return false;
}
// Check if we have enough money
if(AccountInfoDouble(ACCOUNT_MARGIN_FREE) <= 0)
{
return false;
}
return true;
}
//+------------------------------------------------------------------+
//| Check RSI crossover conditions |
//+------------------------------------------------------------------+
void CheckRSICrossover()
{
// Reset crossover flags
rsiCrossedOverbought = false;
rsiCrossedOversold = false;
rsiCrossedExitLevel = false;
// Check for overbought crossover (RSI crosses above overbought level)
if(rsiPrevious < OverboughtLevel && rsiCurrent >= OverboughtLevel)
{
rsiCrossedOverbought = true;
}
// Check for oversold crossover (RSI crosses below oversold level)
if(rsiPrevious > OversoldLevel && rsiCurrent <= OversoldLevel)
{
rsiCrossedOversold = true;
}
// Check for exit level crossover
if(rsiPrevious < RSIExitLevel && rsiCurrent >= RSIExitLevel)
{
rsiCrossedExitLevel = true;
}
else if(rsiPrevious > RSIExitLevel && rsiCurrent <= RSIExitLevel)
{
rsiCrossedExitLevel = true;
}
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialize RSI indicator
rsiHandle = iRSI(_Symbol, PERIOD_M15, RSIPeriod, PRICE_CLOSE);
if(rsiHandle == INVALID_HANDLE)
{
return(INIT_FAILED);
}
// Wait a bit for the indicator to be ready
Sleep(100);
// Initialize RSI values with retry logic
double rsi[];
ArraySetAsSeries(rsi, true);
int retryCount = 0;
bool rsiInitialized = false;
while(retryCount < 10 && !rsiInitialized)
{
int copied = CopyBuffer(rsiHandle, 0, 0, 3, rsi);
if(copied >= 3)
{
rsiCurrent = rsi[0];
rsiPrevious = rsi[1];
rsiPrevious2 = rsi[2];
rsiInitialized = true;
}
else
{
retryCount++;
Sleep(100);
}
}
if(!rsiInitialized)
{
// Don't fail initialization, just set default values
rsiCurrent = 50.0;
rsiPrevious = 50.0;
rsiPrevious2 = 50.0;
}
// Create panel
CreatePanel();
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Release indicator handles
IndicatorRelease(rsiHandle);
// Remove panel objects
ObjectsDeleteAll(0, panelName);
}
//+------------------------------------------------------------------+
//| Close all trades for the current symbol |
//+------------------------------------------------------------------+
bool CloseAllTrades(string reason = "")
{
bool allClosed = true;
int totalPositions = PositionsTotal();
if(totalPositions == 0)
return true;
// Check if there are any positions with our magic number
bool hasOurPositions = false;
for(int i = 0; i < totalPositions; i++)
{
if(PositionGetSymbol(i) == _Symbol && PositionGetInteger(POSITION_MAGIC) == 123456)
{
hasOurPositions = true;
break;
}
}
for(int i = totalPositions - 1; i >= 0; i--)
{
if(PositionGetSymbol(i) == _Symbol)
{
// Try to close position with retry logic
int retryCount = 0;
bool positionClosed = false;
while(retryCount < 3 && !positionClosed)
{
if(trade.PositionClose(_Symbol))
{
isPositionOpen = false;
positionClosed = true;
}
else
{
int error = GetLastError();
// If error is 4756 (Trade disabled), wait longer before retry
if(error == 4756)
{
Sleep(5000); // Wait 5 seconds before retry
retryCount++;
}
else
{
// For other errors, break the loop
break;
}
}
}
if(!positionClosed)
{
allClosed = false;
}
}
}
return allClosed;
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check if trading is allowed
if(!IsTradingAllowed())
{
return;
}
// Check if we're in Asian session
if(!IsAsianSession())
{
// Close all positions if outside Asian session and CloseOutsideSession is true
if(CloseOutsideSession && !sessionCloseAttempted)
{
CloseAllTrades("Outside Asian session");
sessionCloseAttempted = true;
}
return;
}
else
{
// Reset the session close attempt flag when we enter Asian session
sessionCloseAttempted = false;
}
// Get current spread
double spread = SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID);
int spreadInPips = (int)(spread / _Point);
// Check if spread is too high
if(spreadInPips > MaxSpread)
{
return;
}
// Get RSI values from bar data
double rsi[];
ArraySetAsSeries(rsi, true);
int copied = CopyBuffer(rsiHandle, 0, 0, 3, rsi);
if(copied < 3)
{
return;
}
// Update RSI values
rsiPrevious2 = rsiPrevious;
rsiPrevious = rsiCurrent;
rsiCurrent = rsi[0];
// Validate RSI values
if(rsiCurrent == 0 || rsiPrevious == 0)
{
return;
}
// Check for RSI crossovers
CheckRSICrossover();
// Get current prices
double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
// Get position status
string positionStatus = "None";
for(int i = 0; i < PositionsTotal(); i++)
{
if(PositionGetSymbol(i) == _Symbol)
{
ENUM_POSITION_TYPE posType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
positionStatus = (posType == POSITION_TYPE_BUY) ? "Long" : "Short";
break;
}
}
// Calculate stop loss and take profit levels
double sl = 0;
double tp = 0;
// Prepare crossover info for panel
string crossInfo = "None";
if(rsiCrossedOverbought) crossInfo = "Overbought";
else if(rsiCrossedOversold) crossInfo = "Oversold";
else if(rsiCrossedExitLevel) crossInfo = "Exit";
// Update panel
UpdatePanel(rsiCurrent, positionStatus, spreadInPips, GetCurrentSession(), sl, tp, crossInfo);
// Check for open position
bool hasOpenPosition = false;
for(int i = 0; i < PositionsTotal(); i++)
{
if(PositionGetSymbol(i) == _Symbol)
{
hasOpenPosition = true;
// Get position details
double positionProfit = PositionGetDouble(POSITION_PROFIT);
double positionVolume = PositionGetDouble(POSITION_VOLUME);
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
ENUM_POSITION_TYPE posType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
// Check for RSI exit if enabled
if(UseRSIExit && rsiCrossedExitLevel)
{
bool shouldExit = false;
// For long positions, exit when RSI crosses above exit level
if(posType == POSITION_TYPE_BUY && rsiCurrent >= RSIExitLevel && rsiPrevious < RSIExitLevel)
{
shouldExit = true;
}
// For short positions, exit when RSI crosses below exit level
else if(posType == POSITION_TYPE_SELL && rsiCurrent <= RSIExitLevel && rsiPrevious > RSIExitLevel)
{
shouldExit = true;
}
if(shouldExit)
{
CloseAllTrades("RSI Exit Crossover");
return;
}
}
// Check for timeout
if(TimeCurrent() - positionOpenTime > MaxDuration * 3600)
{
CloseAllTrades("Timeout");
return;
}
break;
}
}
// If no position is open, look for entry signals based on RSI crossover
if(!hasOpenPosition)
{
// Place buy order if RSI crosses below oversold level (oversold crossover)
if(rsiCrossedOversold)
{
double sl = UseStopLoss ? currentBid - StopLossPips * _Point : 0;
double tp = UseTakeProfit ? currentBid + TakeProfitPips * _Point : 0;
if(UseStopLoss && sl >= currentBid)
return;
if(UseTakeProfit && tp <= currentBid)
return;
// Set trade parameters
trade.SetDeviationInPoints(3);
trade.SetTypeFilling(ORDER_FILLING_IOC);
trade.SetExpertMagicNumber(123456);
// Place buy order using CTrade
if(trade.Buy(MaxLotSize, _Symbol, currentAsk, sl, tp, "RSI Oversold Crossover Buy"))
{
isPositionOpen = true;
positionOpenPrice = currentAsk;
positionOpenTime = TimeCurrent();
lastPositionType = POSITION_TYPE_BUY;
}
}
// Place sell order if RSI crosses above overbought level (overbought crossover)
else if(rsiCrossedOverbought)
{
double sl = UseStopLoss ? currentAsk + StopLossPips * _Point : 0;
double tp = UseTakeProfit ? currentAsk - TakeProfitPips * _Point : 0;
if(UseStopLoss && sl <= currentAsk)
return;
if(UseTakeProfit && tp >= currentAsk)
return;
// Set trade parameters
trade.SetDeviationInPoints(3);
trade.SetTypeFilling(ORDER_FILLING_IOC);
trade.SetExpertMagicNumber(123456);
// Place sell order using CTrade
if(trade.Sell(MaxLotSize, _Symbol, currentBid, sl, tp, "RSI Overbought Crossover Sell"))
{
isPositionOpen = true;
positionOpenPrice = currentBid;
positionOpenTime = TimeCurrent();
lastPositionType = POSITION_TYPE_SELL;
}
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 250 KiB

-281
View File
@@ -1,281 +0,0 @@
//+------------------------------------------------------------------+
//| RSIScalping.mq5 |
//| Copyright 2025, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#include <Trade\Trade.mqh>
//--- Input parameters
input ENUM_TIMEFRAMES TimeFrame = PERIOD_H4; // Timeframe for Analysis
input int RSI_Period = 14; // RSI Period
input ENUM_APPLIED_PRICE RSI_Applied_Price = PRICE_CLOSE; // RSI Applied Price
input double RSI_Overbought = 82; // RSI Overbought Level
input double RSI_Oversold = 55; // RSI Oversold Level
input double RSI_Target_Buy = 39; // RSI Target for Buy Exit
input double RSI_Target_Sell = 35; // RSI Target for Sell Exit
input int BarsToWait = 2; // Bars to wait when RSI goes against position
input double LotSize = 50; // Lot Size
input int MagicNumber = 12345; // Magic Number
input int Slippage = 3; // Slippage in points
//--- Global variables
CTrade trade;
int rsi_handle;
double rsi_buffer[];
double rsi_prev, rsi_current, rsi_two_bars_ago;
bool position_open = false;
int position_ticket = 0;
ENUM_POSITION_TYPE current_position_type = POSITION_TYPE_BUY;
datetime last_bar_time = 0;
bool rsi_against_position = false;
int bars_against_count = 0;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialize RSI indicator
rsi_handle = iRSI(_Symbol, TimeFrame, RSI_Period, RSI_Applied_Price);
if(rsi_handle == INVALID_HANDLE)
{
return(INIT_FAILED);
}
// Initialize trade object
trade.SetExpertMagicNumber(MagicNumber);
trade.SetDeviationInPoints(Slippage);
trade.SetTypeFilling(ORDER_FILLING_FOK);
// Allocate arrays
ArraySetAsSeries(rsi_buffer, true);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
if(rsi_handle != INVALID_HANDLE)
IndicatorRelease(rsi_handle);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check if we have enough bars
if(Bars(_Symbol, TimeFrame) < RSI_Period + 2)
{
return;
}
// Check if this is a new bar
datetime current_bar_time = iTime(_Symbol, TimeFrame, 0);
if(current_bar_time == last_bar_time)
{
return; // Still the same bar, don't process
}
last_bar_time = current_bar_time;
// Update RSI values
if(!UpdateRSI())
{
return;
}
// Check for existing position
CheckExistingPosition();
// Check for new entry signals
if(!position_open)
{
CheckEntrySignals();
}
}
//+------------------------------------------------------------------+
//| Update RSI values |
//+------------------------------------------------------------------+
bool UpdateRSI()
{
if(CopyBuffer(rsi_handle, 0, 0, 3, rsi_buffer) < 3)
{
return false;
}
rsi_current = rsi_buffer[0]; // Current bar
rsi_prev = rsi_buffer[1]; // Previous bar
rsi_two_bars_ago = rsi_buffer[2]; // Two bars ago
return true;
}
//+------------------------------------------------------------------+
//| Check existing position for exit conditions |
//+------------------------------------------------------------------+
void CheckExistingPosition()
{
if(!position_open)
{
return;
}
// Check if position still exists
if(!PositionSelectByTicket(position_ticket))
{
position_open = false;
position_ticket = 0;
rsi_against_position = false;
bars_against_count = 0;
return;
}
// Exit conditions based on RSI target
if(current_position_type == POSITION_TYPE_BUY)
{
// Check if RSI is against the position (below oversold)
if(rsi_current < RSI_Oversold)
{
if(!rsi_against_position)
{
rsi_against_position = true;
bars_against_count = 1;
}
else
{
bars_against_count++;
}
// Close position if RSI has been against for Y bars
if(bars_against_count >= BarsToWait)
{
ClosePosition();
return;
}
}
else
{
// RSI is no longer against the position, reset counter
if(rsi_against_position)
{
rsi_against_position = false;
bars_against_count = 0;
}
// Exit long position when RSI reaches buy target
if(rsi_current >= RSI_Target_Buy)
{
ClosePosition();
}
}
}
else if(current_position_type == POSITION_TYPE_SELL)
{
// Check if RSI is against the position (above overbought)
if(rsi_current > RSI_Overbought)
{
if(!rsi_against_position)
{
rsi_against_position = true;
bars_against_count = 1;
}
else
{
bars_against_count++;
}
// Close position if RSI has been against for Y bars
if(bars_against_count >= BarsToWait)
{
ClosePosition();
return;
}
}
else
{
// RSI is no longer against the position, reset counter
if(rsi_against_position)
{
rsi_against_position = false;
bars_against_count = 0;
}
// Exit short position when RSI reaches sell target
if(rsi_current <= RSI_Target_Sell)
{
ClosePosition();
}
}
}
}
//+------------------------------------------------------------------+
//| Check for entry signals |
//+------------------------------------------------------------------+
void CheckEntrySignals()
{
// Buy signal: RSI crosses from oversold to above oversold (checking the actual crossover)
if(rsi_two_bars_ago <= RSI_Oversold && rsi_prev > RSI_Oversold)
{
OpenBuyPosition();
}
// Sell signal: RSI crosses from overbought to below overbought (checking the actual crossover)
if(rsi_two_bars_ago >= RSI_Overbought && rsi_prev < RSI_Overbought)
{
OpenSellPosition();
}
}
//+------------------------------------------------------------------+
//| Open buy position |
//+------------------------------------------------------------------+
void OpenBuyPosition()
{
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
if(trade.Buy(LotSize, _Symbol, ask, 0, 0, "RSI Scalping Buy"))
{
position_ticket = trade.ResultOrder();
position_open = true;
current_position_type = POSITION_TYPE_BUY;
}
}
//+------------------------------------------------------------------+
//| Open sell position |
//+------------------------------------------------------------------+
void OpenSellPosition()
{
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
if(trade.Sell(LotSize, _Symbol, bid, 0, 0, "RSI Scalping Sell"))
{
position_ticket = trade.ResultOrder();
position_open = true;
current_position_type = POSITION_TYPE_SELL;
}
}
//+------------------------------------------------------------------+
//| Close current position |
//+------------------------------------------------------------------+
void ClosePosition()
{
if(trade.PositionClose(position_ticket))
{
position_open = false;
position_ticket = 0;
rsi_against_position = false;
bars_against_count = 0;
}
}
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 229 KiB

-363
View File
@@ -1,363 +0,0 @@
//+------------------------------------------------------------------+
//| RSIScalping.mq5 |
//| Copyright 2025, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#include <Trade\Trade.mqh>
//--- Input parameters
input ENUM_TIMEFRAMES TimeFrame = PERIOD_M30; // Timeframe for Analysis
input int RSI_Period = 14; // RSI Period
input ENUM_APPLIED_PRICE RSI_Applied_Price = PRICE_CLOSE; // RSI Applied Price
input double RSI_Overbought = 77; // RSI Overbought Level
input double RSI_Oversold = 10; // RSI Oversold Level
input double RSI_Target_Buy = 27; // RSI Target for Buy Exit
input double RSI_Target_Sell = 43; // RSI Target for Sell Exit
input int BarsToWait = 14; // Bars to wait when RSI goes against position
input double LotSize = 0.1; // Lot Size
input int MagicNumber = 12345; // Magic Number
input int Slippage = 3; // Slippage in points
//--- Global variables
CTrade trade;
int rsi_handle;
double rsi_buffer[];
double rsi_prev, rsi_current, rsi_two_bars_ago;
bool position_open = false;
int position_ticket = 0;
ENUM_POSITION_TYPE current_position_type = POSITION_TYPE_BUY;
datetime last_bar_time = 0;
bool rsi_against_position = false;
int bars_against_count = 0;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialize RSI indicator
rsi_handle = iRSI(_Symbol, TimeFrame, RSI_Period, RSI_Applied_Price);
if(rsi_handle == INVALID_HANDLE)
{
Print("Error creating RSI indicator");
return(INIT_FAILED);
}
// Initialize trade object
trade.SetExpertMagicNumber(MagicNumber);
trade.SetDeviationInPoints(Slippage);
trade.SetTypeFilling(ORDER_FILLING_FOK);
// Allocate arrays
ArraySetAsSeries(rsi_buffer, true);
Print("RSI Scalping EA initialized successfully on timeframe: ", EnumToString(TimeFrame));
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
if(rsi_handle != INVALID_HANDLE)
IndicatorRelease(rsi_handle);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check if we have enough bars
if(Bars(_Symbol, TimeFrame) < RSI_Period + 2)
{
Print("TRACE: Not enough bars. Bars=", Bars(_Symbol, TimeFrame), " RSI_Period+2=", RSI_Period+2);
return;
}
// Check if this is a new bar
datetime current_bar_time = iTime(_Symbol, TimeFrame, 0);
if(current_bar_time == last_bar_time)
{
Print("TRACE: Same bar, skipping. current_bar_time=", current_bar_time, " last_bar_time=", last_bar_time);
return; // Still the same bar, don't process
}
Print("TRACE: New bar detected. current_bar_time=", current_bar_time, " last_bar_time=", last_bar_time);
last_bar_time = current_bar_time;
// Update RSI values
if(!UpdateRSI())
{
Print("TRACE: Failed to update RSI values");
return;
}
Print("TRACE: RSI values - Current=", rsi_current, " Previous=", rsi_prev);
// Check for existing position
CheckExistingPosition();
// Check for new entry signals
if(!position_open)
{
Print("TRACE: No position open, checking entry signals");
CheckEntrySignals();
}
else
{
Print("TRACE: Position already open, skipping entry signals");
}
}
//+------------------------------------------------------------------+
//| Update RSI values |
//+------------------------------------------------------------------+
bool UpdateRSI()
{
Print("TRACE: Updating RSI values...");
if(CopyBuffer(rsi_handle, 0, 0, 3, rsi_buffer) < 3)
{
Print("TRACE: Error copying RSI data. Copied=", CopyBuffer(rsi_handle, 0, 0, 3, rsi_buffer));
return false;
}
rsi_current = rsi_buffer[0]; // Current bar
rsi_prev = rsi_buffer[1]; // Previous bar
rsi_two_bars_ago = rsi_buffer[2]; // Two bars ago
Print("TRACE: RSI buffer values - [0]=", rsi_buffer[0], " [1]=", rsi_buffer[1], " [2]=", rsi_buffer[2]);
return true;
}
//+------------------------------------------------------------------+
//| Check existing position for exit conditions |
//+------------------------------------------------------------------+
void CheckExistingPosition()
{
if(!position_open)
{
Print("TRACE: No position open, skipping position check");
return;
}
Print("TRACE: Checking existing position. Ticket=", position_ticket, " Type=", (current_position_type == POSITION_TYPE_BUY ? "BUY" : "SELL"));
// Check if position still exists
if(!PositionSelectByTicket(position_ticket))
{
Print("TRACE: Position no longer exists, resetting state");
position_open = false;
position_ticket = 0;
rsi_against_position = false;
bars_against_count = 0;
return;
}
// Exit conditions based on RSI target
if(current_position_type == POSITION_TYPE_BUY)
{
Print("TRACE: Checking BUY position exit - rsi_current=", rsi_current, " RSI_Target_Buy=", RSI_Target_Buy, " RSI_Oversold=", RSI_Oversold);
// Check if RSI is against the position (below oversold)
if(rsi_current < RSI_Oversold)
{
if(!rsi_against_position)
{
Print("TRACE: RSI went against BUY position (below oversold), starting counter");
rsi_against_position = true;
bars_against_count = 1;
}
else
{
bars_against_count++;
Print("TRACE: RSI still against BUY position. Bars against: ", bars_against_count, "/", BarsToWait);
}
// Close position if RSI has been against for Y bars
if(bars_against_count >= BarsToWait)
{
Print("TRACE: RSI against BUY position for ", BarsToWait, " bars, closing position!");
ClosePosition();
return;
}
}
else
{
// RSI is no longer against the position, reset counter
if(rsi_against_position)
{
Print("TRACE: RSI no longer against BUY position, resetting counter");
rsi_against_position = false;
bars_against_count = 0;
}
// Exit long position when RSI reaches buy target
if(rsi_current >= RSI_Target_Buy)
{
Print("TRACE: BUY position target reached!");
ClosePosition();
}
else
{
Print("TRACE: BUY position exit condition not met");
}
}
}
else if(current_position_type == POSITION_TYPE_SELL)
{
Print("TRACE: Checking SELL position exit - rsi_current=", rsi_current, " RSI_Target_Sell=", RSI_Target_Sell, " RSI_Overbought=", RSI_Overbought);
// Check if RSI is against the position (above overbought)
if(rsi_current > RSI_Overbought)
{
if(!rsi_against_position)
{
Print("TRACE: RSI went against SELL position (above overbought), starting counter");
rsi_against_position = true;
bars_against_count = 1;
}
else
{
bars_against_count++;
Print("TRACE: RSI still against SELL position. Bars against: ", bars_against_count, "/", BarsToWait);
}
// Close position if RSI has been against for Y bars
if(bars_against_count >= BarsToWait)
{
Print("TRACE: RSI against SELL position for ", BarsToWait, " bars, closing position!");
ClosePosition();
return;
}
}
else
{
// RSI is no longer against the position, reset counter
if(rsi_against_position)
{
Print("TRACE: RSI no longer against SELL position, resetting counter");
rsi_against_position = false;
bars_against_count = 0;
}
// Exit short position when RSI reaches sell target
if(rsi_current <= RSI_Target_Sell)
{
Print("TRACE: SELL position target reached!");
ClosePosition();
}
else
{
Print("TRACE: SELL position exit condition not met");
}
}
}
}
//+------------------------------------------------------------------+
//| Check for entry signals |
//+------------------------------------------------------------------+
void CheckEntrySignals()
{
Print("TRACE: Checking entry signals...");
Print("TRACE: Buy condition - rsi_two_bars_ago <= RSI_Oversold && rsi_prev > RSI_Oversold");
Print("TRACE: Buy condition values - rsi_two_bars_ago=", rsi_two_bars_ago, " <= ", RSI_Oversold, " && rsi_prev=", rsi_prev, " > ", RSI_Oversold);
// Buy signal: RSI crosses from oversold to above oversold (checking the actual crossover)
if(rsi_two_bars_ago <= RSI_Oversold && rsi_prev > RSI_Oversold)
{
Print("TRACE: Buy signal detected!");
OpenBuyPosition();
}
else
{
Print("TRACE: Buy signal condition not met");
}
Print("TRACE: Sell condition - rsi_two_bars_ago >= RSI_Overbought && rsi_prev < RSI_Overbought");
Print("TRACE: Sell condition values - rsi_two_bars_ago=", rsi_two_bars_ago, " >= ", RSI_Overbought, " && rsi_prev=", rsi_prev, " < ", RSI_Overbought);
// Sell signal: RSI crosses from overbought to below overbought (checking the actual crossover)
if(rsi_two_bars_ago >= RSI_Overbought && rsi_prev < RSI_Overbought)
{
Print("TRACE: Sell signal detected!");
OpenSellPosition();
}
else
{
Print("TRACE: Sell signal condition not met");
}
}
//+------------------------------------------------------------------+
//| Open buy position |
//+------------------------------------------------------------------+
void OpenBuyPosition()
{
Print("TRACE: Attempting to open buy position...");
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
Print("TRACE: Current ask price=", ask, " LotSize=", LotSize);
if(trade.Buy(LotSize, _Symbol, ask, 0, 0, "RSI Scalping Buy"))
{
position_ticket = trade.ResultOrder();
position_open = true;
current_position_type = POSITION_TYPE_BUY;
Print("TRACE: Buy position opened successfully! Ticket=", position_ticket, " Price=", ask);
}
else
{
Print("TRACE: Error opening buy position. Retcode=", trade.ResultRetcode(), " Description=", trade.ResultRetcodeDescription());
}
}
//+------------------------------------------------------------------+
//| Open sell position |
//+------------------------------------------------------------------+
void OpenSellPosition()
{
Print("TRACE: Attempting to open sell position...");
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
Print("TRACE: Current bid price=", bid, " LotSize=", LotSize);
if(trade.Sell(LotSize, _Symbol, bid, 0, 0, "RSI Scalping Sell"))
{
position_ticket = trade.ResultOrder();
position_open = true;
current_position_type = POSITION_TYPE_SELL;
Print("TRACE: Sell position opened successfully! Ticket=", position_ticket, " Price=", bid);
}
else
{
Print("TRACE: Error opening sell position. Retcode=", trade.ResultRetcode(), " Description=", trade.ResultRetcodeDescription());
}
}
//+------------------------------------------------------------------+
//| Close current position |
//+------------------------------------------------------------------+
void ClosePosition()
{
Print("TRACE: Attempting to close position. Ticket=", position_ticket);
if(trade.PositionClose(position_ticket))
{
Print("TRACE: Position closed successfully! Ticket=", position_ticket);
position_open = false;
position_ticket = 0;
rsi_against_position = false;
bars_against_count = 0;
}
else
{
Print("TRACE: Error closing position. Retcode=", trade.ResultRetcode(), " Description=", trade.ResultRetcodeDescription());
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 223 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 234 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 201 KiB

-281
View File
@@ -1,281 +0,0 @@
//+------------------------------------------------------------------+
//| RSIScalping.mq5 |
//| Copyright 2025, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#include <Trade\Trade.mqh>
//--- Input parameters
input ENUM_TIMEFRAMES TimeFrame = PERIOD_H1; // Timeframe for Analysis
input int RSI_Period = 14; // RSI Period
input ENUM_APPLIED_PRICE RSI_Applied_Price = PRICE_CLOSE; // RSI Applied Price
input double RSI_Overbought = 49; // RSI Overbought Level
input double RSI_Oversold = 46; // RSI Oversold Level
input double RSI_Target_Buy = 85; // RSI Target for Buy Exit
input double RSI_Target_Sell = 35; // RSI Target for Sell Exit
input int BarsToWait = 10; // Bars to wait when RSI goes against position
input double LotSize = 0.1; // Lot Size
input int MagicNumber = 12345; // Magic Number
input int Slippage = 3; // Slippage in points
//--- Global variables
CTrade trade;
int rsi_handle;
double rsi_buffer[];
double rsi_prev, rsi_current, rsi_two_bars_ago;
bool position_open = false;
int position_ticket = 0;
ENUM_POSITION_TYPE current_position_type = POSITION_TYPE_BUY;
datetime last_bar_time = 0;
bool rsi_against_position = false;
int bars_against_count = 0;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialize RSI indicator
rsi_handle = iRSI(_Symbol, TimeFrame, RSI_Period, RSI_Applied_Price);
if(rsi_handle == INVALID_HANDLE)
{
return(INIT_FAILED);
}
// Initialize trade object
trade.SetExpertMagicNumber(MagicNumber);
trade.SetDeviationInPoints(Slippage);
trade.SetTypeFilling(ORDER_FILLING_FOK);
// Allocate arrays
ArraySetAsSeries(rsi_buffer, true);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
if(rsi_handle != INVALID_HANDLE)
IndicatorRelease(rsi_handle);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check if we have enough bars
if(Bars(_Symbol, TimeFrame) < RSI_Period + 2)
{
return;
}
// Check if this is a new bar
datetime current_bar_time = iTime(_Symbol, TimeFrame, 0);
if(current_bar_time == last_bar_time)
{
return; // Still the same bar, don't process
}
last_bar_time = current_bar_time;
// Update RSI values
if(!UpdateRSI())
{
return;
}
// Check for existing position
CheckExistingPosition();
// Check for new entry signals
if(!position_open)
{
CheckEntrySignals();
}
}
//+------------------------------------------------------------------+
//| Update RSI values |
//+------------------------------------------------------------------+
bool UpdateRSI()
{
if(CopyBuffer(rsi_handle, 0, 0, 3, rsi_buffer) < 3)
{
return false;
}
rsi_current = rsi_buffer[0]; // Current bar
rsi_prev = rsi_buffer[1]; // Previous bar
rsi_two_bars_ago = rsi_buffer[2]; // Two bars ago
return true;
}
//+------------------------------------------------------------------+
//| Check existing position for exit conditions |
//+------------------------------------------------------------------+
void CheckExistingPosition()
{
if(!position_open)
{
return;
}
// Check if position still exists
if(!PositionSelectByTicket(position_ticket))
{
position_open = false;
position_ticket = 0;
rsi_against_position = false;
bars_against_count = 0;
return;
}
// Exit conditions based on RSI target
if(current_position_type == POSITION_TYPE_BUY)
{
// Check if RSI is against the position (below oversold)
if(rsi_current < RSI_Oversold)
{
if(!rsi_against_position)
{
rsi_against_position = true;
bars_against_count = 1;
}
else
{
bars_against_count++;
}
// Close position if RSI has been against for Y bars
if(bars_against_count >= BarsToWait)
{
ClosePosition();
return;
}
}
else
{
// RSI is no longer against the position, reset counter
if(rsi_against_position)
{
rsi_against_position = false;
bars_against_count = 0;
}
// Exit long position when RSI reaches buy target
if(rsi_current >= RSI_Target_Buy)
{
ClosePosition();
}
}
}
else if(current_position_type == POSITION_TYPE_SELL)
{
// Check if RSI is against the position (above overbought)
if(rsi_current > RSI_Overbought)
{
if(!rsi_against_position)
{
rsi_against_position = true;
bars_against_count = 1;
}
else
{
bars_against_count++;
}
// Close position if RSI has been against for Y bars
if(bars_against_count >= BarsToWait)
{
ClosePosition();
return;
}
}
else
{
// RSI is no longer against the position, reset counter
if(rsi_against_position)
{
rsi_against_position = false;
bars_against_count = 0;
}
// Exit short position when RSI reaches sell target
if(rsi_current <= RSI_Target_Sell)
{
ClosePosition();
}
}
}
}
//+------------------------------------------------------------------+
//| Check for entry signals |
//+------------------------------------------------------------------+
void CheckEntrySignals()
{
// Buy signal: RSI crosses from oversold to above oversold (checking the actual crossover)
if(rsi_two_bars_ago <= RSI_Oversold && rsi_prev > RSI_Oversold)
{
OpenBuyPosition();
}
// Sell signal: RSI crosses from overbought to below overbought (checking the actual crossover)
if(rsi_two_bars_ago >= RSI_Overbought && rsi_prev < RSI_Overbought)
{
OpenSellPosition();
}
}
//+------------------------------------------------------------------+
//| Open buy position |
//+------------------------------------------------------------------+
void OpenBuyPosition()
{
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
if(trade.Buy(LotSize, _Symbol, ask, 0, 0, "RSI Scalping Buy"))
{
position_ticket = trade.ResultOrder();
position_open = true;
current_position_type = POSITION_TYPE_BUY;
}
}
//+------------------------------------------------------------------+
//| Open sell position |
//+------------------------------------------------------------------+
void OpenSellPosition()
{
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
if(trade.Sell(LotSize, _Symbol, bid, 0, 0, "RSI Scalping Sell"))
{
position_ticket = trade.ResultOrder();
position_open = true;
current_position_type = POSITION_TYPE_SELL;
}
}
//+------------------------------------------------------------------+
//| Close current position |
//+------------------------------------------------------------------+
void ClosePosition()
{
if(trade.PositionClose(position_ticket))
{
position_open = false;
position_ticket = 0;
rsi_against_position = false;
bars_against_count = 0;
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 238 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 233 KiB