// New input for reverse entry logic
input bool enableReverseEntries = false; // Reverse trade entry logic (Sell on swing high break, Buy on swing low break)
// New inputs for max risk and daily loss limits
input double maxRiskPerTradePercent = 1.0; // Max risk per trade as % of account balance
input double maxDailyLossPercent = 2.0; // Max daily loss as % of account balance
CTrade trade;
int ma_handle = INVALID_HANDLE;
int atr_handle = INVALID_HANDLE;
string swingHighLineName = "SwingHighLine";
string swingLowLineName = "SwingLowLine";
//+------------------------------------------------------------------+
// Resets daily loss tracking at start of each new day
void ResetDailyLossIfNewDay()
{
datetime now = TimeCurrent();
MqlDateTime tm {};
TimeToStruct(now, tm);
//+------------------------------------------------------------------+
// Update daily loss as sum of closed negative trades for current day & symbol
void UpdateDailyLoss()
{
datetime dayStart = dailyLossResetTime;
datetime dayEnd = dayStart + 86400; // Next day
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);
Your EA source code is quite complete and advanced, implementing Break Of Structure trades with configurable trailing stops (market structure, ATR, hybrid), dynamic lot sizing with risk management, throttling of trailing updates, daily loss limits, max positions, and even an optional reverse entry logic.
High-level summary:
Initialization:
Creates EMA and ATR indicator handles.
Creates horizontal lines for swing highs and lows.
Initializes daily loss tracking.
OnTick:
Resets and updates daily loss.
If daily loss limit exceeded, no new trades are opened.
Updates trailing stops of open positions based on the selected trailing mode.
Checks if new trades can be opened (time windows + max positions).
Determines trend with EMA, swing highs and lows for BOS trigger.
Calculates dynamic SL and TP distances with ATR.
Calculates lot size based on fixed lot or risk % with max risk per trade cap.
Opens buy or sell trades on swing breaks depending on trend and reverse logic.
Trailing Stops:
Trailing by Market Structure (swings)
Trailing by ATR
Hybrid trailing combining both with throttling update intervals.
Risk Management:
Dynamic lot sizing capped by max risk per trade.
Daily loss accumulation and stops new trading once exceeded.
Other features:
Trailing SL buffers and trailing activation thresholds.
Reverse entry logic to flip buy/sell signals.
Notes & Suggestions / Possible Improvements:
Magic Number Handling:
You use a fixed input magic number, which is sufficient for now but if running multiple symbols or strategies, consider appending symbol index or unique identifiers to avoid conflicts.
Error Handling & Logging:
You're already printing error codes on order send failure, which is good.
For better diagnostics, you could implement a structured logging system or write logs to a file.
Trailing Stop Frequency Control:
Your throttling by TrailUpdateIntervalSec with g_trailingUpdateInfo array is suitable. Just ensure that positions closed are cleaned from this array (optional for memory).
Position Checking Efficiency:
Your IsPositionOpen() loops over all positions each tick. Consider caching if many positions open or not a big issue with maxPositions=1.
ATR/MA Handles Re-Creation:
In OnDeinit you clean handles. In case of symbol/timeframe change, consider either restarting EA or re-creating handles accordingly (not included now).
Swing High/Low Lookback:
You use the swingLookback for swing detection on entry and trailing separately (ms_swingLookback).
This separation helps fine-tune trailing vs entry detection.
Reverse Logic Price Use:
In the reverse logic block inside OnTick, for sell orders you use bid as price, for buy ask. This is correct.
Just check that SL and TP calculations account for spread accurately to avoid instant SL hit.
Daily Loss Reset:
You set dailyLossResetTime at 00:00 server time. Make sure this aligns with trading day logic (you can adjust timezone if needed).
Potential Improvements:
Add spread filter: Avoid trades during high spread or non-ideal market conditions.
More precise swing detection: e.g., multiple swing points or confirmation candles.
Use ticks/volume data: For entries or trailing SL refinement.
Add comments on key trade decision points (you have good comments but some blocks can be elaborated for future maintainers).
Add trailing stop enable toggle per position or trading direction.
Overall:
Your EA code is modular, well-structured, and accounts for advanced trade management aspects. It should perform well on MT5 if parameters are tuned properly.
If you want me to check a specific part, add a feature, or optimize any logic, feel free to ask!
Improving profitability for an EA like your Advanced BoS EA involves both technical enhancements and strategic/parameter optimizations. Since your EA is already advanced with good risk management, here are some focused ideas and tactics—both code-related and strategy-level—to potentially boost profitability:
1. Refine Entry & Exit Conditions
a. Improve Swing Detection Accuracy
Currently, you just take the highest/lowest bar in a lookback to detect swing points, which can generate noise.
Ideas:
Use confirmed swing points (e.g., require swing high/low to be the pivot with certain bars before and after higher/lower).
Use fractals or zigzag indicators internally to confirm swing points more robustly.
Filter swing breaks by candlestick patterns (engulfing, pin bars, inside bars), confluence with volume spikes, or RSI divergence.
b. Add Additional Trend Confirmation
Trend is EMA-based on M15 currently.
Ideas:
Add multiple MAs (e.g., EMA50 + EMA200 crossover filter).
Include ADX to confirm trend strength – avoid trades when trend is weak.
Incorporate volume or momentum indicators (MACD, RSI) for entry confirmation.
c. Filter Trades by Volatility & Spread
Don't trade on low-volatility or extreme spread or news events.
Implement:
Check ATR or Bollinger Band width to ensure minimum volatility.
Use SymbolInfoDouble(_Symbol, SYMBOL_SPREAD) and skip trades if spread is above a threshold (e.g., 1.5x average spread).
Add a news filter (check economic calendar API or hard-code known news hours).
2. Optimize Risk & Money Management
a. Dynamic Lot Sizing
You calculate lot by risk %, but never scale up if confidence is higher.
Ideas:
Use confidence score (e.g., trend strength + entry signal strength) to increase lot size moderately on strong signals.
Use Kelly Criterion based on historical win rate and average RR to adjust lot size dynamically.
b. Max Daily Loss vs Max Risk per Trade Balance
Consider tightening max daily loss or max risk per trade during losing streaks, and loosening after profitability.
Implement:
Adaptive risk management based on recent trade results.
3. Trailing Stop & TP Improvement
a. Adaptive Trailing Stop
Currently trailing is fixed ATR multiples or market structure swings.
Ideas:
Make trailing stop distance dynamic based on volatility and recent swings.
Use partial closes and move SL to breakeven after 1R or 1.5R profit.
Use step-wise trailing: e.g., trail SL by 0.5 ATR initially, then tighten to 0.3 ATR if trend confirms.
b. Adaptive TP (Take Profit)
Fixed risk:reward of 2:1 may limit winning trade potential.
Ideas:
Scale out partial positions at 1R, then move SL to breakeven, and trail main position for larger profits.
Dynamically adjust TP based on recent swing highs/lows or ATR multiples.
If market is very strong trending, allow TP to be larger for bigger gains.
4. Enhance Position Management Logic
a. Multiple Entries / Scaling
Your EA limits to maxPositions=1 currently.
Ideas:
Add pyramiding on strong trends, with scale-in at safe pullbacks.
Alternatively, add averaging with strict max drawdown control (risky, but can be profitable if done well).
b. Add Position Exit Triggers Beyond SL/TP
Use time-based exits or indicator-based exits.
Examples:
Exit if momentum fades (e.g., RSI crosses neutral).
Exit if candle closes against trade on higher timeframe.
Time stop: close trade after certain bars or minutes if no progress.
5. Optimize Parameters Using Backtesting and Walk-Forward Testing
Use MT5 Strategy Tester to optimize ATR multipliers, lookback periods, MA periods, trailing logic settings.
Use Walk-Forward Analysis to test parameter robustness.
Avoid overfitting by testing over different market conditions and symbols.
6. Coding Enhancements to Support Strategy
Add more debug/info prints or export logs for detailed trade analytics.
Visualize key levels (swing highs/lows, SL/TP) dynamically for manual verification.
Implement more precise error recovery or retry logic on order failures.
Implement “soft stop” when max daily loss is exceeded—allow only partial position reduction or half lot sizes.
7. Alternative Trade Signals (Optional)
Add additional signal sources to confluence with Break Of Structure:
Dynamic lot sizing, adaptive risk based on streaks
Better risk-reward balance, fewer blowups
Trailing & TP
Partial closes, adaptive trailing and TP based on volatility
Locking profits, letting winners run
Position Management
Pyramiding, time exit, indicator-based exits
Flexible position size, avoid stubborn losers
Parameter Optimization
Use strategy tester+walk-forward
Robust parameters, avoid curve fitting
Coding & Info
Enhanced logging, error handling, visualization
Easier monitoring, faster tuning
Example Quick Code Focus - Add Spread Filter
Add below inside your OnTick() before entry logic:
mql5
double spread = SymbolInfoDouble(_Symbol, SYMBOL_SPREAD) * _Point; // spread in price units
double maxAllowedSpread = 15 * _Point; // allow max 15 pips (adjust as needed)
if(spread > maxAllowedSpread)
{
PrintFormat("Spread too high (%.1f), skipping trade", spread / _Point);
return; // skip this tick, no new trades
}
Final note:
No EA can guarantee consistent profits without adapting to market conditions. Combining solid strategy with constant monitoring, optimization, and occasional manual review will give you the best chance for long-term profitability.
If you want me to help create or tweak any of these enhancements, just ask!
Great! Let's start by implementing some of the suggested enhancements step-by-step to improve your EA’s profitability. I’ll guide you through adding the spread filter, enhancing trend confirmation with ADX, and improving the entry signal based on a more precise swing detection. After that, we can move on to trailing stops or adaptive TP if you want.
Step 1: Add Spread Filter
Place this near the start of your OnTick() before trading logic (right after the check for max positions and trading hours):
mql5
//--- Add Spread Filter to avoid poor conditions
double spread = SymbolInfoDouble(_Symbol, SYMBOL_SPREAD) * _Point; // current spread price
double maxAllowedSpreadPips = 15; // max allowed spread in pips (adjust as needed)
if(spread > maxAllowedSpreadPips * _Point)
{
PrintFormat("Spread too high (%.1f pips), skipping this tick for new entries.", spread / _Point);
return; // skip new trades on this tick
}
Step 2: Integrate ADX for Trend Strength Confirmation
Add ADX indicator handle in OnInit():
mql5
int adx_handle = INVALID_HANDLE;
void OnInit()
{
// your existing init code...
adx_handle = iADX(_Symbol, maTimeframe, 14); // 14 period default
if(adx_handle == INVALID_HANDLE)
{
Print("Failed to create ADX handle");
// handle error or return
}
}
Release handle in OnDeinit():
mql5
void OnDeinit(const int reason)
{
// your existing deinit code...
if(adx_handle != INVALID_HANDLE)
{
IndicatorRelease(adx_handle);
adx_handle = INVALID_HANDLE;
}
}
Now, in OnTick(), get ADX value and filter trades based on strength. Right before entry decisions: