//+------------------------------------------------------------------+
//| 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 |
//| Updated to open trades when FVG appears AFTER breakout |
//| Updated swing detection to classical swing points method |
//+------------------------------------------------------------------+
#property copyright ""
#property version "1.8"
#property strict
#include <Trade\Trade.mqh>
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
// *** 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
// --- New for breakout tracking ---
bool breakoutDetected = false;
int breakoutDirection = 0; // 1 = bullish breakout, -1 = bearish breakout
datetime breakoutCandleTime = 0;
int breakoutWaitCounter = 0; // number of bars waited for FVG since breakout
//-- 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
if(CopyRates(_Symbol, timeframe, startShift, 3, bars) != 3)
{
Print("DetectFairValueGap: failed to copy 3 bars");
return 0;
}
int FindRecentSwingLow(int startShift, int searchBars, int strength, ENUM_TIMEFRAMES tf)
{
MqlRates rates[];
int neededBars = searchBars + strength + 1;
if(CopyRates(_Symbol, tf, startShift, neededBars, rates) != neededBars)
{
Print("FindRecentSwingLow: Failed to get enough bars");
return -1;
}
Your EA code is well structured, implementing multiple filters (ADX, losing streak, cooldowns, Fair Value Gap) and a breakout+FVG trade entry logic with reversal options. The main update you introduced is the fix for the breakoutWaitCounter to increment only once per new bar on the swingTF timeframe.
Quick summary of your core fix in the current code:
You added the static variable lastBreakoutWaitBarTime to track the last swingTF candle time when the wait counter was incremented.
Only when a new bar forms (currentWaitBarTime != lastBreakoutWaitBarTime), breakoutWaitCounter is incremented.
This prevents multiple increments of breakoutWaitCounter on the very same bar, which would otherwise fast-forward your wait and cancel the breakout prematurely.
Here is that key snippet for clarity:
mql5
static datetime lastBreakoutWaitBarTime = 0;
// ...
datetime currentWaitBarTime = rates[0].time;
if(currentWaitBarTime != lastBreakoutWaitBarTime)
{
breakoutWaitCounter++;
lastBreakoutWaitBarTime = currentWaitBarTime;
PrintFormat("Breakout wait counter incremented to %d at bar time %s", breakoutWaitCounter, TimeToString(currentWaitBarTime));
}
This throttling per bar is necessary because OnTick() executes multiple times per bar, and without this guard, breakoutWaitCounter would increment on every tick within the same bar.
Additional recommendations or improvements you might consider:
Check FVG on multiple recent bars:
Sometimes the FVG may appear not exactly at shift=1 candle, but a bit later or earlier; checking a few recent bars to confirm could reduce missed trades.
Robust Swing Detection:
Your classical swing detection looks solid. However, you rely on FindRecentSwingHigh/Low to return absolute bar indices but call iHigh/iLow with those indices which return shifted bars at swingTF. Be sure indices are coherent with timeframe and bar count.
Fair Value Gap detection:
The DetectFairValueGap() function scans 3 bars starting at startShift. Make sure the logic is consistent with the direction of scanning and that you process fully closed bars only. You might want to add a small fuzz factor if prices are very close but no literal gap exists.
Cooldown & Time Filter:
Your cooldowns and interval filtering appear thorough. To avoid skipping too many trades during prolonged times without entries, consider a reset or reduced cooldown resets based on performance or daily trading hours.
Magic number & symbol checks:
You correctly filter positions & history by magic and symbol, which is good for multi-symbol/multi-EA setups.
Final overall remarks:
Your code is clean, use of MqlRates arrays and indicator handles is proper.
The logic structure allows easy toggling of reverse entries and filters.
Implementing the lastBreakoutWaitBarTime check fixes the premature reset problem effectively.
The comments and print statements enhance traceability and debugging.
Make sure to test thoroughly in strategy tester with visual mode to confirm the interplay of breakout, FVG wait, and final trade placement.
If you want, I can also help you write a fully commented snippet for the breakout wait counter fix or suggest code for checking FVG over multiple bars. Just ask!
Certainly! Here is a more organized and grouped version of the input parameters from your EA code. Grouping inputs by category improves readability and ease of parameter tuning.
mql5
//+---------------- Input Parameters Organized --------------------+
// --- Trading Control ---
input int tradeStartHour = 7; // Trading start hour (server time)
input int tradeEndHour = 22; // Trading end hour (server time)
input int maxPositions = 1; // Max concurrent open positions
input uint inpMagicNumber = 123456; // Magic number for trades
input bool enableReverseEntries = true; // Enable reverse entries mode
// --- Position Sizing ---
input double inpLot = 0.05; // Default lot size if risk percent off
input bool useRiskPercent = true; // Use % risk per trade or fixed lot
input double riskPercent = 1.0; // Position risk % per trade (if enabled)
input double maxRiskPerTradePercent = 1.0; // Floating risk cap (max loss %) per position
// --- Risk Management & Equity Drawdown ---
input double maxDailyLossAmount = 350.0; // Maximum daily loss before disabling trades
input int maxLosingStreak = 3; // Max consecutive losing trades allowed
// --- Cooldowns ---
input int postCloseCooldownSeconds = 180; // Cooldown after position close (seconds)
input int tradeIntervalSeconds = 180; // Min seconds between trades
input ENUM_TIMEFRAMES cooldownTimeframe = PERIOD_M1; // Timeframe used for candle-based cooldown
// --- Indicator Settings ---
// ATR for Stop Loss / Volatility measurement
input ENUM_TIMEFRAMES volatilityTF = PERIOD_M5; // Timeframe for volatility ATR calculation
input int atrPeriod = 14; // ATR period
input int sl_atr_mult = 3; // SL distance as ATR multiplier
// Risk Reward Ratio (TP=SL * r2r_ratio)
input double r2r_ratio = 2.0;
// Moving Averages (Trend Filter)
// Short-term MA
input int maPeriod = 50;
input ENUM_TIMEFRAMES maTimeframe = PERIOD_M15;
// Medium-term MA
input int maPeriod2 = 100;
input ENUM_TIMEFRAMES maTimeframe2 = PERIOD_M15;
// Long-term MA
input int maPeriod3 = 200;
input ENUM_TIMEFRAMES maTimeframe3 = PERIOD_M15;
// --- ADX Filter ---
input int adxPeriod = 14; // ADX period
input double adxThreshold = 25.0; // Minimum ADX threshold to allow trading
input ENUM_TIMEFRAMES adxTimeframe = PERIOD_M15; // ADX calculation timeframe
// --- Break of Structure / Swing Detection ---
input int swingLookback = 20; // Bars to look back for swing detection
input ENUM_TIMEFRAMES swingTF = PERIOD_M1; // Swing detection timeframe
input int swingStrength = 3; // Number bars each side for classical swing detection
// --- Fair Value Gap (FVG) Filter ---
input bool useFairValueGapFilter = true; // Enable FVG filter to confirm entries
input int maxBreakoutWaitBars = 3; // Bars max to wait for FVG after breakout
//+----------------------------------------------------------------+
Explanation:
Inputs are grouped by their role: Trading Control, Position sizing, Risk management, Cooldowns, Indicators, ADX filter, Swing Detection, FVG filter.
This organization simplifies parameter tuning and reading, both in code and inside MetaTrader's EA properties window.
Let me know if you want me to generate the complete updated EA input section with comments formatted as above.