This commit is contained in:
zhutoutoutousan
2026-01-05 05:37:33 +01:00
parent 7d41b04aef
commit 5b44e14211
79 changed files with 19884 additions and 0 deletions
+440
View File
@@ -0,0 +1,440 @@
//+------------------------------------------------------------------+
//| DarvasBox.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\Trade.mqh>
#include <Indicators\Trend.mqh>
#include <Indicators\Volumes.mqh>
// Input parameters
input int BoxPeriod = 165; // Period for Darvas Box calculation
input double BoxDeviation = 25140; // Box deviation in points
input int VolumeThreshold = 938; // Minimum volume for confirmation
input double StopLoss = 1665; // Stop loss in points (increased for BTCUSD)
input double TakeProfit = 3685; // Take profit in points (increased for BTCUSD)
input bool EnableLogging = false; // Enable detailed logging
input color BoxColor = clrBlue; // Color for Darvas Box
input int BoxWidth = 1; // Width of box lines
// Trend confirmation parameters
input ENUM_TIMEFRAMES TrendTimeframe = PERIOD_H2; // Timeframe for trend analysis
input int MA_Period = 125; // Moving Average period for trend
input ENUM_MA_METHOD MA_Method = MODE_EMA; // Moving Average method
input ENUM_APPLIED_PRICE MA_Price = PRICE_WEIGHTED; // Price type for MA
input double TrendThreshold = 4.94; // Trend strength threshold
// Volume analysis parameters
input int VolumeMA_Period = 110; // Period for Volume MA
input double VolumeThresholdMultiplier = 1.5; // Volume spike threshold
// Global variables
double boxHigh = 0;
double boxLow = 0;
bool boxFormed = false;
datetime lastBoxTime = 0;
string boxName = "DarvasBox_";
double minStopLevel = 0;
double point = 0;
CTrade trade;
ulong magicNumber = 135790;
// Indicator handles
int maHandle;
int volumeHandle;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialize indicators and variables
boxHigh = 0;
boxLow = 0;
boxFormed = false;
lastBoxTime = 0;
// Get symbol properties
point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
minStopLevel = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * point;
// Initialize indicators
maHandle = iMA(_Symbol, TrendTimeframe, MA_Period, 0, MA_Method, MA_Price);
volumeHandle = iVolumes(_Symbol, PERIOD_CURRENT, VOLUME_TICK);
if(maHandle == INVALID_HANDLE || volumeHandle == INVALID_HANDLE)
{
Print("Error creating indicators");
return(INIT_FAILED);
}
// Configure trade object
trade.SetDeviationInPoints(10);
trade.SetTypeFilling(ORDER_FILLING_IOC);
trade.SetAsyncMode(false);
trade.SetExpertMagicNumber(magicNumber);
if(EnableLogging)
{
Print("Darvas Box Expert Advisor initialized");
Print("Symbol: ", _Symbol);
Print("Point: ", point);
Print("Minimum Stop Level: ", minStopLevel);
}
// Delete any existing box objects
ObjectsDeleteAll(0, boxName);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Draw Darvas Box on chart |
//+------------------------------------------------------------------+
void DrawDarvasBox()
{
if(!boxFormed) return;
datetime time1 = iTime(_Symbol, PERIOD_H1, BoxPeriod);
datetime time2 = iTime(_Symbol, PERIOD_H1, 0);
// Delete old box
ObjectsDeleteAll(0, boxName);
// Draw box
ObjectCreate(0, boxName + "Top", OBJ_TREND, 0, time1, boxHigh, time2, boxHigh);
ObjectCreate(0, boxName + "Bottom", OBJ_TREND, 0, time1, boxLow, time2, boxLow);
// Set box properties
ObjectSetInteger(0, boxName + "Top", OBJPROP_COLOR, BoxColor);
ObjectSetInteger(0, boxName + "Bottom", OBJPROP_COLOR, BoxColor);
ObjectSetInteger(0, boxName + "Top", OBJPROP_WIDTH, BoxWidth);
ObjectSetInteger(0, boxName + "Bottom", OBJPROP_WIDTH, BoxWidth);
ObjectSetInteger(0, boxName + "Top", OBJPROP_RAY_RIGHT, true);
ObjectSetInteger(0, boxName + "Bottom", OBJPROP_RAY_RIGHT, true);
}
//+------------------------------------------------------------------+
//| Calculate Darvas Box levels |
//+------------------------------------------------------------------+
void CalculateDarvasBox()
{
double high = 0;
double low = DBL_MAX;
// Find highest high and lowest low in the period
for(int i = 0; i < BoxPeriod; i++)
{
high = MathMax(high, iHigh(_Symbol, PERIOD_H1, i));
low = MathMin(low, iLow(_Symbol, PERIOD_H1, i));
}
double range = high - low;
double allowedRange = BoxDeviation * _Point;
if(EnableLogging)
{
Print("Box Calculation - High: ", high, " Low: ", low, " Range: ", range, " Allowed Range: ", allowedRange);
}
// Check if box is formed
if(range <= allowedRange)
{
boxHigh = high;
boxLow = low;
boxFormed = true;
lastBoxTime = iTime(_Symbol, PERIOD_CURRENT, 0);
// Draw the box
DrawDarvasBox();
if(EnableLogging)
Print("Box Formed - High: ", boxHigh, " Low: ", boxLow, " Time: ", lastBoxTime);
}
else
{
boxFormed = false;
// Delete box if it exists
ObjectsDeleteAll(0, boxName);
}
}
//+------------------------------------------------------------------+
//| Validate and adjust stop levels |
//+------------------------------------------------------------------+
bool ValidateStopLevels(double price, double &sl, double &tp, ENUM_ORDER_TYPE orderType)
{
double minSlDistance = MathMax(minStopLevel, StopLoss * point);
double minTpDistance = MathMax(minStopLevel, TakeProfit * point);
if(EnableLogging)
{
Print("Minimum SL Distance: ", minSlDistance);
Print("Minimum TP Distance: ", minTpDistance);
}
// Adjust stop loss
if(orderType == ORDER_TYPE_BUY)
{
sl = price - minSlDistance;
tp = price + minTpDistance;
if(EnableLogging)
{
Print("Buy Order Levels:");
Print("Entry: ", price);
Print("Stop Loss: ", sl);
Print("Take Profit: ", tp);
}
}
else // ORDER_TYPE_SELL
{
sl = price + minSlDistance;
tp = price - minTpDistance;
if(EnableLogging)
{
Print("Sell Order Levels:");
Print("Entry: ", price);
Print("Stop Loss: ", sl);
Print("Take Profit: ", tp);
}
}
return true;
}
//+------------------------------------------------------------------+
//| Check trend direction and strength |
//+------------------------------------------------------------------+
bool IsTrendFavorable(ENUM_ORDER_TYPE orderType)
{
double ma[];
ArraySetAsSeries(ma, true);
if(CopyBuffer(maHandle, 0, 0, 2, ma) <= 0)
return false;
double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double trendStrength = MathAbs(currentPrice - ma[0]) / point;
if(EnableLogging)
Print("Trend Strength: ", trendStrength);
if(orderType == ORDER_TYPE_BUY)
return (currentPrice > ma[0] && trendStrength > TrendThreshold);
else
return (currentPrice < ma[0] && trendStrength > TrendThreshold);
}
//+------------------------------------------------------------------+
//| Check volume conditions |
//+------------------------------------------------------------------+
bool CheckVolumeConditions()
{
double volumes[];
ArraySetAsSeries(volumes, true);
if(CopyBuffer(volumeHandle, 0, 0, VolumeMA_Period + 1, volumes) <= 0)
return false;
double volumeMA = 0;
for(int i = 1; i <= VolumeMA_Period; i++)
volumeMA += volumes[i];
volumeMA /= VolumeMA_Period;
double currentVolume = volumes[0];
double volumeRatio = currentVolume / volumeMA;
if(EnableLogging)
Print("Volume Ratio: ", volumeRatio);
return (volumeRatio > VolumeThresholdMultiplier);
}
//+------------------------------------------------------------------+
//| Place trade order |
//+------------------------------------------------------------------+
bool PlaceOrder(ENUM_ORDER_TYPE orderType, double price, double sl, double tp)
{
// Validate and adjust stop levels
if(!ValidateStopLevels(price, sl, tp, orderType))
{
if(EnableLogging)
Print("Invalid stop levels after adjustment");
return false;
}
// Check trend and volume conditions
if(!IsTrendFavorable(orderType))
{
if(EnableLogging)
Print("Trend not favorable for trade");
return false;
}
if(!CheckVolumeConditions())
{
if(EnableLogging)
Print("Volume conditions not met");
return false;
}
if(EnableLogging)
{
Print("Order Details:");
Print("Type: ", EnumToString(orderType));
Print("Price: ", price);
Print("Stop Loss: ", sl);
Print("Take Profit: ", tp);
}
bool result = false;
if(orderType == ORDER_TYPE_BUY)
{
result = trade.Buy(0.01, _Symbol, price, sl, tp, "Darvas Box Breakout");
}
else
{
result = trade.Sell(0.01, _Symbol, price, sl, tp, "Darvas Box Breakdown");
}
if(EnableLogging)
{
if(result)
Print((orderType == ORDER_TYPE_BUY ? "Buy" : "Sell"), " Order Placed Successfully");
else
Print((orderType == ORDER_TYPE_BUY ? "Buy" : "Sell"), " Order Failed - Error: ", trade.ResultRetcode(), " Description: ", trade.ResultRetcodeDescription());
}
return result;
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Calculate new box levels
CalculateDarvasBox();
// Check for trading signals
if(boxFormed)
{
double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double currentVolume = iVolume(_Symbol, PERIOD_CURRENT, 0);
if(EnableLogging)
{
Print("Current Price: ", currentPrice, " Box High: ", boxHigh, " Box Low: ", boxLow);
Print("Current Volume: ", currentVolume, " Volume Threshold: ", VolumeThreshold);
}
// Check for breakout above box
if(currentPrice > boxHigh && currentVolume > VolumeThreshold)
{
if(EnableLogging)
Print("Breakout Signal Detected - Price above box high");
// Buy signal
if(PositionsTotal() == 0) // No existing positions
{
double sl = currentPrice - StopLoss * _Point;
double tp = currentPrice + TakeProfit * _Point;
if(EnableLogging)
Print("Preparing Buy Order - Price: ", currentPrice, " SL: ", sl, " TP: ", tp);
PlaceOrder(ORDER_TYPE_BUY, currentPrice, sl, tp);
}
else if(EnableLogging)
Print("Skipping Buy Signal - Position already exists");
}
// Check for breakdown below box
if(currentPrice < boxLow && currentVolume > VolumeThreshold)
{
if(EnableLogging)
Print("Breakdown Signal Detected - Price below box low");
// Sell signal
if(PositionsTotal() == 0) // No existing positions
{
double sl = currentPrice + StopLoss * _Point;
double tp = currentPrice - TakeProfit * _Point;
if(EnableLogging)
Print("Preparing Sell Order - Price: ", currentPrice, " SL: ", sl, " TP: ", tp);
PlaceOrder(ORDER_TYPE_SELL, currentPrice, sl, tp);
}
else if(EnableLogging)
Print("Skipping Sell Signal - Position already exists");
}
}
else if(EnableLogging)
Print("No Box Formed - Waiting for consolidation");
}
//+------------------------------------------------------------------+
//| Get last error description |
//+------------------------------------------------------------------+
string GetLastErrorDescription()
{
string errorDescription;
switch(GetLastError())
{
case 0: errorDescription = "No error"; break;
case 1: errorDescription = "No error, but result unknown"; break;
case 2: errorDescription = "Common error"; break;
case 3: errorDescription = "Invalid trade parameters"; break;
case 4: errorDescription = "Trade server is busy"; break;
case 5: errorDescription = "Old version of the client terminal"; break;
case 6: errorDescription = "No connection with trade server"; break;
case 7: errorDescription = "Not enough rights"; break;
case 8: errorDescription = "Too frequent requests"; break;
case 9: errorDescription = "Malfunctional trade operation"; break;
case 64: errorDescription = "Account disabled"; break;
case 65: errorDescription = "Invalid account"; break;
case 128: errorDescription = "Trade timeout"; break;
case 129: errorDescription = "Invalid price"; break;
case 130: errorDescription = "Invalid stops"; break;
case 131: errorDescription = "Invalid trade volume"; break;
case 132: errorDescription = "Market is closed"; break;
case 133: errorDescription = "Trade is disabled"; break;
case 134: errorDescription = "Not enough money"; break;
case 135: errorDescription = "Price changed"; break;
case 136: errorDescription = "Off quotes"; break;
case 137: errorDescription = "Broker is busy"; break;
case 138: errorDescription = "Requote"; break;
case 139: errorDescription = "Order is locked"; break;
case 140: errorDescription = "Long positions only allowed"; break;
case 141: errorDescription = "Too many requests"; break;
case 145: errorDescription = "Modification denied because order is too close to market"; break;
case 146: errorDescription = "Trade context is busy"; break;
case 147: errorDescription = "Expirations are denied by broker"; break;
case 148: errorDescription = "Amount of open and pending orders has reached the limit"; break;
case 149: errorDescription = "Hedging is prohibited"; break;
case 150: errorDescription = "Prohibited by FIFO rules"; break;
default: errorDescription = "Unknown error"; break;
}
return errorDescription;
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Delete all box objects
ObjectsDeleteAll(0, boxName);
if(EnableLogging)
Print("Expert Advisor deinitialized - Reason: ", reason);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 239 KiB

@@ -0,0 +1,515 @@
//+------------------------------------------------------------------+
//| EMACrossOver.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>
//--- Eingabeparameter (Input Parameters)
input int EMA_Periode = 26; // EMA Periode
input double PreisSchwelle = 2050.0; // Preisbewegung Schwelle in Pips
input double SteigungSchwelle = 100.0; // EMA Steigung Schwelle in Pips
input int ÜberwachungTimeout = 750; // Überwachungszeit in Sekunden
input double TrailingStop = 400.0; // Gleitender Stop in Pips
input double LotGröße = 0.1; // Handelsvolumen
input int MagicNumber = 12350; // Magic Number für Trades
input bool UseSpreadAdjustment = true; // Spread-Anpassung verwenden
input ENUM_TIMEFRAMES Timeframe = PERIOD_H1; // Zeitraum für Analyse
input bool UseBarData = true; // Bar-Daten statt Tick-Daten verwenden
input int MaxTradesPerCrossover = 4; // Maximale Trades pro Crossover-Ereignis
input int ProfitCheckBars = 26; // Bars bis zur Profit-Prüfung
input bool CloseUnprofitableTrades = true; // Unprofitable Trades nach X Bars schließen
//--- Globale Variablen (Global Variables)
int ema_handle; // EMA Indicator Handle
double ema_array[]; // Array für EMA
datetime letzte_überwachung_zeit; // Zeit der letzten Überwachung
bool überwachung_aktiv = false; // Überwachungsstatus
bool preis_trigger_aktiv = false; // Preis-Trigger Status
bool steigung_trigger_aktiv = false; // Steigungs-Trigger Status
int ticket = 0; // Trade Ticket
CTrade trade; // CTrade Objekt
int trades_in_current_crossover = 0; // Anzahl Trades im aktuellen Crossover
bool crossover_detected = false; // Crossover erkannt
datetime trade_open_time = 0; // Zeitpunkt des Trade-Öffnens
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- CTrade konfigurieren (Configure CTrade)
trade.SetExpertMagicNumber(MagicNumber);
trade.SetDeviationInPoints(10);
trade.SetTypeFilling(ORDER_FILLING_IOC);
//--- EMA Indicator Handle erstellen (Create EMA indicator handle)
ema_handle = iMA(_Symbol, Timeframe, EMA_Periode, 0, MODE_EMA, PRICE_CLOSE);
if(ema_handle == INVALID_HANDLE)
{
Print("Fehler beim Erstellen des EMA Indicators");
return(INIT_FAILED);
}
//--- Arrays initialisieren (Initialize arrays)
ArraySetAsSeries(ema_array, true);
//--- Arrays mit aktuellen Werten füllen (Fill arrays with current values)
BerechneEMA();
Print("EMA EA initialisiert - Periode: ", EMA_Periode, " Timeframe: ", EnumToString(Timeframe), " Handle: ", ema_handle);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- Indicator Handle freigeben (Release indicator handle)
if(ema_handle != INVALID_HANDLE)
{
IndicatorRelease(ema_handle);
}
Print("EA beendet - Grund: ", reason);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- Bar-Daten oder Tick-Daten verwenden (Use bar data or tick data)
if(UseBarData)
{
//--- Nur bei neuen Bars ausführen (Only execute on new bars)
static datetime last_bar_time = 0;
datetime current_bar_time = iTime(_Symbol, Timeframe, 0);
if(current_bar_time == last_bar_time)
{
return; // Kein neuer Bar, nichts tun
}
last_bar_time = current_bar_time;
}
//--- EMA Werte berechnen (Calculate EMA values)
BerechneEMA();
//--- Debug: Aktuelle Werte ausgeben (Debug: Output current values)
if(ArraySize(ema_array) > 0)
{
double aktueller_close = iClose(_Symbol, Timeframe, 0);
double ema_aktuell = ema_array[0];
double ema_vorher = ema_array[1];
double preis_abstand = MathAbs(aktueller_close - ema_aktuell) / _Point;
double steigung = (ema_aktuell - ema_vorher) / _Point;
if(UseBarData)
{
Print("=== DEBUG INFO (Neuer Bar) ===");
Print("Bar Zeit: ", TimeToString(iTime(_Symbol, Timeframe, 0)));
}
else
{
Print("=== DEBUG INFO (Tick) ===");
}
Print("Aktueller Close: ", aktueller_close);
Print("EMA: ", ema_aktuell);
Print("Preis-Abstand: ", preis_abstand, " Pips");
Print("EMA Steigung: ", steigung, " Pips");
Print("Differenz Close-EMA: ", aktueller_close - ema_aktuell);
Print("Preis-Trigger: ", preis_trigger_aktiv, " Steigungs-Trigger: ", steigung_trigger_aktiv);
Print("Überwachung aktiv: ", überwachung_aktiv);
Print("Position offen: ", PositionSelect(_Symbol));
Print("Trades im aktuellen Crossover: ", trades_in_current_crossover, "/", MaxTradesPerCrossover);
Print("==================");
}
//--- Überwachung prüfen (Check monitoring)
if(überwachung_aktiv)
{
if(UseBarData)
{
// Bar-basierte Überwachungszeit
int bars_since_monitoring = iBarShift(_Symbol, Timeframe, letzte_überwachung_zeit);
int timeout_bars = (int)(ÜberwachungTimeout / PeriodSeconds(Timeframe));
if(bars_since_monitoring > timeout_bars)
{
überwachung_aktiv = false;
preis_trigger_aktiv = false;
steigung_trigger_aktiv = false;
Print("Überwachung beendet - Bar-basierte Zeitüberschreitung (", bars_since_monitoring, " Bars)");
}
}
else
{
// Tick-basierte Überwachungszeit
if(TimeCurrent() - letzte_überwachung_zeit > ÜberwachungTimeout)
{
überwachung_aktiv = false;
preis_trigger_aktiv = false;
steigung_trigger_aktiv = false;
Print("Überwachung beendet - Tick-basierte Zeitüberschreitung");
}
}
}
//--- Trigger-Bedingungen prüfen (Check trigger conditions)
PrüfeTrigger();
//--- Trade Management (Trade management)
VerwalteTrades();
}
//+------------------------------------------------------------------+
//| EMA Berechnung (EMA Calculation) |
//+------------------------------------------------------------------+
void BerechneEMA()
{
//--- EMA Werte vom Indicator kopieren (Copy EMA values from indicator)
int copied = CopyBuffer(ema_handle, 0, 0, 3, ema_array);
if(copied <= 0)
{
Print("TRACE: Fehler beim Kopieren der EMA Werte - Copied: ", copied);
return;
}
Print("TRACE: EMA Werte kopiert: ", copied, " Bars");
Print("TRACE: EMA [0]: ", ema_array[0], " [1]: ", ema_array[1], " [2]: ", ema_array[2]);
}
//+------------------------------------------------------------------+
//| Trigger-Bedingungen prüfen (Check trigger conditions) |
//+------------------------------------------------------------------+
void PrüfeTrigger()
{
if(ArraySize(ema_array) < 2)
{
Print("TRACE: Array zu klein - Größe: ", ArraySize(ema_array));
return;
}
//--- Aktuelle Werte (Current values)
double aktueller_preis = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double aktueller_ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double aktueller_close = iClose(_Symbol, Timeframe, 0);
double pips_multiplier = (_Digits == 3 || _Digits == 5) ? 10.0 : 1.0;
//--- EMA Werte in Variablen (EMA values in variables)
double ema_aktuell = ema_array[0];
double ema_vorher = ema_array[1];
//--- EMA Crossover Erkennung (EMA Crossover Detection)
// Prüfe ob Preis die EMA kreuzt (Check if price crosses EMA)
static double last_close = 0;
static double last_ema = 0;
if(last_close != 0 && last_ema != 0)
{
bool crossover_bullish = (last_close <= last_ema) && (aktueller_close > ema_aktuell);
bool crossover_bearish = (last_close >= last_ema) && (aktueller_close < ema_aktuell);
//--- Neues Crossover-Ereignis erkannt (New crossover event detected)
if(crossover_bullish || crossover_bearish)
{
trades_in_current_crossover = 0; // Reset trade counter
Print("TRACE: EMA Crossover erkannt - ", (crossover_bullish ? "BULLISH" : "BEARISH"), " - Trade-Counter zurückgesetzt");
Print("TRACE: Vorher: Close=", last_close, " EMA=", last_ema, " Jetzt: Close=", aktueller_close, " EMA=", ema_aktuell);
}
}
//--- Aktuelle Werte für nächsten Vergleich speichern (Save current values for next comparison)
last_close = aktueller_close;
last_ema = ema_aktuell;
//--- Preisbewegung zur EMA prüfen (Check price action to EMA)
double preis_abstand = MathAbs(aktueller_close - ema_aktuell) / _Point / pips_multiplier;
Print("TRACE: Preis-Abstand: ", preis_abstand, " Pips (Schwelle: ", PreisSchwelle, ")");
Print("TRACE: Close: ", aktueller_close, " EMA: ", ema_aktuell);
Print("TRACE: Trades im aktuellen Crossover: ", trades_in_current_crossover, "/", MaxTradesPerCrossover);
if(preis_abstand > PreisSchwelle && !preis_trigger_aktiv)
{
preis_trigger_aktiv = true;
Print("TRACE: Preis-Trigger aktiviert: ", preis_abstand, " Pips");
}
//--- EMA Steigung prüfen (Check EMA slope)
double steigung = (ema_aktuell - ema_vorher) / _Point / pips_multiplier;
Print("TRACE: EMA Steigung: ", steigung, " Pips (Schwelle: ", SteigungSchwelle, ")");
if(MathAbs(steigung) > SteigungSchwelle && !steigung_trigger_aktiv)
{
steigung_trigger_aktiv = true;
Print("TRACE: Steigungs-Trigger aktiviert: ", steigung, " Pips");
}
//--- Überwachung starten wenn beide Trigger aktiv sind (Start monitoring when both triggers are active)
if(preis_trigger_aktiv && steigung_trigger_aktiv && !überwachung_aktiv)
{
überwachung_aktiv = true;
if(UseBarData)
{
letzte_überwachung_zeit = iTime(_Symbol, Timeframe, 0); // Aktuelle Bar-Zeit
Print("TRACE: Überwachung gestartet - Beide Trigger aktiv (Bar: ", TimeToString(letzte_überwachung_zeit), ")");
}
else
{
letzte_überwachung_zeit = TimeCurrent(); // Aktuelle Tick-Zeit
Print("TRACE: Überwachung gestartet - Beide Trigger aktiv (Tick)");
}
}
//--- Trade platzieren wenn Überwachung aktiv und Preis über/unter EMA (Place trade when monitoring active and price above/below EMA)
if(überwachung_aktiv)
{
bool bullish_signal = aktueller_close > ema_aktuell;
bool bearish_signal = aktueller_close < ema_aktuell;
Print("TRACE: Signal Check - Bullish: ", bullish_signal, " Bearish: ", bearish_signal);
Print("TRACE: Close: ", aktueller_close, " EMA: ", ema_aktuell);
Print("TRACE: Differenz: ", aktueller_close - ema_aktuell);
//--- Trade-Limit prüfen (Check trade limit)
if(trades_in_current_crossover >= MaxTradesPerCrossover)
{
Print("TRACE: Trade-Limit erreicht (", MaxTradesPerCrossover, ") - Kein neuer Trade");
return;
}
if(bullish_signal && !PositionSelect(_Symbol))
{
Print("TRACE: Versuche KAUF-Trade zu platzieren (Trade #", trades_in_current_crossover + 1, ")");
if(PlatziereTrade(ORDER_TYPE_BUY))
{
trades_in_current_crossover++;
}
}
else if(bearish_signal && !PositionSelect(_Symbol))
{
Print("TRACE: Versuche VERKAUF-Trade zu platzieren (Trade #", trades_in_current_crossover + 1, ")");
if(PlatziereTrade(ORDER_TYPE_SELL))
{
trades_in_current_crossover++;
}
}
else if(PositionSelect(_Symbol))
{
Print("TRACE: Position bereits offen - kein neuer Trade");
}
}
}
//+------------------------------------------------------------------+
//| Trade platzieren (Place trade) |
//+------------------------------------------------------------------+
bool PlatziereTrade(ENUM_ORDER_TYPE order_type)
{
Print("TRACE: Versuche Trade zu platzieren - Typ: ", (order_type == ORDER_TYPE_BUY) ? "KAUF" : "VERKAUF");
Print("TRACE: Lot: ", LotGröße);
bool success = false;
if(order_type == ORDER_TYPE_BUY)
{
success = trade.Buy(LotGröße, _Symbol, 0, 0, 0, "EMA Crossover Trade");
}
else
{
success = trade.Sell(LotGröße, _Symbol, 0, 0, 0, "EMA Crossover Trade");
}
if(success)
{
ticket = (int)trade.ResultOrder();
Print("TRACE: Trade erfolgreich platziert: ", (order_type == ORDER_TYPE_BUY) ? "KAUF" : "VERKAUF", " Ticket: ", ticket);
//--- Trade-Öffnungszeit speichern (Save trade opening time)
trade_open_time = iTime(_Symbol, Timeframe, 0);
Print("TRACE: Trade-Öffnungszeit: ", TimeToString(trade_open_time));
//--- Überwachung zurücksetzen (Reset monitoring)
überwachung_aktiv = false;
preis_trigger_aktiv = false;
steigung_trigger_aktiv = false;
return true;
}
else
{
Print("TRACE: Fehler beim Platzieren des Trades - Retcode: ", trade.ResultRetcode());
Print("TRACE: Fehlerbeschreibung: ", trade.ResultRetcodeDescription());
return false;
}
}
//+------------------------------------------------------------------+
//| Trades verwalten (Manage trades) |
//+------------------------------------------------------------------+
void VerwalteTrades()
{
if(!PositionSelect(_Symbol))
return;
double position_profit = PositionGetDouble(POSITION_PROFIT);
double position_open_price = PositionGetDouble(POSITION_PRICE_OPEN);
double current_price = PositionGetDouble(POSITION_PRICE_CURRENT);
ENUM_POSITION_TYPE position_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
double pips_multiplier = (_Digits == 3 || _Digits == 5) ? 10.0 : 1.0;
double trailing_stop_pips = TrailingStop;
//--- Gleitender Stop (Trailing Stop) - nur wenn Position im Profit ist
if(position_profit > 0) // Only apply trailing stop when in profit
{
if(position_type == POSITION_TYPE_BUY)
{
double new_stop_loss = current_price - (trailing_stop_pips * _Point * pips_multiplier);
double current_stop_loss = PositionGetDouble(POSITION_SL);
// Only move stop loss if new stop is higher than current stop
if(new_stop_loss > current_stop_loss)
{
ÄndereStopLoss(new_stop_loss);
}
}
else if(position_type == POSITION_TYPE_SELL)
{
double new_stop_loss = current_price + (trailing_stop_pips * _Point * pips_multiplier);
double current_stop_loss = PositionGetDouble(POSITION_SL);
// Only move stop loss if new stop is lower than current stop
if(new_stop_loss < current_stop_loss || current_stop_loss == 0)
{
ÄndereStopLoss(new_stop_loss);
}
}
}
//--- Ausstieg bei Preis unter/über EMA (Exit when price below/above EMA)
if(ArraySize(ema_array) >= 1)
{
double aktueller_close = iClose(_Symbol, Timeframe, 0);
double ema_aktuell = ema_array[0];
bool exit_bullish = (position_type == POSITION_TYPE_SELL && aktueller_close > ema_aktuell);
bool exit_bearish = (position_type == POSITION_TYPE_BUY && aktueller_close < ema_aktuell);
if(exit_bullish || exit_bearish)
{
Print("TRACE: Ausstiegssignal - Close: ", aktueller_close, " EMA: ", ema_aktuell);
SchließePosition("EMA Crossover Exit");
Print("TRACE: Position geschlossen - Trade-Counter bleibt bei ", trades_in_current_crossover);
}
}
//--- Profit-Prüfung nach X Bars (Profit check after X bars)
if(CloseUnprofitableTrades && trade_open_time != 0 && PositionSelect(_Symbol))
{
Print("TRACE: Profit-Prüfung aktiviert - CloseUnprofitableTrades: ", CloseUnprofitableTrades);
PrüfeProfitNachBars();
}
else if(!CloseUnprofitableTrades)
{
Print("TRACE: Profit-Prüfung deaktiviert - CloseUnprofitableTrades: ", CloseUnprofitableTrades);
}
}
//+------------------------------------------------------------------+
//| Profit-Prüfung nach X Bars (Profit check after X bars) |
//+------------------------------------------------------------------+
void PrüfeProfitNachBars()
{
if(!PositionSelect(_Symbol))
{
return; // Keine Position offen
}
datetime current_bar_time = iTime(_Symbol, Timeframe, 0);
int bars_since_trade_open = iBarShift(_Symbol, Timeframe, trade_open_time);
Print("TRACE: Bars seit Trade-Öffnung: ", bars_since_trade_open, "/", ProfitCheckBars);
//--- Prüfe ob genügend Bars vergangen sind (Check if enough bars have passed)
if(bars_since_trade_open >= ProfitCheckBars)
{
double position_profit = PositionGetDouble(POSITION_PROFIT);
double position_volume = PositionGetDouble(POSITION_VOLUME);
ENUM_POSITION_TYPE position_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
Print("TRACE: Profit-Prüfung nach ", ProfitCheckBars, " Bars");
Print("TRACE: Position Profit: ", position_profit, " USD");
//--- Schließe Position wenn nicht im Profit (Close position if not in profit)
if(position_profit <= 0)
{
Print("TRACE: Position nicht im Profit - Schließe Position");
SchließePosition("Profit Check - Unprofitable");
//--- Trade-Öffnungszeit zurücksetzen (Reset trade opening time)
trade_open_time = 0;
Print("TRACE: Trade-Öffnungszeit zurückgesetzt");
}
else
{
Print("TRACE: Position im Profit - Behalte Position");
//--- Trade-Öffnungszeit zurücksetzen um weitere Prüfungen zu vermeiden (Reset to avoid further checks)
trade_open_time = 0;
}
}
}
//+------------------------------------------------------------------+
//| Stop Loss ändern (Modify Stop Loss) |
//+------------------------------------------------------------------+
void ÄndereStopLoss(double new_stop_loss)
{
Print("TRACE: Versuche Stop Loss zu ändern auf: ", new_stop_loss);
bool success = trade.PositionModify(_Symbol, new_stop_loss, PositionGetDouble(POSITION_TP));
if(success)
{
Print("TRACE: Stop Loss erfolgreich geändert auf: ", new_stop_loss);
}
else
{
Print("TRACE: Fehler beim Ändern des Stop Loss - Retcode: ", trade.ResultRetcode());
Print("TRACE: Fehlerbeschreibung: ", trade.ResultRetcodeDescription());
}
}
//+------------------------------------------------------------------+
//| Position schließen (Close position) |
//+------------------------------------------------------------------+
void SchließePosition(string reason = "Unbekannt")
{
Print("TRACE: Versuche Position zu schließen - Grund: ", reason);
bool success = trade.PositionClose(_Symbol);
if(success)
{
Print("TRACE: Position erfolgreich geschlossen - Grund: ", reason);
}
else
{
Print("TRACE: Fehler beim Schließen der Position - Retcode: ", trade.ResultRetcode());
Print("TRACE: Fehlerbeschreibung: ", trade.ResultRetcodeDescription());
}
}
//+------------------------------------------------------------------+
Binary file not shown.

After

Width:  |  Height:  |  Size: 250 KiB

@@ -0,0 +1,315 @@
// Input Parameters
#include <Trade\Trade.mqh>
input group "Trade Management"
input int MagicNumber = 7;
input int rsiPeriod = 19; // RSI period
input int overboughtLevel = 93; // Overbought level (RSI > 70 for sell)
input int oversoldLevel = 22; // Oversold level (RSI < 30 for buy)
input double entryRSIBuySpread = 0;
input double entryRSISellSpread = 0;
input double lotSize = 0.01; // Trade lot size
input int slippage = 3; // Slippage for orders
input int cooldownSeconds = 209; // Cooldown period in seconds
input ENUM_TIMEFRAMES TimeFrame1 = PERIOD_M1; // RSI Timeframe
input ENUM_TIMEFRAMES TimeFrame2 = PERIOD_M1; // EMA Timeframe
input ENUM_TIMEFRAMES BarTimeFrame = PERIOD_M12; // EMA Timeframe
input int emaPeriod = 140; // EMA period
input double emaSlopeThreshold = 105; // EMA slope threshold for trend strength
input double exitBuyRSI = 86;
input double exitSellRSI = 10;
input double TrailingStop = 295;
input double emaDistanceThreshold = 165;
input int tradingHourOneBegin = 24;
input int tradingHourOneEnd = 22;
input int tradingHourTwoBegin = 6;
input int tradingHourTwoEnd = 19;
datetime bartime;
// RSI Handle
int rsiHandle;
input bool Sunday =false; // Sunday
input bool Monday =false; // Monday
input bool Tuesday =true; // Tuesday
input bool Wednesday=true; // Wednesday
input bool Thursday =true; // Thursday
input bool Friday =false; // Friday
input bool Saturday =false; // Saturday
bool WeekDays[7];
void WeekDays_Init()
{
WeekDays[0]=Sunday;
WeekDays[1]=Monday;
WeekDays[2]=Tuesday;
WeekDays[3]=Wednesday;
WeekDays[4]=Thursday;
WeekDays[5]=Friday;
WeekDays[6]=Saturday;
}
bool WeekDays_Check(datetime aTime)
{
MqlDateTime stm;
TimeToStruct(aTime,stm);
return(WeekDays[stm.day_of_week]);
}
// EMA Handle
int emaHandle;
double previousRSIDef = 0;
// Create CTrade object for executing trades
CTrade trade;
// Track the last trade time
datetime lastTradeTime = 0;
void OnInit() {
WeekDays_Init();
// Create RSI handle
rsiHandle = iRSI(_Symbol, TimeFrame1, rsiPeriod, PRICE_CLOSE);
if (rsiHandle == INVALID_HANDLE) {
Print("Error creating RSI handle: ", GetLastError());
return;
}
// Create EMA handle
emaHandle = iMA(_Symbol, TimeFrame2, emaPeriod, 0, MODE_EMA, PRICE_CLOSE);
if (emaHandle == INVALID_HANDLE) {
Print("Error creating EMA handle: ", GetLastError());
return;
}
// Initialization successful
Print("RSI and EMA Reversal Strategy Initialized.");
}
void OnTick() {
if(bartime==iTime(_Symbol,BarTimeFrame,0))return;
bartime=iTime(_Symbol,BarTimeFrame,0);
// Check if RSI data is available
double rsi[];
if (CopyBuffer(rsiHandle, 0, 0, 2, rsi) <= 0) {
Print("Error copying RSI data: ", GetLastError());
return;
}
// Check if EMA data is available
double ema[];
if (CopyBuffer(emaHandle, 0, 0, 2, ema) <= 0) {
Print("Error copying EMA data: ", GetLastError());
return;
}
// Get the current time
datetime currentTime = TimeCurrent();
int currentHour = TimeHour(TimeCurrent());
if(!WeekDays_Check(TimeTradeServer())) {
Close_Position_MN(MagicNumber);
return;
}
if (!(currentHour < tradingHourOneEnd && currentHour > tradingHourOneBegin || currentHour < tradingHourTwoEnd && currentHour > tradingHourTwoBegin))
{
Close_Position_MN(MagicNumber);
return; // Prevent further trading during this time
}
// Ensure there is at least one position
bool hasPosition = (PositionsTotal() > 0);
// Get the current and previous RSI values
double currentRSI = rsi[0];
double previousRSI = rsi[1];
if(previousRSIDef == 0) {
previousRSIDef = currentRSI;
return;
}
// Get the current and previous EMA values
double currentEMA = ema[0];
double previousEMA = ema[1];
// Calculate the EMA slope (difference between current and previous EMA values)
double emaSlope = (currentEMA - previousEMA) * 100;
Print(emaSlope);
double closeCurr = iClose(Symbol(), Period(), 0); // Close of current bar
// ** NEW CODE: Calculate distance to EMA and adjust score **
double priceToEmaDistance = (closeCurr - currentEMA) * 10; // Distance between the current price and the EMA
Print("priceToEmaDistance");
Print(priceToEmaDistance);
// Determine if there are existing buy or sell positions
bool isBuyPosition = false;
bool isSellPosition = false;
if (hasPosition) {
if (PositionSelect(_Symbol)) {
int positionType = PositionGetInteger(POSITION_TYPE);
if (positionType == POSITION_TYPE_BUY) {
isBuyPosition = true;
} else if (positionType == POSITION_TYPE_SELL) {
isSellPosition = true;
}
}
}
ApplyTrailingStop();
// Check if the cooldown period has elapsed since the last trade
bool cooldownPassed = (currentTime - lastTradeTime) >= cooldownSeconds;
// Check if EMA slope is above the threshold (indicating strong trend)
bool isTrendStrong = MathAbs(emaSlope) > emaSlopeThreshold || MathAbs(priceToEmaDistance) > emaDistanceThreshold;
// Close trade logic when RSI crosses 50
if (isBuyPosition && currentRSI > exitBuyRSI) {
// Close buy position
Close_Position_MN(MagicNumber);
lastTradeTime = currentTime; // Update last trade time
}
if (isSellPosition && currentRSI < exitSellRSI) {
Close_Position_MN(MagicNumber);
lastTradeTime = currentTime; // Update last trade time
}
// If the EMA slope is strong, do not place new trades
if (isTrendStrong) {
Close_Position_MN(MagicNumber);
lastTradeTime = currentTime; // Update last trade time
Print("Strong trend detected (EMA slope), skipping new trade.");
return;
}
// SELL logic (RSI crosses over the overbought level)
if (currentRSI < overboughtLevel - entryRSISellSpread && previousRSIDef >= overboughtLevel && !isSellPosition && !hasPosition && cooldownPassed) {
trade.SetExpertMagicNumber(MagicNumber);
if (trade.Sell(lotSize, _Symbol, 0, 0, "Sell Order")) {
Print("Sell order placed.");
lastTradeTime = currentTime; // Update last trade time
} else {
Print("Error placing sell order: ", GetLastError());
}
}
// BUY logic (RSI crosses below the oversold level)
if (currentRSI > oversoldLevel + entryRSIBuySpread && previousRSIDef <= oversoldLevel && !isBuyPosition && !hasPosition && cooldownPassed) {
trade.SetExpertMagicNumber(MagicNumber);
if (trade.Buy(lotSize, _Symbol, 0, 0, "Buy Order")) {
Print("Buy order placed.");
lastTradeTime = currentTime; // Update last trade time
} else {
Print("Error placing buy order: ", GetLastError());
}
}
previousRSIDef = currentRSI;
}
void OnDeinit(const int reason) {
// Release RSI and EMA handles on deinitialization
if (rsiHandle != INVALID_HANDLE) {
IndicatorRelease(rsiHandle);
Print("RSI handle released.");
}
if (emaHandle != INVALID_HANDLE) {
IndicatorRelease(emaHandle);
Print("EMA handle released.");
}
}
void Close_Position_MN(ulong magicNumber)
{
int total = PositionsTotal();
for(int i = total - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
// Use PositionSelect by symbol instead of ticket
string symbol = PositionGetSymbol(i);
if(PositionSelect(symbol))
{
if (PositionGetInteger(POSITION_MAGIC) == magicNumber && PositionGetInteger(POSITION_TICKET) == ticket)
{
if(symbol == _Symbol) // Verify the symbol
{
Print("MN " + magicNumber);
trade.PositionClose(ticket);
}
}
}
else
{
int errorCode = GetLastError();
Print("aaaa PositionSelect failed with error code: ", errorCode);
}
}
}
void ApplyTrailingStop()
{
Print("Scanning for trailing stop");
for(int i=PositionsTotal()-1; i>=0; i--)
{
string symbol = PositionGetSymbol(i);
ulong PositionTicket = PositionGetTicket(i);
long trade_type = PositionGetInteger(POSITION_TYPE);
if(!PositionGetInteger(POSITION_MAGIC) == MagicNumber) {
return;
}
double POINT = SymbolInfoDouble( symbol, SYMBOL_POINT );
int DIGIT = (int) SymbolInfoInteger( symbol, SYMBOL_DIGITS );
if(trade_type == 0)
{
double Bid = NormalizeDouble(SymbolInfoDouble(symbol,SYMBOL_BID),DIGIT);
if(Bid-PositionGetDouble(POSITION_PRICE_OPEN) > NormalizeDouble(POINT * TrailingStop,DIGIT))
{
if(PositionGetDouble(POSITION_SL) < NormalizeDouble(Bid - POINT * TrailingStop,DIGIT))
{
trade.PositionModify(PositionTicket,NormalizeDouble(Bid - POINT * TrailingStop,DIGIT),PositionGetDouble(POSITION_TP));
}
}
}
if(trade_type == 1)
{
double Ask = NormalizeDouble(SymbolInfoDouble(symbol,SYMBOL_ASK),DIGIT);
if((PositionGetDouble(POSITION_PRICE_OPEN) - Ask) > NormalizeDouble( POINT * TrailingStop,DIGIT))
{
if((PositionGetDouble(POSITION_SL) > NormalizeDouble(Ask + POINT * TrailingStop,DIGIT)) || (PositionGetDouble(POSITION_SL)==0))
{
trade.PositionModify(PositionTicket,NormalizeDouble(Ask + POINT * TrailingStop,DIGIT),PositionGetDouble(POSITION_TP));
}
}
}
}
}
int TimeHour(datetime when=0){ if(when == 0) when = TimeCurrent();
return when / 3600 % 24;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 233 KiB

@@ -0,0 +1,586 @@
//+------------------------------------------------------------------+
//| 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.

After

Width:  |  Height:  |  Size: 242 KiB

@@ -0,0 +1,601 @@
//+------------------------------------------------------------------+
//| 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_H1; // 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 = 0.0; // Lock Profit Threshold (pips)
input bool InpCloseOppositeTrades = false; // Close Opposite Trades When Profiting
input group "RSI Follow Strategy"
input int InpRSIPeriod = 32; // RSI Period
input int InpRSIOverbought = 78; // RSI Overbought Level
input int InpRSIOversold = 46; // RSI Oversold Level
input int InpRSIExitLevel = 44; // RSI Exit Level
input int InpRSIFollowStartHour = 23; // 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 = 59; // RSI Period
input int InpRSIReverseOverbought = 51; // RSI Overbought Level
input int InpRSIReverseOversold = 49; // RSI Oversold Level
input int InpRSIReverseCrossLevel = 53; // RSI Cross Level
input int InpRSIReverseExitLevel = 48; // RSI Exit Level
input int InpRSIReverseStartHour = 7; // RSI Reverse Start Hour (0-23)
input int InpRSIReverseEndHour = 13; // RSI Reverse End Hour (0-23)
input bool InpRSIReverseCloseOutsideHours = false; // Close trades outside trading hours
input int InpRSIReverseCooldownBars = 15; // RSI Reverse Cooldown (bars)
input bool InpRSIReverseCooldownOnLoss = true; // Apply cooldown only on loss
input group "EMA Cross Strategy"
input int InpEMAPeriod = 120; // EMA Period
input int InpEMACrossStartHour = 8; // EMA Cross Start Hour (0-23)
input int InpEMACrossEndHour = 14; // EMA Cross End Hour (0-23)
input bool InpEMACrossCloseOutsideHours = true; // Close trades outside trading hours
input bool InpUseEMADistanceEntry = true; // Use EMA Distance Entry
input double InpEMADistancePips = 160.0; // EMA Distance Threshold (pips)
input int InpEMADistancePeriod = 26; // 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;
double lastBarRSI = 0; // Store last bar's RSI value
double lastBarRSIReverse = 0; // Store last bar's RSI Reverse value
double lastBarEMA = 0; // Store last bar's EMA value
double lastBarClose = 0; // Store last bar's close value
double lastBarEMAPrev = 0; // Store previous bar's EMA value
double lastBarClosePrev = 0; // Store previous bar's close value
//+------------------------------------------------------------------+
//| 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;
// Use lastBarRSI instead of copying buffer
if(lastBarRSI > InpRSIOverbought)
rsiOverbought = true;
else if(lastBarRSI < InpRSIOversold)
rsiOversold = true;
// Check for entry signals
if(rsiOverbought && lastBarRSI < InpRSIExitLevel)
{
// Sell signal
if(!HasPosition(InpMagicNumberRSIFollow))
{
trade.SetExpertMagicNumber(InpMagicNumberRSIFollow);
trade.Sell(InpLotSize, _Symbol, 0, 0, 0, "RSI Follow");
}
rsiOverbought = false;
}
else if(rsiOversold && lastBarRSI > 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;
// Use lastBarRSIReverse instead of copying buffer
if(lastBarRSIReverse > InpRSIReverseOverbought)
rsiReverseOverbought = true;
else if(lastBarRSIReverse < InpRSIReverseOversold)
rsiReverseOversold = true;
// Check for entry signals
if(rsiReverseOverbought && lastBarRSIReverse < InpRSIReverseCrossLevel)
{
// Sell signal
if(!HasPosition(InpMagicNumberRSIReverse))
{
trade.SetExpertMagicNumber(InpMagicNumberRSIReverse);
trade.Sell(InpLotSize, _Symbol, 0, 0, 0, "RSI Reverse");
}
rsiReverseOverbought = false;
}
else if(rsiReverseOversold && lastBarRSIReverse > 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;
// Check for cross signals using stored values
if(lastBarEMAPrev < lastBarClosePrev && lastBarEMA > lastBarClose)
{
// Buy cross signal
emaCrossBuySignal = true;
emaCrossSellSignal = false;
emaCrossSignalBar = 0;
}
else if(lastBarEMAPrev > lastBarClosePrev && lastBarEMA < lastBarClose)
{
// 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;
double emaHistory[], closeHistory[];
ArraySetAsSeries(emaHistory, true);
ArraySetAsSeries(closeHistory, true);
if(CopyBuffer(emaHandle, 0, 0, InpEMADistancePeriod, emaHistory) > 0 &&
CopyClose(_Symbol, InpTimeframe, 0, InpEMADistancePeriod, closeHistory) > 0)
{
for(int i = 0; i < InpEMADistancePeriod; i++)
{
double distance = (closeHistory[i] - emaHistory[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;
double emaHistory[], closeHistory[];
ArraySetAsSeries(emaHistory, true);
ArraySetAsSeries(closeHistory, true);
if(CopyBuffer(emaHandle, 0, 0, InpEMADistancePeriod, emaHistory) > 0 &&
CopyClose(_Symbol, InpTimeframe, 0, InpEMADistancePeriod, closeHistory) > 0)
{
for(int i = 0; i < InpEMADistancePeriod; i++)
{
double distance = (emaHistory[i] - closeHistory[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 using stored values
if(lastBarEMAPrev < lastBarClosePrev && lastBarEMA > lastBarClose)
{
// Buy signal
if(!HasPosition(InpMagicNumberEMACross))
{
trade.SetExpertMagicNumber(InpMagicNumberEMACross);
trade.Buy(InpLotSize, _Symbol, 0, 0, 0, "EMA Cross");
}
}
else if(lastBarEMAPrev > lastBarClosePrev && lastBarEMA < lastBarClose)
{
// 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;
// Get indicator values for the new bar
double rsi[], rsiReverse[], ema[], close[];
ArraySetAsSeries(rsi, true);
ArraySetAsSeries(rsiReverse, true);
ArraySetAsSeries(ema, true);
ArraySetAsSeries(close, true);
// Store previous values
lastBarEMAPrev = lastBarEMA;
lastBarClosePrev = lastBarClose;
// Get new values
if(CopyBuffer(rsiHandle, 0, 0, 1, rsi) > 0)
lastBarRSI = rsi[0];
if(CopyBuffer(rsiReverseHandle, 0, 0, 1, rsiReverse) > 0)
lastBarRSIReverse = rsiReverse[0];
if(CopyBuffer(emaHandle, 0, 0, 1, ema) > 0)
lastBarEMA = ema[0];
if(CopyClose(_Symbol, InpTimeframe, 0, 1, close) > 0)
lastBarClose = close[0];
// 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()
{
if(InpEnableRSIFollow)
{
// Check RSI Follow exit conditions
if(HasPosition(InpMagicNumberRSIFollow))
{
if((positionInfo.PositionType() == POSITION_TYPE_BUY && lastBarRSI < InpRSIExitLevel) ||
(positionInfo.PositionType() == POSITION_TYPE_SELL && lastBarRSI > InpRSIExitLevel))
{
ClosePosition(InpMagicNumberRSIFollow);
}
}
}
if(InpEnableRSIReverse)
{
// Check RSI Reverse exit conditions
if(HasPosition(InpMagicNumberRSIReverse))
{
if((positionInfo.PositionType() == POSITION_TYPE_BUY && lastBarRSIReverse < InpRSIReverseExitLevel) ||
(positionInfo.PositionType() == POSITION_TYPE_SELL && lastBarRSIReverse > InpRSIReverseExitLevel))
{
ClosePosition(InpMagicNumberRSIReverse);
}
}
}
if(InpEnableEMACross)
{
// Check EMA Cross exit conditions using stored values
if(HasPosition(InpMagicNumberEMACross))
{
if((positionInfo.PositionType() == POSITION_TYPE_BUY && lastBarEMA > lastBarClose) ||
(positionInfo.PositionType() == POSITION_TYPE_SELL && lastBarEMA < lastBarClose))
{
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.

After

Width:  |  Height:  |  Size: 280 KiB

@@ -0,0 +1,539 @@
//+------------------------------------------------------------------+
//| 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.

After

Width:  |  Height:  |  Size: 241 KiB

@@ -0,0 +1,539 @@
//+------------------------------------------------------------------+
//| 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.

After

Width:  |  Height:  |  Size: 250 KiB

+281
View File
@@ -0,0 +1,281 @@
//+------------------------------------------------------------------+
//| 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;
}
}
+281
View File
@@ -0,0 +1,281 @@
//+------------------------------------------------------------------+
//| 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 = 90; // RSI Overbought Level
input double RSI_Oversold = 73; // RSI Oversold Level
input double RSI_Target_Buy = 88; // RSI Target for Buy Exit
input double RSI_Target_Sell = 48; // RSI Target for Sell Exit
input int BarsToWait = 6; // 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.

After

Width:  |  Height:  |  Size: 229 KiB

+363
View File
@@ -0,0 +1,363 @@
//+------------------------------------------------------------------+
//| 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.

After

Width:  |  Height:  |  Size: 223 KiB

+281
View File
@@ -0,0 +1,281 @@
//+------------------------------------------------------------------+
//| 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_H3; // 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 = 19; // RSI Overbought Level
input double RSI_Oversold = 50; // RSI Oversold Level
input double RSI_Target_Buy = 71; // RSI Target for Buy Exit
input double RSI_Target_Sell = 70; // RSI Target for Sell Exit
input int BarsToWait = 1; // 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.

After

Width:  |  Height:  |  Size: 234 KiB

+281
View File
@@ -0,0 +1,281 @@
//+------------------------------------------------------------------+
//| 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 = 54; // RSI Overbought Level
input double RSI_Oversold = 73; // RSI Oversold Level
input double RSI_Target_Buy = 87; // RSI Target for Buy Exit
input double RSI_Target_Sell = 33; // RSI Target for Sell Exit
input int BarsToWait = 1; // 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.

After

Width:  |  Height:  |  Size: 201 KiB

+281
View File
@@ -0,0 +1,281 @@
//+------------------------------------------------------------------+
//| 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.

After

Width:  |  Height:  |  Size: 238 KiB

+281
View File
@@ -0,0 +1,281 @@
//+------------------------------------------------------------------+
//| 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 = 71; // RSI Overbought Level
input double RSI_Oversold = 57; // RSI Oversold Level
input double RSI_Target_Buy = 80; // RSI Target for Buy Exit
input double RSI_Target_Sell = 57; // RSI Target for Sell Exit
input int BarsToWait = 4; // 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.

After

Width:  |  Height:  |  Size: 233 KiB

@@ -0,0 +1,32 @@
SSE Index Multi-Timeframe RSI Momentum Strategy with EMA Distance Trading
Strategy Overview:
This advanced momentum-based trading system is specifically designed for the Shanghai Stock Exchange (SSE) Index, capturing RSI bounce opportunities across multiple timeframes while incorporating sophisticated EMA distance-based entries. The strategy combines traditional RSI oversold/overbought analysis with modern volatility-adjusted position management.
Core Trading Logic:
Weekly RSI Signals: Large position entries (10% equity) when weekly RSI crosses above 30 after being oversold, targeting major trend reversals
Daily RSI Signals: Medium position entries (5% equity) when daily RSI crosses above 30, capturing short-term momentum shifts
EMA Distance Entries: Strategic entries (7.5% equity) when price extends 50+ pips from 200 EMA while remaining above it, exploiting mean reversion opportunities
Risk Management System:
Partial Profit Taking: Both RSI positions scale out 25% when daily RSI becomes overbought (>70), allowing multiple profit captures
Complete Weekly Exits: All weekly positions close when weekly RSI becomes overbought, ensuring trend-following discipline
EMA Crossover Exits: EMA distance trades exit cleanly when price crosses below 50 EMA, providing responsive trend change detection
Emergency Exit: Master exit when EMA crosses above price, protecting all positions during major trend reversals
Advanced Features:
Concurrent Position Management: Up to 100 pyramiding positions across three distinct entry strategies
Multi-Timeframe Analysis: Seamlessly integrates weekly and daily RSI data regardless of chart timeframe
Real-Time Monitoring: Comprehensive information table displaying RSI levels, EMA distances, position quantities, and trade counts
Visual Feedback System: Color-coded entry/exit signals with background highlighting for immediate market condition recognition
Ideal Market Conditions:
Optimized for volatile, emotion-driven markets like Chinese equities where RSI bounces from oversold levels frequently create profitable momentum shifts. The strategy's multiple entry mechanisms ensure comprehensive market coverage while sophisticated exit rules protect capital during adverse conditions.
Technical Requirements:
Recommended for SSE Composite Index, SSE 50, or related Chinese equity ETFs
Best performance on daily charts with sufficient historical data
Suitable for accounts with minimum $10,000 capital for effective position sizing
This strategy represents a complete trading system combining technical analysis fundamentals with modern risk management principles, specifically calibrated for the unique characteristics of Chinese equity markets.
@@ -0,0 +1,202 @@
//@version=6
strategy("SSE Index RSI Bounce Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, initial_capital=10000, pyramiding=100, calc_on_every_tick=false, calc_on_order_fills=false)
// Input parameters
rsi_length = input.int(17, "RSI Length", minval=1)
rsi_oversold = input.int(27, "RSI Oversold Level", minval=1, maxval=50)
rsi_overbought = input.int(86, "RSI Overbought Level", minval=50, maxval=100)
ema_length = input.int(177, "EMA Length", minval=1)
weekly_position_size = input.float(14.0, "Weekly Signal Position Size (%)", minval=0.1, maxval=100)
daily_position_size = input.float(11.0, "Daily Signal Position Size (%)", minval=0.1, maxval=100)
partial_exit_percent = input.float(41.0, "Partial Exit Percentage on Daily RSI Overbought (%)", minval=10.0, maxval=50.0)
// New EMA Distance Trading Parameters
ema_distance_threshold = input.float(16.0, "EMA Distance Threshold (Pips)", minval=1.0, maxval=1000.0)
ema_distance_position_size = input.float(53, "EMA Distance Position Size (%)", minval=0.1, maxval=100)
// EMA Distance Exit Parameters
ema_exit_period = input.int(34, "EMA Exit Period", minval=10, maxval=200)
enable_volume_confirmation = input.bool(true, "Require Volume Confirmation for EMA Exit")
// Calculate indicators
rsi_daily = ta.rsi(close, rsi_length)
rsi_weekly = request.security(syminfo.tickerid, "1W", ta.rsi(close, rsi_length))
ema_200 = ta.ema(close, ema_length)
ema_exit = ta.ema(close, ema_exit_period)
// EMA Distance Trading Logic
pip_size = syminfo.mintick * 10 // Adjust pip size based on instrument
price_ema_distance = math.abs(close - ema_200) / pip_size
ema_distance_entry = price_ema_distance >= ema_distance_threshold * 100 and close > ema_200 // Only enter when price above EMA
// RSI bounce conditions - back to original crossover logic
// Weekly RSI bounce: RSI was below 30 and now crosses above 30
rsi_weekly_prev = request.security(syminfo.tickerid, "1W", ta.rsi(close, rsi_length)[1])
weekly_bounce = rsi_weekly_prev < rsi_oversold and rsi_weekly > rsi_oversold
// Daily RSI bounce: RSI was below 30 and now crosses above 30
daily_bounce = rsi_daily[1] < rsi_oversold and rsi_daily > rsi_oversold
// Overbought conditions for exits - keep as crossovers for exits
daily_rsi_overbought = rsi_daily > rsi_overbought and rsi_daily[1] <= rsi_overbought
weekly_rsi_overbought = rsi_weekly > rsi_overbought and rsi_weekly_prev <= rsi_overbought
// EMA exit condition: EMA was above price but now below price
ema_above_price_prev = ema_200[1] > close[1]
ema_below_price_now = ema_200 < close
ema_exit_condition = ema_above_price_prev and ema_below_price_now
// EMA Distance exit condition - EMA crossover exit
// Price crosses below shorter period EMA (more responsive than 200 EMA)
price_above_ema_exit_prev = close[1] > ema_exit[1]
price_below_ema_exit_now = close < ema_exit
ema_crossover_exit = price_above_ema_exit_prev and price_below_ema_exit_now
// Optional volume confirmation
volume_confirmation = not enable_volume_confirmation or volume > ta.sma(volume, 20)
ema_distance_exit_condition = ema_crossover_exit and volume_confirmation
// Track positions separately with counters for multiple trades
var int weekly_trade_count = 0
var int daily_trade_count = 0
var int ema_distance_trade_count = 0
var float weekly_position_qty = 0.0
var float daily_position_qty = 0.0
var float ema_distance_position_qty = 0.0
// Entry conditions - allow multiple concurrent trades
weekly_entry = weekly_bounce
daily_entry = daily_bounce
// Strategy execution - ensure ALL signals result in trades
if weekly_entry
strategy.entry("Weekly_Long", strategy.long, qty=weekly_position_size, comment="Weekly RSI Bounce #" + str.tostring(weekly_trade_count + 1), alert_message="Weekly Entry")
weekly_trade_count := weekly_trade_count + 1
weekly_position_qty := weekly_position_qty + weekly_position_size
if daily_entry
strategy.entry("Daily_Long", strategy.long, qty=daily_position_size, comment="Daily RSI Bounce #" + str.tostring(daily_trade_count + 1), alert_message="Daily Entry")
daily_trade_count := daily_trade_count + 1
daily_position_qty := daily_position_qty + daily_position_size
if ema_distance_entry
strategy.entry("EMA_Distance_Long", strategy.long, qty=ema_distance_position_size, comment="EMA Distance Entry #" + str.tostring(ema_distance_trade_count + 1), alert_message="EMA Distance Entry")
ema_distance_trade_count := ema_distance_trade_count + 1
ema_distance_position_qty := ema_distance_position_qty + ema_distance_position_size
// Debug - show actual entry attempts
if weekly_entry
label.new(bar_index, high + (high - low) * 0.1, "WEEKLY ENTRY ATTEMPT",
color=color.green, textcolor=color.white, size=size.normal, style=label.style_label_down)
if daily_entry
label.new(bar_index, high + (high - low) * 0.15, "DAILY ENTRY ATTEMPT",
color=color.blue, textcolor=color.white, size=size.normal, style=label.style_label_down)
if ema_distance_entry
label.new(bar_index, high + (high - low) * 0.2, "EMA DISTANCE: " + str.tostring(price_ema_distance, "#.#") + " pips",
color=color.purple, textcolor=color.white, size=size.normal, style=label.style_label_down)
// Partial exit for weekly positions on daily RSI overbought
if daily_rsi_overbought and weekly_position_qty > 0
exit_qty = weekly_position_qty * (partial_exit_percent / 100)
strategy.close("Weekly_Long", qty=exit_qty, comment="Weekly Partial Exit Daily OB")
weekly_position_qty := math.max(0, weekly_position_qty - exit_qty)
// Partial exit for daily positions on daily RSI overbought
if daily_rsi_overbought and daily_position_qty > 0
exit_qty_daily = daily_position_qty * (partial_exit_percent / 100)
strategy.close("Daily_Long", qty=exit_qty_daily, comment="Daily Partial Exit OB")
daily_position_qty := math.max(0, daily_position_qty - exit_qty_daily)
// Complete exit for weekly positions on weekly RSI overbought
if weekly_rsi_overbought and weekly_position_qty > 0
strategy.close("Weekly_Long", comment="Complete Exit Weekly OB")
weekly_position_qty := 0.0
weekly_trade_count := 0
// Exit all positions when EMA crosses from above price to below price
if ema_exit_condition and strategy.position_size > 0
strategy.close_all("EMA Cross Exit")
weekly_position_qty := 0.0
daily_position_qty := 0.0
ema_distance_position_qty := 0.0
weekly_trade_count := 0
daily_trade_count := 0
ema_distance_trade_count := 0
// Exit EMA distance positions when price crosses below EMA (anti-crossover)
if ema_distance_exit_condition and ema_distance_position_qty > 0
strategy.close("EMA_Distance_Long", comment="EMA Distance Anti-Cross Exit")
ema_distance_position_qty := 0.0
ema_distance_trade_count := 0
// Plotting
plot(ema_200, "200 EMA", color=color.orange, linewidth=2)
plot(ema_exit, "EMA Exit", color=color.purple, linewidth=1, style=plot.style_line)
plot(rsi_daily, "Daily RSI", color=color.blue, display=display.data_window)
plot(rsi_weekly, "Weekly RSI", color=color.red, display=display.data_window)
// Plot RSI levels
hline(rsi_oversold, "Oversold Level", color=color.red, linestyle=hline.style_dashed)
hline(rsi_overbought, "Overbought Level", color=color.green, linestyle=hline.style_dashed)
// Background color for RSI conditions
bgcolor(weekly_bounce ? color.new(color.green, 90) : na, title="Weekly RSI Bounce")
bgcolor(daily_bounce ? color.new(color.blue, 90) : na, title="Daily RSI Bounce")
bgcolor(daily_rsi_overbought and (weekly_position_qty > 0 or daily_position_qty > 0) ? color.new(color.yellow, 90) : na, title="Daily RSI Overbought (Partial Exit)")
bgcolor(weekly_rsi_overbought and weekly_position_qty > 0 ? color.new(color.orange, 90) : na, title="Weekly RSI Overbought (Complete Exit)")
bgcolor(ema_exit_condition and strategy.position_size > 0 ? color.new(color.red, 90) : na, title="EMA Cross Exit")
bgcolor(ema_distance_exit_condition and ema_distance_position_qty > 0 ? color.new(color.maroon, 90) : na, title="EMA Distance Anti-Cross Exit")
bgcolor(ema_distance_entry ? color.new(color.purple, 90) : na, title="EMA Distance Entry")
// Plot entry and exit signals with enhanced debugging
plotshape(weekly_entry, "Weekly Entry", shape.triangleup, location.belowbar, color.green, size=size.normal)
plotshape(daily_entry, "Daily Entry", shape.triangleup, location.belowbar, color.blue, size=size.small)
plotshape(ema_distance_entry, "EMA Distance Entry", shape.triangleup, location.belowbar, color.purple, size=size.normal)
plotshape(daily_rsi_overbought and (weekly_position_qty > 0 or daily_position_qty > 0), "Partial Exit Both", shape.circle, location.abovebar, color.yellow, size=size.small)
plotshape(weekly_rsi_overbought and weekly_position_qty > 0, "Complete Exit Weekly OB", shape.triangledown, location.abovebar, color.orange, size=size.normal)
plotshape(ema_exit_condition and strategy.position_size > 0, "EMA Cross Exit", shape.triangledown, location.abovebar, color.red, size=size.large)
plotshape(ema_distance_exit_condition and ema_distance_position_qty > 0, "EMA Distance Anti-Cross Exit", shape.triangledown, location.abovebar, color.maroon, size=size.normal)
// Debug labels to show when conditions are met
if weekly_bounce
label.new(bar_index, low - (high - low) * 0.1, "W-RSI: " + str.tostring(rsi_weekly, "#.##"),
color=color.green, textcolor=color.white, size=size.small, style=label.style_label_up)
if daily_bounce
label.new(bar_index, low - (high - low) * 0.05, "D-RSI: " + str.tostring(rsi_daily, "#.##"),
color=color.blue, textcolor=color.white, size=size.small, style=label.style_label_up)
// Table to show current status
var table info_table = table.new(position.top_right, 2, 12, bgcolor=color.white, border_width=1)
if barstate.islast
table.cell(info_table, 0, 0, "Indicator", bgcolor=color.gray, text_color=color.white)
table.cell(info_table, 1, 0, "Value", bgcolor=color.gray, text_color=color.white)
table.cell(info_table, 0, 1, "Daily RSI", bgcolor=color.white)
table.cell(info_table, 1, 1, str.tostring(rsi_daily, "#.##"), bgcolor=color.white)
table.cell(info_table, 0, 2, "Weekly RSI", bgcolor=color.white)
table.cell(info_table, 1, 2, str.tostring(rsi_weekly, "#.##"), bgcolor=color.white)
table.cell(info_table, 0, 3, "200 EMA", bgcolor=color.white)
table.cell(info_table, 1, 3, str.tostring(ema_200, "#.##"), bgcolor=color.white)
table.cell(info_table, 0, 4, "EMA Distance", bgcolor=color.white)
table.cell(info_table, 1, 4, str.tostring(price_ema_distance, "#.#") + " pips", bgcolor=color.white)
table.cell(info_table, 0, 5, "EMA Exit Level", bgcolor=color.white)
table.cell(info_table, 1, 5, str.tostring(ema_exit, "#.##"), bgcolor=color.white)
table.cell(info_table, 0, 6, "Total Position", bgcolor=color.white)
table.cell(info_table, 1, 6, strategy.position_size > 0 ? "Long" : "None",
bgcolor=strategy.position_size > 0 ? color.green : color.white)
table.cell(info_table, 0, 7, "Total Size", bgcolor=color.white)
table.cell(info_table, 1, 7, str.tostring(strategy.position_size, "#.####"), bgcolor=color.white)
table.cell(info_table, 0, 8, "Weekly Qty", bgcolor=color.white)
table.cell(info_table, 1, 8, str.tostring(weekly_position_qty, "#.####"),
bgcolor=weekly_position_qty > 0 ? color.green : color.white)
table.cell(info_table, 0, 9, "Daily Qty", bgcolor=color.white)
table.cell(info_table, 1, 9, str.tostring(daily_position_qty, "#.####"),
bgcolor=daily_position_qty > 0 ? color.blue : color.white)
table.cell(info_table, 0, 10, "EMA Distance Qty", bgcolor=color.white)
table.cell(info_table, 1, 10, str.tostring(ema_distance_position_qty, "#.####"),
bgcolor=ema_distance_position_qty > 0 ? color.purple : color.white)
table.cell(info_table, 0, 11, "Trade Counts", bgcolor=color.white)
table.cell(info_table, 1, 11, "W:" + str.tostring(weekly_trade_count) + " D:" + str.tostring(daily_trade_count) + " E:" + str.tostring(ema_distance_trade_count), bgcolor=color.white)
@@ -0,0 +1,255 @@
//@version=6
strategy("SSE Index RSI Bounce Strategy - Enhanced", overlay=true, default_qty_type=strategy.percent_of_equity, initial_capital=10000, pyramiding=100, calc_on_every_tick=false, calc_on_order_fills=false)
// Input parameters
rsi_length = input.int(17, "RSI Length", minval=1)
rsi_oversold = input.int(27, "RSI Oversold Level", minval=1, maxval=50)
rsi_overbought = input.int(86, "RSI Overbought Level", minval=50, maxval=100)
ema_length = input.int(177, "EMA Length", minval=1)
weekly_position_size = input.float(14.0, "Weekly Signal Position Size (%)", minval=0.1, maxval=100)
daily_position_size = input.float(11.0, "Daily Signal Position Size (%)", minval=0.1, maxval=100)
partial_exit_percent = input.float(41.0, "Partial Exit Percentage on Daily RSI Overbought (%)", minval=10.0, maxval=50.0)
// Enhanced EMA Distance Trading Parameters
ema_distance_threshold = input.float(16.0, "EMA Distance Threshold (Pips)", minval=1.0, maxval=1000.0)
ema_distance_position_size = input.float(53, "EMA Distance Position Size (%)", minval=0.1, maxval=100)
// New EMA Alignment Filter Parameters
fast_ema_length = input.int(21, "Fast EMA Length", minval=5, maxval=50)
slow_ema_length = input.int(55, "Slow EMA Length", minval=20, maxval=200)
ema_alignment_threshold = input.float(15000.0, "EMA Alignment Threshold (Pips)", minval=0.5, maxval=500000.0, tooltip="Minimum distance required between fast and slow EMAs")
ema_alignment_direction = input.string("both", "EMA Alignment Direction", options=["both", "above", "below"], tooltip="Direction for EMA alignment check")
// Price Proximity Filter Parameters
price_proximity_threshold = input.float(535.0, "Price Proximity Threshold (Pips)", minval=1.0, maxval=100000.0, tooltip="Minimum distance required between price and 200 EMA to allow trades")
// EMA Distance Exit Parameters
ema_exit_period = input.int(34, "EMA Exit Period", minval=10, maxval=200)
enable_volume_confirmation = input.bool(true, "Require Volume Confirmation for EMA Exit")
// Calculate indicators
rsi_daily = ta.rsi(close, rsi_length)
rsi_weekly = request.security(syminfo.tickerid, "1W", ta.rsi(close, rsi_length))
ema_200 = ta.ema(close, ema_length)
ema_exit = ta.ema(close, ema_exit_period)
// Enhanced EMA Distance Trading Logic with Alignment Filter
pip_size = syminfo.mintick * 10 // Adjust pip size based on instrument
price_ema_distance = math.abs(close - ema_200) / pip_size
// Calculate fast and slow EMAs for alignment check
fast_ema = ta.ema(close, fast_ema_length)
slow_ema = ta.ema(close, slow_ema_length)
ema_alignment_distance = math.abs(fast_ema - slow_ema) / pip_size
// EMA Alignment Filter Logic
ema_alignment_ok = false
if ema_alignment_direction == "both"
ema_alignment_ok := ema_alignment_distance >= ema_alignment_threshold
else if ema_alignment_direction == "above"
ema_alignment_ok := fast_ema > slow_ema and ema_alignment_distance >= ema_alignment_threshold
else if ema_alignment_direction == "below"
ema_alignment_ok := fast_ema < slow_ema and ema_alignment_distance >= ema_alignment_threshold
// Price Proximity Filter - prevent trades when price is too close to 200 EMA
price_proximity_ok = price_ema_distance >= price_proximity_threshold * 100
// Enhanced EMA Distance Entry with Alignment Filter and Price Proximity
ema_distance_entry = price_ema_distance >= ema_distance_threshold * 100 and close > ema_200 and ema_alignment_ok and price_proximity_ok
// RSI bounce conditions - back to original crossover logic
// Weekly RSI bounce: RSI was below 30 and now crosses above 30
rsi_weekly_prev = request.security(syminfo.tickerid, "1W", ta.rsi(close, rsi_length)[1])
weekly_bounce = rsi_weekly_prev < rsi_oversold and rsi_weekly > rsi_oversold
// Daily RSI bounce: RSI was below 30 and now crosses above 30
daily_bounce = rsi_daily[1] < rsi_oversold and rsi_daily > rsi_oversold
// Apply price proximity filter to RSI signals as well
weekly_entry = weekly_bounce and price_proximity_ok
daily_entry = daily_bounce and price_proximity_ok
// Overbought conditions for exits - keep as crossovers for exits
daily_rsi_overbought = rsi_daily > rsi_overbought and rsi_daily[1] <= rsi_overbought
weekly_rsi_overbought = rsi_weekly > rsi_overbought and rsi_weekly_prev <= rsi_overbought
// EMA exit condition: EMA was above price but now below price
ema_above_price_prev = ema_200[1] > close[1]
ema_below_price_now = ema_200 < close
ema_exit_condition = ema_above_price_prev and ema_below_price_now
// EMA Distance exit condition - EMA crossover exit
// Price crosses below shorter period EMA (more responsive than 200 EMA)
price_above_ema_exit_prev = close[1] > ema_exit[1]
price_below_ema_exit_now = close < ema_exit
ema_crossover_exit = price_above_ema_exit_prev and price_below_ema_exit_now
// Optional volume confirmation
volume_confirmation = not enable_volume_confirmation or volume > ta.sma(volume, 20)
ema_distance_exit_condition = ema_crossover_exit and volume_confirmation
// Track positions separately with counters for multiple trades
var int weekly_trade_count = 0
var int daily_trade_count = 0
var int ema_distance_trade_count = 0
var float weekly_position_qty = 0.0
var float daily_position_qty = 0.0
var float ema_distance_position_qty = 0.0
// Strategy execution - ensure ALL signals result in trades
if weekly_entry
strategy.entry("Weekly_Long", strategy.long, qty=weekly_position_size, comment="Weekly RSI Bounce #" + str.tostring(weekly_trade_count + 1), alert_message="Weekly Entry")
weekly_trade_count := weekly_trade_count + 1
weekly_position_qty := weekly_position_qty + weekly_position_size
if daily_entry
strategy.entry("Daily_Long", strategy.long, qty=daily_position_size, comment="Daily RSI Bounce #" + str.tostring(daily_trade_count + 1), alert_message="Daily Entry")
daily_trade_count := daily_trade_count + 1
daily_position_qty := daily_position_qty + daily_position_size
if ema_distance_entry
strategy.entry("EMA_Distance_Long", strategy.long, qty=ema_distance_position_size, comment="EMA Distance Entry #" + str.tostring(ema_distance_trade_count + 1), alert_message="EMA Distance Entry")
ema_distance_trade_count := ema_distance_trade_count + 1
ema_distance_position_qty := ema_distance_position_qty + ema_distance_position_size
// Debug - show actual entry attempts
if weekly_entry
label.new(bar_index, high + (high - low) * 0.1, "WEEKLY ENTRY ATTEMPT",
color=color.green, textcolor=color.white, size=size.normal, style=label.style_label_down)
if daily_entry
label.new(bar_index, high + (high - low) * 0.15, "DAILY ENTRY ATTEMPT",
color=color.blue, textcolor=color.white, size=size.normal, style=label.style_label_down)
if ema_distance_entry
label.new(bar_index, high + (high - low) * 0.2, "EMA DISTANCE: " + str.tostring(price_ema_distance, "#.#") + " pips\nALIGNMENT: " + str.tostring(ema_alignment_distance, "#.#") + " pips",
color=color.purple, textcolor=color.white, size=size.normal, style=label.style_label_down)
// Show alignment filter status
if not ema_alignment_ok and price_ema_distance >= ema_distance_threshold * 100 and close > ema_200 and price_proximity_ok
label.new(bar_index, high + (high - low) * 0.25, "ALIGNMENT BLOCKED\nFast-Slow: " + str.tostring(ema_alignment_distance, "#.#") + " pips\nRequired: " + str.tostring(ema_alignment_threshold) + " pips",
color=color.red, textcolor=color.white, size=size.small, style=label.style_label_down)
// Show price proximity filter status
if not price_proximity_ok and (weekly_bounce or daily_bounce or (price_ema_distance >= ema_distance_threshold * 100 and close > ema_200 and ema_alignment_ok))
label.new(bar_index, high + (high - low) * 0.3, "PROXIMITY BLOCKED\nPrice-EMA: " + str.tostring(price_ema_distance, "#.#") + " pips\nRequired: " + str.tostring(price_proximity_threshold) + " pips",
color=color.orange, textcolor=color.white, size=size.small, style=label.style_label_down)
// Partial exit for weekly positions on daily RSI overbought
if daily_rsi_overbought and weekly_position_qty > 0
exit_qty = weekly_position_qty * (partial_exit_percent / 100)
strategy.close("Weekly_Long", qty=exit_qty, comment="Weekly Partial Exit Daily OB")
weekly_position_qty := math.max(0, weekly_position_qty - exit_qty)
// Partial exit for daily positions on daily RSI overbought
if daily_rsi_overbought and daily_position_qty > 0
exit_qty_daily = daily_position_qty * (partial_exit_percent / 100)
strategy.close("Daily_Long", qty=exit_qty_daily, comment="Daily Partial Exit OB")
daily_position_qty := math.max(0, daily_position_qty - exit_qty_daily)
// Complete exit for weekly positions on weekly RSI overbought
if weekly_rsi_overbought and weekly_position_qty > 0
strategy.close("Weekly_Long", comment="Complete Exit Weekly OB")
weekly_position_qty := 0.0
weekly_trade_count := 0
// Exit all positions when EMA crosses from above price to below price
if ema_exit_condition and strategy.position_size > 0
strategy.close_all("EMA Cross Exit")
weekly_position_qty := 0.0
daily_position_qty := 0.0
ema_distance_position_qty := 0.0
weekly_trade_count := 0
daily_trade_count := 0
ema_distance_trade_count := 0
// Exit EMA distance positions when price crosses below EMA (anti-crossover)
if ema_distance_exit_condition and ema_distance_position_qty > 0
strategy.close("EMA_Distance_Long", comment="EMA Distance Anti-Cross Exit")
ema_distance_position_qty := 0.0
ema_distance_trade_count := 0
// Plotting
plot(ema_200, "200 EMA", color=color.orange, linewidth=2)
plot(ema_exit, "EMA Exit", color=color.purple, linewidth=1, style=plot.style_line)
plot(fast_ema, "Fast EMA", color=color.lime, linewidth=1, style=plot.style_line)
plot(slow_ema, "Slow EMA", color=color.navy, linewidth=1, style=plot.style_line)
plot(rsi_daily, "Daily RSI", color=color.blue, display=display.data_window)
plot(rsi_weekly, "Weekly RSI", color=color.red, display=display.data_window)
// Plot RSI levels
hline(rsi_oversold, "Oversold Level", color=color.red, linestyle=hline.style_dashed)
hline(rsi_overbought, "Overbought Level", color=color.green, linestyle=hline.style_dashed)
// Background color for RSI conditions
bgcolor(weekly_bounce ? color.new(color.green, 90) : na, title="Weekly RSI Bounce")
bgcolor(daily_bounce ? color.new(color.blue, 90) : na, title="Daily RSI Bounce")
bgcolor(daily_rsi_overbought and (weekly_position_qty > 0 or daily_position_qty > 0) ? color.new(color.yellow, 90) : na, title="Daily RSI Overbought (Partial Exit)")
bgcolor(weekly_rsi_overbought and weekly_position_qty > 0 ? color.new(color.orange, 90) : na, title="Weekly RSI Overbought (Complete Exit)")
bgcolor(ema_exit_condition and strategy.position_size > 0 ? color.new(color.red, 90) : na, title="EMA Cross Exit")
bgcolor(ema_distance_exit_condition and ema_distance_position_qty > 0 ? color.new(color.maroon, 90) : na, title="EMA Distance Anti-Cross Exit")
bgcolor(ema_distance_entry ? color.new(color.purple, 90) : na, title="EMA Distance Entry")
bgcolor(not ema_alignment_ok and price_ema_distance >= ema_distance_threshold * 100 and close > ema_200 and price_proximity_ok ? color.new(color.red, 95) : na, title="EMA Alignment Blocked")
bgcolor(not price_proximity_ok and (weekly_bounce or daily_bounce or (price_ema_distance >= ema_distance_threshold * 100 and close > ema_200 and ema_alignment_ok)) ? color.new(color.orange, 95) : na, title="Price Proximity Blocked")
// Plot entry and exit signals with enhanced debugging
plotshape(weekly_entry, "Weekly Entry", shape.triangleup, location.belowbar, color.green, size=size.normal)
plotshape(daily_entry, "Daily Entry", shape.triangleup, location.belowbar, color.blue, size=size.small)
plotshape(ema_distance_entry, "EMA Distance Entry", shape.triangleup, location.belowbar, color.purple, size=size.normal)
plotshape(daily_rsi_overbought and (weekly_position_qty > 0 or daily_position_qty > 0), "Partial Exit Both", shape.circle, location.abovebar, color.yellow, size=size.small)
plotshape(weekly_rsi_overbought and weekly_position_qty > 0, "Complete Exit Weekly OB", shape.triangledown, location.abovebar, color.orange, size=size.normal)
plotshape(ema_exit_condition and strategy.position_size > 0, "EMA Cross Exit", shape.triangledown, location.abovebar, color.red, size=size.large)
plotshape(ema_distance_exit_condition and ema_distance_position_qty > 0, "EMA Distance Anti-Cross Exit", shape.triangledown, location.abovebar, color.maroon, size=size.normal)
// Debug labels to show when conditions are met
if weekly_bounce
label.new(bar_index, low - (high - low) * 0.1, "W-RSI: " + str.tostring(rsi_weekly, "#.##"),
color=color.green, textcolor=color.white, size=size.small, style=label.style_label_up)
if daily_bounce
label.new(bar_index, low - (high - low) * 0.05, "D-RSI: " + str.tostring(rsi_daily, "#.##"),
color=color.blue, textcolor=color.white, size=size.small, style=label.style_label_up)
// Enhanced Table to show current status with alignment info
var table info_table = table.new(position.top_right, 2, 16, bgcolor=color.white, border_width=1)
if barstate.islast
table.cell(info_table, 0, 0, "Indicator", bgcolor=color.gray, text_color=color.white)
table.cell(info_table, 1, 0, "Value", bgcolor=color.gray, text_color=color.white)
table.cell(info_table, 0, 1, "Daily RSI", bgcolor=color.white)
table.cell(info_table, 1, 1, str.tostring(rsi_daily, "#.##"), bgcolor=color.white)
table.cell(info_table, 0, 2, "Weekly RSI", bgcolor=color.white)
table.cell(info_table, 1, 2, str.tostring(rsi_weekly, "#.##"), bgcolor=color.white)
table.cell(info_table, 0, 3, "200 EMA", bgcolor=color.white)
table.cell(info_table, 1, 3, str.tostring(ema_200, "#.##"), bgcolor=color.white)
table.cell(info_table, 0, 4, "Fast EMA", bgcolor=color.white)
table.cell(info_table, 1, 4, str.tostring(fast_ema, "#.##"), bgcolor=color.white)
table.cell(info_table, 0, 5, "Slow EMA", bgcolor=color.white)
table.cell(info_table, 1, 5, str.tostring(slow_ema, "#.##"), bgcolor=color.white)
table.cell(info_table, 0, 6, "EMA Alignment", bgcolor=color.white)
table.cell(info_table, 1, 6, str.tostring(ema_alignment_distance, "#.#") + " pips",
bgcolor=ema_alignment_ok ? color.green : color.red)
table.cell(info_table, 0, 7, "Price Proximity", bgcolor=color.white)
table.cell(info_table, 1, 7, str.tostring(price_ema_distance, "#.#") + " pips",
bgcolor=price_proximity_ok ? color.green : color.orange)
table.cell(info_table, 0, 8, "EMA Exit Level", bgcolor=color.white)
table.cell(info_table, 1, 8, str.tostring(ema_exit, "#.##"), bgcolor=color.white)
table.cell(info_table, 0, 9, "Total Position", bgcolor=color.white)
table.cell(info_table, 1, 9, strategy.position_size > 0 ? "Long" : "None",
bgcolor=strategy.position_size > 0 ? color.green : color.white)
table.cell(info_table, 0, 10, "Total Size", bgcolor=color.white)
table.cell(info_table, 1, 10, str.tostring(strategy.position_size, "#.####"), bgcolor=color.white)
table.cell(info_table, 0, 11, "Weekly Qty", bgcolor=color.white)
table.cell(info_table, 1, 11, str.tostring(weekly_position_qty, "#.####"),
bgcolor=weekly_position_qty > 0 ? color.green : color.white)
table.cell(info_table, 0, 12, "Daily Qty", bgcolor=color.white)
table.cell(info_table, 1, 12, str.tostring(daily_position_qty, "#.####"),
bgcolor=daily_position_qty > 0 ? color.blue : color.white)
table.cell(info_table, 0, 13, "EMA Distance Qty", bgcolor=color.white)
table.cell(info_table, 1, 13, str.tostring(ema_distance_position_qty, "#.####"),
bgcolor=ema_distance_position_qty > 0 ? color.purple : color.white)
table.cell(info_table, 0, 14, "Trade Counts", bgcolor=color.white)
table.cell(info_table, 1, 14, "W:" + str.tostring(weekly_trade_count) + " D:" + str.tostring(daily_trade_count) + " E:" + str.tostring(ema_distance_trade_count), bgcolor=color.white)
table.cell(info_table, 0, 15, "Trade Status", bgcolor=color.white)
table.cell(info_table, 1, 15, price_proximity_ok ? "Allowed" : "Blocked",
bgcolor=price_proximity_ok ? color.green : color.orange)