//+------------------------------------------------------------------+ //| LiquiditySweep_MSS_FVG_EA.mq5 | //| Flowchart-driven MQL5 EA | //+------------------------------------------------------------------+ #property copyright "Flowchart EA" #property version "1.00" #property strict #include //--- Input Parameters input group "=== General & Scanning ===" input string InpSymbols = ""; // Symbols (comma-separated, empty = current chart) input ulong InpMagicNumber = 20261123; // Magic Number input int InpMaxSpreadPoints = 30; // Max allowed spread in points input bool InpOneTradePerSym = true; // Allow only 1 open position per symbol input group "=== Trading Session (Server Time) ===" input bool InpUseSessionFilter = true; // Enable trading session filter input int InpSessionStartHour = 8; // Session start hour (0-23) input int InpSessionEndHour = 20; // Session end hour (0-23) input group "=== HTF Bias & Structure ===" input ENUM_TIMEFRAMES InpHTF_Primary = PERIOD_H4; // Primary HTF for direction input ENUM_TIMEFRAMES InpHTF_Secondary = PERIOD_H1; // Secondary HTF confirmation input int InpSwingLookback = 5; // Fractal/swing left & right bars input int InpSearchBars = 80; // Bars to search for liquidity & MSS input group "=== Sweep, Displacement & PD Array ===" input ENUM_TIMEFRAMES InpSetupTF = PERIOD_M15; // Setup timeframe (sweep, MSS, FVG) input ENUM_TIMEFRAMES InpEntryTF = PERIOD_M5; // Lower TF for entry confirmation input int InpAtrPeriod = 14; // ATR period for displacement & PD quality input double InpDispBodyAtrMult = 1.3; // Min impulse candle body (x ATR) input double InpMinFvgAtrMult = 0.3; // Min FVG gap size (x ATR) input double InpSweepBufferPts = 5.0; // Extra buffer beyond liquidity level (points) input group "=== Risk & Trade Management ===" input double InpRiskPercent = 1.0; // Risk per trade (% of balance) input double InpSlBufferPoints = 15.0; // Stop-loss buffer beyond invalidation (points) input double InpRiskReward = 2.0; // Take-profit Risk:Reward ratio input bool InpUseBreakEven = true; // Move SL to breakeven at 1R input bool InpUseTrailingStop = false; // Enable trailing stop input double InpTrailStartR = 1.5; // Start trailing at this R multiple input double InpTrailStepPts = 100.0; // Trailing step in points //--- Symbol State Structure struct SymbolState { string symbol; int atrHandleSetup; int atrHandleEntry; int direction; // 1 = Bullish, -1 = Bearish, 0 = None bool swept; double sweepExtreme; bool mssConfirmed; double fvgHigh; double fvgLow; bool fvgValid; datetime lastBarTime; }; CTrade trade; SymbolState states[]; string activeSymbols[]; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { trade.SetExpertMagicNumber(InpMagicNumber); ParseSymbols(); int count = ArraySize(activeSymbols); if(count <= 0) { Print("No valid symbols configured."); return(INIT_FAILED); } ArrayResize(states, count); for(int i = 0; i < count; i++) { ResetSymbolState(states[i], activeSymbols[i]); states[i].atrHandleSetup = iATR(states[i].symbol, InpSetupTF, InpAtrPeriod); states[i].atrHandleEntry = iATR(states[i].symbol, InpEntryTF, InpAtrPeriod); if(states[i].atrHandleSetup == INVALID_HANDLE || states[i].atrHandleEntry == INVALID_HANDLE) { Print("Failed to create ATR handles for ", states[i].symbol); return(INIT_FAILED); } if(!SymbolSelect(states[i].symbol, true)) { Print("Failed to select symbol ", states[i].symbol); return(INIT_FAILED); } } return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { for(int i = 0; i < ArraySize(states); i++) { if(states[i].atrHandleSetup != INVALID_HANDLE) IndicatorRelease(states[i].atrHandleSetup); if(states[i].atrHandleEntry != INVALID_HANDLE) IndicatorRelease(states[i].atrHandleEntry); } } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // Manage open positions first ManageOpenPositions(); // Check trading session if(InpUseSessionFilter && !IsWithinSession()) return; // Scan configured Forex pairs for(int i = 0; i < ArraySize(states); i++) { ProcessSymbol(states[i]); } } //+------------------------------------------------------------------+ //| Parse comma-separated symbols or use current chart symbol | //+------------------------------------------------------------------+ void ParseSymbols() { string trimmed = InpSymbols; StringTrimLeft(trimmed); StringTrimRight(trimmed); if(trimmed == "") { ArrayResize(activeSymbols, 1); activeSymbols[0] = _Symbol; return; } string parts[]; int n = StringSplit(trimmed, ',', parts); ArrayResize(activeSymbols, 0); for(int i = 0; i < n; i++) { string s = parts[i]; StringTrimLeft(s); StringTrimRight(s); if(s != "") { int idx = ArraySize(activeSymbols); ArrayResize(activeSymbols, idx + 1); activeSymbols[idx] = s; } } } //+------------------------------------------------------------------+ //| Reset setup state for a symbol | //+------------------------------------------------------------------+ void ResetSymbolState(SymbolState &st, const string sym) { st.symbol = sym; st.direction = 0; st.swept = false; st.sweepExtreme = 0.0; st.mssConfirmed = false; st.fvgHigh = 0.0; st.fvgLow = 0.0; st.fvgValid = false; st.lastBarTime = 0; } //+------------------------------------------------------------------+ //| Check if current server time is within trading session | //+------------------------------------------------------------------+ bool IsWithinSession() { MqlDateTime dt; TimeToStruct(TimeCurrent(), dt); int h = dt.hour; if(InpSessionStartHour <= InpSessionEndHour) return (h >= InpSessionStartHour && h < InpSessionEndHour); else return (h >= InpSessionStartHour || h < InpSessionEndHour); // Overnight wrap } //+------------------------------------------------------------------+ //| Check if EA already has an open position on symbol | //+------------------------------------------------------------------+ bool HasOpenPosition(const string sym) { for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong ticket = PositionGetTicket(i); if(ticket == 0) continue; if(PositionGetString(POSITION_SYMBOL) == sym && PositionGetInteger(POSITION_MAGIC) == (long)InpMagicNumber) { return true; } } return false; } //+------------------------------------------------------------------+ //| Identify HTF direction (1 = Bullish, -1 = Bearish, 0 = Neutral) | //+------------------------------------------------------------------+ int GetHTFDirection(const string sym) { MqlRates htf1[], htf2[]; ArraySetAsSeries(htf1, true); ArraySetAsSeries(htf2, true); if(CopyRates(sym, InpHTF_Primary, 1, 20, htf1) < 10) return 0; if(CopyRates(sym, InpHTF_Secondary, 1, 20, htf2) < 10) return 0; // Simple structure bias: compare recent swing/close momentum over last 10 bars double high1 = htf1[1].high, low1 = htf1[1].low; double high2 = htf1[1].high, low2 = htf1[1].low; for(int k = 1; k <= 10; k++) { if(htf1[k].high > high1) high1 = htf1[k].high; if(htf1[k].low < low1) low1 = htf1[k].low; } double mid1 = 0.5 * (high1 + low1); int bias1 = (htf1[1].close > mid1) ? 1 : ((htf1[1].close < mid1) ? -1 : 0); for(int k = 1; k <= 10; k++) { if(htf2[k].high > high2) high2 = htf2[k].high; if(htf2[k].low < low2) low2 = htf2[k].low; } double mid2 = 0.5 * (high2 + low2); int bias2 = (htf2[1].close > mid2) ? 1 : ((htf2[1].close < mid2) ? -1 : 0); if(bias1 == 1 && bias2 == 1) return 1; if(bias1 == -1 && bias2 == -1) return -1; return 0; } //+------------------------------------------------------------------+ //| Find recent swing high or swing low on SetupTF | //+------------------------------------------------------------------+ bool FindRecentSwing(const MqlRates &rates[], int total, bool findHigh, int startIdx, int endIdx, double &priceOut, int &barIdxOut) { for(int i = startIdx; i <= endIdx; i++) { if(i - InpSwingLookback < 0 || i + InpSwingLookback >= total) continue; bool isExtreme = true; for(int j = 1; j <= InpSwingLookback; j++) { if(findHigh) { if(rates[i].high <= rates[i - j].high || rates[i].high < rates[i + j].high) { isExtreme = false; break; } } else { if(rates[i].low >= rates[i - j].low || rates[i].low > rates[i + j].low) { isExtreme = false; break; } } } if(isExtreme) { priceOut = findHigh ? rates[i].high : rates[i].low; barIdxOut = i; return true; } } return false; } //+------------------------------------------------------------------+ //| Detect Fair Value Gap (FVG) with displacement & quality check | //+------------------------------------------------------------------+ bool DetectFVGWithDisplacement(const MqlRates &rates[], int total, int dir, double atr, double &fvgLowOut, double &fvgHighOut) { double point = SymbolInfoDouble(rates[0].symbol, SYMBOL_POINT); // note: MqlRates lacks symbol, pass separately return false; } bool DetectFVG(const string sym, const MqlRates &rates[], int total, int dir, double atr, double &fvgLowOut, double &fvgHighOut) { if(atr <= 0.0 || total < 6) return false; double point = SymbolInfoDouble(sym, SYMBOL_POINT); double minGap = MathMax(InpMinFvgAtrMult * atr, 5.0 * point); // Look at 3-candle patterns [i+2, i+1, i] in series order (1 = most recently closed bar) for(int i = 1; i <= MathMin(15, total - 3); i++) { double body1 = MathAbs(rates[i].close - rates[i].open); if(body1 < InpDispBodyAtrMult * atr) continue; if(dir == 1) // Bullish FVG: candle[i+2].high < candle[i].low and candle[i] is bullish { if(rates[i].close > rates[i].open && rates[i].low > rates[i + 2].high) { double low = rates[i + 2].high; double high = rates[i].low; if((high - low) >= minGap) { fvgLowOut = low; fvgHighOut = high; return true; } } } else if(dir == -1) // Bearish FVG: candle[i+2].low > candle[i].high and candle[i] is bearish { if(rates[i].close < rates[i].open && rates[i].high < rates[i + 2].low) { double low = rates[i].high; double high = rates[i + 2].low; if((high - low) >= minGap) { fvgLowOut = low; fvgHighOut = high; return true; } } } } return false; } //+------------------------------------------------------------------+ //| Lower TF entry confirmation (engulfing / strong rejection) | //+------------------------------------------------------------------+ bool HasLowerTFConfirmation(const string sym, int dir) { MqlRates m[]; ArraySetAsSeries(m, true); if(CopyRates(sym, InpEntryTF, 1, 3, m) < 3) return false; double prevBody = MathAbs(m[2].close - m[2].open); double currBody = MathAbs(m[1].close - m[1].open); if(dir == 1) { // Bullish engulfing on closed candle m[1] if(m[2].close < m[2].open && m[1].close > m[1].open && m[1].close >= m[2].open && m[1].open <= m[2].close && currBody > prevBody) return true; } else if(dir == -1) { // Bearish engulfing on closed candle m[1] if(m[2].close > m[2].open && m[1].close < m[1].open && m[1].close <= m[2].open && m[1].open >= m[2].close && currBody > prevBody) return true; } return false; } //+------------------------------------------------------------------+ //| Calculate risk-adjusted lot size | //+------------------------------------------------------------------+ double CalculateLotSize(const string sym, double entryPrice, double stopLossPrice) { double dist = MathAbs(entryPrice - stopLossPrice); double point = SymbolInfoDouble(sym, SYMBOL_POINT); if(dist <= 0.0 || point <= 0.0) return 0.0; double balance = AccountInfoDouble(ACCOUNT_BALANCE); double riskMoney = balance * (InpRiskPercent / 100.0); double tickValue = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_VALUE); double tickSize = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_SIZE); if(tickValue <= 0.0 || tickSize <= 0.0) return 0.0; double lossPerLot = (dist / tickSize) * tickValue; if(lossPerLot <= 0.0) return 0.0; double rawLots = riskMoney / lossPerLot; double minLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN); double maxLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX); double stepLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP); double lots = MathFloor(rawLots / stepLot) * stepLot; lots = MathMax(minLot, MathMin(maxLot, lots)); return NormalizeDouble(lots, 2); } //+------------------------------------------------------------------+ //| Process a single symbol through the flowchart stages | //+------------------------------------------------------------------+ void ProcessSymbol(SymbolState &st) { string sym = st.symbol; if(InpOneTradePerSym && HasOpenPosition(sym)) return; // Spread filter int spread = (int)SymbolInfoInteger(sym, SYMBOL_SPREAD); if(InpMaxSpreadPoints > 0 && spread > InpMaxSpreadPoints) return; // Identify HTF Direction (4H / 1H) int htfDir = GetHTFDirection(sym); if(htfDir == 0) { st.direction = 0; return; } // If HTF bias flipped, reset current setup if(st.direction != 0 && st.direction != htfDir) ResetSymbolState(st, sym); st.direction = htfDir; MqlRates rates[]; ArraySetAsSeries(rates, true); int copied = CopyRates(sym, InpSetupTF, 0, InpSearchBars, rates); if(copied < 25) return; double atrBuf[]; ArraySetAsSeries(atrBuf, true); if(CopyBuffer(st.atrHandleSetup, 0, 1, 1, atrBuf) < 1) return; double atr = atrBuf[0]; double point = SymbolInfoDouble(sym, SYMBOL_POINT); int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS); // Step 1: Liquidity sweep (SSL for bullish, BSL for bearish) if(!st.swept) { double liqPrice = 0.0; int liqBar = 0; bool foundLiq = FindRecentSwing(rates, copied, (st.direction == -1), 3, copied - 4, liqPrice, liqBar); if(!foundLiq) return; double sweepBuf = InpSweepBufferPts * point; if(st.direction == 1) // Bullish: sweep below SSL and close back above { if(rates[1].low < (liqPrice - sweepBuf) && rates[1].close > liqPrice) { st.swept = true; st.sweepExtreme = rates[1].low; } } else // Bearish: sweep above BSL and close back below { if(rates[1].high > (liqPrice + sweepBuf) && rates[1].close < liqPrice) { st.swept = true; st.sweepExtreme = rates[1].high; } } } // Step 2: Displacement + Market Structure Shift (MSS) + PD Array (FVG) if(st.swept && !st.mssConfirmed) { double swingLevel = 0.0; int swingBar = 0; // For bullish MSS, break prior swing high; for bearish MSS, break prior swing low bool foundSwing = FindRecentSwing(rates, copied, (st.direction == 1), 2, 25, swingLevel, swingBar); double body1 = MathAbs(rates[1].close - rates[1].open); bool displaced = (atr > 0.0 && body1 >= InpDispBodyAtrMult * atr); if(foundSwing && displaced) { bool mss = (st.direction == 1) ? (rates[1].close > swingLevel) : (rates[1].close < swingLevel); if(mss) { double fvgLow = 0.0, fvgHigh = 0.0; if(DetectFVG(sym, rates, copied, st.direction, atr, fvgLow, fvgHigh)) { st.mssConfirmed = true; st.fvgLow = fvgLow; st.fvgHigh = fvgHigh; st.fvgValid = true; } } } } // Step 3: Wait for retracement into PD Array + Lower TF confirmation if(st.swept && st.mssConfirmed && st.fvgValid) { MqlTick tick; if(!SymbolInfoTick(sym, tick)) return; // Check if PD array invalidated if(st.direction == 1 && tick.bid < st.fvgLow - (InpSlBufferPts * point)) { ResetSymbolState(st, sym); return; } if(st.direction == -1 && tick.ask > st.fvgHigh + (InpSlBufferPts * point)) { ResetSymbolState(st, sym); return; } // Retracement check bool inZone = (tick.bid <= st.fvgHigh && tick.ask >= st.fvgLow); if(!inZone) return; // Lower TF entry confirmation if(!HasLowerTFConfirmation(sym, st.direction)) return; // Valid trading setup -> Calculate lot size & enter trade double slBuf = InpSlBufferPts * point; double entry = (st.direction == 1) ? tick.ask : tick.bid; double sl = 0.0; if(st.direction == 1) { double refLow = (st.sweepExtreme > 0.0) ? MathMin(st.sweepExtreme, st.fvgLow) : st.fvgLow; sl = refLow - slBuf; if(sl >= entry) return; } else { double refHigh = (st.sweepExtreme > 0.0) ? MathMax(st.sweepExtreme, st.fvgHigh) : st.fvgHigh; sl = refHigh + slBuf; if(sl <= entry) return; } double slDist = MathAbs(entry - sl); double tp = (st.direction == 1) ? entry + (slDist * InpRiskReward) : entry - (slDist * InpRiskReward); double lots = CalculateLotSize(sym, entry, sl); if(lots <= 0.0) return; entry = NormalizeDouble(entry, digits); sl = NormalizeDouble(sl, digits); tp = NormalizeDouble(tp, digits); bool opened = false; if(st.direction == 1) opened = trade.Buy(lots, sym, entry, sl, tp, "Bullish Sweep+MSS+FVG"); else opened = trade.Sell(lots, sym, entry, sl, tp, "Bearish Sweep+MSS+FVG"); if(opened) { // Reset state so EA can scan for fresh setups after trade completes ResetSymbolState(st, sym); } } } //+------------------------------------------------------------------+ //| Manage open trades (Break-Even & Trailing Stop) | //+------------------------------------------------------------------+ void ManageOpenPositions() { for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong ticket = PositionGetTicket(i); if(ticket == 0) continue; if(PositionGetInteger(POSITION_MAGIC) != (long)InpMagicNumber) continue; string sym = PositionGetString(POSITION_SYMBOL); long posType = PositionGetInteger(POSITION_TYPE); double openPrice = PositionGetDouble(POSITION_PRICE_OPEN); double sl = PositionGetDouble(POSITION_SL); double tp = PositionGetDouble(POSITION_TP); int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS); double point = SymbolInfoDouble(sym, SYMBOL_POINT); MqlTick tick; if(!SymbolInfoTick(sym, tick)) continue; double riskDist = MathAbs(openPrice - sl); if(riskDist <= 0.0) continue; if(posType == POSITION_TYPE_BUY) { double currentProfitDist = tick.bid - openPrice; double newSl = sl; if(InpUseBreakEven && currentProfitDist >= riskDist) { double beSl = NormalizeDouble(openPrice + (2.0 * point), digits); if(beSl > newSl) newSl = beSl; } if(InpUseTrailingStop && currentProfitDist >= (InpTrailStartR * riskDist)) { double trailSl = NormalizeDouble(tick.bid - (InpTrailStepPts * point), digits); if(trailSl > newSl) newSl = trailSl; } if(newSl > sl && newSl < tick.bid) trade.PositionModify(ticket, newSl, tp); } else if(posType == POSITION_TYPE_SELL) { double currentProfitDist = openPrice - tick.ask; double newSl = sl; if(InpUseBreakEven && currentProfitDist >= riskDist) { double beSl = NormalizeDouble(openPrice - (2.0 * point), digits); if(sl == 0.0 || beSl < newSl) newSl = beSl; } if(InpUseTrailingStop && currentProfitDist >= (InpTrailStartR * riskDist)) { double trailSl = NormalizeDouble(tick.ask + (InpTrailStepPts * point), digits); if(sl == 0.0 || trailSl < newSl) newSl = trailSl; } if((sl == 0.0 || newSl < sl) && newSl > tick.ask) trade.PositionModify(ticket, newSl, tp); } } } //+------------------------------------------------------------------+