Drawdown 1.00% exceeds max 1.00%, closing all EA positions
OE 0 23:00:46.028 Core 1 2025.03.03 10:31:25 Closing pos 2 (type 0) vol=0.10 at price=22532.81000 bid=22532.81000 ask=22537.36000 deviation=50
PF 2 23:00:46.028 Core 1 2025.03.03 10:31:25 failed request sell 0.1 at 22532.81 , close #2 buy 0.1 GER30 22629.07 [Invalid request]
KK 0 23:00:46.028 Core 1 2025.03.03 10:31:25 Failed to close position 2, OrderSend error 4756
MG 0 23:00:46.028 Core 1 2025.03.03 10:31:25 Drawdown 1.00% exceeds max 1.00%, closing all EA positions
HF 0 23:00:46.028 Core 1 2025.03.03 10:31:25 Closing pos 2 (type 0) vol=0.10 at price=22532.58000 bid=22532.58000 ask=22537.13000 deviation=50
RI 2 23:00:46.028 Core 1 2025.03.03 10:31:25 failed request sell 0.1 at 22532.58 , close #2 buy 0.1 GER30 22629.07 [Invalid request]
MF 0 23:00:46.028 Core 1 2025.03.03 10:31:25 Failed to close position 2, OrderSend error 4756
HS 0 23:00:46.028 Core 1 2025.03.03 10:31:25 Drawdown 1.01% exceeds max 1.00%, closing all EA positions
OS 0 23:00:46.028 Core 1 2025.03.03 10:31:25 Closing pos 2 (type 0) vol=0.10 at price=22532.36000 bid=22532.36000 ask=22536.91000 deviation=50
HL 2 23:00:46.028 Core 1 2025.03.03 10:31:25 failed request sell 0.1 at 22532.36 , close #2 buy 0.1 GER30 22629.07 [Invalid request]
OE 0 23:00:46.028 Core 1 2025.03.03 10:31:25 Failed to close position 2, OrderSend error 4756
JP 0 23:00:46.028 Core 1 2025.03.03 10:31:25 Drawdown 1.01% exceeds max 1.00%, closing all EA positions
PL 0 23:00:46.028 Core 1 2025.03.03 10:31:25 Closing pos 2 (type 0) vol=0.10 at price=22532.14000 bid=22532.14000 ask=22536.69000 deviation=50
NO 2 23:00:46.028 Core 1 2025.03.03 10:31:25 failed request sell 0.1 at 22532.14 , close #2 buy 0.1 GER30 22629.07 [Invalid request]
QP 0 23:00:46.028 Core 1 2025.03.03 10:31:25 Failed to close position 2, OrderSend error 4756
DM 0 23:00:46.028 Core 1 2025.03.03 10:31:25 Drawdown 1.01% exceeds max 1.00%, closing all EA positions
FI 0 23:00:46.028 Core 1 2025.03.03 10:31:25 Closing pos 2 (type 0) vol=0.10 at price=22531.92000 bid=22531.92000 ask=22536.47000 deviation=50
GR 2 23:00:46.028 Core 1 2025.03.03 10:31:25 failed request sell 0.1 at 22531.92 , close #2 buy 0.1 GER30 22629.07 [Invalid request]
CO 0 23:00:46.028 Core 1 2025.03.03 10:31:25 Failed to close position 2, OrderSend error 4756
CJ 0 23:00:46.028 Core 1 2025.03.03 10:31:26 Drawdown 1.01% exceeds max 1.00%, closing all EA positions
NE 0 23:00:46.028 Core 1 2025.03.03 10:31:26 Closing pos 2 (type 0) vol=0.10 at price=22531.69000 bid=22531.69000 ask=22536.24000 deviation=50
HE 2 23:00:46.028 Core 1 2025.03.03 10:31:26 failed request sell 0.1 at 22531.69 , close #2 buy 0.1 GER30 22629.07 [Invalid request]
DJ 0 23:00:46.028 Core 1 2025.03.03 10:31:26 Failed to close position 2, OrderSend error 4756
EK 0 23:00:46.028 Core 1 2025.03.03 10:31:26 stop loss triggered #2 buy 0.1 GER30 22629.07 sl: 22531.53 tp: 22824.14 [#3 sell 0.1 GER30 at 22531.53]
Assistant
The log you posted shows an Expert Advisor (EA) attempting to close all positions when the drawdown threshold of 1.00% is exceeded, but failing with repeated "Invalid request" and "OrderSend error 4756" messages on closing position #2 (a buy of GER30). Finally, a stop loss on that position triggers.
What does this mean?
Drawdown exceeded: The EA's risk control activated since losses reached/exceeded 1.00%.
Attempted closing: The EA tries multiple times to close position #2 (buy GER30), with repeated failures.
OrderSend error 4756: MetaTrader error code indicating "Invalid trade volume" or an issue with the order parameters.
Invalid request: Usually means the trade request is malformed or doesn't meet broker/server requirements.
Stop loss triggered at last line: Position closed automatically by the broker's stop loss mechanism.
Possible issues and suggestions:
Trade volume or symbol mismatch
Although the volume is 0.10 lots (which seems normal), the repeated invalid request errors suggest something wrong with the trade request:
Check if for the symbol GER30 the minimum volume, step size or maximum volume limits are being respected.
Confirm the symbol name is correct — does the broker use "GER30" exactly or a different symbol name?
Price / Deviation issue
The prices attempting to close at might be invalid or the deviation parameter (slippage tolerance) is too low/high.
Validate the price used in OrderSend matches the current market prices.
Consider increasing the allowed deviation.
OrderSend with wrong order type or times
Ensure the EA is sending a close order for the existing position, i.e., sending a SELL to close a BUY, with correct parameters.
Check that the EA isn't trying to close an already closed or nonexistent position.
Broker restrictions
Some brokers have restrictions on partial close, minimal lot sizes, or cannot close at market under certain conditions.
Verify broker rules.
Test manual closing similarly sized position to rule out broker-specific issues.
EA logic problem
The EA might be attempting the close in a wrong way or ignoring errors.
Add verbose debugging in EA code for trade requests and check response codes.
User
this is the code:
//+------------------------------------------------------------------+
//| 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";
// 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);
Assistant
Your CloseAllPositionsIfDrawdown() function looks mostly correct in principle, but based on your error logs, the root of the “OrderSend error 4756 [Invalid request]” problem is very likely caused by the volume normalization and rounding logic inside your position-closing loop.
Key issues in the CloseAllPositionsIfDrawdown() code related to error 4756:
Volume rounding incorrectly can result in zero volume:
Your logic rounds down volume like this:
mql5
volume = MathFloor(volume / vol_step) * vol_step;
If volume is equal to the minimum volume exactly, or slightly above it but less than one full vol_step, this rounding may zero out the volume or reduce it below minimum allowed volume, silently invalidating the volume.
You clamp volume before rounding instead of after rounding:
This is wrong because rounding down after clamping may drop it below min_vol.
Ignoring volume precision digits:
Some symbols require volume rounded to a certain number of decimal places consistent with SYMBOL_VOLUME_STEP; you do not normalize volume with NormalizeDouble.
How to fix this?
Use this volume normalization approach when closing positions:
mql5
User
please update code
Assistant
Certainly! Here's an updated version of the CloseAllPositionsIfDrawdown() function with a proper volume normalization helper function included and integrated. This should fix the "OrderSend error 4756" issue by correctly rounding and clamping the volume before sending the close order.
Updated code snippet (replace inside your EA):
mql5
User
give me full code updated
Assistant
Certainly! Below is your full EA code, updated with the fixed drawdown closing logic that includes the proper NormalizeVolume function and the improved CloseAllPositionsIfDrawdown() function integrating that fix.
mql5
User
same error
Assistant
The persistent OrderSend error 4756 (Invalid request) when closing a position—despite the volume normalization fix—strongly suggests that the issue is related to something beyond just the volume rounding. Let me guide you through additional troubleshooting steps and code modifications that will likely resolve this:
Possible causes and solutions beyond volume rounding:
1. Incorrect use of close_req.position
In MT5, when closing a position with PositionClose type requests, trade.position is not always accepted as in MT4. Instead, you should use a TRADE_ACTION_CLOSE_POSITION or TRADE_ACTION_DEAL with the proper closure approach.
But Microsoft documentation and multiple examples show that to close a position by ticket, you should use:
mql5
close_req.action = TRADE_ACTION_CLOSE_BY;
close_req.position = ticket;
close_req.volume = volume;
// optionally set price & deviation, but often not needed
Or, the most consistent approach is to use OrderClose via Trade.PositionClose() function available in CTrade class (from Trade.mqh library).
2. Suggestion — Use CTrade::PositionClose
It greatly simplifies closing positions by ticket and handles all the complexities internally.
Example:
mql5
User
please
Assistant
Sure! Below is your full updated EA code, replacing the manual close logic inside CloseAllPositionsIfDrawdown() with calls to CTrade::PositionClose(), which is the recommended and reliable way to close positions in MT5.
Complete Updated Code with CTrade::PositionClose() used for closing:
mql5
User
please remove this block/option Max drawdown % before closing all positions
Assistant
Certainly! I have removed the maxDrawdownPct input and all related drawdown checking and position closing code from the EA.
Below is the revised full EA code without the max drawdown drawdown protection and closing logic:
mql5
User
tell me about atr trailing stop
Assistant
Certainly! Here's an explanation of the ATR Trailing Stop, what it is, how it works, and how traders use it:
What is ATR?
ATR (Average True Range) is a technical indicator developed by J. Welles Wilder that measures market volatility. It calculates the average range (high to low) of price movements over a specified period, regardless of direction.
Higher ATR = higher volatility.
Lower ATR = lower volatility.
ATR is useful because it adapts stops dynamically based on how much price moves, rather than fixed points/pips.
What is an ATR Trailing Stop?
An ATR trailing stop is a volatility-based trailing stop-loss order that moves the stop level in the direction of a trade as price moves favorably. It uses the ATR indicator to determine how far away the stop should be from the current price.
How it works:
Calculate the ATR value over a certain period (usually 14 periods).
Multiply ATR by a factor or multiplier (e.g., 1.5, 2, 3) to get stop distance.
For a long (buy) trade, the trailing stop price = current highest price since entry - (ATR * multiplier).
For a short (sell) trade, trailing stop price = current lowest price since entry + (ATR * multiplier).
As price moves in your favor, the trailing stop moves up (long) or moves down (short) accordingly, never retracting.
If price reverses and hits the trailing stop, the position is closed, locking in profits or limiting losses.
Benefits of ATR trailing stop:
Dynamic adjustment: adapts to market volatility — wide stop in volatile markets, tighter in calm markets.
Avoids premature stop-out: stops aren’t fixed, so normal market noise less likely to close you out.
Locks profit: trailing stop moves with price, locking profits as trend continues.
Simple and rule based: easy to automate in EAs/scripts.
Example:
ATR(14) = 20 pips
Multiplier = 3
Stop distance = 20 * 3 = 60 pips
A buy trade opens at 1.2000. Your trailing stop is calculated as:
Trailing stop = Highest price since entry - 60 pips.
So if the highest price reaches 1.2100, trailing stop moves up to 1.2040 (1.2100 - 0.0060). The stop only moves up (never down). If price falls to 1.2040, the position closes.
User
add this option to my ea
Assistant
Certainly! I'll help you add an ATR trailing stop option to your existing EA.
What I'll do:
Add a new input option to enable/disable ATR trailing stop.
Add an input for the ATR multiplier that controls trailing distance.
On every tick, if you have an open position, update its stop loss using the ATR trailing stop method:
For buy: new SL = highest price since entry - ATR * multiplier
For sell: new SL = lowest price since entry + ATR * multiplier
Only move the stop in the favorable direction (don't move stop backwards).
Modify your OnTick() to update stops accordingly.
Updated code snippets and instructions:
1. Add inputs at the top (below your existing inputs):
The built-in iATR function returns an indicator handle and takes only 3 parameters:
mql5
int iATR(
const string symbol, // symbol name
ENUM_TIMEFRAMES timeframe,// timeframe
int period // ATR period
);
To get the ATR value at a specific shift/bar, you need to first create a handle with iATR(), then call CopyBuffer() on that handle to retrieve the ATR values.
How to fix it properly?
Since you already have atr_handle created in your OnInit:
Use CopyBuffer() on atr_handle to fetch ATR values
This applies also for ma_handle or any indicator handles you create
If you want, I can provide the fixed UpdatePositionATRTrailingStop() function with the correct ATR reading implemented.
User
complete code plese
Assistant
Certainly! Below is your full EA code with the ATR trailing stop properly fixed to use the ATR handle and CopyBuffer, including all previous improvements and properly fetching ATR values inside the trailing stop update function.
mql5
User
i was checking the trades, ea dont place tp, all trades are closed by trailing stop only
Assistant
This behavior is expected because your EA modifies the stop loss dynamically using the ATR trailing stop but does not update the take profit (TP) after the trade is opened. Thus, the initially set TP remains fixed, and if the trailing stop is hit first (or if TP is not properly set), trades close by the trailing stop.
You need to ensure your TP is placed further than the freeze level plus spread.
3. Optionally update TP dynamically
If you want to move or manage TP dynamically in the same way you do the trailing stop, you can:
Compute a new TP price on each OnTick (for example, setting a fixed reward-to-risk ratio or locking in profits)
Use MqlTradeRequest with TRADE_ACTION_SLTP to modify the TP similarly to how you modify SL in UpdatePositionATRTrailingStop()
User
i have this option : Risk-to-Reward ratio (TP = SL * r2r_ratio), it must work
Assistant
Yes, your existing Risk-to-Reward ratio (TP = SL * r2r_ratio) should indeed work and your EA does set the TP at order open accordingly. However, if your trades are all closing by the trailing stop rather than TP, it usually means:
Either TP was not set properly (due to minimal distance/restrictions),
Or TP is too far away to be reached,
Or TP gets invalidated (for example modified or removed),
Or market pulls back hitting trailing stop before TP happens.
What to check and fix to make sure TP works per your R:R ratio:
1. Verify TP distance is valid and complies with broker minimums
Get minimal allowed TP distance (SYMBOL_TRADE_FREEZE_LEVEL) and check if your computed TP is at least that far from open price.
If TP is 0 or not printed correctly, it wasn’t set.
3. Adjust your TP calculation
Make sure initial TP is:
For buy: TP > Price + minimal distance
For sell: TP < Price - minimal distance
If this is violated, TP won't be accepted or appear on chart.
4. Check if EA or broker removes/modifies TP
If you modify SL dynamically but not TP, sometimes broker or EA itself may remove TP — check logs and EA code for TP reset or removal.
User
remove art stop loss option
Assistant
Certainly! Below is your full EA code with the ATR trailing stop feature completely removed — all associated inputs, variables, and functions related to ATR trailing stop have been deleted, so the EA will no longer modify stops dynamically.
mql5
User
dinamyc trail stop based on market structure?
Assistant
A dynamic trailing stop based on market structure typically means adjusting your stop loss levels to recent swing highs and lows (support and resistance levels), or other significant price action points, instead of fixed pips or volatility indicators like ATR.
Concept:
For a long position, trailing stop is placed just below recent swing lows.
For a short position, trailing stop is placed just above recent swing highs.
As the market moves favorably, the stop moves accordingly to protect profits but only moves in the direction to tighten the stop.
This method adapts the stop loss to price action, possibly preventing premature stop outs compared to fixed trailing stops.
How to implement it?
Detect recent swing highs and swing lows (your EA already uses swings).
For long trades, trail the stop below swing lows that occur after your position entry.
For short trades, trail the stop above swing highs that occur after your position entry.
Update the stop loss only if the new stop is more favorable than the current stop.
On each tick, check if trailing stop should be moved.
Sample approach using your existing swing detection:
Since your EA uses swing highs/lows lines (swingHighLineName, swingLowLineName), you can:
Use those swing levels to update your stop loss dynamically.
Or scan recent bars for actual swing highs/lows dynamically per position.
Simplified code snippet concept (you'll integrate into OnTick or dedicated function):
mql5
User
yes please
Assistant
Certainly! Below is your EA code with a dynamic trailing stop based on market structure (recent swing highs/lows) fully integrated.
What was added:
UpdateTrailingStopByMarketStructure(ulong position_ticket) function to trail stops just beyond recent swing lows (for longs) or swing highs (for shorts)
This function is called on every tick for all open EA positions before any new trades
Trailing stop updates only move the SL in a favorable direction (never backward)
A small buffer (2 points) is used to place the trailing stop slightly beyond the swing level
Configurable swingLookback input from your original settings defines the lookback period for swings
Full updated EA code snippet — focused on trailing stop part with your existing logic intact:
mql5
User
full complete EA
Assistant
Certainly! Below is the full complete EA code with your existing logic plus a dynamic trailing stop based on market structure, trailed to recent swing highs/lows with a small buffer, integrated neatly into the OnTick() function.
mql5
User
this deactivated the tp,
Assistant
The dynamic trailing stop based on market structure should not inherently deactivate or remove the initial Take Profit (TP). However, in many brokers or MT5 environments, modifying the stop loss alone (via a TRADE_ACTION_SLTP request) without explicitly including TP can sometimes cause the TP to be reset or removed, depending on broker/server behavior.
Why TP might disappear?
When you send a TRADE_ACTION_SLTP request setting only SL and omitting TP, some brokers reset TP to zero.
To avoid this, include both current SL and TP in your modify request.
Or explicitly maintain the existing TP on each SL modification.
How to fix in your EA:
When updating SL dynamically, always read the current TP and send it along with the SL in the OrderSend modify request.
Fix in UpdateTrailingStopByMarketStructure function:
Replace your modifying portion with logic to:
Get current TP from the position.
Include that TP in the modification request alongside the new SL.
Example code snippet:
mql5
User
yes please, and another update, sl must trail after price is at half distance of tp
Assistant
Certainly! Below is your full updated EA with two key improvements:
Trailing stop updates include current TP on every modify request, so TP remains active and visible on the chart.
Trailing stop only moves if price has advanced at least halfway toward the TP, i.e., SL starts trailing once price reaches 50% of the distance to TP.
Key logic for (2):
For longs: trail SL only if current Bid price >= Entry price + 0.5 * (TP - Entry price)
For shorts: trail SL only if current Ask price <= Entry price - 0.5 * (Entry price - TP)
After price crosses halfway, trailing stop moves toward swing low/high as before.
Full EA source code with requested updates:
mql5
User
option to enable or disable this Trailing SL
Assistant
Certainly! You can add a simple boolean input to enable or disable the trailing stop feature. Then, just wrap the trailing stop update call inside an if condition checking that flag.
Here is the relevant modification to add to the EA:
1. Add input at the top (with other inputs):
mql5
input bool enableTrailingSL = true; // Enable dynamic trailing stop based on market structure
2. Wrap the trailing stop update call in OnTick() with this check:
mql5
void OnTick()
{
if(enableTrailingSL)
{
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)
{
UpdateTrailingStopByMarketStructure(ticket);
}
}
}
}
// ... rest of your OnTick trading logic here unchanged
}
Your existing code remains intact, just this simple toggle input and if-condition control whether trailing stop logic executes.
Full snippet example integrated with your existing EA:
mql5
input bool enableTrailingSL = true; // Enable dynamic trailing stop based on market structure
// --- inside OnTick ---
void OnTick()
{
if(enableTrailingSL)
{
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)
{
UpdateTrailingStopByMarketStructure(ticket);
}
}
}
}
// rest of your tick/open trade code here
}
This way you can enable or disable the market-structure trailing stop easily in inputs without modifying your EA further.
If you want, I can provide the full updated EA source with this toggle fully integrated as well!
User
please
Assistant
Certainly! Below is your full complete EA source with a new input enableTrailingSL that lets you easily enable or disable the dynamic trailing stop based on market structure:
Your tester report shows the EA is placing orders with SL and TP properly set, trailing stops adjust SL, and the strategy is overall profitable but with some drawdowns.
If you want any help interpreting this report, further improving the EA, or testing variations — just ask!
If you want, here are some quick notes based on your report:
Total Net Profit 342.21 USD on 10,000 USD over two months (M1) is modest but positive.
Drawdown ~19.9% is fairly high vs profit — may want to optimize risk or trailing stop parameters.
Win rate is about 36%-37% for longs and shorts — fairly typical for strategies relying on R:R > 2.0.
Largest wins larger than largest losses, showing positive expectancy.
Max consecutive losses is 10 trades — consider if setting max drawdown or max loss limits might help.
Positions held on average ~7 hours shows this is a swing-style or daytrading style EA.
You might experiment with input values (ATR multipliers, R:R ratio, swing lookback) to manage drawdown and improve net profit.
Feel free to share any specific questions or next steps you'd like to pursue!
User
not great results
Assistant
Your summary is correct — the results indicate a modest profit with fairly high drawdown and a relatively low win rate, which can be improved. Here are some recommendations to potentially improve performance:
Suggestions to improve your EA’s results:
Optimize Parameters
ATR multiplier (sl_atr_mult): Adjust to balance between too tight (many stop-outs) and too loose (big losses).
Risk-to-Reward ratio (r2r_ratio): Testing different values might improve payoff and trade exit quality.
Swing lookback (swingLookback): Adjust how far you detect swing highs/lows which drive trailing stops.
Time filters: Consider narrowing trading window or avoiding low-volume hours to reduce noise.
Add More Filters
Use additional trend filters (e.g., higher timeframe confirmation).
Use volume or volatility filters (e.g., minimum ATR, session volume).
Max Drawdown or Max Loss Cutoff
Consider adding an equity or balance drawdown cutoff that disables trading or closes positions to limit losses.
Improved Trade Management
Dynamically adjust TP like SL (e.g., trail TP or lock in partial profits).
Smart position sizing aligned with market volatility and account size.
Backtest on Different Symbols or Timeframes
Sometimes the EA logic suits certain markets/timeframes better. Consider trying e.g. 5m, 15m charts or different indices.
Forward Test or Demo Run
Sometimes strategy holds up differently in live vs test environments. Use demo accounts for validation.
Next Steps:
If you want, I can help by:
Building an optimization script to test various input combos.
Adding additional filters or money management features.
Helping you analyze equity curve and trades for patterns.
Feel free to share your goals/expectations and I’ll assist!
User
Building an optimization script to test various input combos.
Assistant
Certainly! To build an optimization script for your EA inputs, you basically need to prepare a testing framework that can systematically run your EA over a range of input parameter combinations, collect the results, and help you analyze which combinations perform better.
Key points of optimization in MetaTrader 5 (MT5):
Built-in Strategy Tester Optimization:
The MT5 platform itself has a very powerful built-in optimization tool that lets you automatically vary input parameters over specified ranges to find best results.
Creating an Optimization Script:
If you want to automate or enhance the optimization process via code (e.g. for custom post-processing), you can create an MQL5 script that loops through parameter values, launches tests and gathers results using the Tester API.
Recommended Approach: Use MT5 Optimization with your EA inputs defined
You don't usually have to write an optimizer script manually since MT5 supports "Input Parameter Optimization" out-of-the-box.
Here's how to set it up for your EA:
Define input parameters properly in your EA (you already have this):
Choose "Optimization" method in Strategy Tester (instead of "Single test").
Set the optimization criteria, e.g., maximize net profit, Sharpe ratio, etc.
Start optimization — MT5 will test all combinations and produce detailed results.
Analyze results directly in Strategy Tester. You can export them or view them with built-in visualization.
Not yet included in a published release.
Next steps to fix:
Review the EA code where OrderSend is called for closing.
Check if PositionSelect confirms the position before sending a close.
Log the exact parameters sent to OrderSend (symbol, volume, price, deviation).
Compare requested close price to market prices.
Confirm the minimum and step lot size for GER30 with your broker.
Try closing the position manually on the platform to replicate.
Summary:
The EA triggered a forced close due to drawdown but failed repeatedly to close the position due to "Invalid request" and error 4756 (likely caused by incorrect volume or invalid price parameters). Finally, the broker’s stop loss triggered and closed the position. To fix, check and adjust EA's order close logic, trade parameters, and confirm with the broker the requirements for closing the positions.
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;
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 to round volume correctly respecting step and min volume
double NormalizeVolume(double volume)
{
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
// Round volume down to nearest allowed step
volume = MathFloor(volume / lot_step) * lot_step;
// Clamp to min and max after rounding
if(volume < min_lot)
volume = min_lot;
if(volume > max_lot)
volume = max_lot;
// Normalize decimals (typically 2 or 3 decimals for volume)
int volume_digits = 0;
string lot_step_str = DoubleToString(lot_step, 8);
int pos = StringFind(lot_step_str, ".");
if(pos >= 0)
volume_digits = StringLen(lot_step_str) - pos - 1;
volume = NormalizeDouble(volume, volume_digits);
return volume;
}
Then, use:
mql5
volume = NormalizeVolume(volume);
before setting close_req.volume = volume;
Also check:
You include correct and valid values for close_req.price (your existing logic looks OK, but always verify price is within market acceptable range).
You have sufficient free margin and market conditions permitting close orders (less relevant here, but ensure).
You are targeting the right position with close_req.position = ticket.
You set close_req.magic = inpMagicNumber; which you do fine.
Deviation is reasonable; 50 is decent for volatile symbols.
Final recommended snippet fix for closing loop:
Replace your current volume rounding portion inside CloseAllPositionsIfDrawdown() with:
mql5
volume = NormalizeVolume(volume);
if(volume <= 0)
{
PrintFormat("Invalid rounded volume %.2f for position %I64d", volume, ticket);
continue;
}
Additional improvements and debugging tips:
After OrderSend(), if it fails, call Print(GetLastError()); to get more error details.
You may want to add a small delay/retry mechanism in case of execution timing or market conditions.
Consider logging the exact parameters sent to OrderSend for all close requests and verify with broker's limits.
Test manually closing similar volume positions on the symbol (GER30) in your broker's terminal.
Summary:
Your code's position-close “invalid request” error is caused by incorrect volume rounding/clamping. Fix the volume normalization with the robust logic I showed, ensuring volume always respects step size and minimum volume after rounding. This should fix error 4756 and allow your EA to close positions on exceeding drawdown.
If you want, I can also help produce a fixed, updated version of your full closing function with corrections applied. Just let me know!
// Helper function: normalize volume according to symbol constraints
double NormalizeVolume(double volume)
{
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
// Round volume down to nearest allowed step
volume = MathFloor(volume / lot_step) * lot_step;
// Clamp after rounding
if(volume < min_lot)
volume = min_lot;
if(volume > max_lot)
volume = max_lot;
// Determine decimals for volume normalization
int volume_digits = 0;
string lot_step_str = DoubleToString(lot_step, 8);
int pos = StringFind(lot_step_str, ".");
if(pos >= 0)
volume_digits = StringLen(lot_step_str) - pos - 1;
volume = NormalizeDouble(volume, volume_digits);
return volume;
}
// 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;
}
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);
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;
}
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
if(bid <= 0 || ask <= 0)
{
PrintFormat("Invalid bid (%.5f) or ask (%.5f) price, skipping close of position %I64d", bid, ask, ticket);
continue;
}
// Normalize the volume properly
volume = NormalizeVolume(volume);
if(volume <= 0)
{
PrintFormat("Invalid normalized volume %.2f for position %I64d", volume, ticket);
continue;
}
close_req.action = TRADE_ACTION_DEAL;
close_req.position = ticket;
close_req.volume = volume;
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
double price_to_use = (pos_type == POSITION_TYPE_BUY) ? bid : ask;
price_to_use = NormalizeDouble(price_to_use, digits);
close_req.price = price_to_use;
close_req.type = (pos_type == POSITION_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
close_req.deviation = 50; // deviation slippage allowance
close_req.magic = inpMagicNumber;
PrintFormat("Closing pos %I64d (type %d) vol=%.2f at price=%.5f bid=%.5f ask=%.5f deviation=%d",
ticket, pos_type, volume, close_req.price, bid, ask, close_req.deviation);
if(!OrderSend(close_req, close_res))
{
int err = GetLastError();
PrintFormat("Failed to close position %I64d, OrderSend error %d", ticket, err);
}
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);
}
}
}
}
}
}
}
What changed?
Added NormalizeVolume() helper function that:
Rounds volume down to nearest lot step.
Clamps volume to minimum and maximum lot sizes after rounding.
Normalizes decimals according to SYMBOL_VOLUME_STEP precision.
Replaced your volume handling with this function.
Added error print detail for OrderSend failures.
How to apply?
Simply copy and paste both the NormalizeVolume function and the updated CloseAllPositionsIfDrawdown function into your EA source file, replacing the old CloseAllPositionsIfDrawdown function.
Let me know if you want me to help update other parts or explain further!
//+------------------------------------------------------------------+
//| 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";
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
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);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
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;
}
}
//+------------------------------------------------------------------+
//| Calculate lot size based on risk or fixed lot |
//+------------------------------------------------------------------+
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;
}
//+------------------------------------------------------------------+
//| Helper function: normalize volume properly |
//+------------------------------------------------------------------+
double NormalizeVolume(double volume)
{
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
// Round volume down to nearest allowed step
volume = MathFloor(volume / lot_step) * lot_step;
// Clamp after rounding
if(volume < min_lot)
volume = min_lot;
if(volume > max_lot)
volume = max_lot;
// Determine decimals for volume normalization
int volume_digits = 0;
string lot_step_str = DoubleToString(lot_step, 8);
int pos = StringFind(lot_step_str, ".");
if(pos >= 0)
volume_digits = StringLen(lot_step_str) - pos - 1;
volume = NormalizeDouble(volume, volume_digits);
return volume;
}
//+------------------------------------------------------------------+
//| Close all positions opened by this EA on this symbol if drawdown exceeded 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;
}
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);
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;
}
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
if(bid <= 0 || ask <= 0)
{
PrintFormat("Invalid bid (%.5f) or ask (%.5f) price, skipping close of position %I64d", bid, ask, ticket);
continue;
}
// Normalize the volume properly
volume = NormalizeVolume(volume);
if(volume <= 0)
{
PrintFormat("Invalid normalized volume %.2f for position %I64d", volume, ticket);
continue;
}
close_req.action = TRADE_ACTION_DEAL;
close_req.position = ticket;
close_req.volume = volume;
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
double price_to_use = (pos_type == POSITION_TYPE_BUY) ? bid : ask;
price_to_use = NormalizeDouble(price_to_use, digits);
close_req.price = price_to_use;
close_req.type = (pos_type == POSITION_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
close_req.deviation = 50; // deviation slippage allowance
close_req.magic = inpMagicNumber;
PrintFormat("Closing pos %I64d (type %d) vol=%.2f at price=%.5f bid=%.5f ask=%.5f deviation=%d",
ticket, pos_type, volume, close_req.price, bid, ask, close_req.deviation);
if(!OrderSend(close_req, close_res))
{
int err = GetLastError();
PrintFormat("Failed to close position %I64d, OrderSend error %d", ticket, err);
}
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);
}
}
}
}
}
}
}
//+------------------------------------------------------------------+
//| Returns true if position of given type opened by EA on symbol |
//+------------------------------------------------------------------+
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;
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
CloseAllPositionsIfDrawdown(maxDrawdownPct);
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;
MqlDateTime tm;
TimeToStruct(TimeCurrent(), tm);
if(tm.hour < tradeStartHour || tm.hour >= tradeEndHour)
return;
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;
}
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;
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;
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);
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;
}
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 %.2f is less than minimum allowed lot", lot);
return;
}
MqlTradeRequest request = {};
MqlTradeResult result = {};
request.symbol = _Symbol;
request.volume = lot;
request.deviation = 10;
request.magic = inpMagicNumber;
if(ask > lastSwingHigh && is_uptrend)
{
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);
}
}
else if(bid < lastSwingLow && is_downtrend)
{
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);
}
}
}
//+------------------------------------------------------------------+
What was fixed/added:
Added the NormalizeVolume() helper function to properly round and clamp volumes for close orders.
Updated the CloseAllPositionsIfDrawdown() function to use this normalization and improve printing of errors.
Kept all your original logic and formatting intact.
Added comments marking the changed/added parts clearly.
You can now compile and run this updated EA, which should avoid "Invalid request" OrderSend error 4756 when closing positions on drawdown.
If you face any further issues or need additional modifications, feel free to ask!
#include <Trade\Trade.mqh>
CTrade trade;
bool ClosePositionByTicket(ulong ticket)
{
if(!PositionSelectByTicket(ticket))
{
PrintFormat("Position %I64d not found", ticket);
return false;
}
bool result = trade.PositionClose(ticket);
if(!result)
{
PrintFormat("Failed to close position %I64d, error %d", ticket, GetLastError());
}
else
{
PrintFormat("Position %I64d successfully closed", ticket);
}
return result;
}
It handles slippage, volume, types, price normalization internally.
It is the officially recommended method from MetaQuotes for closing positions.
It automatically chooses correct order parameters based on position info.
No need to worry about deviation, price, or volume rounding errors manually.
5. Additional best practice:
Call ResetLastError(); before calling any trade function to get clearer errors.
Example:
mql5
ResetLastError();
bool result = trade.PositionClose(ticket);
if(!result)
{
int err = GetLastError();
PrintFormat("Failed to close position %I64d error %d", ticket, err);
}
6. Summary
Replace manual trade request close logic with trade.PositionClose(ticket).
Remove your current MqlTradeRequest method in CloseAllPositionsIfDrawdown().
Keep or remove your NormalizeVolume() function since it is unnecessary with the CTrade methods.
trade.PositionClose() will solve the invalid request 4756 error.
If you want, I can provide your entire updated EA code with this fix integrated. Would you like me to do that?
//+------------------------------------------------------------------+
//| 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)
// Create global CTrade object for placing and closing trades
CTrade trade;
int ma_handle = INVALID_HANDLE;
int atr_handle = INVALID_HANDLE;
string swingHighLineName = "SwingHighLine";
string swingLowLineName = "SwingLowLine";
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
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);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
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;
}
}
//+------------------------------------------------------------------+
//| Calculate lot size based on risk or fixed lot |
//+------------------------------------------------------------------+
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;
}
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);
for(int i=total-1; i>=0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
ResetLastError();
if(!trade.PositionClose(ticket))
{
int err = GetLastError();
PrintFormat("Failed to close position %I64d, error %d", ticket, err);
}
else
{
PrintFormat("Position %I64d closed due to drawdown protection", ticket);
}
}
}
}
}
}
}
//+------------------------------------------------------------------+
//| Returns true if position of given type opened by EA on symbol |
//+------------------------------------------------------------------+
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;
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
CloseAllPositionsIfDrawdown(maxDrawdownPct);
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;
MqlDateTime tm;
TimeToStruct(TimeCurrent(), tm);
if(tm.hour < tradeStartHour || tm.hour >= tradeEndHour)
return;
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;
}
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;
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;
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);
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;
}
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 %.2f is less than minimum allowed lot", lot);
return;
}
MqlTradeRequest request = {};
MqlTradeResult result = {};
request.symbol = _Symbol;
request.volume = lot;
request.deviation = 10;
request.magic = inpMagicNumber;
if(ask > lastSwingHigh && is_uptrend)
{
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);
}
}
else if(bid < lastSwingLow && is_downtrend)
{
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);
}
}
}
//+------------------------------------------------------------------+
How this fixes your issue:
Replaced manual MqlTradeRequest position close code with trade.PositionClose(ticket) call inside CloseAllPositionsIfDrawdown().
CTrade::PositionClose() safely handles all parameters needed to close positions avoiding common mistakes leading to error 4756.
Added ResetLastError() before closing calls to get accurate error info if something fails.
Your entry logic and other parts left intact.
Test this updated EA in Strategy Tester or on your demo account to confirm closing on drawdown works without errors.
If you encounter other errors or have further questions—just ask!
Entire drawdown check and automatic closing of positions are removed.
EA simply runs trading logic without drawdown-based intervention.
Let me know if you want me to help add anything else!
Implementation Notes:
You'll need to track the highest price since entry (long) or lowest price since entry (short).
Update trailing stop on each tick or bar.
Compare current ATR value and recompute trailing stop accordingly.
Ensure stop distance always reflects current volatility.
Summary:
An ATR trailing stop is a volatility-adjusted, dynamic trailing stop loss. It helps protect profits while allowing reasonable room for price fluctuations, adapting automatically to changing market conditions using the ATR indicator multiplied by a chosen factor.
If you want, I can help write example MQL5 code for an ATR trailing stop for your EA! Just ask.
void UpdatePositionATRTrailingStop(ulong ticket)
{
if(!enable_ATR_trailing_stop)
return;
if(!PositionSelectByTicket(ticket))
return;
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
double entry_price = PositionGetDouble(POSITION_PRICE_OPEN);
double current_sl = PositionGetDouble(POSITION_SL);
double volume = PositionGetDouble(POSITION_VOLUME);
string symbol = PositionGetString(POSITION_SYMBOL);
// Get current ATR value
double atr = iATR(symbol, volatilityTF, atrPeriod, 0);
if(atr <= 0)
{
Print("Invalid ATR value for trailing stop");
return;
}
double trailing_distance = atr * atr_trailing_stop_mult;
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
if(bid <= 0 || ask <= 0)
{
Print("Invalid bid or ask price for trailing stop");
return;
}
// To determine highest/lowest price since entry, we simply look at price data since entry time
datetime entry_time = (datetime)PositionGetInteger(POSITION_TIME);
int bars_since_entry = iBarShift(symbol, PERIOD_CURRENT, entry_time, true);
if(bars_since_entry == -1)
{
Print("Failed to find bar for entry time");
return;
}
double highest_since_entry = -DBL_MAX;
double lowest_since_entry = DBL_MAX;
// Loop from entry bar until current bar to find extremes
for(int i = bars_since_entry; i >= 0; i--)
{
double high = iHigh(symbol, PERIOD_CURRENT, i);
double low = iLow(symbol, PERIOD_CURRENT, i);
if(high > highest_since_entry) highest_since_entry = high;
if(low < lowest_since_entry) lowest_since_entry = low;
}
double new_sl = 0.0;
if(pos_type == POSITION_TYPE_BUY)
{
// Calculate new SL as highest_since_entry - trailing distance, move only if greater than current SL
new_sl = NormalizeDouble(highest_since_entry - trailing_distance, digits);
if(current_sl < new_sl && new_sl < bid) // Move SL up only and not above current price
{
MqlTradeRequest req = {};
MqlTradeResult res = {};
req.action = TRADE_ACTION_SLTP; // Modify SL/TP
req.position = ticket;
req.symbol = symbol;
req.sl = new_sl;
if(!OrderSend(req, res))
PrintFormat("Failed to update trailing SL for position %I64d, error %d", ticket, GetLastError());
else if(res.retcode != TRADE_RETCODE_DONE)
PrintFormat("Trailing SL update rejected for position %I64d, retcode %d", ticket, res.retcode);
else
PrintFormat("Trailing SL moved up for position %I64d: new SL = %.5f", ticket, new_sl);
}
}
else if(pos_type == POSITION_TYPE_SELL)
{
// Calculate new SL as lowest_since_entry + trailing distance, move only if less than current SL
new_sl = NormalizeDouble(lowest_since_entry + trailing_distance, digits);
if(current_sl > new_sl && new_sl > ask) // Move SL down only and not below current price
{
MqlTradeRequest req = {};
MqlTradeResult res = {};
req.action = TRADE_ACTION_SLTP; // Modify SL/TP
req.position = ticket;
req.symbol = symbol;
req.sl = new_sl;
if(!OrderSend(req, res))
PrintFormat("Failed to update trailing SL for position %I64d, error %d", ticket, GetLastError());
else if(res.retcode != TRADE_RETCODE_DONE)
PrintFormat("Trailing SL update rejected for position %I64d, retcode %d", ticket, res.retcode);
else
PrintFormat("Trailing SL moved down for position %I64d: new SL = %.5f", ticket, new_sl);
}
}
}
4. Call this function for each open position opened by your EA in OnTick() before any new trades:
mql5
void OnTick()
{
// Update ATR trailing stops for all EA positions on symbol
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)
{
UpdatePositionATRTrailingStop(ticket);
}
}
}
// ... your existing OnTick trading logic (open new trades, etc)
// rest of your existing OnTick here without changes
}
Summary:
Added two inputs to enable and configure ATR trailing stop.
Added a function UpdatePositionATRTrailingStop() which:
Finds highest/lowest price since position entry,
Computes trailing SL using ATR * multiplier,
Sends SL modification order if new SL is more favorable.
Call that function for each open position in OnTick before trading logic.
Important notes:
The code uses the current chart’s timeframe (PERIOD_CURRENT) to scan bars for extreme prices since position entry.
You may tune timeframe or ATR parameters as needed.
The trailing stop moves only in the direction that protects profits — it never moves backward.
Check your broker’s policy on modifying SL frequently to avoid rejection or requotes.
If you want, I can update your full EA code with this included or help with any clarifications!
4. Optional: Dynamically adjust TP similar to trailing stop
Trailing stops update dynamically, but TP doesn't update in your EA.
If you want an updated TP alongside trailing stop (e.g. lock profits at adjusted levels), you can add code similar to the trailing stop update but for TP, using your r2r_ratio.
Example: Adjust TP dynamically based on current SL and R:R ratio
Removed all ATR trailing stop related inputs, variables, and functions.
EA now sets SL and TP on order open and does not modify SL or TP afterwards.
You can build on this base to add other trade management features later if desired.
If you need help adding other features or clarifications, just ask!
void UpdateTrailingStopByMarketStructure(ulong position_ticket)
{
if(!PositionSelectByTicket(position_ticket))
return;
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
double current_sl = PositionGetDouble(POSITION_SL);
string symbol = PositionGetString(POSITION_SYMBOL);
// Assuming swingLookback bars to find swings
int swing_bars = 20;
// Find highest and lowest prices in lookback for trailing stops
int highestBar = iHighest(symbol, PERIOD_CURRENT, MODE_HIGH, swing_bars, 0);
int lowestBar = iLowest(symbol, PERIOD_CURRENT, MODE_LOW, swing_bars, 0);
double swing_high = iHigh(symbol, PERIOD_CURRENT, highestBar);
double swing_low = iLow(symbol, PERIOD_CURRENT, lowestBar);
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
MqlTradeRequest req = {};
MqlTradeResult res = {};
req.action = TRADE_ACTION_SLTP;
req.position = position_ticket;
req.symbol = symbol;
req.sl = current_sl; // default if no move
if(pos_type == POSITION_TYPE_BUY)
{
// For longs, trail SL just below recent swing low (with small buffer)
double new_sl = NormalizeDouble(swing_low - 2*_Point, digits);
if(new_sl > current_sl && new_sl < PositionGetDouble(POSITION_PRICE_OPEN))
{
req.sl = new_sl;
}
else
{
return; // no improvement move
}
}
else if(pos_type == POSITION_TYPE_SELL)
{
// For shorts, trail SL just above recent swing high (with small buffer)
double new_sl = NormalizeDouble(swing_high + 2*_Point, digits);
if(new_sl < current_sl && new_sl > PositionGetDouble(POSITION_PRICE_OPEN))
{
req.sl = new_sl;
}
else
{
return; // no improvement move
}
}
else return; // unsupported position type
if(req.sl != current_sl)
{
if(!OrderSend(req, res))
PrintFormat("Failed to update trailing SL for position %I64d, error %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 moved for position %I64d: new SL = %.5f", position_ticket, req.sl);
}
}
Integration notes:
Call this function for each open position on every tick.
Adjust the lookback period and buffer (2*_Point) as preferred.
You can improve the trailing stop by storing swing highs/lows separately or calculating only after position entry (to avoid placing stop behind entry price).
This method trails stops closely aligned with price action.
Summary
A dynamic trailing stop based on market structure trails stops near recent swing lows/highs depending on position direction. It adapts stops to price action instead of fixed volatility or pips.
If you want, I can help you integrate this function fully into your EA with detailed coding!
// +------------------------------------------------------------------+
// | Add this function to your EA source |
// +------------------------------------------------------------------+
void UpdateTrailingStopByMarketStructure(ulong position_ticket)
{
if(!PositionSelectByTicket(position_ticket))
return;
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
double current_sl = PositionGetDouble(POSITION_SL);
double entry_price = PositionGetDouble(POSITION_PRICE_OPEN);
string symbol = PositionGetString(POSITION_SYMBOL);
// Find the highest and lowest swing bars during the lookback period
int highestBar = iHighest(symbol, PERIOD_CURRENT, MODE_HIGH, swingLookback, 0);
int lowestBar = iLowest(symbol, PERIOD_CURRENT, MODE_LOW, swingLookback, 0);
if(highestBar < 0 || lowestBar < 0)
return; // cannot get swing bars
double swing_high = iHigh(symbol, PERIOD_CURRENT, highestBar);
double swing_low = iLow(symbol, PERIOD_CURRENT, lowestBar);
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
// Small buffer (you can adjust this)
double buffer = 2 * point;
MqlTradeRequest req = {};
MqlTradeResult res = {};
req.action = TRADE_ACTION_SLTP;
req.position = position_ticket;
req.symbol = symbol;
double new_sl = 0.0;
if(pos_type == POSITION_TYPE_BUY)
{
// Trailing stop should be just below swing low minus buffer
new_sl = NormalizeDouble(swing_low - buffer, digits);
// Only move the stop up (if new_sl > current_sl), and not above entry price
if(new_sl > current_sl && new_sl < entry_price)
{
req.sl = new_sl;
}
else
return; // no move needed
}
else if(pos_type == POSITION_TYPE_SELL)
{
// Trailing stop should be just above swing high plus buffer
new_sl = NormalizeDouble(swing_high + buffer, digits);
// Only move stop down (if new_sl < current_sl), and not below entry price
if(new_sl < current_sl && new_sl > entry_price)
{
req.sl = new_sl;
}
else
return; // no move needed
}
else
return; // unsupported position type
if(req.sl != current_sl)
{
if(!OrderSend(req, res))
PrintFormat("Failed to update trailing SL for position %I64d, error %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: new SL=%.5f", position_ticket, req.sl);
}
}
// +------------------------------------------------------------------+
// | Modify your OnTick() function to call this new trailing stop |
// +------------------------------------------------------------------+
void OnTick()
{
// --- Update trailing stops dynamically based on market structure ---
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)
{
UpdateTrailingStopByMarketStructure(ticket);
}
}
}
// --- Your existing open trade logic below ---
// (Keep your existing OnTick logic unchanged except for adding above)
// For example, your existing code here...
// ...
}
How to integrate:
Paste UpdateTrailingStopByMarketStructure() function into your EA.
Add the call inside your OnTick() above your existing trade logic (before opening new trades).
Ensure swingLookback is properly set via input (already present in your EA).
Compile and run.
Explanation:
Swing highs/lows are the max/min over the last swingLookback bars on the current chart timeframe.
The trailing stop is set just beyond these swing points with a small buffer.
Stop loss only moves in the profit-protecting direction.
If the price moves against you and hits the trailing stop, your position closes, locking profit or limiting loss.
If you'd like, I can provide the full complete EA with this integrated or assist with any other requests!
Use input enableTrailingSL to enable or disable the dynamic trailing stop.
Trailing stops will activate only when price moves halfway to the TP.
Stops trail to recent market structure swing lows/highs with a small buffer.
TP is preserved on stop loss moves.
If you need further tweaks or explanations just ask!
im
u
m
co
n
sec
u
t
i
v
e
l
osses
(
Automating optimization via MQL5 (optional advanced)
You can use the TesterSet* and TesterStart functions in MQL5 to programmatically launch strategy tests, but this is quite advanced and mainly useful for meta-optimization or integration with external tools.
An example pseudo-code snippet (not full working script):
mql5
void RunOptimization()
{
for(double sl_mult=1.0; sl_mult<=5.0; sl_mult+=0.5)
{
for(double r2r=1.0; r2r<=3.0; r2r+=0.5)
{
// Set input parameters for next test run
TesterSetString("sl_atr_mult", DoubleToString(sl_mult));
TesterSetString("r2r_ratio", DoubleToString(r2r));
// Start test run
TesterStart();
// Wait for run to complete and collect results (complex)
// ...
}
}
}
Summary:
Best practice is to use MT5's built-in Strategy Tester Optimization — it's powerful, visual, and easy to setup for your EA’s inputs.
You already have nicely defined input parameters — just set their ranges in tester Inputs tab and let MT5 do the rest.
Analyze the output to find best combinations.
If you need, I can help you setup/export the results or help with advanced automation.
If you want, I can also help write a basic MQL5 script example to launch tests programmatically, but generally it's not necessary.
Would you like me to guide you step-by-step through the MT5 Strategy Tester Optimization or provide a helper script?