New free code from MQL5: indicators, EAs, and scripts for traders.
#property copyright "Samson Mwita 2025" #property link "Samson Mwita 2025" #property version "1.00" #property description "Advanced price action-based dynamic exit strategy" #property description "Monitors Fibonacci, market structure, candlestick patterns" #property description "and behavioral patterns for optimal exit timing" //--- Input Parameters input double ProfitActivationPercent = 70.0; // Start monitoring when trade is X% to TP input bool UseRSIReversal = true; // Use RSI for reversal detection input int RSIPeriod = 14; // RSI Period input double RSIOverbought = 70.0; // RSI Overbought level input double RSI_Oversold = 30.0; // RSI Oversold level input bool UseCandlestickPatterns = true; // Use candlestick patterns input bool UseMovingAverageCross = false; // Use MA cross for confirmation input int FastMA_Period = 5; // Fast MA Period input int SlowMA_Period = 10; // Slow MA Period input int CheckEveryXSeconds = 10; // How often to check (seconds) //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { //--- Display script started message Print("Dynamic Exit Protector Started - Monitoring Trades..."); //--- Create a timer for continuous monitoring EventSetTimer(CheckEveryXSeconds); } //+------------------------------------------------------------------+ //| Timer function - runs every X seconds | //+------------------------------------------------------------------+ void OnTimer() { CheckAndProtectTrades(); } //+------------------------------------------------------------------+ //| Main function to check and protect trades | //+------------------------------------------------------------------+ void CheckAndProtectTrades() { int total = PositionsTotal(); for(int i = total-1; i >= 0; i--) { ulong ticket = PositionGetTicket(i); if(ticket > 0) { string symbol = PositionGetString(POSITION_SYMBOL); double volume = PositionGetDouble(POSITION_VOLUME); double openPrice = PositionGetDouble(POSITION_PRICE_OPEN); double currentProfit = PositionGetDouble(POSITION_PROFIT); ulong type = PositionGetInteger(POSITION_TYPE); double sl = PositionGetDouble(POSITION_SL); double tp = PositionGetDouble(POSITION_TP); //--- Skip if no Take Profit is set if(tp == 0) continue; double currentPrice = (type == POSITION_TYPE_BUY) ? SymbolInfoDouble(symbol, SYMBOL_BID) : SymbolInfoDouble(symbol, SYMBOL_ASK); //--- Calculate how close we are to TP (in percentage) double distanceToTP = 0; double progressToTP = 0; if(type == POSITION_TYPE_BUY) { distanceToTP = tp - openPrice; progressToTP = (currentPrice - openPrice) / distanceToTP * 100; } else // SELL position { distanceToTP = openPrice - tp; progressToTP = (openPrice - currentPrice) / distanceToTP * 100; } //--- If we're close enough to TP, check for reversals if(progressToTP >= ProfitActivationPercent) { bool shouldClose = false; string reason = ""; //--- Check RSI Reversal (if enabled) if(UseRSIReversal && CheckRSI_Reversal(symbol, type)) { shouldClose = true; reason = "RSI Reversal Signal"; } //--- Check Candlestick Patterns (if enabled) if(UseCandlestickPatterns && CheckCandlestickReversal(symbol, type)) { shouldClose = true; reason = "Candlestick Reversal Pattern"; } //--- Check MA Cross (if enabled) if(UseMovingAverageCross && CheckMA_Cross(symbol)) { shouldClose = true; reason = "Moving Average Cross"; } //--- Additional safety: If profit starts decreasing significantly if(IsProfitDecreasing(symbol, ticket, currentProfit)) { shouldClose = true; reason = "Profit Retracement Detected"; } //--- Close the trade if any reversal condition is met if(shouldClose) { if(ClosePosition(ticket, symbol, volume, type)) { Print("Position #", ticket, " closed. Reason: ", reason, " | Progress to TP: ", DoubleToString(progressToTP, 1), "%", " | Final Profit: ", DoubleToString(currentProfit, 2)); } } } } } } //+------------------------------------------------------------------+ //| Check RSI for reversal signals | //+------------------------------------------------------------------+ bool CheckRSI_Reversal(string symbol, ulong positionType) { double rsi[]; ArraySetAsSeries(rsi, true); int handle = iRSI(symbol, PERIOD_CURRENT, RSIPeriod, PRICE_CLOSE); if(CopyBuffer(handle, 0, 0, 3, rsi) > 0) { // For BUY positions: Watch for RSI going into overbought and turning down if(positionType == POSITION_TYPE_BUY) { if(rsi[0] < rsi[1] && rsi[1] > RSIOverbought) return true; } // For SELL positions: Watch for RSI going into oversold and turning up else { if(rsi[0] > rsi[1] && rsi[1] < RSI_Oversold) return true; } } return false; } //+------------------------------------------------------------------+ //| Check for candlestick reversal patterns | //+------------------------------------------------------------------+ bool CheckCandlestickReversal(string symbol, ulong positionType) { MqlRates rates[]; ArraySetAsSeries(rates, true); if(CopyRates(symbol, PERIOD_CURRENT, 0, 3, rates) > 0) { // Simple bearish reversal pattern for BUY positions if(positionType == POSITION_TYPE_BUY) { // Check for bearish engulfing or shooting star if((rates[1].close > rates[1].open && rates[0].close < rates[0].open && rates[0].close < rates[1].open) || // Bearish engulfing (rates[0].high - MathMax(rates[0].open, rates[0].close) > MathAbs(rates[0].close - rates[0].open) * 2)) // Shooting star return true; } // Simple bullish reversal pattern for SELL positions else { // Check for bullish engulfing or hammer if((rates[1].close < rates[1].open && rates[0].close > rates[0].open && rates[0].close > rates[1].open) || // Bullish engulfing (MathMin(rates[0].open, rates[0].close) - rates[0].low > MathAbs(rates[0].close - rates[0].open) * 2)) // Hammer return true; } } return false; } //+------------------------------------------------------------------+ //| Check for Moving Average cross | //+------------------------------------------------------------------+ bool CheckMA_Cross(string symbol) { double fastMA[], slowMA[]; ArraySetAsSeries(fastMA, true); ArraySetAsSeries(slowMA, true); int fast_handle = iMA(symbol, PERIOD_CURRENT, FastMA_Period, 0, MODE_SMA, PRICE_CLOSE); int slow_handle = iMA(symbol, PERIOD_CURRENT, SlowMA_Period, 0, MODE_SMA, PRICE_CLOSE); if(CopyBuffer(fast_handle, 0, 0, 2, fastMA) > 0 && CopyBuffer(slow_handle, 0, 0, 2, slowMA) > 0) { // Check for bearish cross (fast MA crosses below slow MA) if(fastMA[1] > slowMA[1] && fastMA[0] < slowMA[0]) return true; } return false; } //+------------------------------------------------------------------+ //| Check if profit is significantly decreasing | //+------------------------------------------------------------------+ bool IsProfitDecreasing(string symbol, ulong ticket, double currentProfit) { // In a real implementation, you might want to track profit history // This is a simplified version - you could store previous profit values // and compare if profit has decreased by a certain percentage // For now, we'll use a simple approach based on price movement static double lastProfit = 0; static ulong lastTicket = 0; if(lastTicket != ticket) { lastProfit = currentProfit; lastTicket = ticket; return false; } // If profit decreases by more than 20% from its peak if(currentProfit < lastProfit * 0.8 && currentProfit > 0) { return true; } // Update the last profit if current is higher if(currentProfit > lastProfit) { lastProfit = currentProfit; } return false; } //+------------------------------------------------------------------+ //| Close position function | //+------------------------------------------------------------------+ bool ClosePosition(ulong ticket, string symbol, double volume, ulong type) { MqlTradeRequest request = {1}; MqlTradeResult result = {0}; request.action = TRADE_ACTION_DEAL; request.position = ticket; request.symbol = symbol; request.volume = volume; request.deviation = 10; request.comment = "Dynamic Exit"; if(type == POSITION_TYPE_BUY) { request.type = ORDER_TYPE_SELL; request.price = SymbolInfoDouble(symbol, SYMBOL_BID); } else { request.type = ORDER_TYPE_BUY; request.price = SymbolInfoDouble(symbol, SYMBOL_ASK); } return OrderSend(request, result); } //+------------------------------------------------------------------+ //| Deinitialization function | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+
Unique stair-step trend trading with the Stairsteps Expert Advisor. Innovative approach for consistent results. Learn more.
Thanks for reading. Discover premium MetaTrader solutions at RobotFX.
66130