// --- ADX filter inputs ---
input int adxPeriod = 14; // ADX period
input double adxThreshold = 25.0; // ADX minimum threshold to allow trading
input ENUM_TIMEFRAMES adxTimeframe = PERIOD_M15; // ADX timeframe to use for filtering
// --- Losing streak inputs ---
input int maxLosingStreak = 3; // Max consecutive losing trades allowed
// --- POST-CLOSE COOLDOWN ---
input int postCloseCooldownSeconds = 60; // Cooldown seconds after a position closes before new trades allowed.
CTrade trade;
int ma_handle = INVALID_HANDLE;
int ma_handle2 = INVALID_HANDLE; // Medium-term MA handle
int ma_handle3 = INVALID_HANDLE; // Long-term MA handle
int atr_handle = INVALID_HANDLE;
int adx_handle = INVALID_HANDLE; // ADX handle
// *** Cooldown globals ***
datetime lastTradeCandleTime = 0; // last candle time when trade opened
ENUM_TIMEFRAMES cooldownTimeframe = swingTF; // timeframe for candle cooldown
datetime lastTradeOpenTime = 0; // last trade open timestamp
int tradeIntervalSeconds = 60; // min seconds between trades
if(!OrderSend(req,res))
PrintFormat("Trailing SL update failed for position %I64d, err=%d", position_ticket, GetLastError());
else if(res.retcode != TRADE_RETCODE_DONE)
PrintFormat("Trailing SL update rejected for position %I64d, retcode=%d", position_ticket, res.retcode);
else
PrintFormat("Trailing SL updated for position %I64d: old SL=%.5f new SL=%.5f", position_ticket, sl, new_sl);
Your provided MQL5 EA code looks structurally solid; it implements a Break of Structure strategy with added risk management features including:
ATR-based SL and TP,
ADX filter to avoid trading in low volatility,
A losing streak filter to prevent trading after several losing trades,
Post-close cooldown and candle-based cooldowns to avoid overtrading,
Trailing Stop Loss with different modes (MS-based, ATR-based, and hybrid),
Floating loss cap logic that closes positions exceeding a certain % loss,
Time-of-day trading restrictions,
Position limit restrictions,
Optional reverse entry feature.
Summary of Key Features & Flow:
On each tick, the EA checks if:
A recent position close cooldown is active.
The daily equity and losing streak get reset as needed.
The losing streak or max daily loss caps prevent trading.
Any open position has loss exceeding the floating risk cap, closing it as necessary.
Trailing stop loss updates are processed based on chosen mode.
Position limit and trading hours are respected.
Minimum time between trades and candle cooldown are respected.
The ADX filter value is above threshold.
Moving averages confirm the trend.
Price breaks swing highs/lows for entry.
Trade entries are placed with calculated lot sizes.
Notes & Potential Improvements:
ADX buffer index correctness:
The ADX indicator buffer index 0 corresponds to ADX itself, which you use — that’s correct. Just ensure that the indicator was created on the correct timeframe.
Trailing SL modes:
Hybrid trailing SL combines both ATR and Market Structure trailing SLs, which is a neat approach.
HistorySelect usage:
The multiple uses of HistorySelect with overlapping time ranges are okay but ensure the broker supports full deal history, else this may silently fail.
Lot sizing:
The CalculateLotSize function tries to calculate lot size based on risk %, balance, and stop distance, which is good.
Cooldown per candle check:
You use CopyRates(..., 1, 1, ...) to get the last closed candle of your cooldown TF. Make sure timeframe and indexing are correct to avoid off-by-one errors.
Potential Minor Fixes / Additions:
User
what can improve for better consistency and trading prop firms
Assistant
Great question! Improving the consistency of your EA and making it more suitable for prop firm challenges requires both strategy and trade management refinements, plus robustness and risk controls that align with typical prop firm rules.
Here's a list of suggestions structured for your current EA:
1. Enhance Risk Management
a) Refine Max Daily Loss / Drawdown Controls
Prop firms often enforce strict daily and maximum drawdowns.
Instead of just checking equity at the EA level, also monitor floating drawdown in real-time for open trades.
Implement max daily net loss and/or max drawdown during the trading day (including floating losses), not only closed trades.
b) Use Position Sizing with More Precision
Your CalculateLotSize uses ATR * SL distance but assumes constant tick value and contract size; consider using realistic slippage and spread adjustments in lot sizing.
Possibly limit max lot size relative to account balance and leverage to avoid margin issues.
Add min/max per-trade risk caps relative to the account or prop firm limits.
2. Improve Entry Conditions and Filters
a) Add Confluence Filters
Traders (and prop firms) value entries with multiple confluence factors. You could add:
Volume filter or OBV (On-Balance Volume): Trade only if volume supports the price move.
Momentum confirmation using RSI or Stochastic: Avoid entering on extreme overbought/oversold conditions.
Higher timeframe trend confirmation:
Right now, your trend is defined by 3 MAs on 15m timeframe only; consider adding a higher TF trend filter (e.g., H1 or H4 MA) to avoid counter-trend entries.
Price action filter: Confirm breakouts with close above swing highs/ lows, volatility contraction/expansion.
b) Adjust ADX Usage
ADX threshold is fixed at 25, sometimes it’s better to have dynamic threshold or add DI+ / DI- directional checks.
Avoid entering when ADX is increasing but market is indecisive (e.g., check trend strength AND direction).
3. Better Entries and Exits
a) Add a Partial Close or Scaling Out
User
i backtest 6 months, one month negative, how to have all on +
Assistant
Backtesting results often exhibit some losing periods even for good strategies — markets vary, and not every month will be profitable. Achieving all-positive months over a 6-month backtest can be very difficult without overfitting. However, here are practical approaches to improve your monthly consistency and reduce negative months:
1. Analyze the Losing Month(s) in Detail
Check specific trades: Were losses caused by a few big losing trades or many small ones?
Look at market conditions: Was the market choppy, volatile, trending?
Examine drawdown causes: Did it violate your risk management or cooldown rules?
Understand why that month lost money, then adjust strategy or filters accordingly.
2. Add More Robust Filters
Trend Confirmation on Higher Timeframe: Add an additional filter to avoid trades against the dominant trend on e.g., H1 or H4 TF MA. Many drawdowns happen when trading counter-trend.
Volatility Filter: Your ADX use is good but consider combining with ATR or Bollinger Band widths to avoid low/noise markets.
Time-of-Day Filter: Avoid trading during bad liquidity or low-volume periods.
3. Tighten Risk Controls
Reduce risk % or lot sizing during periods of higher volatility.
Add a dynamic risk scale (reduce risk after losing trades, pause after hitting max daily loss).
4. Add Exit Management
Consider partial profit-taking or scaling out before final TP to lock in consistent gains, reducing the chance of giving back profits.
Use breakeven stops after partial profits.
Consider time stops to close trades that aren’t moving.
5. Consider Walk-Forward Optimization
Instead of static parameters (ATR multipliers, streak limits), optimize parameters on rolling windows and apply those parameters forward.
This reduces overfitting and adapts the strategy to changing market regimes.
6. Avoid Overtrading
Make cooldowns stricter — one trade per X candles/hours.
Set rigid limits for max trades per day or max consecutive losses before pause.
This prevents noise trades in sideways markets.
User
adx was set on 0, sorry
Assistant
Thanks for clarifying that ADX period/input was set to 0 by mistake. That definitely can cause your ADX filter to fail or return invalid values, which would affect your trade logic and could lead to inconsistent or unintended behavior.
What happens if ADX period = 0?
iADX() indicator creation with period 0 is invalid — indicator handle will likely be invalid or produce empty/garbage data.
Your EA code has protections checking if adx_handle == INVALID_HANDLE and if CopyBuffer(adx_handle,...) <= 0, which may cause it to return early, blocking any new trades (or missing important filtering).
Consequently, your EA might never enter trades, or might trade without proper ADX filtering, increasing losing trades or missing valid ones.
How to fix
Set ADX period to a valid integer > 1, e.g., 14 (a standard default).
mql5
input int adxPeriod = 14;
Confirm your ADX indicator handle is created successfully in OnInit():
Confirm your ADX threshold is reasonable (usually 20 or 25):
mql5
input double adxThreshold = 25.0;
Run tests to ensure that when ADX < threshold no trades are placed, and trades open only when ADX >= threshold.
Additional Recommendations
Add runtime checks to notify if ADX values are unreasonable or zero. This helps catch bad input values.
User
lot size settings,
Assistant
Your current lot sizing code attempts to calculate position size either as a fixed lot size (inpLot) or via risk % per trade based on stop loss distance (in price), ATR, and account balance. This is conceptually correct but can be refined for better accuracy, safety, and prop firm compatibility.
Review of your existing CalculateLotSize() function
you can remove fixed lot size fixed balance size, account balance in time increase,
Assistant
Got it — you want your lot sizing to be completely dynamic based on current account balance and risk % per trade, without any fixed lot size or fixed balance assumption. That means lots will scale automatically as account equity grows or shrinks, which is essential for consistency and prop firm rules.
How to make your lot sizing fully dynamic based on current balance
Key points
Do not allow manual fixed lot input to override risk % sizing (disable fixed lot or ignore it).
Always calculate lot size based on current account balance or equity (equity preferred for margin/MT5).
Use stop loss distance in price or pips, adjusted by spread/slippage (optional).
Calculate trading volume to risk only a fixed % of current balance (e.g., 1% risk per trade).
Enforce broker minimum and maximum lots and proper lot step rounding.
Optionally include margin/leverage checks (to avoid too large lots).
On account growth, lot size grows; on drawdowns, lot size shrinks automatically.
Example adjusted CalculateLotSize function fully dynamic (ignoring any fixed lot settings):
mql5
double CalculateDynamicLot(double sl_distance_price)
{
// Defensive
if(sl_distance_price <= 0)
return 0.0;
double balance = AccountInfoDouble(ACCOUNT_BALANCE); // Or ACCOUNT_EQUITY if you prefer equity-based sizing
if(balance <= 0)
return 0.0;
// Fetch symbol trading parameters
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);
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
if(tick_value <= 0 || tick_size <= 0 || contract_size <= 0)
return 0.0;
// Calculate point value in account currency
double point_value = tick_value / tick_size;
// Calculate risk amount in account currency
double risk_amount = balance * (riskPercent / 100.0);
// Calculate lot size to risk risk_amount for sl_distance_price
double raw_lot = risk_amount / (sl_distance_price * point_value * contract_size);
// Clamp and round
double lot = MathFloor(raw_lot / lot_step) * lot_step;
if(lot < min_lot)
lot = 0.0; // too small to trade meaningfully
else if(lot > max_lot)
lot = max_lot;
return lot;
}
User
two options : current account balance and fixed balance i can set
Assistant
Understood! You want to give the user two options for risk calculation:
Option 1 (default): Dynamic lot sizing based on current account balance / equity — lot size adjusts automatically as the account grows or shrinks.
Option 2: Fixed balance sizing — always calculate lot sizes as if the account balance were some fixed amount, so risk remains consistent relative to that baseline (useful for testing, prop firm consistency, or backward compatibility).
How to implement this with a switch input
You can add an input option to your EA such as:
mql5
enum ENUM_RiskBalanceMode
{
RiskBalance_CurrentAccount = 0,
RiskBalance_FixedBalance = 1
};
input ENUM_RiskBalanceMode RiskBalanceMode = RiskBalance_CurrentAccount;
input double FixedBalance = 10000.0; // Used only if RiskBalanceMode==FixedBalance
input double riskPercent = 1.0; // Risk percent per trade
Adjusted CalculateLotSize function showing both modes:
integrate this into your entry and lot sizing workflow.
Assistant
Certainly! Below is a clean, integrated example of how to incorporate the two-options lot sizing (current account balance or fixed balance) into your existing entry and lot sizing workflow inside your OnTick() trade logic.
Step 1: Inputs for Risk Mode and Fixed Balance
Add these inputs near the top of your code (before OnInit):
mql5
enum ENUM_RiskBalanceMode
{
RiskBalance_CurrentAccount = 0,
RiskBalance_FixedBalance = 1
};
input ENUM_RiskBalanceMode RiskBalanceMode = RiskBalance_CurrentAccount;
input double FixedBalance = 10000.0; // Used only if RiskBalanceMode == FixedBalance
input double riskPercent = 1.0; // Position risk % per trade
Step 2: Lot sizing function integrated with mode
You can replace your existing CalculateLotSize() function with:
but you commented it is used with MathMax later — check logical consistency of SL tightening adjustment for buy vs sell sides.
Position opening logic uses OrderSend() returning a bool but no retries or error code handling beyond a simple print. Consider enhanced error handling or logging.
maxPositions check counts all positions matching magic & symbol. If your strategy allows multiple orders with the same ticket but multiple positions, this is fine.
The IsPositionOpen() returns true on the first position matching the side, magic & symbol — what if multiple positions in the same direction exist? Current logic prohibits multiple positions of the same direction, which fits maxPositions=1.
Summary:
Your EA implements the specified Break of Structure entry logic with multiple enhanced safety filters correctly.
It should compile and work as intended under MQL5 environment.
If you want me to:
Add more features,
Explain any function,
Help test or debug,
Convert to another language or platform,
… please specify!
Prop firms prefer smoother equity curve with less volatility, so adding partial closes on TP1 and moving SL to breakeven on TP1 can improve consistency.
Consider scaling out of winners instead of all-or-nothing.
b) Improve Trailing Stops
Your Hybrid trailing SL is great. Consider adaptive trailing stops based on volatility or price structure.
Add ATR-based time stops or reverse signals to avoid overstaying in trades.
4. Cooldown and Overtrading Control
You already have candle-based and time-based cooldowns.
Consider adding max trades per day, max trades per hour limits aligned with prop firm rules.
Include max daily volume traded or exposure limits.
5. Account for Spread, Slippage, and Execution
Explicitly factor average spread and slippage into your SL and TP distances.
Slippage can cause stop hunt and repeated losses.
For prop firm precision, consider setting order deviation larger, or implementing retry logic on request failures.
6. Improve Logging and Monitoring
Add detailed logging of entries, exits, reasons for rejections for later analysis.
Use internal variables to track running statistics: winning %, average RR, max consecutive winners/losers, expectancy.
Some prop firms expect you to submit trading logs — auto-export logs or signals could help.
7. Testing and Optimization
Run extensive walk-forward testing across different market conditions.
Optimize parameters like ATR multiplier, loss streak limit, ADX threshold on out-of-sample data.
Test on multiple symbols and timeframes for robustness.
8. Additional Prop-Firm Friendly Features
Consider hedging off, or auto-disable the EA when propagating positions larger than max allowed.
Add trade management restrictions—avoid large floating losses, have max drawdown per trade, and max margin use restrictions.
Include time stop (forced exit after X hours so as not to hold trades too long).
9. Code & Logic Improvements
Centralize risk and money management logic to handle multiple trade scenarios (partial closes, pyramiding).
Ensure all OrderSend code handles errors gracefully, implement retry/backoff for failed orders.
Clear state management on EA reboots or terminal reconnects.
Example Implementation Ideas for Prop Firm:
Add daily PnL tracker to stop trading after hitting the max daily loss.
Implement consecutive winning trade limit to avoid greed (e.g., stop trading after 5 winners, resting EA).
Trade only during high-volume market sessions (London / NY open).
Use tighter max open positions (maybe 1) and aggregate risk limits.
Max trades/day, time cooldowns, candle cooldown confirmed
Avoid overtrading, reduce stress
Execution Robustness
Factor spread/slippage into SL/TP, retry failed orders
More reliable execution
Logging & Monitoring
Detailed logs and performance stats
Allows analysis and improvement
Testing & Optimization
Walk-forward testing, multi-symbol validation
Strategy robustness
Prop Firm Constraints
Risk and max position checks, session/time limits
Compliance with prop firm rules
If you like, I can help you code specific improvements (e.g., partial close logic, daily drawdown stop, advanced filters), or help you build a testing plan.
Would you like assistance with any particular part?
7. Improve Trailing Stop Logic
Adjust trailing stops to be more adaptive based on volatility.
Use tighter stops in low-volatility, wider in trending environments.
8. Use Ensemble or Multi-Strategy Approaches
Combine your Break of Structure strategy with another low-correlation system.
This can smooth equity curve and reduce losing months by diversification.
9. Manually Inspect/Mitigate Drawdown Events
Sometimes manual or semi-automated “filter-off” during known news events or unusual market conditions helps avoid sharp drawdowns.
10. Backtest with Realistic Execution Parameters
Include spreads, slippage, commissions in backtest.
Make sure trade timing and data quality are adequate.
Summary: Action Plan to Reduce Negative Months
Step
Action
Result
1. Analyze Losing Month
Identify trade patterns or market regimes causing loss
Targeted fixes instead of guesswork
2. Add Robust Filters
Higher TF trend, volatility, time-of-day filters
Avoid bad market regimes
3. Tighten Risk Controls
Lower risk %, dynamic risk scaling
Reduce losses in bad periods
4. Add Exit Management
Partial close, breakeven, time stops
Protect profits and reduce whipsaws
5. Walk-Forward Optimize
Periodic parameter tuning
Adapt strategy to market changes
6. Limit Overtrading
Cooldowns, max trades per day/hours
Avoid impulsive, low quality trades
7. Adjust Trailing Stops
Volatility adaptive trailing
Stay in winners, avoid premature stopouts
8. Consider Multi-Strategy
Add uncorrelated methods
Smoother equity performance
Example: Adding Higher Timeframe Trend Filter to Your EA
You can add a simple condition like:
mql5
// Create H1 MA handle once in OnInit()
int maHandleH1 = iMA(_Symbol, PERIOD_H1, maPeriod3, 0, MODE_EMA, PRICE_CLOSE);
// ...
// In OnTick(), get H1 MA current value
double maH1_buf[];
if(CopyBuffer(maHandleH1, 0, 1, 1, maH1_buf) <= 0)
return;
double maH1 = maH1_buf[0];
// Then check whether price aligns with H1 trend for buy/sell signals:
bool h1Uptrend = (MA1 > MA2) && (MA2 > MA3) && (Close[0] > maH1);
bool h1Downtrend = (MA1 < MA2) && (MA2 < MA3) && (Close[0] < maH1);
// Combine with your existing uptrend/downtrend booleans:
if(!enableReverseEntries)
{
if(ask > lastSwingHigh && is_uptrend && h1Uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
{
// Buy logic
}
else if(bid < lastSwingLow && is_downtrend && h1Downtrend && !IsPositionOpen(POSITION_TYPE_SELL))
{
// Sell logic
}
}
Final Thoughts
Do not over-optimize to get 100% positive months — it usually causes overfitting and poor real forward results.
Aim instead for a robust positive expectancy, where some losing periods are expected but overall growth is stable.
Include psychology-friendly features like max drawdown stops and alerts.
If you want, I can help you code improvements for any of the above or design a testing and optimization procedure to improve consistency.
Would you like to work on a specific improvement next?
Example:
mql5
if(adx_value <= 0)
{
Print("Warning: ADX value is zero or invalid, check indicator inputs");
return;
}
Consider making adxPeriod input limited, e.g.:
mql5
input int adxPeriod = 14;
and validate user inputs on start or via inpInt range restrictions if using a GUI inputs form.
Why ADX matters for your EA consistency
ADX measures trend strength.
A zero or missing ADX disables your trend strength filter, so your EA may enter trades during non-trending markets (noise), leading to more losses and inconsistent drawdowns.
Proper ADX filtering ensures you only trade when momentum/trend strength is enough to support Break of Structure entries.
TL;DR
Set ADX period to a valid positive integer (>1), typically 14.
Confirm indicator handle is valid before use.
Check your EA’s logic responds appropriately to ADX readings.
Rerun your backtests after correcting this — you might see better consistency and fewer noisy entries.
If you want, I can help you add input validation, better ADX error checking, or demonstrate how to debug ADX values during the EA runtime. Just ask!
Suggestions to improve the lot sizing:
1. Use POSITION_MARGIN and leverage (for margin precise sizing)
For prop firms and consistent money management, recalculating lot size based on margin required for SL risk can better match your account limits.
2. Use symbol-specific info carefully
Tick value, tick size, and contract size sometimes vary by broker symbol settings (e.g., CFDs vs forex).
Use SYMBOL_TRADE_TICK_VALUE carefully and confirm correctness.
Alternative method (more robust, in MQL5) is to calculate risk in account currency, factoring symbol's point value in the account currency.
3. Add Max Lot clamp against leverage/margin use and prop firm limits
To prevent large positions that your margin or prop firm caps don’t allow.
Example: cap position size to not exceed a % of free margin.
4. Factor in Spread and Slippage margin
When calculating SL distance (price), consider widening it by expected spread or slippage buffer — this avoids underestimating risk.
5. Round lot size to allowed lots with MathFloor
You already do this — just verify lot steps are correct.
6. Add Minimum risk per trade or minimum lot limit
Even if risk calcs to smaller lots, avoid trading lots so small they cause execution/pricing issues or aren't accepted.
7. Optional: Output expected risk amount in account currency
double adj_sl_distance = Adjust_SL_Distance_For_Spread(sl_distance_price);
double lot = CalculateDynamicLot(adj_sl_distance);
What this accomplishes
Your risk per trade is always exactly your configured risk % of the current balance.
As your account balance grows, your lot sizes automatically grow proportionally.
On drawdowns, lot sizes shrink to preserve capital.
No hard-coded fixed lots or assumptions.
Better aligned with prop firm expectations for consistent risk management and scaling.
Avoids "fixed lot but fixed balance" problem that leads to inconsistency as account balance changes.
Additional tips
Use ACCOUNT_EQUITY for sizing if your EA runs continuously (equity reflects real-time profit/loss).
Include safety checks, e.g. minimum lot sizes or a min risk threshold below which no trades are opened (to avoid overtrading tiny lots).
For better risk control, consider dynamic riskPercent adjusting based on recent drawdowns or losing streaks (reduce risk % after losses).
Log actual risk $ per trade and lot size opened to verify correctness.
If you want, I can help you integrate this into your EA code, add logging for lots and risk, or build the full position sizing module with dynamic risk management and optional scaling! Just let me know.
Usage tips:
Set RiskBalanceMode to RiskBalance_CurrentAccount to size by live balance (dynamic scaling).
Set RiskBalanceMode to RiskBalance_FixedBalance and specify FixedBalance for consistent, unmoving sizing regardless of account change.
For prop firms, using FixedBalance mode with your target prop firm account size can give consistent trade sizing and risk usage.
When live trading, RiskBalance_CurrentAccount is usually preferred for realistic sizing that grows/shrinks with your equity.
Example input declarations to put in your code:
mql5
input ENUM_RiskBalanceMode RiskBalanceMode = RiskBalance_CurrentAccount;
input double FixedBalance = 10000.0; // Set fixed balance for FixedBalance sizing mode
input double riskPercent = 1.0; // Risk % per trade
If you want, I can help you implement this fully with input UI, add logging of chosen balance mode and risk amount per trade, or help integrate this into your entry and lot sizing workflow.
Just say which part you'd like next!
Step 3: Integrate into your OnTick() entry logic
In your OnTick() where you calculate stop loss distance and lot size for new trades, replace or modify the lot calculation section as such (simplified snippet):
mql5
// Calculate SL and TP distances
double sl_dist = atr * sl_atr_mult;
double tp_dist = sl_dist * r2r_ratio;
// Calculate lot size dynamically based on selected mode
double lot = CalculateLotSize(sl_dist);
if(lot <= 0)
{
// Lot too small due to small risk or SL size, skip trade
return;
}
// Before creating trade request:
MqlTradeRequest request = {};
MqlTradeResult result = {};
request.symbol = _Symbol;
request.volume = lot;
request.deviation = 10;
request.magic = inpMagicNumber;
// other setup below as you have (price, SL, TP, order type) ...
// Example Buy entry snippet:
if(ask > lastSwingHigh && is_uptrend && !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 (RiskMode=%d Balance=%.2f)",
ask, lot, request.sl, request.tp, RiskBalanceMode,
(RiskBalanceMode == RiskBalance_CurrentAccount) ? AccountInfoDouble(ACCOUNT_BALANCE) : FixedBalance);
// Update cooldowns and timestamps here
lastTradeCandleTime = currentCandleTime;
lastTradeOpenTime = now;
}
}
(Do similarly for your sell or reverse entries.)
Step 4: Optional — Add logging to see risk amount per trade
For debugging/logging, you might want to print out the actual risk dollars for a trade:
mql5
double actual_risk = lot * sl_dist * (SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE) / SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE)) * SymbolInfoDouble(_Symbol, SYMBOL_TRADE_CONTRACT_SIZE);
PrintFormat("Trade risk amount would be approx %.2f in account currency, riskPercent=%.2f%%, balance used=%.2f",
actual_risk, riskPercent, (RiskBalanceMode == RiskBalance_CurrentAccount) ? AccountInfoDouble(ACCOUNT_BALANCE) : FixedBalance);
Summary
You now have one lot sizing function handling both current and fixed balance modes.
Your trade entries dynamically calculate lots according to risk % and either live or fixed balance.
You can easily switch between modes without changing logic elsewhere.
Logging helps verify correctness live or in backtest.