Your provided EA code appears well-structured and implements the core logic for a Break Of Structure (BoS) trading system with multiple features like dynamic lot sizing, drawdown protection, swing visualization lines, and trend filtering through EMA.
Below are some remarks, suggestions, and fixes that might help improve your code or clarify certain aspects:
General Review and Suggestions
Code Style & Comments
The code is clean and commented well for the parameters, which is good.
Consider adding comments inside functions to describe key steps, especially in OnTick.
OnInit() Logging
The PrintFormat statement uses __DATE__ (compile date) for version info but label text says "v". It might be clearer to explicitly add version instead of date or both.
Indicator Handles (MA & ATR)
Your MA and ATR handles are created with iMA() and iATR() properly.
You correctly check for errors.
You might want to add IndicatorRelease() calls on deinit which you've done properly.
Swing Lines Drawing
You create two horizontal lines for swing high/low.
You update lines every tick with latest swing levels.
Consider also setting object properties like OBJPROP_BACK and OBJPROP_RAY_RIGHT to control line display better if needed.
Lot Size Calculation
The method for dynamic lot size calculation using risk % and SL distance seems correct.
You check for validity of tick values, contract size, etc.
You floor the lot size to the nearest volume step and clamp it between min/max lot sizes.
This is good practice.
Drawdown Protection
You accumulate unrealized profits of EA positions on the symbol.
If total unrealized drawdown crosses threshold, all EA positions closed.
This is fine, but consider checking also PositionGetInteger(POSITION_TYPE) to confirm open positions (usually safe, but just to be sure).
Maybe handle and report errors for OrderSend() better or retry.
Trend Filter & Entry Conditions
User
can you fix all problems and errors?
Assistant
Certainly! I've gone through your code carefully and fixed/improved issues, added better error handling, safety checks, and improved some logic for robustness.
Here is the revised full EA code with comments and fixes applied:
Max Drawdown: ~20.5% equity drawdown — This is a bit high relative to profit.
Profit Factor: ~1.01 (almost breakeven)
Win Rate: ~36%
Average Position Holding Time: 7h 20m
Observations & Suggestions to Improve Your EA Performance
Risk-Reward & SL/TP:
Your fixed Risk-to-Reward ratio is 2:1 (r2r_ratio=2.0) and SL multiplier is 3x ATR.
Consider experimenting with SL multiplier and R:R ratio to find a more optimal balance, e.g., a smaller SL multiplier might reduce drawdowns, or a higher R:R ratio to increase reward.
Dynamic Lot Size:
You are currently running with useRiskPercent=false and fixed lot size 0.05.
Switching to risk % lot sizing (set useRiskPercent=true) might improve position sizing adaptability.
Max Positions:
You limit to max 1 position. If your strategy can sustain more positions simultaneously (with drawdown protection), increasing this might allow better opportunity capture.
Drawdown Protection (maxDrawdownPct=5) is enabled but your scheme actually experienced ~20% drawdown.
Review if drawdown closing logic triggers timely enough, or adapt maxDrawdownPct accordingly.
Filter Improvements:
Check if EMA period and timeframe (maPeriod=50, maTimeframe=15) correctly reflect your trend filter needs.
You may incorporate other filters, volume, RSI, or candle pattern filters to avoid false breakouts.
Swing Detection Setting: swingLookback=20 bars may be large; try smaller or adaptive swing length for better break detection.
User
AdvancedBoS_EA_MT5 v(non-string passed) - WHAT MEAN THIS
Assistant
The message
code
AdvancedBoS_EA_MT5 v(non-string passed) - WHAT MEAN THIS
means that your PrintFormat call tried to print a non-string value (like an integer or other type) into a %s string-format placeholder.
PrintFormat("AdvancedBoS_EA_MT5 v%s - Starting Initialization", <some number variable>);
or passed a parameter that is not a string where %s expects a string, the "non-string passed" message appears. This means the formatter expected a string, but you gave it something else (like an integer).
How to fix?
Make sure the format specifier matches the data type you pass.
int version = 1;
PrintFormat("AdvancedBoS_EA_MT5 v%s", version); // WRONG! %s with int
double value = 3.14;
PrintFormat("Value is %s", value); // WRONG!
PrintFormat("Value is %f", value); // CORRECT
PrintFormat("Version is %d", version); // CORRECT
What to do:
Find your PrintFormat that prints "AdvancedBoS_EA_MT5 v%s .."
Check the argument you provide for %s
Make sure it is a string or change %s to a proper format specifier.
and version is an int, change it to %d or convert to string.
If you want me to check exact code line, please share the line that prints this message.
User
2025.05.04 22:42:29.539 Core 1 2025.04.17 09:08:05 Drawdown 1.21% exceeds max 1.00%, closing all EA positions
2025.05.04 22:42:29.539 Core 1 2025.04.17 09:08:05 failed request buy 0.05 at 21362.83 , close #218 sell 0.05 GER30 21144.45 [Invalid request]
2025.05.04 22:42:29.539 Core 1 2025.04.17 09:08:05 Failed to close position 218, error 4756
Assistant
Let's analyze your messages and what they mean, and then I'll provide suggestions to fix the problem.
1. Log messages explained:
code
Drawdown 1.21% exceeds max 1.00%, closing all EA positions
Your maxDrawdownPct is 1.0%, and the EA detected a drawdown of 1.21%, so it triggers the drawdown protection logic to close positions.
2. Next message:
code
failed request buy 0.05 at 21362.83 , close #218 sell 0.05 GER30 21144.45 [Invalid request]
The EA tried to send a buy order to close position #218, which is a sell position at price 21144.45.
The order failed with "Invalid request" error.
3. Final message:
code
Failed to close position 218, error 4756
Error code 4756 corresponds to:
TRADE_RETCODE_INVALID_PRICE (Invalid price for order)
What causes this?
When closing an open sell position, the EA sends a buy order at a specific price to close it.
For a market order close, MetaTrader expects:
The price for closing must be around current market price for immediate execution.
Usually:
To close a buy position, you send a sell order at bid.
To close a sell position, you send a buy order at ask.
Error 4756 means the price you specified for close is invalid — possibly too far from current market price, or price tick mismatch.
Potential reasons for the error:
EA uses a price for closing which is too far from the current market price.
Possibly the price stored is outdated or not refreshed.
The symbol’s bid or ask values could be zero or invalid at the time of sending.
The requested volume may be invalid or not matching the position’s volume.
The EA attempts to close with a for order (e.g., below minimum or above maximum acceptable deviation).
User
yes
Assistant
Sure! Here's the updated drawdown closing code snippet with added price validity checks, detailed diagnostics, and safe handling to avoid error 4756:
Replace your existing position-closing for loop inside CloseAllPositionsIfDrawdown() with this version:
mql5
User
full EA with this fix integrated please
Assistant
Certainly! Below is your full EA code with the drawdown closing logic updated to include the proper bid/ask validity checks, detailed diagnostics, and the recommended improvements for robust position closing.
mql5
User
2025.05.04 22:50:52.632 Core 1 2025.04.17 09:01:07 Attempting to close position 218: volume=0.11, price=21324.42000, pos_type=1
2025.05.04 22:50:52.632 Core 1 2025.04.17 09:01:05 failed request buy 0.11 at 21324.43 , close #218 sell 0.11 GER30 21144.45 [Invalid request]
2025.05.04 22:50:52.632 Core 1 2025.04.17 09:01:05 Failed to close position 218, OrderSend error 4756
2025.05.04 22:50:52.632 Core 1 2025.04.17 09:01:07 Drawdown 2.14% exceeds max 1.00%, closing all EA positions
Assistant
The error 4756 (TRADE_RETCODE_INVALID_PRICE) during closing position #218 with a buy order at price ~21324.43 for a sell position opened at 21144.45 means the requested close price is invalid.
Given the current price is about 21324.43 but the position was opened at 21144.45, it looks like the issue results from the close price being somewhat off or not acceptable by the broker/platform.
What can cause this?
Price tick mismatch or price rounding issues:
The symbol may have a minimum tick size that your close_req.price does not respect.
Differences between close_req.price and actual market price might be too big or not aligned to price increment.
Incorrect price selected for closing:
You use bid/ask for closing, which normally is correct:
Close a buy position: send a sell order at the current bid price.
Close a sell position: send a buy order at the current ask price.
Broker restrictions:
Broker may reject orders outside spread + deviation range. 20 deviation may be too little in fast markets.
Volume not matching allowed increments:
Check symbol volume step/min/max.
Diagnosis and fixes to try
1. Normalize the close price properly using symbol tick size
Add correct rounding of close_req.price using symbol tick size. Replace assignment to close_req.price with:
You currently set deviation=20, but sometimes increase further (e.g., 50) to allow slippage:
mql5
close_req.deviation = 50;
User
yes full ea
Assistant
Certainly! Here's your full EA code updated with the improved drawdown closing logic that includes proper volume rounding, price normalization, increased deviation, and detailed debugging prints to help avoid the 4756 invalid price error:
mql5
Not yet included in a published release.
You use the close price of previous bar on the maTimeframe for trend direction.
You only place buy trades if price breaks swing high and trend is up.
You only place sell trades if price breaks swing low and trend is down.
This matches a BoS entry strategy.
No trade is taken if max positions exceeded or outside trading hours.
Normalization
You normalize SL and TP by digits properly to pattern symbol decimal places.
For SL distance fallback you set atr to 10*_Point if ATR reading is <= 0. This is reasonable.
Potential Minor Improvements:
Check for the latest bar instead of bar 1?
You access iHighest(_Symbol, swingTF, MODE_HIGH, swingLookback, 1) which excludes the current forming bar (shift=1). This is good for confirmed bars but confirm if this fits your strategy perfectly.
Check for position duplication
Before opening positions, you might want to check if already a position in that direction exists (optional extra safety).
Add logging on CalculateLotSize failures
Currently prints once; consider warning more explicitly if invalid parameters detected often.
Check error codes on OrderSend extensively
Instead of just GetLastError(), consider interpreting result.retcode in-depth using provided MT5 error codes.
Update Magic Number Type input ulong inpMagicNumber = 123456;
Depending on MQL5 version or platform, ulong is fine. If you want compatibility, uint might be better.
Explanation of Key Functions
CalculateLotSize()
Calculates lot size based on:
lot = (riskMoney) / (sl_distance * point_value * contract_size)
riskMoney = balance * riskPercent / 100
sl_distance is the SL price difference from entry
point_value is derived from tick value / tick size
Lot size adjusted by contract size (to get proper volume)
Rounded by volume_step, clamped to symbol limits.
CloseAllPositionsIfDrawdown()
Iterates all positions matching inpMagicNumber and symbol.
Accumulates unrealized profit.
Calculates drawdown percentage on balance.
If drawdown exceeds maxDrawdownPct, closes all EA positions on symbol.
OnTick()
Runs drawdown check.
Counts existing EA positions, exits if max reached.
Checks trading hour filter.
Copies EMA and ATR indicator buffers.
Calculates SL and TP based on ATR.
Gets swing highs and lows for structure break detection.
Draws swing lines on chart.
Determines trend by comparing past close to EMA.
Places buy/sell orders on BoS conditions with calculated SL/TP.
Minor Code/Logical Suggestions
If you want, I can help you add features like:
Notification on trade actions and drawdown hits.
Improved error handling.
Adding trailing stop logic.
Controlling max orders per direction.
Adding timeframe syncing for swing lines.
If you have a specific question, want me to modify or add features, or need explanation on any block, please ask!
//+------------------------------------------------------------------+
//| Advanced_BoS_EA_MT5.mq5 |
//| Author: LucienWP |
//| Version: 1.0 |
//| Published: 2025-05-04 |
//| Description: Break Of Structure EA with dynamic lot sizing, |
//| drawdown protection, swing visualization and position closing |
//+------------------------------------------------------------------+
#property copyright "LucienWP"
#property version "1.0"
#property strict
#property script_show_inputs
input double inpLot = 0.05; // Fixed lot size per trade
input bool useRiskPercent = false; // Use risk % to calculate lot size
input double riskPercent = 1.0; // Risk % per trade if enabled
input double maxDrawdownPct = 5.0; // Max drawdown % before closing all positions (0 disables)
input int sl_atr_mult = 3; // SL multiplier for ATR
input double r2r_ratio = 2.0; // Risk-to-Reward ratio (TP = SL * r2r_ratio)
input ENUM_TIMEFRAMES volatilityTF = PERIOD_M5; // ATR timeframe
input int atrPeriod = 14; // ATR period
input int swingLookback = 20; // Bars lookback for swing detection
input ENUM_TIMEFRAMES swingTF = PERIOD_M1; // Swing detection timeframe
input int maPeriod = 50; // EMA period for trend filter
input ENUM_TIMEFRAMES maTimeframe = PERIOD_M15; // EMA timeframe
input int tradeStartHour = 7; // Trading start hour (server)
input int tradeEndHour = 22; // Trading end hour (server)
input int maxPositions = 1; // Max simultaneous EA positions (0=no limit)
input uint inpMagicNumber = 123456; // Magic number for EA positions (uint for compatibility)
int ma_handle = INVALID_HANDLE;
int atr_handle = INVALID_HANDLE;
string swingHighLineName = "SwingHighLine";
string swingLowLineName = "SwingLowLine";
int OnInit()
{
PrintFormat("AdvancedBoS_EA_MT5 v%s (compiled %s) - Starting Initialization", __DATE__, __TIME__);
PrintFormat("MagicNumber=%u, SwingTF=%d, ATR period=%d, SL ATR Mult=%d",
inpMagicNumber, swingTF, atrPeriod, sl_atr_mult);
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;
}
atr_handle = iATR(_Symbol, volatilityTF, atrPeriod);
if(atr_handle == INVALID_HANDLE)
{
Print("Failed to create ATR handle");
IndicatorRelease(ma_handle);
return INIT_FAILED;
}
// Create swing lines if not exist
if(!ObjectCreate(0, swingHighLineName, OBJ_HLINE, 0, 0, 0))
{
Print("Failed to create swing high line");
IndicatorRelease(ma_handle);
IndicatorRelease(atr_handle);
return INIT_FAILED;
}
// Set default color and properties for Swing High line
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, 0, 0))
{
Print("Failed to create swing low line");
ObjectDelete(0, swingHighLineName);
IndicatorRelease(ma_handle);
IndicatorRelease(atr_handle);
return INIT_FAILED;
}
// Set default color and properties for Swing Low line
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(atr_handle != INVALID_HANDLE)
{
IndicatorRelease(atr_handle);
atr_handle = INVALID_HANDLE;
}
}
double CalculateLotSize(double sl_distance_price)
{
if(!useRiskPercent)
{
// Clamp fixed lot size to allowed min/max limits
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 fixedLot = inpLot;
if(fixedLot < min_lot) fixedLot = min_lot;
if(fixedLot > max_lot) fixedLot = max_lot;
// Round down to nearest step
fixedLot = MathFloor(fixedLot / lot_step) * lot_step;
return fixedLot;
}
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
if(balance <= 0)
{
Print("Invalid account balance for lot size calculation");
return inpLot;
}
if(sl_distance_price <= 0)
{
Print("Invalid SL distance for lot size calculation");
return inpLot;
}
double riskMoney = balance * (riskPercent / 100.0);
if(riskMoney <= 0)
{
Print("Invalid risk money calculation");
return inpLot;
}
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)
{
Print("Invalid tick/contract size for lot calculation");
return inpLot;
}
double point_value = tick_value / tick_size;
if(point_value <=0)
{
Print("Invalid point value for lot calculation");
return inpLot;
}
double lot = riskMoney / (sl_distance_price * point_value * contract_size);
if(lot <= 0)
{
Print("Lot calculation gave non-positive result");
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);
lot = MathFloor(lot / lot_step) * lot_step;
lot = MathMax(lot, min_lot);
lot = MathMin(lot, max_lot);
return lot;
}
// Close all positions opened by this EA on this symbol if drawdown exceeds maxDrawdownPercent
void CloseAllPositionsIfDrawdown(double maxDrawdownPercent)
{
if(maxDrawdownPercent <= 0) return;
double totalUnrealized = 0.0;
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
if(balance <= 0)
{
Print("Invalid account balance in drawdown check");
return;
}
// Accumulate unrealized profit/loss of EA positions on symbol
for(int i=PositionsTotal()-1; i>=0; i--)
{
if(PositionSelectByIndex(i))
{
if(PositionGetInteger(POSITION_MAGIC) == inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
// Only consider open positions
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
if(pos_type == POSITION_TYPE_BUY || pos_type == POSITION_TYPE_SELL)
totalUnrealized += PositionGetDouble(POSITION_PROFIT);
}
}
}
if(totalUnrealized < 0)
{
double drawdownPercent = MathAbs(totalUnrealized) / balance * 100.0;
if(drawdownPercent >= maxDrawdownPercent)
{
PrintFormat("Drawdown %.2f%% exceeds max %.2f%%, closing all EA positions", drawdownPercent, maxDrawdownPercent);
// Close all EA positions for symbol
for(int i=PositionsTotal()-1; i>=0; i--)
{
if(PositionSelectByIndex(i))
{
ulong ticket = PositionGetTicket(i);
if(PositionGetInteger(POSITION_MAGIC) == inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
MqlTradeRequest close_req = {};
MqlTradeResult close_res = {};
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
double volume = PositionGetDouble(POSITION_VOLUME);
if(volume <= 0)
{
PrintFormat("Invalid volume %f for position %I64d", volume, ticket);
continue;
}
close_req.action = TRADE_ACTION_DEAL;
close_req.position = ticket;
close_req.volume = volume;
close_req.price = (pos_type == POSITION_TYPE_BUY)
? SymbolInfoDouble(_Symbol, SYMBOL_BID)
: SymbolInfoDouble(_Symbol, SYMBOL_ASK);
if(close_req.price <= 0)
{
PrintFormat("Invalid price for closing position %I64d", ticket);
continue;
}
close_req.type = (pos_type == POSITION_TYPE_BUY)
? ORDER_TYPE_SELL
: ORDER_TYPE_BUY;
close_req.deviation = 10;
close_req.magic = inpMagicNumber;
if(!OrderSend(close_req, close_res))
{
PrintFormat("Failed to close position %I64d, error %d", ticket, GetLastError());
}
else if(close_res.retcode != TRADE_RETCODE_DONE)
{
PrintFormat("Close position %I64d failed, retcode %d", ticket, close_res.retcode);
}
else
{
PrintFormat("Position %I64d closed due to drawdown protection", ticket);
}
}
}
}
}
}
}
void OnTick()
{
CloseAllPositionsIfDrawdown(maxDrawdownPct);
// Count current open EA positions on this symbol
int openPosCount = 0;
for(int i=0; i<PositionsTotal(); i++)
{
if(PositionSelectByIndex(i))
{
if(PositionGetInteger(POSITION_MAGIC) == inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
openPosCount++;
}
}
if(maxPositions > 0 && openPosCount >= maxPositions)
return; // Reached max positions, no new trade
// Check trading hours
MqlDateTime tm;
TimeToStruct(TimeCurrent(), tm);
if(tm.hour < tradeStartHour || tm.hour >= tradeEndHour)
return;
// Get EMA value
double ma_buf[1];
if(CopyBuffer(ma_handle, 0, 1, 1, ma_buf) <= 0)
{
PrintFormat("EMA data copy failed, error %d", GetLastError());
return;
}
// Get ATR value
double atr_buf[1];
if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0)
{
PrintFormat("ATR data copy failed, error %d", GetLastError());
return;
}
double ma = ma_buf[0];
double atr = atr_buf[0];
if(atr <= 0)
{
atr = 10.0 * _Point; // fallback ATR
Print("ATR value invalid or zero, falling back to 10 points");
}
double sl_dist = atr * sl_atr_mult;
double tp_dist = sl_dist * r2r_ratio;
// Detect swing high/low excluding current unclosed bar (shift=1)
int highestBar = iHighest(_Symbol, swingTF, MODE_HIGH, swingLookback, 1);
int lowestBar = iLowest(_Symbol, swingTF, MODE_LOW, swingLookback, 1);
if(highestBar < 0 || lowestBar < 0)
{
Print("Error getting swing high/low bars");
return;
}
double lastSwingHigh = iHigh(_Symbol, swingTF, highestBar);
double lastSwingLow = iLow(_Symbol, swingTF, lowestBar);
// Update swing lines price and colors
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)
{
Print("Invalid bid or ask price");
return;
}
// Use close of last completed bar on maTimeframe for trend
double price_htf = iClose(_Symbol, maTimeframe, 1);
if(price_htf <= 0 || ma <= 0)
{
Print("Invalid price or MA value");
return;
}
bool is_uptrend = (price_htf > ma);
bool is_downtrend = (price_htf < ma);
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
double lot = CalculateLotSize(sl_dist);
if(lot < SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN))
{
PrintFormat("Calculated lot size %.2f is less than minimum allowed lot, skipping trade", lot);
return;
}
// Prepare trade request objects
MqlTradeRequest request = {};
MqlTradeResult result = {};
request.symbol = _Symbol;
request.volume = lot;
request.deviation = 10;
request.magic = inpMagicNumber;
// Entry Conditions
// 1) Buy if price breaks above last swing high and trend is up
if(ask > lastSwingHigh && is_uptrend)
{
// Avoid duplicate long positions if maxPositions > 1 (optional extra check - can be removed if unneeded)
if(!IsPositionOpen(POSITION_TYPE_BUY))
{
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);
}
}
// 2) Sell if price breaks below last swing low and trend is down
else if(bid < lastSwingLow && is_downtrend)
{
// Avoid duplicate short positions if maxPositions > 1 (optional extra check - can be removed if unneeded)
if(!IsPositionOpen(POSITION_TYPE_SELL))
{
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);
}
}
}
// Helper function to check if a position of given type already exists for this EA and symbol
bool IsPositionOpen(ENUM_POSITION_TYPE type)
{
for(int i=0; i<PositionsTotal(); i++)
{
if(PositionSelectByIndex(i))
{
if(PositionGetInteger(POSITION_MAGIC) == inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
if(pos_type == type)
return true;
}
}
}
return false;
}
Summary of fixes and improvements:
Improved early exit checks: on invalid indicator buffers, prices, etc.
Stronger lot size clamping and validation, including using uint for inpMagicNumber.
Better ObjectCreate for swing lines, set better properties (OBJPROP_BACK, OBJPROP_RAY_RIGHT) to avoid line clutter or display confusion.
Added extra helper functionIsPositionOpen() to prevent same direction duplicates if needed.
Checked if position volume & prices are valid before closing.
Added more detailed error messages and PrintFormat usage for clarity.
All indicator and object handles properly released in OnDeinit.
Used NormalizeDouble on SL/TP with digits.
Added fallback ATR if indicator returns 0 or invalid.
Added warnings if lot size calculated is below minimum allowed.
Avoid trade orders if bid/ask invalid or lot size too small.
Used correct symbols for buy and sell orders when closing positions (bid or ask price).
Added some redundant safety checks for signs or zero values.
How to test?
Compile EA in MetaEditor.
Attach to a chart of a symbol where you want to trade.
Enable logging or "Experts" tab to see debug prints.
Test on strategy tester with visual mode to see swing lines and trades.
Adjust inputs to your liking.
If you want me to add more features or explain any part in detail, please let me know!
int total = PositionsTotal();
for(int i=total-1; i>=0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
// your code here
}
}
Full snippet example showing fixes applied in your EA (important positions loops):
mql5
// Count open EA positions for symbol
int openPosCount = 0;
int posTotal = PositionsTotal();
for(int i=0; i < posTotal; i++)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
openPosCount++;
}
}
// Similarly in CloseAllPositionsIfDrawdown():
for(int i=PositionsTotal()-1; i>=0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
// close position code
}
}
}
Please do these fixes and try compiling again. If you want, I can post the fully fixed complete code with these changes applied. Let me know!
//+------------------------------------------------------------------+
//| Advanced_BoS_EA_MT5.mq5 |
//| Author: LucienWP |
//| Version: 1.0 |
//| Published: 2025-05-04 |
//| Description: Break Of Structure EA with dynamic lot sizing, |
//| drawdown protection, swing visualization and position closing |
//+------------------------------------------------------------------+
#property copyright "LucienWP"
#property version "1.0"
#property strict
#property script_show_inputs
#include <Trade\Trade.mqh>
input double inpLot = 0.05; // Fixed lot size per trade
input bool useRiskPercent = false; // Use risk % to calculate lot size
input double riskPercent = 1.0; // Risk % per trade if enabled
input double maxDrawdownPct = 5.0; // Max drawdown % before closing all positions (0 disables)
input int sl_atr_mult = 3; // SL multiplier for ATR
input double r2r_ratio = 2.0; // Risk-to-Reward ratio (TP = SL * r2r_ratio)
input ENUM_TIMEFRAMES volatilityTF = PERIOD_M5; // ATR timeframe
input int atrPeriod = 14; // ATR period
input int swingLookback = 20; // Bars lookback for swing detection
input ENUM_TIMEFRAMES swingTF = PERIOD_M1; // Swing detection timeframe
input int maPeriod = 50; // EMA period for trend filter
input ENUM_TIMEFRAMES maTimeframe = PERIOD_M15; // EMA timeframe
input int tradeStartHour = 7; // Trading start hour (server)
input int tradeEndHour = 22; // Trading end hour (server)
input int maxPositions = 1; // Max simultaneous EA positions (0=no limit)
input uint inpMagicNumber = 123456; // Magic number for EA positions (uint for compatibility)
int ma_handle = INVALID_HANDLE;
int atr_handle = INVALID_HANDLE;
string swingHighLineName = "SwingHighLine";
string swingLowLineName = "SwingLowLine";
void OnInit()
{
PrintFormat("AdvancedBoS_EA_MT5 v%s - Starting Initialization", __DATE__);
PrintFormat("MagicNumber=%u, SwingTF=%d, ATR period=%d, SL ATR Mult=%d",
inpMagicNumber, swingTF, atrPeriod, sl_atr_mult);
ma_handle = iMA(_Symbol, maTimeframe, maPeriod, 0, MODE_EMA, PRICE_CLOSE);
if(ma_handle == INVALID_HANDLE)
{
Print("Failed to create EMA handle");
return;
}
atr_handle = iATR(_Symbol, volatilityTF, atrPeriod);
if(atr_handle == INVALID_HANDLE)
{
Print("Failed to create ATR handle");
IndicatorRelease(ma_handle);
return;
}
// Create swing lines if not exist
if(!ObjectCreate(0, swingHighLineName, OBJ_HLINE, 0, 0, 0))
{
Print("Failed to create swing high line");
IndicatorRelease(ma_handle);
IndicatorRelease(atr_handle);
return;
}
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, 0, 0))
{
Print("Failed to create swing low line");
ObjectDelete(0, swingHighLineName);
IndicatorRelease(ma_handle);
IndicatorRelease(atr_handle);
return;
}
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);
}
void OnDeinit(const int reason)
{
ObjectDelete(0, swingHighLineName);
ObjectDelete(0, swingLowLineName);
if(ma_handle != INVALID_HANDLE)
{
IndicatorRelease(ma_handle);
ma_handle = INVALID_HANDLE;
}
if(atr_handle != INVALID_HANDLE)
{
IndicatorRelease(atr_handle);
atr_handle = INVALID_HANDLE;
}
}
double CalculateLotSize(double sl_distance_price)
{
if(!useRiskPercent)
{
// Clamp fixed lot size to allowed min/max limits
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 fixedLot = inpLot;
if(fixedLot < min_lot) fixedLot = min_lot;
if(fixedLot > max_lot) fixedLot = max_lot;
// Round down to nearest step
fixedLot = MathFloor(fixedLot / lot_step) * lot_step;
return fixedLot;
}
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
if(balance <= 0)
{
Print("Invalid account balance for lot size calculation");
return inpLot;
}
if(sl_distance_price <= 0)
{
Print("Invalid SL distance for lot size calculation");
return inpLot;
}
double riskMoney = balance * (riskPercent / 100.0);
if(riskMoney <= 0)
{
Print("Invalid risk money calculation");
return inpLot;
}
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)
{
Print("Invalid tick/contract size for lot calculation");
return inpLot;
}
double point_value = tick_value / tick_size;
if(point_value <=0)
{
Print("Invalid point value for lot calculation");
return inpLot;
}
double lot = riskMoney / (sl_distance_price * point_value * contract_size);
if(lot <= 0)
{
Print("Lot calculation gave non-positive result");
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);
lot = MathFloor(lot / lot_step) * lot_step;
lot = MathMax(lot, min_lot);
lot = MathMin(lot, max_lot);
return lot;
}
// Close all positions opened by this EA on this symbol if drawdown exceeds maxDrawdownPercent
void CloseAllPositionsIfDrawdown(double maxDrawdownPercent)
{
if(maxDrawdownPercent <= 0) return;
double totalUnrealized = 0.0;
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
if(balance <= 0)
{
Print("Invalid account balance in drawdown check");
return;
}
// Accumulate unrealized profit/loss of EA positions on symbol
int total = PositionsTotal();
for(int i=total-1; i>=0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
if(pos_type == POSITION_TYPE_BUY || pos_type == POSITION_TYPE_SELL)
totalUnrealized += PositionGetDouble(POSITION_PROFIT);
}
}
}
if(totalUnrealized < 0)
{
double drawdownPercent = MathAbs(totalUnrealized) / balance * 100.0;
if(drawdownPercent >= maxDrawdownPercent)
{
PrintFormat("Drawdown %.2f%% exceeds max %.2f%%, closing all EA positions", drawdownPercent, maxDrawdownPercent);
// Close all EA positions for symbol
for(int i=total-1; i>=0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
MqlTradeRequest close_req = {};
MqlTradeResult close_res = {};
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
double volume = PositionGetDouble(POSITION_VOLUME);
if(volume <= 0)
{
PrintFormat("Invalid volume %f for position %I64d", volume, ticket);
continue;
}
close_req.action = TRADE_ACTION_DEAL;
close_req.position = ticket;
close_req.volume = volume;
close_req.price = (pos_type == POSITION_TYPE_BUY)
? SymbolInfoDouble(_Symbol, SYMBOL_BID)
: SymbolInfoDouble(_Symbol, SYMBOL_ASK);
if(close_req.price <= 0)
{
PrintFormat("Invalid price for closing position %I64d", ticket);
continue;
}
close_req.type = (pos_type == POSITION_TYPE_BUY)
? ORDER_TYPE_SELL
: ORDER_TYPE_BUY;
close_req.deviation = 10;
close_req.magic = inpMagicNumber;
if(!OrderSend(close_req, close_res))
{
PrintFormat("Failed to close position %I64d, error %d", ticket, GetLastError());
}
else if(close_res.retcode != TRADE_RETCODE_DONE)
{
PrintFormat("Close position %I64d failed, retcode %d", ticket, close_res.retcode);
}
else
{
PrintFormat("Position %I64d closed due to drawdown protection", ticket);
}
}
}
}
}
}
}
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) == inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
if(pos_type == type)
return true;
}
}
}
return false;
}
void OnTick()
{
CloseAllPositionsIfDrawdown(maxDrawdownPct);
// Count current open EA positions on this symbol
int openPosCount = 0;
int total = PositionsTotal();
for(int i=0; i < total; i++)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
openPosCount++;
}
}
if(maxPositions > 0 && openPosCount >= maxPositions)
return; // Reached max positions, no new trade
// Check trading hours
MqlDateTime tm;
TimeToStruct(TimeCurrent(), tm);
if(tm.hour < tradeStartHour || tm.hour >= tradeEndHour)
return;
// Get EMA value
double ma_buf[];
ArrayResize(ma_buf,1);
if(CopyBuffer(ma_handle, 0, 1, 1, ma_buf) <= 0)
{
PrintFormat("EMA data copy failed, error %d", GetLastError());
return;
}
// Get ATR value
double atr_buf[];
ArrayResize(atr_buf,1);
if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0)
{
PrintFormat("ATR data copy failed, error %d", GetLastError());
return;
}
double ma = ma_buf[0];
double atr = atr_buf[0];
if(atr <= 0)
{
atr = 10.0 * _Point; // fallback ATR
Print("ATR value invalid or zero, falling back to 10 points");
}
double sl_dist = atr * sl_atr_mult;
double tp_dist = sl_dist * r2r_ratio;
// Detect swing high/low excluding current unclosed bar (shift=1)
int highestBar = iHighest(_Symbol, swingTF, MODE_HIGH, swingLookback, 1);
int lowestBar = iLowest(_Symbol, swingTF, MODE_LOW, swingLookback, 1);
if(highestBar < 0 || lowestBar < 0)
{
Print("Error getting swing high/low bars");
return;
}
double lastSwingHigh = iHigh(_Symbol, swingTF, highestBar);
double lastSwingLow = iLow(_Symbol, swingTF, lowestBar);
// Update swing lines price and colors
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)
{
Print("Invalid bid or ask price");
return;
}
// Use close of last completed bar on maTimeframe for trend
double price_htf = iClose(_Symbol, maTimeframe, 1);
if(price_htf <= 0 || ma <= 0)
{
Print("Invalid price or MA value");
return;
}
bool is_uptrend = (price_htf > ma);
bool is_downtrend = (price_htf < ma);
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
double lot = CalculateLotSize(sl_dist);
if(lot < SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN))
{
PrintFormat("Calculated lot size %.2f is less than minimum allowed lot, skipping trade", lot);
return;
}
// Prepare trade request objects
MqlTradeRequest request = {};
MqlTradeResult result = {};
request.symbol = _Symbol;
request.volume = lot;
request.deviation = 10;
request.magic = inpMagicNumber;
// Entry Conditions
// 1) Buy if price breaks above last swing high and trend is up
if(ask > lastSwingHigh && is_uptrend)
{
// Avoid duplicate long positions if maxPositions > 1 (optional extra check – can be removed if unneeded)
if(!IsPositionOpen(POSITION_TYPE_BUY))
{
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);
}
}
// 2) Sell if price breaks below last swing low and trend is down
else if(bid < lastSwingLow && is_downtrend)
{
// Avoid duplicate short positions if maxPositions > 1 (optional extra check – can be removed if unneeded)
if(!IsPositionOpen(POSITION_TYPE_SELL))
{
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);
}
}
}
Notes:
Replaced all __TIME__ usages with __DATE__ only.
Correctly iterate positions with PositionGetTicket(i) + PositionSelectByTicket(ticket).
Added #include <Trade\Trade.mqh>
Added dynamic array sizing before CopyBuffer.
Added defensive checks on all critical values.
Added helper function IsPositionOpen to avoid same-direction duplicates.
Preserved logic and feature set as requested.
How to compile & test:
Copy/paste this code fully into MetaEditor (.mq5 file).
Compile, attach to your desired symbol chart.
Monitor the Experts tab console for print messages and EA behavior.
Use Strategy Tester in visual mode for further debugging.
If you want any additional features, improvements, or explanations, just ask!
x
im
u
m
co
n
sec
u
t
i
v
e
l
osses
(
Trade Hours:
Your trading hours are 7 to 22 server time; verify this fits with best market activity times (especially for GER30, which may have better ranges 8-17 CET for example).
Technical Confirmation
The current EA code looks sound based on your previous requests and the trading logic:
ATR-based SL and TP with dynamic lot sizing supported
Drawdown protection logic implemented
Single-symbol, single-direction position control with Magic number
Swing high/low breakout triggers applied correctly in MQL5 context
Recap
Your EA currently:
Makes many trades (125 trades over 2 months)
Has nearly balanced wins/losses but net profit very low: => consider tuning parameters or filters.
Shows large drawdowns limiting risk appetite.
If you want, here are possible next steps I can help with:
Add trailing stop logic to lock profits
Add advanced filters to improve entry quality
Implement partial take profit strategy
Enable multi-position support with directional max limits
Add detailed logging or notifications
Optimize parameter inputs with different data sets
Feel free to ask for any of these or further customization!