//+------------------------------------------------------------------+
//| 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>
// 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 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
// --- Breakout wait bars timeout (how many bars to wait for FVG after breakout) ---
input int maxBreakoutWaitBars = 3;
// --- Classical Swing detection strength ---
input int swingStrength = 3; // Number of bars on each side for classical swing detection
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
Assistant
User
tell me about Detects swing highs/lows using a classical swing points method
Assistant
User
what parameter i can set for swings?
Assistant
User
i can set this only inside code?
Assistant
Yes, in the current version of your EA code, the swing detection parameters are declared as input variables at the top of the code, which means:
input int swingLookback = 20; // Number of bars to look back for swing detection
input ENUM_TIMEFRAMES swingTF = PERIOD_M1; // Timeframe for swing detection
input int swingStrength = 3; // Number of bars on each side for classical swing detection
What does input mean here?
variables are user-modifiable parameters that can be changed directly from the EA’s properties dialog inside MetaTrader when you attach or run the EA.
User
tell me how swing detection works now after update
Assistant
User
and swing lookback?
Assistant
User
and how works together swinlookback and strenght?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// *** 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;
}
The provided EA implements a Break of Structure (BoS) with a floating risk cap and multiple filters, including ADX, losing streak, cooldowns, and Fair Value Gap (FVG) confirmation on entries. The code looks complete, well-structured, and sophisticated. Below are some notes and highlights in case you want to understand, verify, or extend functionality:
Key Features and Flow
Risk Management
Lot size can be fixed or calculated based on a risk percentage and SL distance derived from ATR.
Floating risk cap (maxRiskPerTradePercent) forcibly closes positions if the drawdown exceeds this % on individual trades.
Daily maximum drawdown (maxDailyLossAmount) stops new entries once triggered.
Losing streak counter prevents trading after hitting maxLosingStreak.
Breakout & Entry Logic
Detects swing highs/lows using a classical swing points method.
Detects breakouts above the last swing high and below the last swing low.
After breakout detection, waits up to maxBreakoutWaitBars bars for a Fair Value Gap on the classical swing timeframe (swingTF).
If FVG matches the breakout direction, the EA opens a trade with SL and TP based on ATR and R:R ratio.
Supports reverse entries (enableReverseEntries) where directionality of entries and trade types are swapped.
Cooldowns
Post-close cooldown: prevents new trades shortly after a position closure.
Minimum time between trades (tradeIntervalSeconds).
Candle cooldown: only one trade per candle timeframe allowed.
Filters
ADX filter prevents trades if trend strength is below adxThreshold.
The FVG filter enforces confirmation of breakout direction before trade entry.
Time-based filtering on trading hours.
Some Explanations and Suggestions
Breakout Wait Counter Logic Fix
The EA increments the bars waited after breakout only once per new candle at the swing timeframe (swingTF), handled by lastBreakoutWaitBarTime.
Makes sure we do not increment multiple times per tick while the candle is still open.
Fair Value Gap (FVG) Detection
Detects a gap when candle1 high < candle3 low (bullish FVG) or candle1 low > candle3 high (bearish FVG).
Offset of startShift=1 means the FVG is actively detected in past candles, not the current forming candle.
Handling Positions
Before opening a trade, the code checks the max positions limit.
Prevents opening duplicate positions in the same direction.
The EA uses the magic number to identify its own trades.
Possible Future Improvements
Add trailing stops using ATR or other methods to lock in profits.
Use events to detect closed trades instead of scanning history every tick for better efficiency.
Add alerts for manual intervention in case of repeated order rejections.
Allow multi-symbol or basket trading by parameterizing symbols (not only _Symbol).
Add slippage and spread checks before placing orders.
Summary
Your EA is quite advanced with multiple layers of filters, risk controls, and classical swing point logic combined to create a robust Break of Structure trading strategy that confirms breakouts with Fair Value Gaps.
If you want me to help add features, explain specific parts, or optimize it further, please ask! Otherwise, the code as given looks ready to be compiled and tested on MetaTrader 5.
Example: How to test the EA
Attach the EA to your preferred chart matching swingTF or smaller timeframe.
Set inputs as desired (e.g., trade hours, risk percentages).
Make sure your broker supports the volume steps and contract size assumptions.
Watch the Logs for breakout detection, FVG confirmations, and trade entries.
Verify cooldowns and floating loss closings are functioning as expected.
If you want, I can also provide a simplified explanation of the core logic or help with optimization or debugging specific issues!
Certainly! The EA uses a classical swing points detection method to identify recent swing highs and swing lows on a given timeframe. This method is often used in technical analysis to find turning points (local maxima and minima) in price data, which can help to detect potential support/resistance or breakout levels.
How the Classical Swing Points Method Works in This EA
Swing High:
A bar (candlestick) is considered a swing high if its high price is strictly greater than the highs of several bars before and after it.
Swing Low:
Similarly, a bar is a swing low if its low price is strictly less than the lows of several bars before and after it.
Implementation Details in the EA
There are two functions:
int FindRecentSwingHigh(int startShift, int searchBars, int strength, ENUM_TIMEFRAMES tf)
int FindRecentSwingLow(int startShift, int searchBars, int strength, ENUM_TIMEFRAMES tf)
Parameters:
startShift: How many bars back from the current bar to start searching.
searchBars: Number of bars in the past to search for swing points.
strength: Number of bars on each side of the candidate bar that must have lower highs/lows.
tf: Timeframe to analyze.
What Happens Inside These Functions:
Data Copy
The functions request and load enough bars (candles) from the specified timeframe into an array of MqlRates.
For example, if searching searchBars=20 with strength=3, it loads 20 + 3 + 1 = 24 bars.
Iterate Over Bars
For each candidate bar in the search window (loop index i from 0 to searchBars - 1), the code checks:
For Swing High:
The candidate bar's high price (currentHigh) must be strictly greater than highs of the next strength bars (i+1 to i+strength).
The candidate bar's high price must also be strictly greater than highs of the previous strength bars (i-1 to i-strength).
If any of these conditions fail, this bar is not a swing high.
For Swing Low:
Similarly, candidate bar’s low is compared to lows of next and previous strength bars, but must be strictly lower.
Return Swing Index
If a bar satisfies the above conditions, it is immediately returned as the most recent swing high/low bar index, adjusted by startShift.
No Swing Found
If no such bar is found, the function returns -1.
Example of Swing High Detection Logic (Simplified)
// Candidate bar at i (shifting from startShift)
currentHigh = rates[i].high;
// Check bars after candidate
for(j=1; j<=strength; j++) {
if(currentHigh <= rates[i + j].high)
isSwingHigh = false;
}
// Check bars before candidate
for(j=1; j<=strength; j++) {
if(currentHigh <= rates[i - j].high)
isSwingHigh = false;
}
if(isSwingHigh)
return startShift + i;
How It Looks On a Chart:
If strength=3, a swing high is a bar whose high is higher than the highs of the previous 3 bars and the next 3 bars.
This creates a local maximum or turning point.
The same applies for swing lows (local minima).
Why Use This Swing Points Method?
It’s a standard and intuitive approach to pick out significant pivot points.
Helps identify support and resistance levels.
In this EA, swing highs/lows define the structure. Breakouts are detected when price crosses those swing points.
Using “strength” filters out less significant swings caused by noise, allowing only stronger pivots to be considered.
Important Notes
The function scans backwards in time starting from startShift, which means it detects past swing points, not the current bar which may still be forming.
It works on the chosen timeframe (swingTF), e.g., M1 or M5.
strength should be tuned:
Too small (e.g., 1) = many false swings (noise).
Too large (e.g., 5+) = picks only very strong swings but fewer signals.
In Your EA
swingStrength=3 by default, so it checks 3 bars before and after for highs/lows.
swingLookback=20 defines how far back the EA will search for swings.
The EA uses these swing points to place horizontal lines (OBJ_HLINE) on the chart visually showing last swing high and low, which act as breakout levels.
Breakouts beyond those lines signal a potential BoS (Break of Structure), which triggers the pending FVG-based entry.
Summary
The classical swing points method in your EA is a robust way to detect recent significant highs and lows by ensuring a candidate bar is a local extremum compared to several bars on either side. This reduces noise and false signals, creating reliable breakout zones.
If you'd like, I can help with example adjustments, optimize the method, or visualize how it works step-by-step on actual bar data!
In your EA, the swing point detection has a few key input parameters and internal constants that you can set or tweak to control how swings are detected and influence the trading signals:
1. swingStrength (Input parameter)
input int swingStrength = 3; // Number of bars on each side for classical swing detection
Defines how many bars before and after the candidate bar must have lower highs (for swing highs) or higher lows (for swing lows).
This controls the "strictness" or "significance" of a swing pivot.
Effect:
Higher values make swing detection stricter, resulting in fewer but stronger swings.
Lower values will detect more swings but with potentially more noise.
Typical range: 2 to 5
3 is a balanced choice for common intraday timeframes.
2. swingLookback (Input parameter)
input int swingLookback = 20;
Number of bars backward from startShift to search for swing highs/lows.
Defines the window size over which the EA searches for swings.
Effect:
Larger values allow detection of swings farther back in history, which might delay trading signals or catch more established structure points.
Smaller values make the EA focus on the very recent swings only.
3. swingTF (Input parameter)
input ENUM_TIMEFRAMES swingTF = PERIOD_M1;
The timeframe on which swing detection is performed.
Swing highs/lows are detected on this timeframe candles, regardless of the chart timeframe the EA is attached to.
Effect:
Lower timeframe (e.g., M1) yields more swings, sensitive to short-term price action.
Higher timeframe (e.g., M5, M15) filters noise and identifies bigger swings but may reduce trade frequency.
4. startShift (Parameter used in functions, typically '1')
In functions like FindRecentSwingHigh(1, swingLookback, swingStrength, swingTF), the startShift is usually fixed at 1, meaning the search starts from the last fully closed bar (shift 1) — not the current forming bar (shift 0).
5. Indirect parameters that affect swing usefulness
tradeStartHour and tradeEndHour define when swings are scanned/used for entry signals.
maxBreakoutWaitBars defines how long the EA waits for a confirming FVG after breakout (which uses swing highs/lows as breakout levels).
enableReverseEntries can invert breakout direction interpretations but relies on same swing points.
How to Choose and Tune Swing Parameters?
Start with defaults:
swingStrength=3
swingLookback=20
swingTF=PERIOD_M1
If you want fewer, stronger signals:
Increase swingStrength to 4 or 5.
Increase swingLookback to 30+ bars.
Use a higher timeframe like M5 or M15 for swingTF.
If you want more frequent entries but potentially more noise:
Decrease swingStrength to 2.
Decrease swingLookback to 10.
Use lower timeframe like M1.
Summary Table for Swing Parameters:
Parameter
Purpose
Typical Range
Effect of Increase
swingStrength
Bars before/after candidate for swing point
2 to 5
Stricter swings, fewer signals
swingLookback
Number of bars to scan backward for swings
10 to 50
More historic swings considered
swingTF
Timeframe of bar data for swing detection
PERIOD_M1 to PERIOD_M15
Swing scale from fine to broad
Feel free to experiment with your particular instrument and timeframe to find a balance between signal quality and frequency! If you want, I can help you create an optimization or visual tester for swing detection parameters too.
If you like, I can also generate a sample recommendation for your specific market or timeframe. Just ask!
input
So you do NOT need to edit the code manually or recompile for these parameters.
You can simply open EA properties, go to the Inputs tab, and adjust these parameters before starting the EA.
How to change swing parameters without editing code:
Attach the EA to the chart.
Before pressing OK, open the Inputs tab.
Find swingLookback, swingTF, and swingStrength.
Change their values as desired.
Click OK, and the EA will start using these new parameters.
What if you want to hard-code them?
You can set them directly in the code by changing the default values in the input declarations, but this is not necessary for normal use.
Using input variables provides flexibility and is the recommended way.
Summary
You can change swing parameters easily through the EA Inputs dialog at runtime.
No need to open the code or recompile if you just want to test different swing settings.
Editing the code and recompiling is only needed if you want to add/move/change parameters beyond the existing inputs.
If you want, I can guide you on exactly how to open the Inputs dialog and adjust parameters in MetaTrader, or help you add new inputs to the EA!
Certainly! I’ll explain how the swing detection works in your updated EA, focusing on the current classical swing points method implementation and how it integrates into the trading logic.
Swing Detection Overview in Your EA
Your EA uses classical swing points to identify recent local highs and local lows on a specified timeframe (swingTF). These swing points define key levels of market structure: recent swing highs act as resistance zones, and recent swing lows act as support zones.
Key Functions Involved
FindRecentSwingHigh(startShift, searchBars, strength, tf)
Returns the index (bar shift) of a recent swing high bar.
FindRecentSwingLow(startShift, searchBars, strength, tf)
Returns the index (bar shift) of a recent swing low bar.
How Do These Functions Work?
Data Retrieval
They load searchBars + strength + 1 bars from the symbol's price history on the timeframe tf starting at startShift.
This ensures enough bars are available around each candidate bar for comparison.
Swing High Criteria
For each candidate bar in the loop:
Look at the currentHigh (the candidate bar’s high price).
Check the strength bars after it: currentHigh must be greater than all those bars’ highs.
Check the strength bars before it: currentHigh must be greater than all those bars’ highs.
If both conditions are true, the bar is a swing high.
Swing Low Criteria
Similarly for currentLow in the candidate bars:
Must be less than lows of strength bars before and after.
If true, the bar is a swing low.
Return
The first bar found that matches the criteria within the search range is returned (with adjustment for startShift).
Example with swingStrength = 3:
To confirm a swing high at bar i, the high of bar i must be higher than highs of bars i-3, i-2, i-1 AND bars i+1, i+2, i+3.
This identifies significant local highs, avoiding noise or minor fluctuations.
The swing levels are then used as breakout triggers:
Bullish breakout: Current asking price crosses above the last swing high.
Bearish breakout: Current bid crosses below the last swing low.
When a breakout is detected, the EA starts monitoring for confirmation using the Fair Value Gap (FVG) filter for a few bars before entering.
Summary: What Swing Detection Achieves Now
Detects meaningful and recent swing highs/lows on the selected timeframe (swingTF) using classical swing point logic.
Filters minor price noise by requiring the candidate bar to exceed multiple bars on both sides (swingStrength).
Provides dynamic, adaptive breakout levels that depend on recent actual market turning points.
These swing levels are central anchors to the Break of Structure strategy: price breaking above/below these leads to the possibility of a new trend or momentum.
The EA uses these swing highs/lows to time entries in combination with ATR-based SL/TP, ADX filter, losing streak limits, cooldowns, and FVG confirmations.
Additional Notes
You can control sensitivity and signal frequency by modifying:
swingStrength (higher → fewer stronger swings)
swingLookback (how far back the EA scans for swings)
swingTF (higher timeframe for bigger swings, lower timeframe for finer swings)
This approach keeps the swing detection classical, well-understood, and transparent.
If you want, I can also explain how this compares to other swing detection methods or how to adjust these parameters to tune the EA’s performance for your market!
Certainly! The swingLookback parameter is another important input that controls the swing detection in your EA.
What is swingLookback?
swingLookback defines how many bars backwards from the starting point the EA scans when searching for recent swing highs and lows.
In other words, it is the size of the sliding window (number of bars) over which the swing detection algorithm looks to find significant pivot points.
How is swingLookback used in your EA?
Look at the signature of the swing detection calls:
int highestBar = FindRecentSwingHigh(1, swingLookback, swingStrength, swingTF);
int lowestBar = FindRecentSwingLow(1, swingLookback, swingStrength, swingTF);
The 1 means start searching from the last fully closed candle (shift 1).
swingLookback is the number of bars to scan backwards from shift 1.
Inside the functions, swing detection loops from i = 0 to i = swingLookback - 1, comparing bars for swing conditions.
Practical effect of swingLookback
A larger swingLookback means the EA scans a bigger section of recent history, therefore it may find swing points further back in time.
This could cause the EA to pick older swivel points as the “last swing high/low,” which means breakout levels may represent more established or stronger structural levels.
Conversely, a smaller swingLookback makes the EA focus on only the most recent few bars, yielding very recent swings that might capture quicker shifts but may be more sensitive to noise.
Recommendations for swingLookback
Value
Behavior
Use Case
10–15
Short lookback, finds very recent/fast swing points
Faster signals, more trades
20–30
Medium lookback (default is 20 in your EA)
Balanced approach, mix of signals
40+
Long lookback, swings may be older, stronger but less frequent
More filtered, slower signals
Interaction With Other Parameters
swingLookback works together with swingStrength:
You must have swingLookback > swingStrength to ensure meaningful swings can be found.
The timeframe swingTF multiplies the real time window:
A swingLookback=20 on M1 means looking back 20 minutes; on M5 it’s 100 minutes, etc.
Effect on Breakout Detection
Because swing highs/lows define breakout thresholds, the choice of swingLookback directly affects how “old” or “new” the breakout structure must be.
Too large lookback might cause breakout detection to lag or miss quick market changes.
Too small might create false breakouts over insignificant swings.
Summary
swingLookback controls how many bars back the EA looks for recent swing highs and lows.
Tune it to balance between signal freshness and reliability.
Default 20 is a good starting point.
Increase for stronger/more stable breakouts; decrease for more agile, faster signals.
If you'd like, I can help you test different values or add visualization to see exactly which bars are considered swings with your settings!
Great question! Understanding how swingLookback and swingStrength work together is important because they define the sensitivity and scope of your swing point detection.
How swingLookback and swingStrength Work Together
swingStrength determines how strict the swing point detection is by requiring a candidate bar’s high/low to be greater/less than a certain number of bars on both sides.
swingLookback determines how far back in history the EA scans for such swing points.
What exactly happens?
The EA loads a set of bars starting at startShift (typically 1) and extending back swingLookback + swingStrength + 1 bars.
It loops through the bars indexed from 0 to swingLookback - 1 (i.e., a window of length swingLookback within that loaded range).
For each candidate bar i in this window:
It checks the swingStrength bars ahead: bars i+1 to i+swingStrength.
It checks the swingStrength bars behind: bars i-1 down to i-swingStrength.
The candidate is a swing high if its high is strictly greater than all swingStrength bars both before and after it.
The candidate is a swing low if its low is strictly less than all swingStrength bars both before and after it.
Why does the EA load more bars than swingLookback?
The extra swingStrength + 1 bars are needed because to check bars on both sides of the candidate, you need a buffer beyond the swingLookback bars.
Without this, the function could run out of bars to compare and miss valid swings near the edges.
Relationship and Constraints
To detect a swing point properly at bar i, you need bars before and after it.
Therefore:
swingLookback > swingStrength
This is required so that for every candidate bar inside your lookback window, the EA can look left and right by swingStrength bars.
If swingStrength is large relative to swingLookback, the window is too small to find any swings because candidates near the edges cannot be validated on both sides.
Effect of varying swingLookback and swingStrength
SwingLookback
SwingStrength
Effect Summary
Larger lookback (e.g. 30) + small strength (e.g. 2)
Small strength means less strict swings, large lookback finds swings further back in time. More swings overall, with some noise.
Smaller lookback (e.g. 10) + large strength (e.g. 4)
Fewer bars to search from, but very strict swing definition means fewer/no swings detected. Could result in no swing detected often.
Balanced: enough bars scanned and enough strictness for meaningful swings. Good starting point.
Intuition/Example:
swingStrength = 3 means: "The current bar’s high/low must be better than 3 bars to the left and 3 bars to the right."
So, if swingLookback = 5, you only have 5 bars scanned backward:
Bars near the boundaries can’t satisfy “3 before and 3 after” condition because you don't have enough bars on one side.
Result: very few or no swings get detected.
If you increase swingLookback to 20, the EA has enough bars in the scanned range to find swings meeting strength condition.
Visual analogy
For candidate bar at index i, swingStrength=3:
| bars indices: i-3 i-2 i-1 i i+1 i+2 i+3
Candidate bar (i) must have a *high* higher than all bars at indices i-3 to i-1 and i+1 to i+3.
To check bars on both sides, the EA must have bars existing at these indices,
so the search window (swingLookback) must be large enough to include these.
Summary
swingStrength controls how many bars on each side the candidate must surpass to qualify as a swing.
swingLookback controls how many bars backward the EA searches for such swings.
swingLookback must be greater than swingStrength to allow proper swing detection.
Larger swingLookback enables detecting swings farther in the past.
Larger swingStrength tightens swing definition, reducing false swings but also reducing frequency.
If you want, I can help you with:
Code to check and enforce swingLookback > swingStrength automatically.
Visual debugging of swing points given parameters.
Parameter suggestions for your specific market/timeframe.