//+------------------------------------------------------------------+
//| Break of Structure EA with floating risk cap (full, compile) |
//+------------------------------------------------------------------+
#property copyright ""
#property version "1.0"
#property strict
#include <Trade\Trade.mqh>
input double inpLot = 0.05;
input bool useRiskPercent = false;
input double riskPercent = 1.0; // Position risk % per trade
input int sl_atr_mult = 3;
input double r2r_ratio = 2.0;
input ENUM_TIMEFRAMES volatilityTF = PERIOD_M5;
input int atrPeriod = 14;
input int swingLookback = 20;
input ENUM_TIMEFRAMES swingTF = PERIOD_M1;
input int maPeriod = 50;
input ENUM_TIMEFRAMES maTimeframe = PERIOD_M15;
input int tradeStartHour = 7;
input int tradeEndHour = 22;
input int maxPositions = 1;
input uint inpMagicNumber = 123456;
if(!OrderSend(req,res))
PrintFormat("Trailing SL update failed for position %I64d, err=%d", position_ticket, GetLastError());
else if(res.retcode != TRADE_RETCODE_DONE)
PrintFormat("Trailing SL update rejected for position %I64d, retcode=%d", position_ticket, res.retcode);
else
PrintFormat("Trailing SL updated for position %I64d: old SL=%.5f new SL=%.5f", position_ticket, sl, new_sl);
Floating loss cap logic to close positions when floating loss exceeds specified %,
Daily loss cap preventing new trades if daily drawdown exceeded,
Optional reverse entry mode,
Time filtering and max number of simultaneous positions,
Proper usage of MqlTradeRequest and OrderSend().
A few remarks/suggestions & things to check:
Position Counting & Magic/Symbol Checking:
You loop through all positions multiple times calling PositionSelectByTicket(ticket) and checking magic number and symbol. This is correct but can be optimized if you cache that in some place — can be significant if many positions.
Trailing Stop Updates:
You use a timer-like mechanism TrailUpdateIntervalSec for each position to limit update frequency, which is good to avoid flooding the trade server.
CalculateLotSize() when using Risk Percent:
Your formula is mostly correct but be aware that tick_value, tick_size, and contract_size must align correctly with your symbol specification (forex pairs, indices, etc).
Also, sometimes for forex the risk calculation can be simplified using:
lot = (balance * (riskPercent/100)) / (sl_distance_price * contract_size);
But the current approach that uses tick values is also valid.
Use of trailing stop buffer constants (e.g., 2*point buffer):
You have hardcoded buffer values like 2*point in trailing stop updates; you may want to expose these as extern/input for easier fine-tuning.
OrderSend() deviations:
You use fixed deviation=10; depending on the broker you may want to make this configurable.
Reverse Logic:
Your reverse entry logic seems correct and is gated via enableReverseEntries.
Daily reset equity calculation
Your daily equity reset in ResetDailyEquityIfNewDay() takes the account equity at midnight and stores it for drawdown calculation.
Consider that equity can fluctuate due to pending orders, swaps, or other factors. If you want a more robust daily loss cap, you may consider also tracking closed profit/loss or use a persistent file/storage.
Possible missing ChartSetInteger(0, CHART_EVENT_MOUSE_MOVE, true);
Not critical, but sometimes useful for interactive debugging if you want to use chart objects to visualize points or levels.
Things to consider adding or enhancing (optional):
Logging improvements: More info on rejected trades and reasons.
Add optional fixed stop loss/take profit override or optional dynamic TP by ATR.
Add a function to check if the market hours involve weekends or holidays.
Consider adding filters for spread or slippage before entering trades.
Implement retry logic on failed order sends.
Summary
The code should fully compile and run on MetaTrader 5 platform as is without syntax errors.
If you want me to help test or add features, debug specific behavior, or optimize parts of it (e.g., trailing stops, position sizing), please ask.
If you want me to double-check anything specific or generate updated/commented code with improvements, feel free to request!
If you want to implement a maximum overall (combined) loss limit, e.g., a cap on total floating losses across all open positions by this EA (not just per-position floating loss cap), you essentially want:
Calculate the combined floating profit/loss for all EA-controlled positions on this symbol
If the combined floating loss is bigger (more negative) than your max allowed loss, then close all positions or stop opening new trades
Your EA code already has a related check for maxDailyLossAmount to prevent new trades if equity drawdown exceeds max daily loss — that one works on overall equity drawdown, but it doesn't automatically close losing positions.
Your floating-per-position stop logic closes positions individually, but no combined total floating loss limit that closes all positions automatically is present.
How to implement "maximum overall floating loss" with auto close of all positions exceeding that max loss
Add in your OnTick() function (could be before or after your existing maxRiskPerTradePercent closing logic), this logic:
// Example: max combined floating loss limit per symbol (or EA)
input double maxCombinedFloatingLoss = 200.0; // maximum total floating loss in account currency
// ...
void OnTick()
{
// ... your existing code ...
// Calculate combined floating loss for all open EA positions on this symbol
double totalFloatingPL = 0.0;
int total = PositionsTotal();
for(int i=0; i<total; i++)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber &&
PositionGetString(POSITION_SYMBOL) == _Symbol)
{
double profit = PositionGetDouble(POSITION_PROFIT);
totalFloatingPL += profit;
}
}
}
// If total floating profit/loss is less than negative maxCombinedFloatingLoss, close all positions
if(totalFloatingPL < -maxCombinedFloatingLoss && totalFloatingPL < 0.0)
{
PrintFormat("Total floating loss %.2f exceeded maxCombinedFloatingLoss %.2f - closing all EA positions!",
totalFloatingPL, maxCombinedFloatingLoss);
for(int i=total-1; i>=0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber &&
PositionGetString(POSITION_SYMBOL) == _Symbol)
{
if(!trade.PositionClose(ticket))
PrintFormat("Failed to close position %I64d, error=%d", ticket, GetLastError());
}
}
}
// Optionally prevent new trades opening this tick
return;
}
// ... rest of your existing OnTick code, e.g. floating per position stop loss close and new trading logic ...
}
Explanation:
maxCombinedFloatingLoss input param allows you to set your combined max floating loss limit.
You sum all EA's positions floating profit/loss for the current symbol.
If this sum is below negative limit (i.e., loss higher than allowed), you loop over and close all those positions.
Then you skip the rest of the trading logic for that tick (to prevent new entries after big loss).
Notes:
This acts as a kind of total floating loss cap for the EA per symbol.
You can extend to include multiple symbols by removing symbol condition or adding more logic.
You can extend to save "stop trading" state and disallow new trades after this event until manual reset or daily reset.
You can add sending alert or email notification on total loss stop.
Let me know if you want me to integrate this fully into your original code or help you add persistent disable-after-loss function!