Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

//+------------------------------------------------------------------+ // Break of…

  1. User

    //+------------------------------------------------------------------+ //| Break of Structure EA with floating risk cap (full, compile) | //| Added ADX filter and Losing Streak filter | //| Added cooldown per candle & minimum time interval cooldown | //| Improved cooldown after close - scanning recent closed deals | //| Added Fair Value Gap (FVG) filter for entry signals | //+------------------------------------------------------------------+ #property copyright "" #property version "1.6" #property strict #include <Trade\Trade.mqh>

    input double inpLot = 0.05; input bool useRiskPercent = true; input double riskPercent = 1.0; // Position risk % per trade input int sl_atr_mult = 3; input double r2r_ratio = 2.0; input ENUM_TIMEFRAMES volatilityTF = PERIOD_M5; input int atrPeriod = 14; input int swingLookback = 20; input ENUM_TIMEFRAMES swingTF = PERIOD_M1;

    // Shortest-term MA (existing) input int maPeriod = 50; input ENUM_TIMEFRAMES maTimeframe = PERIOD_M15;

    // Medium-term MA (new) input int maPeriod2 = 100; input ENUM_TIMEFRAMES maTimeframe2 = PERIOD_M15;

    // Long-term MA (new) input int maPeriod3 = 200; input ENUM_TIMEFRAMES maTimeframe3 = PERIOD_M15;

    input int tradeStartHour = 7; input int tradeEndHour = 22; input int maxPositions = 1; input uint inpMagicNumber = 123456;

    input bool enableTrailingSL = true;

    enum ENUM_TrailingStopMode { TrailingNone = 0, TrailingMarketStructure = 1, TrailingATR = 2, TrailingHybrid = 3 }; input ENUM_TrailingStopMode trailingStopMode = TrailingHybrid; input int ms_swingLookback = 20; input double atr_trail_mult = 2.5; input uint TrailUpdateIntervalSec = 15; input double MinSLBufferATRMult = 1.0; input double TrailingProfitTriggerPerc = 0.5; input bool enableReverseEntries = true; input double maxRiskPerTradePercent = 1.0; // Floating loss cap only! input double maxDailyLossAmount = 350.0;

    // --- ADX filter inputs --- input int adxPeriod = 14; // ADX period input double adxThreshold = 25.0; // ADX minimum threshold to allow trading input ENUM_TIMEFRAMES adxTimeframe = PERIOD_M15; // ADX timeframe to use for filtering

    // --- Losing streak inputs --- input int maxLosingStreak = 3; // Max consecutive losing trades allowed

    // --- POST-CLOSE COOLDOWN --- input int postCloseCooldownSeconds = 180; // Cooldown seconds after a position closes before new trades allowed.

    // --- Fair Value Gap filter input --- input bool useFairValueGapFilter = true; // Enable Fair Value Gap filter for entries

    CTrade trade;

    int ma_handle = INVALID_HANDLE; int ma_handle2 = INVALID_HANDLE; // Medium-term MA handle int ma_handle3 = INVALID_HANDLE; // Long-term MA handle int atr_handle = INVALID_HANDLE; int adx_handle = INVALID_HANDLE; // ADX handle

    string swingHighLineName = "SwingHighLine"; string swingLowLineName = "SwingLowLine";

    struct TrailingUpdateInfo { ulong position_ticket; datetime last_update; }; TrailingUpdateInfo g_trailingUpdateInfo[];

    static double g_initialEquity = 0.0; static datetime g_lastResetDay = 0;

    static int g_currentLosingStreak = 0; static datetime g_lastLosingStreakResetDay = 0; static ulong g_lastHistoryTickTime = 0;

    // *** Cooldown globals *** datetime lastTradeCandleTime = 0; // last candle time when trade opened ENUM_TIMEFRAMES cooldownTimeframe = swingTF; // timeframe for candle cooldown

    datetime lastTradeOpenTime = 0; // last trade open timestamp int tradeIntervalSeconds = 180; // min seconds between trades

    //+------------------------------------------------------------------+ void ResetDailyEquityIfNewDay() { datetime now = TimeCurrent(); MqlDateTime tm; TimeToStruct(now, tm);

    MqlDateTime todayMidnight = {};
    todayMidnight.year = tm.year;
    todayMidnight.mon  = tm.mon;
    todayMidnight.day  = tm.day;
    todayMidnight.hour = 0;
    todayMidnight.min  = 0;
    todayMidnight.sec  = 0;
    datetime midnightTime = StructToTime(todayMidnight);
    
    if(g_lastResetDay != midnightTime)
    {
        g_lastResetDay = midnightTime;
        g_initialEquity = AccountInfoDouble(ACCOUNT_EQUITY);
        PrintFormat("Daily equity reset at %s new initialEquity=%.2f", TimeToString(now, TIME_DATE|TIME_SECONDS), g_initialEquity);
    }
    

    } //+------------------------------------------------------------------+ void ResetLosingStreakIfNewDay() { datetime now = TimeCurrent(); MqlDateTime tm; TimeToStruct(now, tm);

    MqlDateTime todayMidnight = {};
    todayMidnight.year = tm.year;
    todayMidnight.mon = tm.mon;
    todayMidnight.day = tm.day;
    todayMidnight.hour = 0;
    todayMidnight.min = 0;
    todayMidnight.sec = 0;
    
    datetime midnightTime = StructToTime(todayMidnight);
    
    if(g_lastLosingStreakResetDay != midnightTime)
    {
        g_lastLosingStreakResetDay = midnightTime;
        g_currentLosingStreak = 0;
        PrintFormat("Losing streak reset at new day %s", TimeToString(now, TIME_DATE|TIME_SECONDS));
    }
    

    } //+------------------------------------------------------------------+ void UpdateLosingStreak() { datetime now = TimeCurrent();

    if(!HistorySelect(now - 86400, now))
    {
        Print("HistorySelect failed");
        return;
    }
    
    ulong maxClosedTime = 0;
    int total = HistoryDealsTotal();
    
    for(int i = total - 1; i >= 0; i--)
    {
        ulong ticket = HistoryDealGetTicket(i);
        datetime closeTime = (datetime)HistoryDealGetInteger(ticket, DEAL_TIME);
    
        if(closeTime <= g_lastHistoryTickTime)
            continue;
    
        maxClosedTime = MathMax(maxClosedTime, (ulong)closeTime);
    
        string symbol = HistoryDealGetString(ticket, DEAL_SYMBOL);
        ulong magic = HistoryDealGetInteger(ticket, DEAL_MAGIC);
    
        if(symbol != _Symbol || magic != inpMagicNumber)
            continue;
    
        long entryType = HistoryDealGetInteger(ticket, DEAL_ENTRY);
    
        if(entryType != DEAL_ENTRY_OUT)
            continue;
    
        double profit = HistoryDealGetDouble(ticket, DEAL_PROFIT);
    
        if(profit < 0)
        {
            g_currentLosingStreak++;
            PrintFormat("Losing trade detected (ticket %I64d, profit %.2f). Current losing streak: %d", ticket, profit, g_currentLosingStreak);
        }
        else
        {
            if(g_currentLosingStreak > 0)
                PrintFormat("Winning trade detected (ticket %I64d, profit %.2f). Resetting losing streak.", ticket, profit);
            g_currentLosingStreak = 0;
        }
    }
    
    if(maxClosedTime > 0)
        g_lastHistoryTickTime = maxClosedTime;
    

    } //+------------------------------------------------------------------+ double CalculateLotSize(double sl_distance_price) { double balance = AccountInfoDouble(ACCOUNT_BALANCE); if(balance <= 0 || sl_distance_price <= 0) return inpLot;

    if(!useRiskPercent) { double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX); double lot = inpLot; if(lot < min_lot) lot = min_lot; if(lot > max_lot) lot = max_lot; lot = MathFloor(lot / lot_step) * lot_step; return lot; } else { double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); double contract_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_CONTRACT_SIZE);

      if(tick_value <= 0 || tick_size <= 0 || contract_size <= 0)
         return inpLot;
    
      double point_value = tick_value / tick_size;
      double calculatedLot = (balance * (riskPercent / 100.0)) / (sl_distance_price * point_value * contract_size);
    
      if(calculatedLot <= 0)
         return inpLot;
    
      double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
      double min_lot  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
      double max_lot  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
    
      double lot = MathFloor(calculatedLot / lot_step) * lot_step;
    
      if(lot < min_lot) lot = min_lot;
      if(lot > max_lot) lot = max_lot;
      return lot;
    

    } } //+------------------------------------------------------------------+ bool IsPositionOpen(ENUM_POSITION_TYPE type) { int total = PositionsTotal(); for(int i = 0; i < total; i++) { ulong ticket = PositionGetTicket(i); if(PositionSelectByTicket(ticket)) { if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol) { ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); if(pos_type == type) return true; } } } return false; } //+------------------------------------------------------------------+ bool CanUpdateTrailing(ulong ticket) { datetime now = TimeCurrent(); int count = ArraySize(g_trailingUpdateInfo); for(int i=0; i<count; i++) { if(g_trailingUpdateInfo[i].position_ticket == ticket) { if(now - g_trailingUpdateInfo[i].last_update < (int)TrailUpdateIntervalSec) return false; g_trailingUpdateInfo[i].last_update = now; return true; } } ArrayResize(g_trailingUpdateInfo, count + 1); g_trailingUpdateInfo[count].position_ticket = ticket; g_trailingUpdateInfo[count].last_update = now; return true; } //+------------------------------------------------------------------+ void UpdateTrailingStopByMarketStructure(ulong position_ticket) { if(!PositionSelectByTicket(position_ticket)) return;

    ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
    double current_sl = PositionGetDouble(POSITION_SL);
    double current_tp = PositionGetDouble(POSITION_TP);
    double entry_price = PositionGetDouble(POSITION_PRICE_OPEN);
    string symbol = PositionGetString(POSITION_SYMBOL);
    
    if(current_tp <= 0)
        return;
    
    if(!CanUpdateTrailing(position_ticket))
        return;
    
    double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
    int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
    
    double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
    double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
    if(bid <= 0 || ask <= 0)
        return;
    
    if(pos_type == POSITION_TYPE_BUY)
    {
        double half_tp_level = entry_price + 0.5 * (current_tp - entry_price);
        if(bid < half_tp_level)
            return;
    
        int lowestBar = iLowest(symbol, PERIOD_CURRENT, MODE_LOW, ms_swingLookback, 0);
        if(lowestBar < 0)
            return;
    
        double swing_low = iLow(symbol, PERIOD_CURRENT, lowestBar);
        double buffer = 2 * point;
        double new_sl = NormalizeDouble(swing_low - buffer, digits);
    
        if(new_sl > current_sl && new_sl < entry_price)
        {
            MqlTradeRequest req = {};
            MqlTradeResult res = {};
            req.action = TRADE_ACTION_SLTP;
            req.position = position_ticket;
            req.symbol = symbol;
            req.sl = new_sl;
            req.tp = current_tp;
            req.deviation = 10;
    
            if(!OrderSend(req, res))
                PrintFormat("Failed to update trailing SL for position %I64d, error %d", position_ticket, GetLastError());
            else if(res.retcode != TRADE_RETCODE_DONE)
                PrintFormat("Trailing SL update rejected for position %I64d, retcode %d", position_ticket, res.retcode);
            else
                PrintFormat("Trailing SL moved up for position %I64d: new SL=%.5f", position_ticket, new_sl);
        }
    }
    else if(pos_type == POSITION_TYPE_SELL)
    {
        double half_tp_level = entry_price - 0.5 * (entry_price - current_tp);
        if(ask > half_tp_level)
            return;
    
        int highestBar = iHighest(symbol, PERIOD_CURRENT, MODE_HIGH, ms_swingLookback, 0);
        if(highestBar < 0)
            return;
    
        double swing_high = iHigh(symbol, PERIOD_CURRENT, highestBar);
        double buffer = 2 * point;
        double new_sl = NormalizeDouble(swing_high + buffer, digits);
    
        if(new_sl < current_sl && new_sl > entry_price)
        {
            MqlTradeRequest req = {};
            MqlTradeResult res = {};
            req.action = TRADE_ACTION_SLTP;
            req.position = position_ticket;
            req.symbol = symbol;
            req.sl = new_sl;
            req.tp = current_tp;
            req.deviation = 10;
    
            if(!OrderSend(req, res))
                PrintFormat("Failed to update trailing SL for position %I64d, error %d", position_ticket, GetLastError());
            else if(res.retcode != TRADE_RETCODE_DONE)
                PrintFormat("Trailing SL update rejected for position %I64d, retcode %d", position_ticket, res.retcode);
            else
                PrintFormat("Trailing SL moved down for position %I64d: new SL=%.5f", position_ticket, new_sl);
        }
    }
    

    } //+------------------------------------------------------------------+ void UpdateTrailingStopByATR(ulong position_ticket) { if(!PositionSelectByTicket(position_ticket)) return;

    ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
    double current_sl = PositionGetDouble(POSITION_SL);
    double entry_price = PositionGetDouble(POSITION_PRICE_OPEN);
    string symbol = PositionGetString(POSITION_SYMBOL);
    
    if(!CanUpdateTrailing(position_ticket))
        return;
    
    double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
    int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
    
    double atr_buf[];
    if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0)
        return;
    double atr = atr_buf[0];
    if(atr <= 0)
        return;
    
    double current_price = (pos_type == POSITION_TYPE_BUY) ? SymbolInfoDouble(symbol, SYMBOL_BID) 
                                                           : SymbolInfoDouble(symbol, SYMBOL_ASK);
    if(current_price <= 0) return;
    
    double new_sl = 0;
    if(pos_type == POSITION_TYPE_BUY)
    {
        new_sl = NormalizeDouble(current_price - atr * atr_trail_mult, digits);
        double min_sl_dist = atr * MinSLBufferATRMult;
        if(new_sl < (current_price - min_sl_dist))
            new_sl = current_price - min_sl_dist;
    
        if(new_sl > current_sl && new_sl < current_price)
        {
            MqlTradeRequest req={};
            MqlTradeResult res={};
            req.action = TRADE_ACTION_SLTP;
            req.position = position_ticket;
            req.symbol = symbol;
            req.sl = new_sl;
            req.tp = PositionGetDouble(POSITION_TP);
            req.deviation = 10;
    
            if(!OrderSend(req, res))
                PrintFormat("ATR trailing SL update failed for position %I64d, error %d", position_ticket, GetLastError());
            else if(res.retcode != TRADE_RETCODE_DONE)
                PrintFormat("ATR trailing SL update rejected for position %I64d, retcode %d", position_ticket, res.retcode);
            else
                PrintFormat("ATR trailing SL moved up for position %I64d: new SL=%.5f", position_ticket, new_sl);
        }
    }
    else if(pos_type == POSITION_TYPE_SELL)
    {
        new_sl = NormalizeDouble(current_price + atr * atr_trail_mult, digits);
        double min_sl_dist = atr * MinSLBufferATRMult;
        if(new_sl > (current_price + min_sl_dist))
            new_sl = current_price + min_sl_dist;
    
        if(new_sl < current_sl && new_sl > current_price)
        {
            MqlTradeRequest req={};
            MqlTradeResult res={};
            req.action = TRADE_ACTION_SLTP;
            req.position = position_ticket;
            req.symbol = symbol;
            req.sl = new_sl;
            req.tp = PositionGetDouble(POSITION_TP);
            req.deviation = 10;
    
            if(!OrderSend(req, res))
                PrintFormat("ATR trailing SL update failed for position %I64d, error %d", position_ticket, GetLastError());
            else if(res.retcode != TRADE_RETCODE_DONE)
                PrintFormat("ATR trailing SL update rejected for position %I64d, retcode %d", position_ticket, res.retcode);
            else
                PrintFormat("ATR trailing SL moved down for position %I64d: new SL=%.5f", position_ticket, new_sl);
        }
    }
    

    } //+------------------------------------------------------------------+ void UpdateTrailingStopHybrid(ulong position_ticket) { if(!PositionSelectByTicket(position_ticket)) return;

    if(!CanUpdateTrailing(position_ticket)) return;

    ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); double sl = PositionGetDouble(POSITION_SL); double tp = PositionGetDouble(POSITION_TP); double entry_price = PositionGetDouble(POSITION_PRICE_OPEN); string symbol = PositionGetString(POSITION_SYMBOL);

    double point = SymbolInfoDouble(symbol, SYMBOL_POINT); int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);

    double atr_buf[]; if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0) return; double atr = atr_buf[0]; if(atr <= 0) return;

    double min_sl_distance = atr * MinSLBufferATRMult; double initial_sl_dist = MathAbs(entry_price - sl); if(initial_sl_dist <= 0) initial_sl_dist = atr * sl_atr_mult;

    double current_price = (pos_type == POSITION_TYPE_BUY) ? SymbolInfoDouble(symbol, SYMBOL_BID) : SymbolInfoDouble(symbol, SYMBOL_ASK); if(current_price <= 0) return;

    double move_in_profit = (pos_type == POSITION_TYPE_BUY) ? (current_price - entry_price) : (entry_price - current_price); if(move_in_profit < TrailingProfitTriggerPerc * initial_sl_dist) return;

    double ms_new_sl = 0; bool ms_sl_valid = false; if(pos_type == POSITION_TYPE_BUY) { int lowestBar = iLowest(symbol, PERIOD_CURRENT, MODE_LOW, ms_swingLookback, 0); if(lowestBar >= 0) { double swing_low = iLow(symbol, PERIOD_CURRENT, lowestBar); ms_new_sl = NormalizeDouble(swing_low - 2point, digits); ms_sl_valid = (ms_new_sl > sl) && (ms_new_sl < entry_price); } } else if(pos_type == POSITION_TYPE_SELL) { int highestBar = iHighest(symbol, PERIOD_CURRENT, MODE_HIGH, ms_swingLookback, 0); if(highestBar >= 0) { double swing_high = iHigh(symbol, PERIOD_CURRENT, highestBar); ms_new_sl = NormalizeDouble(swing_high + 2point, digits); ms_sl_valid = (ms_new_sl < sl) && (ms_new_sl > entry_price); } }

    double atr_new_sl = 0; if(pos_type == POSITION_TYPE_BUY) { atr_new_sl = NormalizeDouble(current_price - atr * atr_trail_mult, digits); atr_new_sl = MathMax(atr_new_sl, current_price - min_sl_distance); atr_new_sl = (atr_new_sl > sl && atr_new_sl < current_price) ? atr_new_sl : 0; } else if(pos_type == POSITION_TYPE_SELL) { atr_new_sl = NormalizeDouble(current_price + atr * atr_trail_mult, digits); atr_new_sl = MathMin(atr_new_sl, current_price + min_sl_distance); atr_new_sl = (atr_new_sl < sl && atr_new_sl > current_price) ? atr_new_sl : 0; }

    double new_sl = 0; if(ms_sl_valid && atr_new_sl > 0) { if(pos_type == POSITION_TYPE_BUY) new_sl = MathMax(ms_new_sl, atr_new_sl); else new_sl = MathMin(ms_new_sl, atr_new_sl); } else if(ms_sl_valid) new_sl = ms_new_sl; else if(atr_new_sl > 0) new_sl = atr_new_sl; else return;

    bool update_sl = false; if(pos_type == POSITION_TYPE_BUY) update_sl = (new_sl > sl && new_sl < current_price); else update_sl = (new_sl < sl && new_sl > current_price);

    if(update_sl) { MqlTradeRequest req={}; MqlTradeResult res={}; req.action = TRADE_ACTION_SLTP; req.position = position_ticket; req.symbol = symbol; req.sl = new_sl; req.tp = tp; req.deviation = 10;

      if(!OrderSend(req,res))
         PrintFormat("Trailing SL update failed for position %I64d, err=%d", position_ticket, GetLastError());
      else if(res.retcode != TRADE_RETCODE_DONE)
         PrintFormat("Trailing SL update rejected for position %I64d, retcode=%d", position_ticket, res.retcode);
      else
         PrintFormat("Trailing SL updated for position %I64d: old SL=%.5f new SL=%.5f", position_ticket, sl, new_sl);
    

    } } //+------------------------------------------------------------------+

    //-- Fair Value Gap detection function -- // Returns: // 1 if bullish FVG detected (Candle1 High < Candle3 Low) // -1 if bearish FVG detected (Candle1 Low > Candle3 High) // 0 if no gap or error int DetectFairValueGap(ENUM_TIMEFRAMES timeframe, int startShift) { MqlRates bars[3]; // Copy 3 bars starting from startShift, i.e. bars[0] = bar at startShift if(CopyRates(_Symbol, timeframe, startShift, 3, bars) != 3) { Print("DetectFairValueGap: failed to copy 3 bars"); return 0; }

    // Candle1 = bars[0], Candle2 = bars[1], Candle3 = bars[2] double c1_high = bars[0].high; double c1_low = bars[0].low; double c3_high = bars[2].high; double c3_low = bars[2].low;

    // Bullish FVG: Candle1 High < Candle3 Low if(c1_high < c3_low) { double gapBull = c3_low - c1_high; PrintFormat("Bullish Fair Value Gap detected between candle1 high %.5f and candle3 low %.5f (Gap %.5f)", c1_high, c3_low, gapBull); return 1; }

    // Bearish FVG: Candle1 Low > Candle3 High if(c1_low > c3_high) { double gapBear = c1_low - c3_high; PrintFormat("Bearish Fair Value Gap detected between candle1 low %.5f and candle3 high %.5f (Gap %.5f)", c1_low, c3_high, gapBear); return -1; }

    return 0; } //+------------------------------------------------------------------+

    int OnInit() { ma_handle = iMA(_Symbol, maTimeframe, maPeriod, 0, MODE_EMA, PRICE_CLOSE); if(ma_handle == INVALID_HANDLE) { Print("Failed to create EMA handle"); return INIT_FAILED; }

    ma_handle2 = iMA(_Symbol, maTimeframe2, maPeriod2, 0, MODE_EMA, PRICE_CLOSE); if(ma_handle2 == INVALID_HANDLE) { Print("Failed to create medium-term EMA handle"); IndicatorRelease(ma_handle); return INIT_FAILED; }

    ma_handle3 = iMA(_Symbol, maTimeframe3, maPeriod3, 0, MODE_EMA, PRICE_CLOSE); if(ma_handle3 == INVALID_HANDLE) { Print("Failed to create long-term EMA handle"); IndicatorRelease(ma_handle); IndicatorRelease(ma_handle2); return INIT_FAILED; }

    atr_handle = iATR(_Symbol, volatilityTF, atrPeriod); if(atr_handle == INVALID_HANDLE) { Print("Failed to create ATR handle"); IndicatorRelease(ma_handle); IndicatorRelease(ma_handle2); IndicatorRelease(ma_handle3); return INIT_FAILED; }

    adx_handle = iADX(_Symbol, adxTimeframe, adxPeriod); if(adx_handle == INVALID_HANDLE) { Print("Failed to create ADX handle"); IndicatorRelease(ma_handle); IndicatorRelease(ma_handle2); IndicatorRelease(ma_handle3); IndicatorRelease(atr_handle); return INIT_FAILED; }

    if(!ObjectCreate(0, swingHighLineName, OBJ_HLINE, 0, TimeCurrent(), 0)) { Print("Failed to create swing high line"); IndicatorRelease(ma_handle); IndicatorRelease(ma_handle2); IndicatorRelease(ma_handle3); IndicatorRelease(atr_handle); IndicatorRelease(adx_handle); return INIT_FAILED; } ObjectSetInteger(0, swingHighLineName, OBJPROP_COLOR, clrGreen); ObjectSetInteger(0, swingHighLineName, OBJPROP_WIDTH, 2); ObjectSetInteger(0, swingHighLineName, OBJPROP_BACK, true); ObjectSetInteger(0, swingHighLineName, OBJPROP_RAY_RIGHT, true);

    if(!ObjectCreate(0, swingLowLineName, OBJ_HLINE, 0, TimeCurrent(), 0)) { Print("Failed to create swing low line"); ObjectDelete(0, swingHighLineName); IndicatorRelease(ma_handle); IndicatorRelease(ma_handle2); IndicatorRelease(ma_handle3); IndicatorRelease(atr_handle); IndicatorRelease(adx_handle); return INIT_FAILED; } ObjectSetInteger(0, swingLowLineName, OBJPROP_COLOR, clrRed); ObjectSetInteger(0, swingLowLineName, OBJPROP_WIDTH, 2); ObjectSetInteger(0, swingLowLineName, OBJPROP_BACK, true); ObjectSetInteger(0, swingLowLineName, OBJPROP_RAY_RIGHT, true); return INIT_SUCCEEDED; } //+------------------------------------------------------------------+

    void OnDeinit(const int reason) { ObjectDelete(0, swingHighLineName); ObjectDelete(0, swingLowLineName);

    if(ma_handle != INVALID_HANDLE) { IndicatorRelease(ma_handle); ma_handle = INVALID_HANDLE; } if(ma_handle2 != INVALID_HANDLE) { IndicatorRelease(ma_handle2); ma_handle2 = INVALID_HANDLE; } if(ma_handle3 != INVALID_HANDLE) { IndicatorRelease(ma_handle3); ma_handle3 = INVALID_HANDLE; } if(atr_handle != INVALID_HANDLE) { IndicatorRelease(atr_handle); atr_handle = INVALID_HANDLE; } if(adx_handle != INVALID_HANDLE) { IndicatorRelease(adx_handle); adx_handle = INVALID_HANDLE; } } //+------------------------------------------------------------------+

    // Static variables to throttle print frequency static datetime lastFvgNoTradePrintCandle = 0; static datetime lastAdxBelowThresholdPrintCandle = 0; static datetime lastPostCloseCooldownPrintTime = 0;

    void OnTick() { datetime now = TimeCurrent();

    // Post-close cooldown message throttled (once every 60s)
    if(postCloseCooldownSeconds > 0 && IsRecentPositionClose(postCloseCooldownSeconds))
    {
        if (now - lastPostCloseCooldownPrintTime >= 60)
        {
            PrintFormat("Post-close cooldown active, skipping trades at %s", TimeToString(now));
            lastPostCloseCooldownPrintTime = now;
        }
        return;
    }
    else
    {
        lastPostCloseCooldownPrintTime = 0;
    }
    
    ResetDailyEquityIfNewDay();
    ResetLosingStreakIfNewDay();
    
    UpdateLosingStreak();
    
    if(maxLosingStreak > 0 && g_currentLosingStreak >= maxLosingStreak)
    {
        PrintFormat("Current losing streak %d >= max allowed %d. No new trades allowed now.", g_currentLosingStreak, maxLosingStreak);
        return;
    }
    
    if(g_initialEquity == 0.0)
        g_initialEquity = AccountInfoDouble(ACCOUNT_EQUITY);
    
    double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
    double equityDrawdown = g_initialEquity - currentEquity;
    
    if(equityDrawdown >= maxDailyLossAmount)
    {
        PrintFormat("Max combined daily loss $%.2f exceeded (drawdown=%.2f). No new trades allowed.", maxDailyLossAmount, equityDrawdown);
        return;
    }
    
    //--- FLOATING RISK CLOSE LOGIC ---
    if(maxRiskPerTradePercent > 0.0)
    {
        int total = PositionsTotal();
        double balance = AccountInfoDouble(ACCOUNT_BALANCE);
        double maxLossMoney = balance * (maxRiskPerTradePercent / 100.0);
    
        for(int i=total-1; i>=0; i--)
        {
            ulong ticket = PositionGetTicket(i);
            if(PositionSelectByTicket(ticket))
            {
                if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber &&
                   PositionGetString(POSITION_SYMBOL) == _Symbol)
                {
                    double currentProfit = PositionGetDouble(POSITION_PROFIT);
                    if(currentProfit < 0 && MathAbs(currentProfit) >= maxLossMoney)
                    {
                        PrintFormat("Closing position %I64d as floating loss reached %.2f (cap is %.2f)",
                                    ticket, MathAbs(currentProfit), maxLossMoney);
                        trade.PositionClose(ticket);
                    }
                }
            }
        }
    }
    
    //--- TRAILING SL ---
    if(enableTrailingSL && trailingStopMode != TrailingNone)
    {
       int total = PositionsTotal();
       for(int i=0; i<total; i++)
       {
          ulong ticket = PositionGetTicket(i);
          if(PositionSelectByTicket(ticket))
          {
             if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
             {
                if(trailingStopMode == TrailingMarketStructure)
                   UpdateTrailingStopByMarketStructure(ticket);
                else if(trailingStopMode == TrailingATR)
                   UpdateTrailingStopByATR(ticket);
                else if(trailingStopMode == TrailingHybrid)
                   UpdateTrailingStopHybrid(ticket);
             }
          }
       }
    }
    
    //--- POSITION LIMIT CHECK ---
    int openPosCount = 0, totalPositions = PositionsTotal();
    for(int i=0; i<totalPositions; i++)
    {
        ulong ticket = PositionGetTicket(i);
        if(PositionSelectByTicket(ticket))
        {
            if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
            {
                openPosCount++;
            }
        }
    }
    if(maxPositions > 0 && openPosCount >= maxPositions)
        return;
    
    //--- TRADING TIME ---
    MqlDateTime tm;
    TimeToStruct(TimeCurrent(), tm);
    if(tm.hour < tradeStartHour || tm.hour >= tradeEndHour)
        return;
    
    // --- MINIMUM TIME INTERVAL COOLDOWN CHECK ---
    if(lastTradeOpenTime != 0 && (now - lastTradeOpenTime) < tradeIntervalSeconds)
        return; // interval cooldown active, skip trade
    
    // --- COOLDOWN PER CANDLE CHECK ---
    MqlRates candleRates[];
    if(CopyRates(_Symbol, cooldownTimeframe, 1, 1, candleRates) != 1)
    {
        Print("Failed to get last closed candle data for cooldown check");
        return;
    }
    datetime currentCandleTime = candleRates[0].time;
    if(currentCandleTime == lastTradeCandleTime)
        return; // candle cooldown active, skip trade
    
    //--- INDICATORS ---
    double ma_buf1[], ma_buf2[], ma_buf3[];
    if(CopyBuffer(ma_handle, 0, 1, 1, ma_buf1) <= 0) return;
    if(CopyBuffer(ma_handle2, 0, 1, 1, ma_buf2) <= 0) return;
    if(CopyBuffer(ma_handle3, 0, 1, 1, ma_buf3) <= 0) return;
    
    double MA1 = ma_buf1[0];
    double MA2 = ma_buf2[0];
    double MA3 = ma_buf3[0];
    
    double atr_buf[];
    if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0)
        return;
    double atr = atr_buf[0];
    if(atr <= 0)
        atr = 10.0 * _Point;
    
    double adx_buf[];
    if(adx_handle == INVALID_HANDLE)
    {
        Print("ADX handle invalid");
        return;
    }
    if(CopyBuffer(adx_handle, 0, 1, 1, adx_buf) <= 0)
    {
        Print("Failed to copy ADX buffer");
        return;
    }
    double adx_value = adx_buf[0];
    
    // ADX below threshold message throttled (once per candle)
    if(adx_value < adxThreshold)
    {
        if(currentCandleTime != lastAdxBelowThresholdPrintCandle)
        {
            PrintFormat("ADX=%.2f below threshold %.2f, skipping new entries", adx_value, adxThreshold);
            lastAdxBelowThresholdPrintCandle = currentCandleTime;
        }
        return; // skip trade entries when ADX too low
    }
    else
    {
        lastAdxBelowThresholdPrintCandle = 0;
    }
    
    double sl_dist = atr * sl_atr_mult;
    double tp_dist = sl_dist * r2r_ratio;
    
    int highestBar = iHighest(_Symbol, swingTF, MODE_HIGH, swingLookback, 1);
    int lowestBar = iLowest(_Symbol, swingTF, MODE_LOW, swingLookback, 1);
    if(highestBar < 0 || lowestBar < 0)
        return;
    
    double lastSwingHigh = iHigh(_Symbol, swingTF, highestBar);
    double lastSwingLow = iLow(_Symbol, swingTF, lowestBar);
    
    ObjectSetDouble(0, swingHighLineName, OBJPROP_PRICE, lastSwingHigh);
    ObjectSetDouble(0, swingLowLineName, OBJPROP_PRICE, lastSwingLow);
    
    double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    if(ask <= 0 || bid <= 0)
        return;
    
    bool is_uptrend = (MA1 > MA2) && (MA2 > MA3) && (ask > MA2);
    bool is_downtrend = (MA1 < MA2) && (MA2 < MA3) && (ask < MA2);
    
    int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
    
    double lot = CalculateLotSize(sl_dist);
    if(lot < SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN))
        return;
    
    // --- Fair Value Gap detection ---
    int fvgSignal = 0;
    if(useFairValueGapFilter)
    {
       // Using shift=1 means last fully formed candles excluding current candle
       fvgSignal = DetectFairValueGap(swingTF, 1);  
       if(fvgSignal == 0)
       {
          if(currentCandleTime != lastFvgNoTradePrintCandle)
          {
              Print("No Fair Value Gap detected, skipping new entries per FVG filter.");
              lastFvgNoTradePrintCandle = currentCandleTime;
          }
          return;  // Skip trades if no FVG detected and filter enabled
       }
       else
       {
          lastFvgNoTradePrintCandle = 0;
       }
    }
    
    MqlTradeRequest request = {};
    MqlTradeResult result = {};
    request.symbol = _Symbol;
    request.volume = lot;
    request.deviation = 10;
    request.magic = inpMagicNumber;
    
    if(!enableReverseEntries)
    {
        if(ask > lastSwingHigh && is_uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
        {
            if(!useFairValueGapFilter || fvgSignal == 1)
            {
                request.action = TRADE_ACTION_DEAL;
                request.type   = ORDER_TYPE_BUY;
                request.price  = ask;
                request.sl     = NormalizeDouble(ask - sl_dist, digits);
                request.tp     = NormalizeDouble(ask + tp_dist, digits);
    
                if(!OrderSend(request, result))
                    PrintFormat("Buy order send failed, error %d", GetLastError());
                else if(result.retcode != TRADE_RETCODE_DONE)
                    PrintFormat("Buy order rejected, retcode %d", result.retcode);
                else
                {
                    PrintFormat("Buy opened @ %.5f lot %.2f SL %.5f TP %.5f", ask, lot, request.sl, request.tp);
                    lastTradeCandleTime = currentCandleTime;
                    lastTradeOpenTime = now;
                }
            }
        }
        else if(bid < lastSwingLow && is_downtrend && !IsPositionOpen(POSITION_TYPE_SELL))
        {
            if(!useFairValueGapFilter || fvgSignal == -1)
            {
                request.action = TRADE_ACTION_DEAL;
                request.type   = ORDER_TYPE_SELL;
                request.price  = bid;
                request.sl     = NormalizeDouble(bid + sl_dist, digits);
                request.tp     = NormalizeDouble(bid - tp_dist, digits);
    
                if(!OrderSend(request, result))
                    PrintFormat("Sell order send failed, error %d", GetLastError());
                else if(result.retcode != TRADE_RETCODE_DONE)
                    PrintFormat("Sell order rejected, retcode %d", result.retcode);
                else
                {
                    PrintFormat("Sell opened @ %.5f lot %.2f SL %.5f TP %.5f", bid, lot, request.sl, request.tp);
                    lastTradeCandleTime = currentCandleTime;
                    lastTradeOpenTime = now;
                }
            }
        }
    }
    else
    {
        if(ask > lastSwingHigh && is_downtrend && !IsPositionOpen(POSITION_TYPE_SELL))
        {
            if(!useFairValueGapFilter || fvgSignal == -1)
            {
                request.action = TRADE_ACTION_DEAL;
                request.type   = ORDER_TYPE_SELL;
                request.price  = bid;
                request.sl     = NormalizeDouble(bid + sl_dist, digits);
                request.tp     = NormalizeDouble(bid - tp_dist, digits);
    
                if(!OrderSend(request, result))
                    PrintFormat("Reverse Sell order send failed, error %d", GetLastError());
                else if(result.retcode != TRADE_RETCODE_DONE)
                    PrintFormat("Reverse Sell order rejected, retcode %d", result.retcode);
                else
                {
                    PrintFormat("Reverse Sell opened @ %.5f lot %.2f SL %.5f TP %.5f", bid, lot, request.sl, request.tp);
                    lastTradeCandleTime = currentCandleTime;
                    lastTradeOpenTime = now;
                }
            }
        }
        else if(bid < lastSwingLow && is_uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
        {
            if(!useFairValueGapFilter || fvgSignal == 1)
            {
                request.action = TRADE_ACTION_DEAL;
                request.type   = ORDER_TYPE_BUY;
                request.price  = ask;
                request.sl     = NormalizeDouble(ask - sl_dist, digits);
                request.tp     = NormalizeDouble(ask + tp_dist, digits);
    
                if(!OrderSend(request, result))
                    PrintFormat("Reverse Buy order send failed, error %d", GetLastError());
                else if(result.retcode != TRADE_RETCODE_DONE)
                    PrintFormat("Reverse Buy order rejected, retcode %d", result.retcode);
                else
                {
                    PrintFormat("Reverse Buy opened @ %.5f lot %.2f SL %.5f TP %.5f", ask, lot, request.sl, request.tp);
                    lastTradeCandleTime = currentCandleTime;
                    lastTradeOpenTime = now;
                }
            }
        }
    }
    

    } //+------------------------------------------------------------------+

    // IsRecentPositionClose function (scans recent closed position deals) bool IsRecentPositionClose(uint cooldownSecs) { datetime now = TimeCurrent();

    if(!HistorySelect(now - cooldownSecs - 10, now))
    {
        Print("HistorySelect failed");
        return false;
    }
    
    int totalDeals = HistoryDealsTotal();
    for(int i = totalDeals - 1; i >= 0; i--)
    {
        ulong ticket = HistoryDealGetTicket(i);
        if(ticket == 0)
            continue;
    
        datetime dealTime = (datetime)HistoryDealGetInteger(ticket, DEAL_TIME);
        if(dealTime == 0 || (now - dealTime) > cooldownSecs)
            continue;
    
        string symbol = HistoryDealGetString(ticket, DEAL_SYMBOL);
        ulong magic = HistoryDealGetInteger(ticket, DEAL_MAGIC);
        long entry = HistoryDealGetInteger(ticket, DEAL_ENTRY);
    
        if(symbol == _Symbol && magic == inpMagicNumber && entry == DEAL_ENTRY_OUT)
        {
            PrintFormat("Recent position close detected at %s, cooldown active.", TimeToString(dealTime));
            return true;
        }
    }
    
    return false;
    

    } //+------------------------------------------------------------------+

  2. Assistant

    Your full EA code looks well-structured and includes the requested features: ADX filter, losing streak filter, cooldown per candle and time interval, improved cooldown checking recent closed deals, and the Fair Value Gap filter.

    Summary of the key functional components you have implemented:

    • Risk and position sizing: Lot size calculated with fixed lot or risk %, with stop loss distance based on ATR.
    • ADX filter: Skips new trades when ADX value (on selected timeframe) is below threshold.
    • Losing streak filter: Tracks consecutive losing trades from history and blocks new trades if max losing streak exceeded.
    • Cooldowns:
      • Per candle cooldown - only one trade per new candle on a chosen timeframe.
      • Minimum interval cooldown - minimum seconds between trades.
      • Post-close cooldown - skip trades for some seconds after any position closes.
    • Trailing stops: Multiple modes including MarketStructure, ATR, and Hybrid.
    • Fair Value Gap filter: Detects bullish or bearish FVG on a given timeframe and requires an FVG for entries if enabled.
    • Floating risk cap: Closes open positions if loss exceeds a floating max risk percentage of account balance.
    • Reverse entries option: Enables opposite direction entries relative to swing and MA trend if true.

    If you want to test, optimize, or expand it further, here are some suggestions and highlights:

    1. Initialization and Resource Management

    • You handle indicator releases correctly in OnDeinit.
    • You create horizontal lines as visual aids for swing highs/lows.
    • The ATR, EMA (3 periods), and ADX indicator handles are created and released properly.

    2. Trade Entry Logic

    • Entries respect trend defined by three MAs.
    • Entries only occur when price breaks above last swing high (long) or below last swing low (short).
    • Entries require no existing position in the same direction (position size management).
    • Fair Value Gap filter restricts entries to only when bullish/bearish FVG is detected (optional).
    • ADX disables entries when below threshold.
    • Trade entry volume calculated considering risk percentage and sl distance.

    3. Trailing Stop Management

    • Multiple trailing stop methods with checks to prevent overly frequent updates.
    • Proper updates to stop loss using market structure or ATR or hybrid method.
    • Correct use of MqlTradeRequest and OrderSend for SL modifications.

    4. Post-Close Cooldown

    • Function IsRecentPositionClose() checks deal history within cooldown seconds.
    • Prevents new entries immediately after a position closes for a configurable time.
    • Throttled print message every 60 seconds during cooldown for clarity.

    5. Losing Streak Calculation

    • Maintains global losing streak count by scanning recent closed trades on every tick.
    • Resets losing streak count daily.
    • Prevents trading when losing streak exceeds max allowed.

    6. Floating Risk Cap for Open Positions

    • Iterates open positions, closes any position if loss exceeds maxRiskPerTradePercent of account balance.

    7. Multi-Timeframe Usage

    • Uses separate timeframes for volatility ATR, swing identification, ADX filtering, etc.

    Minor Suggestions or Possible Improvements:

    • Error Handling for OrderSend
      Currently prints errors but could add retry or alternative handling if needed.

    • Cache Indicator Buffers
      Using global arrays and updating them each tick might be more efficient if you do large-copy requests (not critical here though).

    • Fine Tune FVG Detection
      Currently detects FVG based on only 3 candles. You might improve it by storing detected FVG zones and checking price interaction for better filtering.

    • Trailing Stop Interval
      You use seconds for trailing update interval, but some brokers/tickers may benefit from adaptive intervals scaled to volatility.

    • Losing Streak Persistence
      Consider storing losing streak in a file or global variable for persistent tracking after EA restarts.

    • Better Logging
      Logs on tick may produce many messages. Consider log level control or use event-based logging.


    Final checks:

    • Make sure to test in a strategy tester with 100% tick data.
    • Verify your broker allows the required stop level and volume steps.
    • If you use symbols with different digits (3, 5, 2, 4), check all NormalizeDouble use matches digits.
    • Test with and without reverse entries, with different trailing stop modes.

    If you want, I can help you write specific improvements, specific features like persistence, or add debugging functions.


    Summary

    Your EA code is a complete, multi-filter, multi-timeframe Break-of-Structure strategy with solid risk management, cooldowns, trailing stops, and entry filters. It should compile and work as intended.

    Feel free to ask for detailed help on testing, improvements, or adding more features!

  3. User

    explain entry in reverse mode

  4. Assistant

    Certainly! Let me explain how the entry logic works when enableReverseEntries = true in your EA.


    Normal Entry Mode (enableReverseEntries = false)

    • Long entry criteria:

      • Current ask > lastSwingHigh (price breaks last swing high)
      • The trend is uptrend based on MAs (MA1 > MA2 > MA3 and price above middle MA)
      • No existing long position open
      • If FVG filter enabled, bullish FVG detected (fvgSignal == 1)
    • Short entry criteria:

      • Current bid < lastSwingLow (price breaks last swing low)
      • The trend is downtrend based on MAs (MA1 < MA2 < MA3 and price below middle MA)
      • No existing short position open
      • If FVG filter enabled, bearish FVG detected (fvgSignal == -1)

    Reverse Entry Mode (enableReverseEntries = true)

    When reverse entries are enabled, your EA inverts the trend condition in entry signals:

    • Reverse SELL entry criteria:

      • Price breaks above last swing high (ask > lastSwingHigh), which normally suggests bullish price action.
      • But trend is downtrend (instead of uptrend).
      • No existing short position.
      • If FVG filter enabled, bearish FVG detected (fvgSignal == -1).
      • Then EA enters a short position against the prevailing downtrend signal.
    • Reverse BUY entry criteria:

      • Price breaks below last swing low (bid < lastSwingLow), which normally suggests bearish price action.
      • But trend is uptrend.
      • No existing long position.
      • If FVG filter enabled, bullish FVG detected (fvgSignal == 1).
      • Then EA enters a long position against the prevailing uptrend signal.

    What does this mean realistically?

    • Normal mode entries follow the classic "break of structure + trend alignment + confirmation by FVG" rule.

    • Reverse mode entries act on "fake breakouts" or counter-trend signals:

      • For example, price breaking above a previous swing high but the longer-term trend is down — the EA shorts expecting the break to fail and the price to revert.
      • Or price breaking below a previous swing low but the trend is up — the EA buys expecting a reversal instead of continuation.

    Code snippet illustrating this:

    if(!enableReverseEntries)
    {
        if(ask > lastSwingHigh && is_uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
        {
            // Normal BUY entry on break of high with uptrend
        }
        else if(bid < lastSwingLow && is_downtrend && !IsPositionOpen(POSITION_TYPE_SELL))
        {
            // Normal SELL entry on break of low with downtrend
        }
    }
    else // Reverse entries enabled
    {
        if(ask > lastSwingHigh && is_downtrend && !IsPositionOpen(POSITION_TYPE_SELL))
        {
            // Reverse SELL entry: price breaks high but trend is down → short expecting reversal.
        }
        else if(bid < lastSwingLow && is_uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
        {
            // Reverse BUY entry: price breaks low but trend is up → long expecting reversal.
        }
    }
    

    Why use reverse entries?

    • To catch false breakouts or exhaustion moves.
    • To profit on price rejections at key structure levels (swing highs/lows) even if the broader trend is opposite.
    • Sometimes counter-trend setups yield good risk/reward.

    Summary:

    ConditionNormal mode entryReverse mode entry
    Breaks swing highEnter long if trend is upEnter short if trend is down
    Breaks swing lowEnter short if trend is downEnter long if trend is up

    If you want, I can help you visualize or backtest specifically just the reverse entries to see how they behave.


    Let me know if you want a more detailed explanation or how this fits into your overall strategy logic!

  5. User

    tell me only reverse mode and fvg filter on. dont say anithing about normal mode

  6. Assistant

    Sure! Here’s how the entry logic works in reverse mode when the Fair Value Gap (FVG) filter is enabled:


    Reverse Entry with FVG Filter Enabled

    • Reverse SELL entry:

      • Price breaks above the last swing high (ask > lastSwingHigh)
      • The trend is downtrend (based on MAs)
      • No existing short position open
      • A bearish Fair Value Gap is detected (fvgSignal == -1)
      • The EA enters a short position expecting a reversal from the failed breakout.
    • Reverse BUY entry:

      • Price breaks below the last swing low (bid < lastSwingLow)
      • The trend is uptrend
      • No existing long position open
      • A bullish Fair Value Gap is detected (fvgSignal == 1)
      • The EA enters a long position expecting a reversal from the failed breakdown.

    Summary

    Price actionTrendFVG requiredAction
    Price breaks above swing highDowntrendBearish FVG (-1)Enter short
    Price breaks below swing lowUptrendBullish FVG (1)Enter long

    The EA only enters reverse trades that align with a corresponding Fair Value Gap to increase the probability of a valid reversal.

  7. User

    in what order filter ? example: 1 trend, 2 fvg 3 break

  8. Assistant

    In the EA's reverse mode with FVG filter enabled, the filters and conditions are applied in this logical order before entering a trade:

    1. Trend filter:
      Check the current trend based on the 3 EMAs to confirm it’s a downtrend (for reverse sell) or uptrend (for reverse buy).

    2. Price break condition:
      Check if price breaks the relevant structure level:

      • For reverse sell: price breaks above last swing high.
      • For reverse buy: price breaks below last swing low.
    3. Fair Value Gap (FVG) filter:
      Confirm that a corresponding FVG exists on the swing timeframe:

      • For reverse sell: bearish FVG detected.
      • For reverse buy: bullish FVG detected.
    4. Position check:
      Confirm there is no existing position in the same direction.

    5. If all above pass, enter the reverse trade.


    Summary sequence for reverse entry:

    Trend direction --> Price break structure --> FVG filter --> Position availability --> Place trade
    

    This order ensures the trade is only opened if all filters align properly for a higher-probability reverse setup.

  9. User

    what i want: is uptrend price break low, bullish fvg apear, then buy

  10. Assistant

    Got it! You want this specific reverse entry setup:

    • Trend: Uptrend (MA1 > MA2 > MA3)
    • Price: Breaks below the last swing low (price dips under swing low)
    • Fair Value Gap: Bullish FVG detected
    • Action: Enter a BUY (long) trade expecting reversal

    How it works in your EA (reverse mode with FVG ON):

    1. Confirm uptrend: moving averages indicate an uptrend.
    2. Detect price has broken below last swing low.
    3. Detect a bullish Fair Value Gap (FVG signal == 1).
    4. Confirm no existing long position.
    5. Place a BUY order.

    Code-check snippet from your EA for reference (reverse buy):

    if(enableReverseEntries)
    {
        if(bid < lastSwingLow && is_uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
        {
            if(!useFairValueGapFilter || fvgSignal == 1)
            {
                // Place buy order here
            }
        }
    }
    

    Summary:

    ConditionRequiredAction
    TrendUptrend (MA1 > MA2 > MA3)—
    Price actionBreaks below last swing low—
    Fair Value Gap (FVG) filterBullish FVG detected (fvgSignal == 1)—
    No existing long positionConfirm no open buy positions—
    ThenBUY trade entered expecting reversalBuy order placed

    If you want I can help you simplify or highlight just this part or add extra alerts for this exact setup!

  11. User

    m1 timeframe example: trend up, 7:27 candle low 19836.7 , 7:32 candle low 19836.45 break previous low (19836.7). 7:34 candle low 19843.7, bullish fvg created. why no trades open?

  12. Assistant

    Let's analyze your example carefully to figure out why no trade is opened, based on your EA's reverse mode with FVG filter ON and on M1 timeframe:


    Your scenario:

    • Timeframe: M1
    • Trend: uptrend (MA1 > MA2 > MA3)
    • 7:27 candle low = 19836.7
    • 7:32 candle low = 19836.45 (breaks previous low 19836.7)
    • 7:34 candle low = 19843.7 (higher than 7:32 low, creates bullish FVG)
    • Expected: Buy trade triggered following reverse logic — price broke below swing low, bullish FVG formed, uptrend confirmed.

    Reasons why EA might not open trades in this situation

    1. Entry candle timing vs cooldowns

    • The EA requires one trade per cooldown candle (cooldown per candle on swingTF).
    • The EA uses the last closed candle for cooldown check (CopyRates(..., 1, 1, ...))
    • If lastTradeCandleTime matches current candle time, no trade opens (candle cooldown not expired).
    • Also, there is a minimum time interval cooldown (tradeIntervalSeconds = 180 by default) between trades.
    • So check that minimum time between trades passed and that cooldown candle changed since last entry.

    2. Swing Low Break Detection

    • You say 7:32 candle low (19836.45) breaks 7:27 low (19836.7) → but your EA finds structure lows over last N bars (swingLookback = 20).
    • It calls iLowest(_Symbol, swingTF, MODE_LOW, swingLookback, 1) to find the swing low.
    • The swing low is recalculated on every tick, possibly the swing low is no longer 19836.7, or the EA expects break above/below the last swing low detected at a certain position (shift).
    • If swing low line (lastSwingLow) returned by EA is not 19836.7 for example, then condition bid < lastSwingLow may not be true at time of tick.

    3. FVG Detection Timing and Parameters

    • DetectFairValueGap(swingTF, 1) copies 3 bars starting at shift=1 (i.e. bars 1, 2, 3 bars back from current bar).
    • The bullish FVG requires candle1 high < candle3 low.
    • Check if the bullish FVG really matches the range of candles 7:27 to 7:34 with correct indices.
    • If the bullish FVG is detected at shift=1, then condition passes; otherwise no trade.

    4. Trend Confirmation

    • The MAs for trend are calculated on maTimeframe = PERIOD_M15.
    • Are you sure the M15 MA trend is up at that time?
    • Because the EA conditions:
      is_uptrend = (MA1 > MA2) && (MA2 > MA3) && (ask > MA2)
      
      where MAs are on M15 timeframe. If M15 is not definitively in uptrend, trade won't trigger.

    5. Position Open State

    • Is there already an open position of the same type?
    • EA prevents duplicate trades in same direction.

    6. Trade Hours

    • Check that system time (7:34) falls between tradeStartHour=7 and tradeEndHour=22.

    7. Post-close cooldown or max losing streak or max daily loss filters

    • Post-close cooldown active? (No trades allowed shortly after a close.)
    • Losing streak exceeded?
    • Max daily loss exceeded?
    • These filters will skip entries silently.

    8. Lot size calculation

    • If lot calculated is less than minimum lot size, trade is skipped.

    How to debug this?

    • Add detailed Print() logs within OnTick() before trade entry conditions to output:

      • Current swing low (lastSwingLow) and current bid.
      • Whether bid < lastSwingLow condition is true.
      • Current MA values and is_uptrend value.
      • FVG detection result and detected candles values.
      • Timestamps of cooldown checks.
      • Lot size value.
      • Any filter that blocks trades in this tick.

    Summary checklist for your case

    Check ItemVerify
    M15 trend upMAs confirms uptrend at 7:34
    swing low pricelastSwingLow equals 19836.7 or correct swing low
    price breakbid < lastSwingLow is true at 7:32/7:34
    FVG detectionDetectFairValueGap(swingTF,1) returns 1 (bullish) for bars surrounding 7:27–7:34
    Cooldown per candleThis is a new candle compared to lastTradeCandleTime
    Minimum interval cooldownAt least tradeIntervalSeconds seconds passed since last trade open
    Post-close cooldownNo recent position close within postCloseCooldownSeconds
    Max losing streakNot exceeded
    Max daily lossNot exceeded
    Lot sizeCalculated lot >= minimum volume
    No open buy positionsNo existing buy position open
    Trading hoursCurrent time within tradeStartHour and tradeEndHour

    Quick tip:

    To test this precise scenario:

    • Temporarily disable cooldown filters (postCloseCooldownSeconds=0, tradeIntervalSeconds=0, maxLosingStreak=0, etc.).
    • Print key variable values every tick to verify logic.
    • Confirm MAs loaded properly.
    • Manually check FVG detection output at the exact candle shifts.

    If you want, I can help you add those debug prints or walk you through simulating this in the strategy tester or with a script.

  13. User

    add those debug prints

  14. Assistant

    Certainly! Below is a set of debug Print() statements added at key points in your OnTick() function, focused on your described issue — especially around trend, swing low, price break, FVG detection, cooldowns, and trade conditions. This will help you identify why a trade is not opening in your specific scenario.


    Add these debug prints inside your existing OnTick() just before the trade entry logic and cooldown checks:

    Find the block around where you get lastSwingLow, check trend, get FVG signal, and before you check entry conditions. Insert code like this:

    // After calculating swing lows/highs and before trade logic
    
    PrintFormat("*** DEBUG: Time=%s ***", TimeToString(TimeCurrent(), TIME_SECONDS));
    
    // Trend info
    PrintFormat("MA1=%.5f MA2=%.5f MA3=%.5f is_uptrend=%s is_downtrend=%s",
                MA1, MA2, MA3,
                (is_uptrend ? "true" : "false"),
                (is_downtrend ? "true" : "false"));
    
    // Swing levels
    PrintFormat("Last swing high: %.5f, last swing low: %.5f", lastSwingHigh, lastSwingLow);
    
    // Current prices
    PrintFormat("Ask=%.5f Bid=%.5f", ask, bid);
    
    // Price break checks
    PrintFormat("Bid < lastSwingLow? %s", (bid < lastSwingLow) ? "true" : "false");
    PrintFormat("Ask > lastSwingHigh? %s", (ask > lastSwingHigh) ? "true" : "false");
    
    // FVG detection details
    if(useFairValueGapFilter)
    {
        PrintFormat("FVG signal: %d (-1 bearish, 0 none, 1 bullish)", fvgSignal);
    
        // Optionally show detailed candles used for FVG (debug)
        MqlRates bars[3];
        if(CopyRates(_Symbol, swingTF, 1, 3, bars) == 3)
        {
            PrintFormat("FVG candles times (shift 1..3): %s, %s, %s",
                        TimeToString(bars[0].time, TIME_SECONDS),
                        TimeToString(bars[1].time, TIME_SECONDS),
                        TimeToString(bars[2].time, TIME_SECONDS));
            PrintFormat("Candle1 High=%.5f Low=%.5f", bars[0].high, bars[0].low);
            PrintFormat("Candle3 High=%.5f Low=%.5f", bars[2].high, bars[2].low);
        }
    }
    else
    {
        Print("FVG filter disabled");
    }
    
    // Cooldown info
    PrintFormat("LastTradeCandleTime=%s CurrentCandleTime=%s", TimeToString(lastTradeCandleTime), TimeToString(currentCandleTime));
    PrintFormat("LastTradeOpenTime=%s Now=%s (diff=%d seconds)",
                TimeToString(lastTradeOpenTime),
                TimeToString(now),
                (int)(now - lastTradeOpenTime));
    
    // Post-close cooldown active?
    if(postCloseCooldownSeconds > 0 && IsRecentPositionClose(postCloseCooldownSeconds))
        Print("Post-close cooldown is active, skipping trades");
    
    // Losing streak info
    PrintFormat("Current losing streak: %d Max losing streak allowed: %d",
                g_currentLosingStreak, maxLosingStreak);
    
    // Max daily loss check
    PrintFormat("Initial equity: %.2f Current equity: %.2f Max daily loss allowed: %.2f",
                g_initialEquity, AccountInfoDouble(ACCOUNT_EQUITY), maxDailyLossAmount);
    
    // Lot size
    PrintFormat("Calculated lot size: %.2f Min lot size: %.2f", lot, SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN));
    

    Also add a debug print inside each trade open block, e.g.:

    For example, inside reverse BUY entry block:

    if(bid < lastSwingLow && is_uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
    {
        if(!useFairValueGapFilter || fvgSignal == 1)
        {
            Print("Conditions met for reverse BUY entry, sending order...");
            // existing order send code here...
        }
        else
        {
            Print("Reverse BUY conditions met but FVG signal mismatch. FVG signal: ", fvgSignal);
        }
    }
    else
    {
        Print("Reverse BUY conditions not met: ");
        if(!(bid < lastSwingLow)) Print(" - Price not below last swing low");
        if(!is_uptrend) Print(" - Trend not up");
        if(IsPositionOpen(POSITION_TYPE_BUY)) Print(" - Buy position already open");
    }
    

    Similarly for reverse SELL and normal entries if you want.


    How to use this:

    • Compile and run EA with these prints.
    • Watch the Experts or Journal tab logs.
    • Check the printed values for trend, swing low, price breaks, FVG signal, cooldown timers.
    • Identify what condition is stopping the trade from triggering.
    • For example, if bid < lastSwingLow is false or is_uptrend false or FVG signal not 1, this will be explicit.
    • Cooldowns or lot size too low will also show clearly.

    If you want, I can prepare a patched full OnTick() snippet with these debug prints integrated exactly to your existing code — just ask.

  15. User

    complete ea code just to compile

  16. Assistant

    Certainly! Below is your complete EA code with the requested debug Print() statements added into the OnTick() function before trade entries and cooldown checks.
    I carefully integrated the debug prints, preserving all your original logic and structure. This full code should compile as-is in MetaEditor.


    //+------------------------------------------------------------------+
    //|   Break of Structure EA with floating risk cap (full, compile)   |
    //|            Added ADX filter and Losing Streak filter             |
    //|      Added cooldown per candle & minimum time interval cooldown  |
    //|    Improved cooldown after close - scanning recent closed deals  |
    //|        Added Fair Value Gap (FVG) filter for entry signals       |
    //+------------------------------------------------------------------+
    #property copyright ""
    #property version   "1.6"
    #property strict
    #include <Trade\Trade.mqh>
    
    input double      inpLot                 = 0.05;
    input bool        useRiskPercent         = true;
    input double      riskPercent            = 1.0;   // Position risk % per trade
    input int         sl_atr_mult            = 3;
    input double      r2r_ratio              = 2.0;
    input ENUM_TIMEFRAMES volatilityTF       = PERIOD_M5;
    input int         atrPeriod              = 14;
    input int         swingLookback          = 20;
    input ENUM_TIMEFRAMES swingTF            = PERIOD_M1;
    
    // Shortest-term MA (existing)
    input int         maPeriod               = 50;
    input ENUM_TIMEFRAMES maTimeframe        = PERIOD_M15;
    
    // Medium-term MA (new)
    input int         maPeriod2              = 100;
    input ENUM_TIMEFRAMES maTimeframe2       = PERIOD_M15;
    
    // Long-term MA (new)
    input int         maPeriod3              = 200;
    input ENUM_TIMEFRAMES maTimeframe3       = PERIOD_M15;
    
    input int         tradeStartHour         = 7;
    input int         tradeEndHour           = 22;
    input int         maxPositions           = 1;
    input uint        inpMagicNumber         = 123456;
    
    input bool        enableTrailingSL       = true;
    
    enum ENUM_TrailingStopMode
    {
       TrailingNone = 0,
       TrailingMarketStructure = 1,
       TrailingATR = 2,
       TrailingHybrid = 3
    };
    input ENUM_TrailingStopMode trailingStopMode = TrailingHybrid;
    input int    ms_swingLookback   = 20;
    input double atr_trail_mult     = 2.5;
    input uint   TrailUpdateIntervalSec    = 15;
    input double MinSLBufferATRMult        = 1.0;
    input double TrailingProfitTriggerPerc = 0.5;
    input bool   enableReverseEntries      = true;
    input double maxRiskPerTradePercent    = 1.0;  // Floating loss cap only!
    input double maxDailyLossAmount        = 350.0;
    
    // --- ADX filter inputs ---
    input int    adxPeriod       = 14;              // ADX period
    input double adxThreshold    = 25.0;            // ADX minimum threshold to allow trading
    input ENUM_TIMEFRAMES adxTimeframe = PERIOD_M15; // ADX timeframe to use for filtering
    
    // --- Losing streak inputs ---
    input int maxLosingStreak = 3;   // Max consecutive losing trades allowed
    
    // --- POST-CLOSE COOLDOWN ---
    input int postCloseCooldownSeconds = 180; // Cooldown seconds after a position closes before new trades allowed.
    
    // --- Fair Value Gap filter input ---
    input bool useFairValueGapFilter = true;  // Enable Fair Value Gap filter for entries
    
    CTrade trade;
    
    int ma_handle = INVALID_HANDLE;
    int ma_handle2 = INVALID_HANDLE;    // Medium-term MA handle
    int ma_handle3 = INVALID_HANDLE;    // Long-term MA handle
    int atr_handle = INVALID_HANDLE;
    int adx_handle = INVALID_HANDLE;  // ADX handle
    
    string swingHighLineName = "SwingHighLine";
    string swingLowLineName  = "SwingLowLine";
    
    struct TrailingUpdateInfo
    {
       ulong position_ticket;
       datetime last_update;
    };
    TrailingUpdateInfo g_trailingUpdateInfo[];
    
    static double g_initialEquity = 0.0;
    static datetime g_lastResetDay = 0;
    
    static int g_currentLosingStreak = 0;
    static datetime g_lastLosingStreakResetDay = 0;
    static ulong g_lastHistoryTickTime = 0;
    
    // *** Cooldown globals ***
    datetime lastTradeCandleTime = 0;                 // last candle time when trade opened
    ENUM_TIMEFRAMES cooldownTimeframe = swingTF;      // timeframe for candle cooldown
    
    datetime lastTradeOpenTime = 0;                    // last trade open timestamp
    int tradeIntervalSeconds = 180;                     // min seconds between trades
    
    //+------------------------------------------------------------------+
    void ResetDailyEquityIfNewDay()
    {
        datetime now = TimeCurrent();
        MqlDateTime tm;
        TimeToStruct(now, tm);
    
        MqlDateTime todayMidnight = {};
        todayMidnight.year = tm.year;
        todayMidnight.mon  = tm.mon;
        todayMidnight.day  = tm.day;
        todayMidnight.hour = 0;
        todayMidnight.min  = 0;
        todayMidnight.sec  = 0;
        datetime midnightTime = StructToTime(todayMidnight);
    
        if(g_lastResetDay != midnightTime)
        {
            g_lastResetDay = midnightTime;
            g_initialEquity = AccountInfoDouble(ACCOUNT_EQUITY);
            PrintFormat("Daily equity reset at %s new initialEquity=%.2f", TimeToString(now, TIME_DATE|TIME_SECONDS), g_initialEquity);
        }
    }
    //+------------------------------------------------------------------+
    void ResetLosingStreakIfNewDay()
    {
        datetime now = TimeCurrent();
        MqlDateTime tm;
        TimeToStruct(now, tm);
    
        MqlDateTime todayMidnight = {};
        todayMidnight.year = tm.year;
        todayMidnight.mon = tm.mon;
        todayMidnight.day = tm.day;
        todayMidnight.hour = 0;
        todayMidnight.min = 0;
        todayMidnight.sec = 0;
    
        datetime midnightTime = StructToTime(todayMidnight);
    
        if(g_lastLosingStreakResetDay != midnightTime)
        {
            g_lastLosingStreakResetDay = midnightTime;
            g_currentLosingStreak = 0;
            PrintFormat("Losing streak reset at new day %s", TimeToString(now, TIME_DATE|TIME_SECONDS));
        }
    }
    //+------------------------------------------------------------------+
    void UpdateLosingStreak()
    {
        datetime now = TimeCurrent();
    
        if(!HistorySelect(now - 86400, now))
        {
            Print("HistorySelect failed");
            return;
        }
    
        ulong maxClosedTime = 0;
        int total = HistoryDealsTotal();
    
        for(int i = total - 1; i >= 0; i--)
        {
            ulong ticket = HistoryDealGetTicket(i);
            datetime closeTime = (datetime)HistoryDealGetInteger(ticket, DEAL_TIME);
    
            if(closeTime <= g_lastHistoryTickTime)
                continue;
    
            maxClosedTime = MathMax(maxClosedTime, (ulong)closeTime);
    
            string symbol = HistoryDealGetString(ticket, DEAL_SYMBOL);
            ulong magic = HistoryDealGetInteger(ticket, DEAL_MAGIC);
    
            if(symbol != _Symbol || magic != inpMagicNumber)
                continue;
    
            long entryType = HistoryDealGetInteger(ticket, DEAL_ENTRY);
    
            if(entryType != DEAL_ENTRY_OUT)
                continue;
    
            double profit = HistoryDealGetDouble(ticket, DEAL_PROFIT);
    
            if(profit < 0)
            {
                g_currentLosingStreak++;
                PrintFormat("Losing trade detected (ticket %I64d, profit %.2f). Current losing streak: %d", ticket, profit, g_currentLosingStreak);
            }
            else
            {
                if(g_currentLosingStreak > 0)
                    PrintFormat("Winning trade detected (ticket %I64d, profit %.2f). Resetting losing streak.", ticket, profit);
                g_currentLosingStreak = 0;
            }
        }
    
        if(maxClosedTime > 0)
            g_lastHistoryTickTime = maxClosedTime;
    }
    //+------------------------------------------------------------------+
    double CalculateLotSize(double sl_distance_price)
    {
       double balance = AccountInfoDouble(ACCOUNT_BALANCE);
       if(balance <= 0 || sl_distance_price <= 0)
          return inpLot;
    
       if(!useRiskPercent)
       {
          double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
          double min_lot  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
          double max_lot  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
          double lot = inpLot;
          if(lot < min_lot) lot = min_lot;
          if(lot > max_lot) lot = max_lot;
          lot = MathFloor(lot / lot_step) * lot_step;
          return lot;
       }
       else
       {
          double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
          double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
          double contract_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_CONTRACT_SIZE);
    
          if(tick_value <= 0 || tick_size <= 0 || contract_size <= 0)
             return inpLot;
    
          double point_value = tick_value / tick_size;
          double calculatedLot = (balance * (riskPercent / 100.0)) / (sl_distance_price * point_value * contract_size);
    
          if(calculatedLot <= 0)
             return inpLot;
    
          double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
          double min_lot  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
          double max_lot  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
    
          double lot = MathFloor(calculatedLot / lot_step) * lot_step;
    
          if(lot < min_lot) lot = min_lot;
          if(lot > max_lot) lot = max_lot;
          return lot;
       }
    }
    //+------------------------------------------------------------------+
    bool IsPositionOpen(ENUM_POSITION_TYPE type)
    {
       int total = PositionsTotal();
       for(int i = 0; i < total; i++)
       {
          ulong ticket = PositionGetTicket(i);
          if(PositionSelectByTicket(ticket))
          {
             if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
             {
                ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
                if(pos_type == type)
                   return true;
             }
          }
       }
       return false;
    }
    //+------------------------------------------------------------------+
    bool CanUpdateTrailing(ulong ticket)
    {
       datetime now = TimeCurrent();
       int count = ArraySize(g_trailingUpdateInfo);
       for(int i=0; i<count; i++)
       {
          if(g_trailingUpdateInfo[i].position_ticket == ticket)
          {
             if(now - g_trailingUpdateInfo[i].last_update < (int)TrailUpdateIntervalSec)
                return false;
             g_trailingUpdateInfo[i].last_update = now;
             return true;
          }
       }
       ArrayResize(g_trailingUpdateInfo, count + 1);
       g_trailingUpdateInfo[count].position_ticket = ticket;
       g_trailingUpdateInfo[count].last_update = now;
       return true;
    }
    //+------------------------------------------------------------------+
    void UpdateTrailingStopByMarketStructure(ulong position_ticket)
    {
        if(!PositionSelectByTicket(position_ticket))
            return;
    
        ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
        double current_sl = PositionGetDouble(POSITION_SL);
        double current_tp = PositionGetDouble(POSITION_TP);
        double entry_price = PositionGetDouble(POSITION_PRICE_OPEN);
        string symbol = PositionGetString(POSITION_SYMBOL);
    
        if(current_tp <= 0)
            return;
    
        if(!CanUpdateTrailing(position_ticket))
            return;
    
        double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
        int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
    
        double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
        double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
        if(bid <= 0 || ask <= 0)
            return;
    
        if(pos_type == POSITION_TYPE_BUY)
        {
            double half_tp_level = entry_price + 0.5 * (current_tp - entry_price);
            if(bid < half_tp_level)
                return;
    
            int lowestBar = iLowest(symbol, PERIOD_CURRENT, MODE_LOW, ms_swingLookback, 0);
            if(lowestBar < 0)
                return;
    
            double swing_low = iLow(symbol, PERIOD_CURRENT, lowestBar);
            double buffer = 2 * point;
            double new_sl = NormalizeDouble(swing_low - buffer, digits);
    
            if(new_sl > current_sl && new_sl < entry_price)
            {
                MqlTradeRequest req = {};
                MqlTradeResult res = {};
                req.action = TRADE_ACTION_SLTP;
                req.position = position_ticket;
                req.symbol = symbol;
                req.sl = new_sl;
                req.tp = current_tp;
                req.deviation = 10;
    
                if(!OrderSend(req, res))
                    PrintFormat("Failed to update trailing SL for position %I64d, error %d", position_ticket, GetLastError());
                else if(res.retcode != TRADE_RETCODE_DONE)
                    PrintFormat("Trailing SL update rejected for position %I64d, retcode %d", position_ticket, res.retcode);
                else
                    PrintFormat("Trailing SL moved up for position %I64d: new SL=%.5f", position_ticket, new_sl);
            }
        }
        else if(pos_type == POSITION_TYPE_SELL)
        {
            double half_tp_level = entry_price - 0.5 * (entry_price - current_tp);
            if(ask > half_tp_level)
                return;
    
            int highestBar = iHighest(symbol, PERIOD_CURRENT, MODE_HIGH, ms_swingLookback, 0);
            if(highestBar < 0)
                return;
    
            double swing_high = iHigh(symbol, PERIOD_CURRENT, highestBar);
            double buffer = 2 * point;
            double new_sl = NormalizeDouble(swing_high + buffer, digits);
    
            if(new_sl < current_sl && new_sl > entry_price)
            {
                MqlTradeRequest req = {};
                MqlTradeResult res = {};
                req.action = TRADE_ACTION_SLTP;
                req.position = position_ticket;
                req.symbol = symbol;
                req.sl = new_sl;
                req.tp = current_tp;
                req.deviation = 10;
    
                if(!OrderSend(req, res))
                    PrintFormat("Failed to update trailing SL for position %I64d, error %d", position_ticket, GetLastError());
                else if(res.retcode != TRADE_RETCODE_DONE)
                    PrintFormat("Trailing SL update rejected for position %I64d, retcode %d", position_ticket, res.retcode);
                else
                    PrintFormat("Trailing SL moved down for position %I64d: new SL=%.5f", position_ticket, new_sl);
            }
        }
    }
    //+------------------------------------------------------------------+
    void UpdateTrailingStopByATR(ulong position_ticket)
    {
        if(!PositionSelectByTicket(position_ticket))
            return;
    
        ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
        double current_sl = PositionGetDouble(POSITION_SL);
        double entry_price = PositionGetDouble(POSITION_PRICE_OPEN);
        string symbol = PositionGetString(POSITION_SYMBOL);
    
        if(!CanUpdateTrailing(position_ticket))
            return;
    
        double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
        int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
    
        double atr_buf[];
        if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0)
            return;
        double atr = atr_buf[0];
        if(atr <= 0)
            return;
    
        double current_price = (pos_type == POSITION_TYPE_BUY) ? SymbolInfoDouble(symbol, SYMBOL_BID) 
                                                               : SymbolInfoDouble(symbol, SYMBOL_ASK);
        if(current_price <= 0) return;
    
        double new_sl = 0;
        if(pos_type == POSITION_TYPE_BUY)
        {
            new_sl = NormalizeDouble(current_price - atr * atr_trail_mult, digits);
            double min_sl_dist = atr * MinSLBufferATRMult;
            if(new_sl < (current_price - min_sl_dist))
                new_sl = current_price - min_sl_dist;
    
            if(new_sl > current_sl && new_sl < current_price)
            {
                MqlTradeRequest req={};
                MqlTradeResult res={};
                req.action = TRADE_ACTION_SLTP;
                req.position = position_ticket;
                req.symbol = symbol;
                req.sl = new_sl;
                req.tp = PositionGetDouble(POSITION_TP);
                req.deviation = 10;
    
                if(!OrderSend(req, res))
                    PrintFormat("ATR trailing SL update failed for position %I64d, error %d", position_ticket, GetLastError());
                else if(res.retcode != TRADE_RETCODE_DONE)
                    PrintFormat("ATR trailing SL update rejected for position %I64d, retcode %d", position_ticket, res.retcode);
                else
                    PrintFormat("ATR trailing SL moved up for position %I64d: new SL=%.5f", position_ticket, new_sl);
            }
        }
        else if(pos_type == POSITION_TYPE_SELL)
        {
            new_sl = NormalizeDouble(current_price + atr * atr_trail_mult, digits);
            double min_sl_dist = atr * MinSLBufferATRMult;
            if(new_sl > (current_price + min_sl_dist))
                new_sl = current_price + min_sl_dist;
    
            if(new_sl < current_sl && new_sl > current_price)
            {
                MqlTradeRequest req={};
                MqlTradeResult res={};
                req.action = TRADE_ACTION_SLTP;
                req.position = position_ticket;
                req.symbol = symbol;
                req.sl = new_sl;
                req.tp = PositionGetDouble(POSITION_TP);
                req.deviation = 10;
    
                if(!OrderSend(req, res))
                    PrintFormat("ATR trailing SL update failed for position %I64d, error %d", position_ticket, GetLastError());
                else if(res.retcode != TRADE_RETCODE_DONE)
                    PrintFormat("ATR trailing SL update rejected for position %I64d, retcode %d", position_ticket, res.retcode);
                else
                    PrintFormat("ATR trailing SL moved down for position %I64d: new SL=%.5f", position_ticket, new_sl);
            }
        }
    }
    //+------------------------------------------------------------------+
    void UpdateTrailingStopHybrid(ulong position_ticket)
    {
       if(!PositionSelectByTicket(position_ticket))
          return;
    
       if(!CanUpdateTrailing(position_ticket))
          return;
    
       ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
       double sl = PositionGetDouble(POSITION_SL);
       double tp = PositionGetDouble(POSITION_TP);
       double entry_price = PositionGetDouble(POSITION_PRICE_OPEN);
       string symbol = PositionGetString(POSITION_SYMBOL);
    
       double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
       int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
    
       double atr_buf[];
       if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0)
          return;
       double atr = atr_buf[0];
       if(atr <= 0)
          return;
    
       double min_sl_distance = atr * MinSLBufferATRMult;
       double initial_sl_dist = MathAbs(entry_price - sl);
       if(initial_sl_dist <= 0) initial_sl_dist = atr * sl_atr_mult;
    
       double current_price = (pos_type == POSITION_TYPE_BUY) ? SymbolInfoDouble(symbol, SYMBOL_BID)
                                                       : SymbolInfoDouble(symbol, SYMBOL_ASK);
       if(current_price <= 0) return;
    
       double move_in_profit = (pos_type == POSITION_TYPE_BUY) ? (current_price - entry_price) : (entry_price - current_price);
       if(move_in_profit < TrailingProfitTriggerPerc * initial_sl_dist)
          return;
    
       double ms_new_sl = 0;
       bool ms_sl_valid = false;
       if(pos_type == POSITION_TYPE_BUY)
       {
          int lowestBar = iLowest(symbol, PERIOD_CURRENT, MODE_LOW, ms_swingLookback, 0);
          if(lowestBar >= 0)
          {
             double swing_low = iLow(symbol, PERIOD_CURRENT, lowestBar);
             ms_new_sl = NormalizeDouble(swing_low - 2*point, digits);
             ms_sl_valid = (ms_new_sl > sl) && (ms_new_sl < entry_price);
          }
       }
       else if(pos_type == POSITION_TYPE_SELL)
       {
          int highestBar = iHighest(symbol, PERIOD_CURRENT, MODE_HIGH, ms_swingLookback, 0);
          if(highestBar >= 0)
          {
             double swing_high = iHigh(symbol, PERIOD_CURRENT, highestBar);
             ms_new_sl = NormalizeDouble(swing_high + 2*point, digits);
             ms_sl_valid = (ms_new_sl < sl) && (ms_new_sl > entry_price);
          }
       }
    
       double atr_new_sl = 0;
       if(pos_type == POSITION_TYPE_BUY)
       {
          atr_new_sl = NormalizeDouble(current_price - atr * atr_trail_mult, digits);
          atr_new_sl = MathMax(atr_new_sl, current_price - min_sl_distance);
          atr_new_sl = (atr_new_sl > sl && atr_new_sl < current_price) ? atr_new_sl : 0;
       }
       else if(pos_type == POSITION_TYPE_SELL)
       {
          atr_new_sl = NormalizeDouble(current_price + atr * atr_trail_mult, digits);
          atr_new_sl = MathMin(atr_new_sl, current_price + min_sl_distance);
          atr_new_sl = (atr_new_sl < sl && atr_new_sl > current_price) ? atr_new_sl : 0;
       }
    
       double new_sl = 0;
       if(ms_sl_valid && atr_new_sl > 0)
       {
          if(pos_type == POSITION_TYPE_BUY)
             new_sl = MathMax(ms_new_sl, atr_new_sl);
          else
             new_sl = MathMin(ms_new_sl, atr_new_sl);
       }
       else if(ms_sl_valid)
          new_sl = ms_new_sl;
       else if(atr_new_sl > 0)
          new_sl = atr_new_sl;
       else
          return;
    
       bool update_sl = false;
       if(pos_type == POSITION_TYPE_BUY)
          update_sl = (new_sl > sl && new_sl < current_price);
       else
          update_sl = (new_sl < sl && new_sl > current_price);
    
       if(update_sl)
       {
          MqlTradeRequest req={};
          MqlTradeResult res={};
          req.action = TRADE_ACTION_SLTP;
          req.position = position_ticket;
          req.symbol = symbol;
          req.sl = new_sl;
          req.tp = tp;
          req.deviation = 10;
    
          if(!OrderSend(req,res))
             PrintFormat("Trailing SL update failed for position %I64d, err=%d", position_ticket, GetLastError());
          else if(res.retcode != TRADE_RETCODE_DONE)
             PrintFormat("Trailing SL update rejected for position %I64d, retcode=%d", position_ticket, res.retcode);
          else
             PrintFormat("Trailing SL updated for position %I64d: old SL=%.5f new SL=%.5f", position_ticket, sl, new_sl);
       }
    }
    //+------------------------------------------------------------------+
    
    //-- Fair Value Gap detection function --
    // Returns:
    //  1 if bullish FVG detected (Candle1 High < Candle3 Low)
    // -1 if bearish FVG detected (Candle1 Low > Candle3 High)
    //  0 if no gap or error
    int DetectFairValueGap(ENUM_TIMEFRAMES timeframe, int startShift)
    {
       MqlRates bars[3];
       if(CopyRates(_Symbol, timeframe, startShift, 3, bars) != 3)
       {
          Print("DetectFairValueGap: failed to copy 3 bars");
          return 0;
       }
       
       double c1_high = bars[0].high;
       double c1_low  = bars[0].low;
       double c3_high = bars[2].high;
       double c3_low  = bars[2].low;
       
       if(c1_high < c3_low)
       {
          double gapBull = c3_low - c1_high;
          PrintFormat("Bullish Fair Value Gap detected between candle1 high %.5f and candle3 low %.5f (Gap %.5f)", c1_high, c3_low, gapBull);
          return 1;
       }
       
       if(c1_low > c3_high)
       {
          double gapBear = c1_low - c3_high;
          PrintFormat("Bearish Fair Value Gap detected between candle1 low %.5f and candle3 high %.5f (Gap %.5f)", c1_low, c3_high, gapBear);
          return -1;
       }
       
       return 0;
    }
    //+------------------------------------------------------------------+
    
    int OnInit()
    {
       ma_handle = iMA(_Symbol, maTimeframe, maPeriod, 0, MODE_EMA, PRICE_CLOSE);
       if(ma_handle == INVALID_HANDLE)
       {
          Print("Failed to create EMA handle");
          return INIT_FAILED;
       }
    
       ma_handle2 = iMA(_Symbol, maTimeframe2, maPeriod2, 0, MODE_EMA, PRICE_CLOSE);
       if(ma_handle2 == INVALID_HANDLE)
       {
          Print("Failed to create medium-term EMA handle");
          IndicatorRelease(ma_handle);
          return INIT_FAILED;
       }
    
       ma_handle3 = iMA(_Symbol, maTimeframe3, maPeriod3, 0, MODE_EMA, PRICE_CLOSE);
       if(ma_handle3 == INVALID_HANDLE)
       {
          Print("Failed to create long-term EMA handle");
          IndicatorRelease(ma_handle);
          IndicatorRelease(ma_handle2);
          return INIT_FAILED;
       }
    
       atr_handle = iATR(_Symbol, volatilityTF, atrPeriod);
       if(atr_handle == INVALID_HANDLE)
       {
          Print("Failed to create ATR handle");
          IndicatorRelease(ma_handle);
          IndicatorRelease(ma_handle2);
          IndicatorRelease(ma_handle3);
          return INIT_FAILED;
       }
    
       adx_handle = iADX(_Symbol, adxTimeframe, adxPeriod);
       if(adx_handle == INVALID_HANDLE)
       {
          Print("Failed to create ADX handle");
          IndicatorRelease(ma_handle);
          IndicatorRelease(ma_handle2);
          IndicatorRelease(ma_handle3);
          IndicatorRelease(atr_handle);
          return INIT_FAILED;
       }
    
       if(!ObjectCreate(0, swingHighLineName, OBJ_HLINE, 0, TimeCurrent(), 0))
       {
          Print("Failed to create swing high line");
          IndicatorRelease(ma_handle);
          IndicatorRelease(ma_handle2);
          IndicatorRelease(ma_handle3);
          IndicatorRelease(atr_handle);
          IndicatorRelease(adx_handle);
          return INIT_FAILED;
       }
       ObjectSetInteger(0, swingHighLineName, OBJPROP_COLOR, clrGreen);
       ObjectSetInteger(0, swingHighLineName, OBJPROP_WIDTH, 2);
       ObjectSetInteger(0, swingHighLineName, OBJPROP_BACK, true);
       ObjectSetInteger(0, swingHighLineName, OBJPROP_RAY_RIGHT, true);
    
       if(!ObjectCreate(0, swingLowLineName, OBJ_HLINE, 0, TimeCurrent(), 0))
       {
          Print("Failed to create swing low line");
          ObjectDelete(0, swingHighLineName);
          IndicatorRelease(ma_handle);
          IndicatorRelease(ma_handle2);
          IndicatorRelease(ma_handle3);
          IndicatorRelease(atr_handle);
          IndicatorRelease(adx_handle);
          return INIT_FAILED;
       }
       ObjectSetInteger(0, swingLowLineName, OBJPROP_COLOR, clrRed);
       ObjectSetInteger(0, swingLowLineName, OBJPROP_WIDTH, 2);
       ObjectSetInteger(0, swingLowLineName, OBJPROP_BACK, true);
       ObjectSetInteger(0, swingLowLineName, OBJPROP_RAY_RIGHT, true);
       return INIT_SUCCEEDED;
    }
    //+------------------------------------------------------------------+
    
    void OnDeinit(const int reason)
    {
       ObjectDelete(0, swingHighLineName);
       ObjectDelete(0, swingLowLineName);
    
       if(ma_handle != INVALID_HANDLE)
       {
          IndicatorRelease(ma_handle);
          ma_handle = INVALID_HANDLE;
       }
       if(ma_handle2 != INVALID_HANDLE)
       {
          IndicatorRelease(ma_handle2);
          ma_handle2 = INVALID_HANDLE;
       }
       if(ma_handle3 != INVALID_HANDLE)
       {
          IndicatorRelease(ma_handle3);
          ma_handle3 = INVALID_HANDLE;
       }
       if(atr_handle != INVALID_HANDLE)
       {
          IndicatorRelease(atr_handle);
          atr_handle = INVALID_HANDLE;
       }
       if(adx_handle != INVALID_HANDLE)
       {
          IndicatorRelease(adx_handle);
          adx_handle = INVALID_HANDLE;
       }
    }
    //+------------------------------------------------------------------+
    
    // Static variables to throttle print frequency
    static datetime lastFvgNoTradePrintCandle = 0;
    static datetime lastAdxBelowThresholdPrintCandle = 0;
    static datetime lastPostCloseCooldownPrintTime = 0;
    
    void OnTick()
    {
        datetime now = TimeCurrent();
    
        // Post-close cooldown message throttled (once every 60s)
        if(postCloseCooldownSeconds > 0 && IsRecentPositionClose(postCloseCooldownSeconds))
        {
            if (now - lastPostCloseCooldownPrintTime >= 60)
            {
                PrintFormat("Post-close cooldown active, skipping trades at %s", TimeToString(now));
                lastPostCloseCooldownPrintTime = now;
            }
            return;
        }
        else
        {
            lastPostCloseCooldownPrintTime = 0;
        }
    
        ResetDailyEquityIfNewDay();
        ResetLosingStreakIfNewDay();
    
        UpdateLosingStreak();
    
        if(maxLosingStreak > 0 && g_currentLosingStreak >= maxLosingStreak)
        {
            PrintFormat("Current losing streak %d >= max allowed %d. No new trades allowed now.", g_currentLosingStreak, maxLosingStreak);
            return;
        }
    
        if(g_initialEquity == 0.0)
            g_initialEquity = AccountInfoDouble(ACCOUNT_EQUITY);
    
        double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
        double equityDrawdown = g_initialEquity - currentEquity;
    
        if(equityDrawdown >= maxDailyLossAmount)
        {
            PrintFormat("Max combined daily loss $%.2f exceeded (drawdown=%.2f). No new trades allowed.", maxDailyLossAmount, equityDrawdown);
            return;
        }
    
        //--- FLOATING RISK CLOSE LOGIC ---
        if(maxRiskPerTradePercent > 0.0)
        {
            int total = PositionsTotal();
            double balance = AccountInfoDouble(ACCOUNT_BALANCE);
            double maxLossMoney = balance * (maxRiskPerTradePercent / 100.0);
    
            for(int i=total-1; i>=0; i--)
            {
                ulong ticket = PositionGetTicket(i);
                if(PositionSelectByTicket(ticket))
                {
                    if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber &&
                       PositionGetString(POSITION_SYMBOL) == _Symbol)
                    {
                        double currentProfit = PositionGetDouble(POSITION_PROFIT);
                        if(currentProfit < 0 && MathAbs(currentProfit) >= maxLossMoney)
                        {
                            PrintFormat("Closing position %I64d as floating loss reached %.2f (cap is %.2f)",
                                        ticket, MathAbs(currentProfit), maxLossMoney);
                            trade.PositionClose(ticket);
                        }
                    }
                }
            }
        }
    
        //--- TRAILING SL ---
        if(enableTrailingSL && trailingStopMode != TrailingNone)
        {
           int total = PositionsTotal();
           for(int i=0; i<total; i++)
           {
              ulong ticket = PositionGetTicket(i);
              if(PositionSelectByTicket(ticket))
              {
                 if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
                 {
                    if(trailingStopMode == TrailingMarketStructure)
                       UpdateTrailingStopByMarketStructure(ticket);
                    else if(trailingStopMode == TrailingATR)
                       UpdateTrailingStopByATR(ticket);
                    else if(trailingStopMode == TrailingHybrid)
                       UpdateTrailingStopHybrid(ticket);
                 }
              }
           }
        }
    
        //--- POSITION LIMIT CHECK ---
        int openPosCount = 0, totalPositions = PositionsTotal();
        for(int i=0; i<totalPositions; i++)
        {
            ulong ticket = PositionGetTicket(i);
            if(PositionSelectByTicket(ticket))
            {
                if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
                {
                    openPosCount++;
                }
            }
        }
        if(maxPositions > 0 && openPosCount >= maxPositions)
            return;
    
        //--- TRADING TIME ---
        MqlDateTime tm;
        TimeToStruct(TimeCurrent(), tm);
        if(tm.hour < tradeStartHour || tm.hour >= tradeEndHour)
            return;
    
        // --- MINIMUM TIME INTERVAL COOLDOWN CHECK ---
        if(lastTradeOpenTime != 0 && (now - lastTradeOpenTime) < tradeIntervalSeconds)
            return; // interval cooldown active, skip trade
    
        // --- COOLDOWN PER CANDLE CHECK ---
        MqlRates candleRates[];
        if(CopyRates(_Symbol, cooldownTimeframe, 1, 1, candleRates) != 1)
        {
            Print("Failed to get last closed candle data for cooldown check");
            return;
        }
        datetime currentCandleTime = candleRates[0].time;
        if(currentCandleTime == lastTradeCandleTime)
            return; // candle cooldown active, skip trade
    
        //--- INDICATORS ---
        double ma_buf1[], ma_buf2[], ma_buf3[];
        if(CopyBuffer(ma_handle, 0, 1, 1, ma_buf1) <= 0) return;
        if(CopyBuffer(ma_handle2, 0, 1, 1, ma_buf2) <= 0) return;
        if(CopyBuffer(ma_handle3, 0, 1, 1, ma_buf3) <= 0) return;
    
        double MA1 = ma_buf1[0];
        double MA2 = ma_buf2[0];
        double MA3 = ma_buf3[0];
    
        double atr_buf[];
        if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0)
            return;
        double atr = atr_buf[0];
        if(atr <= 0)
            atr = 10.0 * _Point;
    
        double adx_buf[];
        if(adx_handle == INVALID_HANDLE)
        {
            Print("ADX handle invalid");
            return;
        }
        if(CopyBuffer(adx_handle, 0, 1, 1, adx_buf) <= 0)
        {
            Print("Failed to copy ADX buffer");
            return;
        }
        double adx_value = adx_buf[0];
    
        // --- DEBUG LOGS ---
        PrintFormat("*** DEBUG: Time=%s ***", TimeToString(TimeCurrent(), TIME_SECONDS));
    
        // Trend info
        bool is_uptrend = (MA1 > MA2) && (MA2 > MA3) && (SymbolInfoDouble(_Symbol, SYMBOL_ASK) > MA2);
        bool is_downtrend = (MA1 < MA2) && (MA2 < MA3) && (SymbolInfoDouble(_Symbol, SYMBOL_ASK) < MA2);
    
        PrintFormat("MA1=%.5f MA2=%.5f MA3=%.5f is_uptrend=%s is_downtrend=%s",
                    MA1, MA2, MA3,
                    (is_uptrend ? "true" : "false"),
                    (is_downtrend ? "true" : "false"));
    
        int highestBar = iHighest(_Symbol, swingTF, MODE_HIGH, swingLookback, 1);
        int lowestBar = iLowest(_Symbol, swingTF, MODE_LOW, swingLookback, 1);
        if(highestBar < 0 || lowestBar < 0)
            return;
    
        double lastSwingHigh = iHigh(_Symbol, swingTF, highestBar);
        double lastSwingLow = iLow(_Symbol, swingTF, lowestBar);
    
        ObjectSetDouble(0, swingHighLineName, OBJPROP_PRICE, lastSwingHigh);
        ObjectSetDouble(0, swingLowLineName, OBJPROP_PRICE, lastSwingLow);
    
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        if(ask <= 0 || bid <= 0)
            return;
    
        PrintFormat("Last swing high: %.5f, last swing low: %.5f", lastSwingHigh, lastSwingLow);
        PrintFormat("Ask=%.5f Bid=%.5f", ask, bid);
        PrintFormat("Bid < lastSwingLow? %s", (bid < lastSwingLow) ? "true" : "false");
        PrintFormat("Ask > lastSwingHigh? %s", (ask > lastSwingHigh) ? "true" : "false");
    
        // ADX below threshold message throttled (once per candle)
        if(adx_value < adxThreshold)
        {
            if(currentCandleTime != lastAdxBelowThresholdPrintCandle)
            {
                PrintFormat("ADX=%.2f below threshold %.2f, skipping new entries", adx_value, adxThreshold);
                lastAdxBelowThresholdPrintCandle = currentCandleTime;
            }
            return; // skip trade entries when ADX too low
        }
        else
        {
            lastAdxBelowThresholdPrintCandle = 0;
        }
    
        int fvgSignal = 0;
        if(useFairValueGapFilter)
        {
           fvgSignal = DetectFairValueGap(swingTF, 1);
           if(fvgSignal == 0)
           {
              if(currentCandleTime != lastFvgNoTradePrintCandle)
              {
                  Print("No Fair Value Gap detected, skipping new entries per FVG filter.");
                  lastFvgNoTradePrintCandle = currentCandleTime;
              }
              return;
           }
           else
           {
              lastFvgNoTradePrintCandle = 0;
           }
    
           // Print FVG bars info
           MqlRates bars[3];
           if(CopyRates(_Symbol, swingTF, 1, 3, bars) == 3)
           {
               PrintFormat("FVG candles times (shift 1..3): %s, %s, %s",
                           TimeToString(bars[0].time, TIME_SECONDS),
                           TimeToString(bars[1].time, TIME_SECONDS),
                           TimeToString(bars[2].time, TIME_SECONDS));
               PrintFormat("Candle1 High=%.5f Low=%.5f", bars[0].high, bars[0].low);
               PrintFormat("Candle3 High=%.5f Low=%.5f", bars[2].high, bars[2].low);
           }
        }
        else
        {
           Print("FVG filter disabled");
        }
    
        double sl_dist = atr * sl_atr_mult;
        double tp_dist = sl_dist * r2r_ratio;
    
        double lot = CalculateLotSize(sl_dist);
        PrintFormat("Calculated lot size: %.2f Min lot size: %.2f", lot, SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN));
        if(lot < SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN))
            return;
    
        // Cooldown prints
        PrintFormat("LastTradeCandleTime=%s CurrentCandleTime=%s", TimeToString(lastTradeCandleTime), TimeToString(currentCandleTime));
        PrintFormat("LastTradeOpenTime=%s Now=%s (diff=%d seconds)",
                    TimeToString(lastTradeOpenTime),
                    TimeToString(now),
                    (int)(now - lastTradeOpenTime));
    
        // Entry logic
        MqlTradeRequest request = {};
        MqlTradeResult result = {};
        request.symbol = _Symbol;
        request.volume = lot;
        request.deviation = 10;
        request.magic = inpMagicNumber;
    
        if(!enableReverseEntries)
        {
            if(ask > lastSwingHigh && is_uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
            {
                if(!useFairValueGapFilter || fvgSignal == 1)
                {
                    request.action = TRADE_ACTION_DEAL;
                    request.type   = ORDER_TYPE_BUY;
                    request.price  = ask;
                    request.sl     = NormalizeDouble(ask - sl_dist, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));
                    request.tp     = NormalizeDouble(ask + tp_dist, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));
    
                    if(!OrderSend(request, result))
                        PrintFormat("Buy order send failed, error %d", GetLastError());
                    else if(result.retcode != TRADE_RETCODE_DONE)
                        PrintFormat("Buy order rejected, retcode %d", result.retcode);
                    else
                    {
                        PrintFormat("Buy opened @ %.5f lot %.2f SL %.5f TP %.5f", ask, lot, request.sl, request.tp);
                        lastTradeCandleTime = currentCandleTime;
                        lastTradeOpenTime = now;
                    }
                }
            }
            else if(bid < lastSwingLow && is_downtrend && !IsPositionOpen(POSITION_TYPE_SELL))
            {
                if(!useFairValueGapFilter || fvgSignal == -1)
                {
                    request.action = TRADE_ACTION_DEAL;
                    request.type   = ORDER_TYPE_SELL;
                    request.price  = bid;
                    request.sl     = NormalizeDouble(bid + sl_dist, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));
                    request.tp     = NormalizeDouble(bid - tp_dist, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));
    
                    if(!OrderSend(request, result))
                        PrintFormat("Sell order send failed, error %d", GetLastError());
                    else if(result.retcode != TRADE_RETCODE_DONE)
                        PrintFormat("Sell order rejected, retcode %d", result.retcode);
                    else
                    {
                        PrintFormat("Sell opened @ %.5f lot %.2f SL %.5f TP %.5f", bid, lot, request.sl, request.tp);
                        lastTradeCandleTime = currentCandleTime;
                        lastTradeOpenTime = now;
                    }
                }
            }
        }
        else
        {
            if(ask > lastSwingHigh && is_downtrend && !IsPositionOpen(POSITION_TYPE_SELL))
            {
                if(!useFairValueGapFilter || fvgSignal == -1)
                {
                    request.action = TRADE_ACTION_DEAL;
                    request.type   = ORDER_TYPE_SELL;
                    request.price  = bid;
                    request.sl     = NormalizeDouble(bid + sl_dist, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));
                    request.tp     = NormalizeDouble(bid - tp_dist, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));
    
                    if(!OrderSend(request, result))
                        PrintFormat("Reverse Sell order send failed, error %d", GetLastError());
                    else if(result.retcode != TRADE_RETCODE_DONE)
                        PrintFormat("Reverse Sell order rejected, retcode %d", result.retcode);
                    else
                    {
                        PrintFormat("Reverse Sell opened @ %.5f lot %.2f SL %.5f TP %.5f", bid, lot, request.sl, request.tp);
                        lastTradeCandleTime = currentCandleTime;
                        lastTradeOpenTime = now;
                    }
                }
            }
            else if(bid < lastSwingLow && is_uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
            {
                if(!useFairValueGapFilter || fvgSignal == 1)
                {
                    request.action = TRADE_ACTION_DEAL;
                    request.type   = ORDER_TYPE_BUY;
                    request.price  = ask;
                    request.sl     = NormalizeDouble(ask - sl_dist, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));
                    request.tp     = NormalizeDouble(ask + tp_dist, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));
    
                    if(!OrderSend(request, result))
                        PrintFormat("Reverse Buy order send failed, error %d", GetLastError());
                    else if(result.retcode != TRADE_RETCODE_DONE)
                        PrintFormat("Reverse Buy order rejected, retcode %d", result.retcode);
                    else
                    {
                        PrintFormat("Reverse Buy opened @ %.5f lot %.2f SL %.5f TP %.5f", ask, lot, request.sl, request.tp);
                        lastTradeCandleTime = currentCandleTime;
                        lastTradeOpenTime = now;
                    }
                }
            }
        }
    }
    //+------------------------------------------------------------------+
    
    // IsRecentPositionClose function (scans recent closed position deals)
    bool IsRecentPositionClose(uint cooldownSecs)
    {
        datetime now = TimeCurrent();
    
        if(!HistorySelect(now - cooldownSecs - 10, now))
        {
            Print("HistorySelect failed");
            return false;
        }
    
        int totalDeals = HistoryDealsTotal();
        for(int i = totalDeals - 1; i >= 0; i--)
        {
            ulong ticket = HistoryDealGetTicket(i);
            if(ticket == 0)
                continue;
    
            datetime dealTime = (datetime)HistoryDealGetInteger(ticket, DEAL_TIME);
            if(dealTime == 0 || (now - dealTime) > cooldownSecs)
                continue;
    
            string symbol = HistoryDealGetString(ticket, DEAL_SYMBOL);
            ulong magic = HistoryDealGetInteger(ticket, DEAL_MAGIC);
            long entry = HistoryDealGetInteger(ticket, DEAL_ENTRY);
    
            if(symbol == _Symbol && magic == inpMagicNumber && entry == DEAL_ENTRY_OUT)
            {
                PrintFormat("Recent position close detected at %s, cooldown active.", TimeToString(dealTime));
                return true;
            }
        }
    
        return false;
    }
    //+------------------------------------------------------------------+
    

    What I added for debugging:

    • Print current time at start of OnTick.
    • Print all 3 MA values and the uptrend/downtrend booleans.
    • Print last swing high/low prices and current bid/ask.
    • Print if price is breaking swing low/high.
    • Print ADX and FVG filter status and detected FVG candles.
    • Print cooldown timestamps and intervals.
    • Print lot size calculated.
    • Print reasons if orders fail or succeed.

    Compile and attach this EA to your chart, then check the Expert tab in MetaTrader terminal for these debug messages. This will help you diagnose all the conditions and figure out why trades aren't opening in your scenario.

    If you want any further help interpreting the logs or tweaking filters, just ask!

  17. User

    2025.06.22 15:17:33.544 2025.05.01 07:32:59 *** DEBUG: Time=07:32:59 *** 2025.06.22 15:17:33.544 2025.05.01 07:32:59 MA1=19687.82498 MA2=19584.69414 MA3=19494.76673 is_uptrend=true is_downtrend=false 2025.06.22 15:17:33.544 2025.05.01 07:32:59 Last swing high: 19859.70000, last swing low: 19836.70000 2025.06.22 15:17:33.544 2025.05.01 07:32:59 Ask=19840.05000 Bid=19836.45000 2025.06.22 15:17:33.544 2025.05.01 07:32:59 Bid < lastSwingLow? true 2025.06.22 15:17:33.544 2025.05.01 07:32:59 Ask > lastSwingHigh? false

  18. Assistant

    Thanks for sharing the debug log snippet. Let's analyze it based on your desire to open a reverse BUY trade under these conditions:


    Your logged values at 07:32:59

    VariableValueNotes
    Time07:32:59Time of the tick/log
    MA119687.82498Short EMA
    MA219584.69414Medium EMA
    MA319494.76673Long EMA
    is_uptrendtrueMA1 > MA2 > MA3 — trend qualifies as uptrend
    is_downtrendfalseCorrect; trend not down
    Last swing high19859.70000Swing high price level
    Last swing low19836.70000Swing low price level
    Ask19840.05000Current ask price
    Bid19836.45000Current bid price
    Bid < lastSwingLow?truePrice has broken below last swing low — reverse entry condition satisfied
    Ask > lastSwingHigh?falsePrice has NOT broken above swing high

    What this means for Reverse BUY entry:

    The reverse BUY entry conditions in your code are (in simplified form):

    if(bid < lastSwingLow && is_uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
        if(!useFairValueGapFilter || fvgSignal == 1)
            // Place Buy order
    
    • Your log shows that bid < lastSwingLow is true.
    • Trend is uptrend → is_uptrend == true.
    • So, based on price and trend filters, the conditions are met up to this point.

    Next step: FVG check

    You haven't logged the fvgSignal yet. The Fair Value Gap filter must detect a bullish FVG (value = 1) for the trade to proceed.

    • If fvgSignal != 1 (i.e., no bullish FVG detected), the trade will not open.
    • From your earlier shared logs of FVG detection, ensure FVG detection is actually identifying a bullish gap for that timeframe and shift.

    What to do next?

    1. Add log for fvgSignal in this tick — if not already printed, make sure to show:
    PrintFormat("FVG signal: %d (1 = bullish, -1 = bearish, 0 = none)", fvgSignal);
    
    1. Check if existing BUY position

      • If a BUY position for your EA symbol/magic is already open, new entry won’t be allowed.
      • Log the result of IsPositionOpen(POSITION_TYPE_BUY).
    2. Check cooldown timers

      • Make sure the cooldown per candle and trade interval (time between trades) aren’t active.
      • The log should already show you lastTradeCandleTime and lastTradeOpenTime to verify this.
    3. Verify lot size

      • Calculated lot must be ≥ minimum lot for the symbol.

    Summary

    • Your MA trend, price break, and swing low conditions are correct — all support reverse BUY.
    • Most likely cause why no trade happened: Fair Value Gap bullish signal was missing (fvgSignal != 1) or cooldown/position check prevents opening.

    Suggested enhanced debug (inside OnTick, near trade decision):

    Add or verify these prints to pinpoint the block:

    PrintFormat("FVG signal: %d (1 = bullish, -1 = bearish, 0 = none)", fvgSignal);
    PrintFormat("Is buy position open? %s", IsPositionOpen(POSITION_TYPE_BUY) ? "Yes" : "No");
    PrintFormat("Cooldown check: lastTradeCandleTime=%s currentCandleTime=%s", 
                TimeToString(lastTradeCandleTime), TimeToString(currentCandleTime));
    PrintFormat("Time since last trade open: %d seconds", (int)(now - lastTradeOpenTime));
    PrintFormat("Lot size calculated: %.2f minimum lot: %.2f", lot, SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN));
    

    If you share that information, we can confirm exactly which condition blocks the trade.


    In short: your price/trend conditions are met and printed correctly; check the FVG detection and cooldown/position status next.

  19. User

    buy position is open at ask or bid price ?

  20. Assistant

    A buy position is opened at the ask price.


    Explanation:

    • When you buy, you enter the market by paying the ask price (the price sellers offer).
    • When you sell, you enter by accepting the bid price (the price buyers offer).

    In MQL5 (as in your EA code):

    request.price = ask;   // Buy orders placed at ask price
    

    This matches real market execution: buying happens at ask, selling at bid.


    Summary:

    Position TypeExecuted Price
    BuyAsk price
    SellBid price

    If you buy at bid price, the order will likely be rejected or get a requote because the executable price is the ask, so using ask for buy and bid for sell is correct practice.

  21. User

    now i know why didnt open buy, Ask 19840.05000 Current ask price,Bid 19836.45000 Current bid price,Last swing low 19836.70000 Swing low price level

  22. Assistant

    Exactly! Your Ask price (19840.05) was above the last swing low (19836.7), so the condition for reverse BUY trade:

    if(bid < lastSwingLow && is_uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
    

    was true because bid < lastSwingLow (19836.45 < 19836.7) is true, but when the trade is placed:

    • The buy order executes at the ask price (19840.05), which is above the swing low, not a break below.

    So the way the price is checked versus swing low is on bid, but order is sent at ask price (higher).


    What this means practically:

    • You detect the trigger by bid < lastSwingLow (price tick bid broke the swing low),
    • But when sending the buy order, market price (ask) is above last swing low.
    • This creates a discrepancy between entry condition and execution price.

    Potential approaches:

    • Usually, entry trigger check for buy uses bid or ask?

      • Since buy executes at ask, it’s safer to check if:

        ask < lastSwingLow
        

        for reverse buy, to confirm your actual buy execution price breaks the swing low.

    • Your current code checks bid < lastSwingLow for reverse buy—this detects downward price move on the bid side but lets buy execute at ask which might be above the swing low.


    In summary:

    • Your entry condition and execution price are based on different market prices (bid vs ask).
    • For tighter consistency, you may want to check the price side that matches the order type price.
    • For buy entries, check if ask < lastSwingLow, for sells check if bid > lastSwingHigh if that fits your logic.

    If you want, I can help you update your reverse entry logic accordingly.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.