// 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
// *** 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 for Break of Structure with floating risk cap and classical swing detection looks quite comprehensive and well structured. From a review perspective, here are some points and remarks about the code logic and correctness:
Key Features and Checks:
Daily Equity Reset:
Uses a daily midnight timestamp to reset equity tracking and losing streak count correctly.
Good use of TimeCurrent(), TimeToStruct(), and StructToTime().
Losing Streak Management:
Scans trade history for closed trades matching Magic Number and symbol.
Increments or resets losing streak accordingly.
Respects losing streak limits to block new entries.
Floating Risk Close Logic:
Iterates open positions and closes if floating loss exceeds maxRiskPerTradePercent.
Position Limit and Time Filters:
Checks max open positions.
Respects trading hours.
Implements cooldown both by candle and by time interval.
Indicator Handles Initialization and Usage:
MA (EMA) handles for 3 MAs on 3 timeframes.
ATR handle for stoploss distance calculation.
ADX filter to avoid entries during low trend strength.
Proper handle release on deinit.
Swing Detection:
Classical swing high/low detection based on strength bars before and after.
Uses this for breakout detection.
Breakout Detection & Delayed Entry with Fair Value Gap (FVG):
Detects breakouts when price breaks last swing high (buy side) or low (sell side).
Waits for up to maxBreakoutWaitBars bars for a matching FVG on swingTF.
Supports reverse entries flag which flips buy/sell logic after break.
Resets breakout if timeout reached without confirming FVG.
Triggers order send once matching FVG detected.
OrderEntry:
Uses low-level MqlTradeRequest instead of CTrade::Buy/Lots for better control.
Normalizes SL and TP based on symbol digits.
Verifies position is not already open for direction.
Throttling Print Messages:
Avoids excessive printing via static datetime checks per candle/time.
Recent Position Close Cooldown:
Prevents new entries soon after a position close.
Suggestions & Potential Improvements:
CopyRates Usage:
In swing detection functions, neededBars = searchBars + strength + 1 — you fetch neededBars bars starting from startShift.
Make sure the indexing logic when testing swing candles is consistent and does not cause out-of-bounds or reversed logic. The current loops attempt to check i + j and i - j and break if out of range, which looks safe.
Breakout Wait Bar Counting:
Your fix to increment breakoutWaitCounter only once per new fully closed swingTF bar time is a good practice.
Verify the timeframe swingTF is the same as cooldown timeframe and swing detection timeframe for consistent timing.
Fair Value Gap Detection:
The gap detection is simple — comparing candle 1 and candle 3 highs/lows.
You may want to enhance to check wick shadows vs real bodies or print more info for debugging.
Position Open Detection:
IsPositionOpen() compares Magic and symbol; good.
Would be good to check all open positions if you ever plan on hedging or multiple magic numbers.
TradeSend Error Handling:
After OrderSend(), currently you print but do not retry or handle known errors like requotes.
Consider adding error handling retries for robust trading.
Potential Race Conditions:
breakoutDetected state and counters are static/global variables modified on each OnTick().
On extremely fast ticks or multi-threaded platforms, consider thread safety or locking.
Efficiency Considerations:
UpdateLosingStreak() and history access might be heavy on each tick.
Consider performing it once per newly closed candle or controlled intervals.
Code Readability:
You can add comments to explain why reversing entry logic is flipped for enableReverseEntries.
Add more logs on order fills or slippage if needed.
Magic Number and Symbol Check Consistency:
Summary:
Your code is clean with good variable naming and logical flow.
The swing point logic and breakout detection with FVG filter is implemented clearly.
Risk and position size calculation is dynamic and adjustable.
Cooldown and losing streak concepts improve risk management.
Final Notes:
If you want me to assist you further to:
Add new features or enhance existing ones,
Debug or optimize parts of the EA,
Improve comments or modularize code,
Or need a walk-through of specific parts,
please let me know!
To add a simple informational box in the top-left corner of the chart that displays the current EMA1, EMA2, EMA3 values, current trend state, ADX value, last swing high and swing low, you can use a chart text object (OBJ_LABEL). This is easy to update on every new tick or even better on every new candle to reduce repainting.
Step-by-step instructions:
Create a label object in OnInit() or dynamically on first OnTick() if it doesn’t exist.
Update the object's text content every tick to show your values.
Position it fixed top-left with some margin.
Use ObjectSetString() and ObjectSetInteger() for style and text content.
Sample code snippet that you can integrate into your EA:
Add the following global constant for the label name near the top (with other global strings):
mql5
string infoLabelName = "EA_InfoBox";
Add this function to create/update the label text:
Then, inside your OnTick()after you have calculated all indicators and swing prices (right before breakout logic or near the bottom of OnTick()), call:
This will create a neat info box in the upper-left corner showing the requested values updated every tick.
Let me know if you want a fancier graphical panel with rectangles, background transparency or more styling!
Certainly! Below is your full EA code with the info box integrated as requested. I inserted all necessary parts so it compiles and runs within your existing structure. The info box updates every tick showing EMA1, EMA2, EMA3, current trend, ADX value, and swing high/low.