//+------------------------------------------------------------------+
//| AdvancedBoS_EA_MT5.mq5 |
//| BoS EA with dynamic lot sizing, drawdown close, swing visualization |
//| and correct position closing for MT5 |
//+------------------------------------------------------------------+
#property copyright "LucienWebP"
#property version "1.0"
#property strict
#property script_show_inputs
input double inpLot = 0.05; // Fixed lot size per trade
input bool useRiskPercent = false; // Use risk %, else fixed lot
input double riskPercent = 1.0; // Risk % per trade if risk mode enabled
input double maxDrawdownPct = 5.0; // Max drawdown % of balance before all close (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; // Timeframe for ATR calculation
input int swingLookback = 20; // Bars to look back for swing detection on M1
input int maPeriod = 50; // EMA period for trend filter M15
input ENUM_TIMEFRAMES maTimeframe = PERIOD_M15; // EMA timeframe
input int tradeStartHour = 7; // Trade start hour (server time)
input int tradeEndHour = 22; // Trade end hour (server time)
input int maxPositions = 1; // Max simultaneous positions (0=no limit)
int ma_handle = INVALID_HANDLE;
int atr_handle = INVALID_HANDLE;
Your MT5 expert advisor code looks quite solid and feature-complete in terms of:
Dynamic lot sizing with risk-percentage option
Drawdown-based forced close protection
Swing high/low visualization lines on the chart
Trend filter by EMA on a higher TF
Correct/clean position closing by ticket & magic number
Trading time restrictions and max open positions control
A brief review and some suggestions/improvements you may consider:
1. CalculateLotSize sl_distance_points unit consistency
In your CalculateLotSize():
mql5
double lot = riskMoney / (sl_distance_points * point_value * contract_size);
Make sure that sl_distance_points is always in points. In your main OnTick(), the SL distance you pass is:
mql5
double sl_dist = atr * sl_atr_mult;
ATR is price units (e.g., points in price, typically). Check that this matches what CalculateLotSize() expects as "points" for the SL distance. If not, you might want to convert price difference into points based on _Point.
2. Better handling of objects on chart
You create two horizontal lines once on OnInit() and update them each tick:
Good practice: check that the objects exist before setting properties, or create/update them dynamically to avoid runtime errors or failing silently on chart changes.
3. Time checks — use TimeCurrent() with TimeLocal() awareness if needed
Using TimeCurrent() for hour check is correct for server time. If you want to use local time of your machine, consider TimeLocal(). Just confirm server time is your intended timing.
4. Magic number as input option
Currently, magic number is hardcoded:
mql5
ulong magic_number = 123456;
User
need a detailed description to publish
Assistant
Certainly! Here’s a detailed professional description for your AdvancedBoS_EA_MT5 Expert Advisor, suitable for publishing on a marketplace, forum, or your website:
AdvancedBoS_EA_MT5 — Break of Structure Expert Advisor for MT5
Version: 1.0 Author: LucienWebP Platform: MetaTrader 5 Strategy Type: Break of Structure (BoS) with trend confirmation and dynamic risk management
Overview
AdvancedBoS_EA_MT5 is a sophisticated and fully automated Expert Advisor designed for the MetaTrader 5 platform. It trades using a classical Break of Structure (BoS) concept reinforced by multiple professional features to enhance performance, manage risk, and improve trade clarity.
This EA suits traders who rely on price action-based entries filtered by trend direction, volatility-based stops, and dynamic position sizing. It is ideal for intraday traders preferring structured disciplined risk with visual market swings to support decision making.
Key Features
1. Break of Structure Entry Logic
Trades are triggered on a Break of Structure defined by recent swings on the M1 timeframe.
Uses defined lookback periods to detect recent swing highs and lows, marking them with horizontal lines for clear visual reference.
Buy trades open when the price breaks above the last swing high during an uptrend.
Sell trades open when the price breaks below the last swing low during a downtrend.
2. Multi-Timeframe Trend Filter
Integrates a trend filter through an Exponential Moving Average (EMA) on a customizable higher timeframe (default: M15).
Only trades in the direction confirmed by EMA, preventing counter-trend entries.
3. Dynamic Lot Size Calculation with Risk Percent Option
Supports fixed lot sizing or advanced risk-percentage position sizing based on the user’s account balance.
Calculates position size dynamically according to stop loss distance and desired risk %, ensuring consistent risk management.
Automatically adjusts lot size within broker constraints (minimum, maximum, step sizes).
4. Volatility-Based Stop Loss and Take Profit
Uses the Average True Range (ATR) indicator (default timeframe M5) to determine Adaptive Stop Loss levels, multiplied by a configurable factor (default 3).
Take Profit is automatically set dynamically using a configurable Risk-to-Reward ratio (default 2.0).
This ensures stops and targets adapt to current market volatility.
User
test on EURUSD,H1 (hedging)
strategy tester report 610 total trades
test on XAUUSD,D1 (hedging)
2021.02.01 07:41:38 failed request sell 0.2 at 1858.94 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:38 failed request sell 0.2 at 1858.91 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:38 failed request sell 0.2 at 1858.88 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:38 failed request sell 0.2 at 1858.86 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:38 failed request sell 0.2 at 1858.83 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:38 failed request sell 0.2 at 1858.80 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:39 failed request sell 0.2 at 1858.77 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:39 failed request sell 0.2 at 1858.74 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:39 failed request sell 0.2 at 1858.71 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:39 failed request sell 0.2 at 1858.68 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:39 failed request sell 0.2 at 1858.66 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:40 failed request sell 0.2 at 1858.63 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:40 failed request sell 0.2 at 1858.60 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:40 failed request sell 0.2 at 1858.57 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:40 failed request sell 0.2 at 1858.54 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:40 failed request sell 0.2 at 1858.51 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:40 failed request sell 0.2 at 1858.48 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:41 failed request sell 0.2 at 1858.46 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:41 failed request sell 0.2 at 1858.43 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:41 failed request sell 0.2 at 1858.40 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
2021.02.01 07:41:41 failed request sell 0.2 at 1858.37 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
strategy tester report 43 total trades
Assistant
Your EA is generating many "failed request ... [Invalid request]" errors during the test on XAUUSD, D1 (hedging enabled), specifically when trying to close buy positions via sell orders.
These invalid request errors usually mean one or more of the following:
Common reasons for [Invalid request] errors on Closing Positions in MT5:
Incorrect request.volume when closing positions:
The volume requested to close must not exceed the current position volume and respects the broker's allowed lot step and min/max.
Wrong request.price for closing orders:
Price passed in the close request for a market order can sometimes cause invalid request if it is not acceptable or when the bid/ask used does not match the position type or market conditions.
Wrong request.action or request.type:
When closing a position, the action is TRADE_ACTION_DEAL. The type must be the exact opposite of the position type (BUY position closed with SELL order, and vice versa).
Position no longer exists or already closed:
When multiple close attempts happen on the same ticket, or the position is no longer available but code tries to close again.
Symbol or volume issues with XAUUSD or specific instrument (Gold):
Gold often has special contract size, min/max lot, step size and often larger minimum price movement. Sometimes tick size, min lot or volume step is different and requires extra care.
Suggestions to fix or diagnose your EA closing code:
1. Verify request.volume
Before closing, get current position volume and adjust to allowable volume steps:
mql5
double pos_volume = PositionGetDouble(POSITION_VOLUME);
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double vol_min = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double vol_max = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
// Normalize volume to lot step
double cl_volume = MathFloor(pos_volume / lot_step) * lot_step;
cl_volume = MathMax(cl_volume, vol_min);
cl_volume = MathMin(cl_volume, vol_max);
// Use cl_volume in close request
User
can you fix it?
Assistant
Absolutely! I've updated your CloseAllPositionsIfDrawdown() function to fix the common causes of invalid close requests—especially for symbols like XAUUSD with hedging enabled.
Key fixes include:
Correct volume normalization based on symbol lot step/min/max
Using correct bid/ask prices to close buy/sell positions
Detailed error and retcode printing for better debugging
Defensive checks to avoid invalid or zero volume closes
Here's the fixed and improved function:
mql5
User
full code please
Assistant
Certainly! Below is your full updated AdvancedBoS_EA_MT5.mq5 code, with the fixed and robust version of the CloseAllPositionsIfDrawdown() function included. The rest of the code is untouched except minor formatting improvements for clarity.
mql5
User
'retcode' - parameter for EnumToString must be an enumeration aaa.mq5 171 139
Assistant
The error 'retcode' - parameter for EnumToString must be an enumeration occurs because retcode in your MqlTradeResult is of type UINT (basically an integer), but EnumToString() expects a parameter of an enumeration type.
In MQL5, TRADE_RETCODE is an enum, but retcode in MqlTradeResult is just a uint representing that enum value.EnumToString() cannot convert it directly unless you cast the integer (retcode) to the enum type.
How to fix it?
Cast the integer retcode to the corresponding enum type before passing to EnumToString(). In your case, the enum is ENUM_TRADE_RETCODE.
Change this line:
mql5
PrintFormat("Closing position %I64d returned retcode %d — \"%s\"", ticket, close_res.retcode, EnumToString(close_res.retcode));
to:
mql5
PrintFormat("Closing position %I64d returned retcode %d — \"%s\"", ticket, close_res.retcode, EnumToString((ENUM_TRADE_RETCODE)close_res.retcode));
Explanation:
(ENUM_TRADE_RETCODE)close_res.retcode converts the uint retcode to the enum type, which EnumToString() requires.
This tells the compiler explicitly how to treat that integer when converting to string.
Full adjusted snippet in context:
mql5
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)
{
// Cast retcode value to ENUM_TRADE_RETCODE for EnumToString
PrintFormat("Closing position %I64d returned retcode %d — \"%s\"", ticket, close_res.retcode, EnumToString((ENUM_TRADE_RETCODE)close_res.retcode));
}
else
{
PrintFormat("Position %I64d closed due to drawdown protection", ticket);
}
If you want, I can provide the full EA code snippet updated accordingly!
User
yes
Assistant
Certainly! Below is the full updated EA code with the proper cast for EnumToString() to fix the 'retcode' enumeration error:
mql5
User
'ENUM_TRADE_RETCODE' - undeclared identifier aaa.mq5 174 48
'retcode' - some operator expected aaa.mq5 174 77
'ENUM_TRADE_RETCODE' - parameter for EnumToString must be an enumeration aaa.mq5 174 48
Assistant
The errors you are encountering indicate that ENUM_TRADE_RETCODE is not recognized in your code, which means your MQL5 environment may not declare it explicitly or you are missing the necessary #include that defines this enum.
How to fix:
Include the trade.mqh library
The enumeration ENUM_TRADE_RETCODE is declared in the standard MetaTrader 5 library file Trade.mqh. You need to include it at the top of your EA code:
mql5
#include <Trade\Trade.mqh>
This will make all trading-related enums, constants, and functions available, including ENUM_TRADE_RETCODE and EnumToString() overloads for it.
Use CTrade class for trading (optional but recommended)
Including Trade.mqh also gives you access to the CTrade class which simplifies order sending and management.
Updated code snippet to add at the very top of your EA, right after your #property lines:
mql5
#include <Trade\Trade.mqh>
Complete minimal example of the fixed PrintFormat line after including the header:
mql5
//+------------------------------------------------------------------+
//| Include standard trade definitions |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>
// Inside CloseAllPositionsIfDrawdown() after OrderSend()
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("Closing position %I64d returned retcode %d — \"%s\"",
ticket, close_res.retcode,
EnumToString((ENUM_TRADE_RETCODE)close_res.retcode));
}
else
{
PrintFormat("Position %I64d closed due to drawdown protection", ticket);
}
Summary
Add #include <Trade\Trade.mqh> at the top of your EA.
This resolves the undeclared identifier errors.
Now the cast to ENUM_TRADE_RETCODE will work correctly.
EnumToString() will output readable string form of the return codes.
Optional
If you want I can provide the full updated code including this include line for your complete EA. Just say so!
User
yes
Assistant
Here is your full EA code including the necessary #include <Trade\Trade.mqh> directive to fix the ENUM_TRADE_RETCODE undeclared error and making EnumToString work correctly:
mql5
User
'ENUM_TRADE_RETCODE' - undeclared identifier aaa.mq5 176 48
'retcode' - some operator expected aaa.mq5 176 77
'ENUM_TRADE_RETCODE' - parameter for EnumToString must be an enumeration aaa.mq5 176 48
Assistant
The error showing 'ENUM_TRADE_RETCODE' - undeclared identifier even after adding #include <Trade\Trade.mqh> can happen if your MT5 build version is older or if the enum is not directly exposed in the global namespace.
Quick Workaround: Manually define the enum or avoid casting
You can do one of the following:
Option 1: Remove the cast and only print the numeric retcode:
Replace this line:
mql5
PrintFormat("Closing position %I64d returned retcode %d — \"%s\"",
ticket, close_res.retcode,
EnumToString((ENUM_TRADE_RETCODE)close_res.retcode));
With this simpler line (no casting, no enum-to-string):
mql5
PrintFormat("Closing position %I64d returned retcode %d", ticket, close_res.retcode);
This will still give you the error code numerically, which is useful.
Option 2: Define your own enum for ENUM_TRADE_RETCODE
You can replicate the relevant enum definitions at the top of your code:
mql5
enum ENUM_TRADE_RETCODE
{
TRADE_RETCODE_DONE = 100,
TRADE_RETCODE_DONE_REMAINDER = 101,
TRADE_RETCODE_REQUOTE = 102,
TRADE_RETCODE_REJECT = 103,
TRADE_RETCODE_CANCEL = 104,
// ... add more codes you want if needed ...
};
string TradeRetcodeToString(UINT code)
{
switch(code)
{
case TRADE_RETCODE_DONE: return "Done";
case TRADE_RETCODE_DONE_REMAINDER: return "Done with remainder";
case TRADE_RETCODE_REQUOTE: return "Requote";
case TRADE_RETCODE_REJECT: return "Reject";
case TRADE_RETCODE_CANCEL: return "Cancel";
default: return "Unknown";
}
}
And then replace your print like this:
mql5
PrintFormat("Closing position %I64d returned retcode %d — \"%s\"",
ticket, close_res.retcode,
TradeRetcodeToString(close_res.retcode));
Why this happens
MT5 library files sometimes change between builds.
ENUM_TRADE_RETCODE and its string conversions are only available in more recent MT5 builds.
Sometimes the include path or files get changed or missing, causing them to be undefined.
Summary recommendation
If you want the fastest fix with minimal changes, use Option 1 — just print the retcode number without converting to string.
If you want readable strings, use Option 2 and define your own minimal enum and string converter as shown.
If you want, I can provide the full EA code modified to use Option 1 or Option 2 — just confirm your preference.
User
code modified to use Option 1
Assistant
Certainly! Here's your full EA code modified to use Option 1 — simply printing the numeric retcode value without trying to convert it to a string enum. This will avoid the ENUM_TRADE_RETCODE undeclared error:
mql5
User
test on EURUSD,H1 (hedging)
strategy tester report 447 total trades
test on XAUUSD,D1 (hedging)
QL 0 14:43:29.432 Core 1 2022.02.01 16:43:12 Drawdown 5.01% >= max 5.00% — closing all EA positions on XAUUSD
2022.02.01 16:43:12 failed request sell 0.2 at 1802.18 , close #8 buy 0.2 XAUUSD 1804.89 [Invalid request]
KP 0 14:43:29.432 Core 1 2022.02.01 16:43:12 Failed to close position 8 — OrderSend error: 4756
EP 0 14:43:29.432 Core 1 2022.02.01 16:43:12 Drawdown 5.05% >= max 5.00% — closing all EA positions on XAUUSD
2022.02.01 16:43:12 failed request sell 0.2 at 1802.16 , close #8 buy 0.2 XAUUSD 1804.89 [Invalid request]
CM 0 14:43:29.432 Core 1 2022.02.01 16:43:12 Failed to close position 8 — OrderSend error: 4756
IE 0 14:43:29.432 Core 1 2022.02.01 16:43:13 Drawdown 5.08% >= max 5.00% — closing all EA positions on XAUUSD
2022.02.01 16:43:13 failed request sell 0.2 at 1802.14 , close #8 buy 0.2 XAUUSD 1804.89 [Invalid request]
LI 0 14:43:29.432 Core 1 2022.02.01 16:43:13 Failed to close position 8 — OrderSend error: 4756
JI 0 14:43:29.432 Core 1 2022.02.01 16:43:13 Drawdown 5.10% >= max 5.00% — closing all EA positions on XAUUSD
2022.02.01 16:43:13 failed request sell 0.2 at 1802.13 , close #8 buy 0.2 XAUUSD 1804.89 [Invalid request]
DF 0 14:43:29.432 Core 1 2022.02.01 16:43:13 Failed to close position 8 — OrderSend error: 4756
NN 0 14:43:29.432 Core 1 2022.02.01 16:43:13 Drawdown 5.14% >= max 5.00% — closing all EA positions on XAUUSD
2022.02.01 16:43:13 failed request sell 0.2 at 1802.11 , close #8 buy 0.2 XAUUSD 1804.89 [Invalid request]
LR 0 14:43:29.432 Core 1 2022.02.01 16:43:13 Failed to close position 8 — OrderSend error: 4756
KR 0 14:43:29.432 Core 1 2022.02.01 16:43:14 Drawdown 5.18% >= max 5.00% — closing all EA positions on XAUUSD
2022.02.01 16:43:14 failed request sell 0.2 at 1802.09 , close #8 buy 0.2 XAUUSD 1804.89 [Invalid request]
IO 0 14:43:29.432 Core 1 2022.02.01 16:43:14 Failed to close position 8 — OrderSend error: 4756
MG 0 14:43:29.432 Core 1 2022.02.01 16:43:14 Drawdown 5.21% >= max 5.00% — closing all EA positions on XAUUSD
2022.02.01 16:43:14 failed request sell 0.2 at 1802.07 , close #8 buy 0.2 XAUUSD 1804.89 [Invalid request]
QK 0 14:43:29.432 Core 1 2022.02.01 16:43:14 Failed to close position 8 — OrderSend error: 4756
strategy tester report 13 total trades
Assistant
The error code 4756 (TRADE_RETCODE_INVALID_ORDER) means the order request is invalid and refuses execution. In your context, this error happens when trying to close a buy position with a sell order at price ~1802.1 when the position's open price is 1804.89, i.e. below current price, so likely the close price or volume or order parameters are incorrect or don't comply with the symbol/instrument rules.
The problem with XAUUSD and closing buy positions with hedging
For a buy position, the closing SELL order must be sent at the ASK price (or market price that broker accepts).
Your code currently uses:
Additionally — double check volume and price validity
Make sure close_volume respects SYMBOL_VOLUME_MIN, , .
User
full updated code
Assistant
Certainly! Below is your full EA code with the critical fix for closing positions — using the correct price when closing buy and sell positions — plus added debug prints to help you track volumes and prices before order sending.
mql5
User
test on EURUSD,H1 (hedging)
strategy tester report 538 total trades
test on XAUUSD,D1 (hedging)
FP 0 14:50:09.392 Core 1 2021.02.01 07:41:38 Drawdown 5.00% >= max 5.00% — closing all EA positions on XAUUSD
2021.02.01 07:41:38 failed request sell 0.2 at 1858.99 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
IN 0 14:50:09.392 Core 1 2021.02.01 07:41:38 Failed to close position 2 — OrderSend error: 4756
HF 0 14:50:09.392 Core 1 2021.02.01 07:41:38 Drawdown 5.06% >= max 5.00% — closing all EA positions on XAUUSD
2021.02.01 07:41:38 failed request sell 0.2 at 1858.96 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
ID 0 14:50:09.392 Core 1 2021.02.01 07:41:38 Failed to close position 2 — OrderSend error: 4756
CL 0 14:50:09.392 Core 1 2021.02.01 07:41:38 Drawdown 5.12% >= max 5.00% — closing all EA positions on XAUUSD
2021.02.01 07:41:38 failed request sell 0.2 at 1858.93 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
IR 0 14:50:09.392 Core 1 2021.02.01 07:41:38 Failed to close position 2 — OrderSend error: 4756
GR 0 14:50:09.392 Core 1 2021.02.01 07:41:38 Drawdown 5.16% >= max 5.00% — closing all EA positions on XAUUSD
2021.02.01 07:41:38 failed request sell 0.2 at 1858.91 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
IH 0 14:50:09.392 Core 1 2021.02.01 07:41:38 Failed to close position 2 — OrderSend error: 4756
FH 0 14:50:09.392 Core 1 2021.02.01 07:41:38 Drawdown 5.22% >= max 5.00% — closing all EA positions on XAUUSD
2021.02.01 07:41:38 failed request sell 0.2 at 1858.88 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
IF 0 14:50:09.392 Core 1 2021.02.01 07:41:38 Failed to close position 2 — OrderSend error: 4756
LN 0 14:50:09.392 Core 1 2021.02.01 07:41:38 Drawdown 5.28% >= max 5.00% — closing all EA positions on XAUUSD
2021.02.01 07:41:38 failed request sell 0.2 at 1858.85 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
IL 0 14:50:09.392 Core 1 2021.02.01 07:41:38 Failed to close position 2 — OrderSend error: 4756
HD 0 14:50:09.392 Core 1 2021.02.01 07:41:39 Drawdown 5.34% >= max 5.00% — closing all EA positions on XAUUSD
2021.02.01 07:41:39 failed request sell 0.2 at 1858.82 , close #2 buy 0.2 XAUUSD 1861.44 [Invalid request]
JJ 0 14:50:09.392 Core 1 2021.02.01 07:41:39 Failed to close position 2 — OrderSend error: 4756
strategy tester report 43 total trades
Assistant
The persistent invalid request (error 4756) when closing buy positions on XAUUSD indicates the close order request is still invalid for the broker/symbol, usually due to mismatch in price, volume, or trading permissions.
Common causes & fixes for error 4756 on position close (particularly on XAUUSD)
Close Price:
For buy position, close (sell) order price must be ASK price, which you already fixed.
Volume:
Must be within allowed volume range and aligned to volume step size.
Price decimal precision:
Price input must have correct decimal places (number of digits) as per symbol.
Check Symbol Properties Used:
Contract size
Tick size (SYMBOL_TRADE_TICK_SIZE)
Tick value
Minimum volume (SYMBOL_VOLUME_MIN)
Volume step (SYMBOL_VOLUME_STEP)
Volume max (SYMBOL_VOLUME_MAX)
Digits (SYMBOL_DIGITS) (number of decimal places price must respect)
Difference between price requested and current market price
Sometimes if price is not exactly matching price rules or is outside allowed range, broker rejects.
No request price for market order (use zero price)
In MetaTrader 5, for market orders (immediate execution) you usually do NOT set the price field, or you set it to 0. Broker uses market price internally.
Your code uses price = close_price when closing — this may cause problem for market orders!
Closing position via TRADE_ACTION_DEAL with type opposite to opened position is a market order.
For market orders, price should be 0 (not current Bid or Ask).
Setting price ≠ 0 causes broker to reject the request as invalid.
Recommended fix: Set price=0 for market order close requests
Change this line inside your CloseAllPositionsIfDrawdown():
From:
mql5
close_req.price = close_price;
To:
User
full
Assistant
Certainly! Below is your full updated EA code with the crucial fix applied to the position-closing logic: market close orders now set price = 0, which avoids invalid requests on symbols like XAUUSD.
mql5
Not yet included in a published release.
Make it an input for easier multi-EA deployments:
mql5
input ulong magic_number = 123456;
5. More verbose error logging for failed OrderSend
When OrderSend fails, you print the last error, but you could retrieve the error from the result structure after OrderSend:
result.retcode offers more detailed order execution info.
6. Trailing stop, partial closes, or multiple position handling
If you want, you could enhance the management of positions with trailing stops or partial closes. Currently, all positions opened per symbol+magic are fully closed on drawdown or manual closure.
7. Efficiency note: copy buffer calls
Each tick, you call CopyBuffer for ATR and EMA once:
mql5
if(CopyBuffer(ma_handle, 0, 1, 1, ma_buf) <= 0)
This is fine but you could also consider caching or updating only on new bar if performance becomes an issue.
Summary
Your EA code is good as is for a BoS strategy with important risk controls and chart visualization. The above notes are mostly minor improvements for robustness, diagnostics, and slight better practices.
If you want, I can help you with a snippet for:
Enhanced error message on order send
Changing magic number to input
Or tighter checking for swing lines object creation
Just ask!
5. Drawdown Protection — Close All on Excessive Losses
Monitors the total unrealized profit/loss of all open positions managed by the EA.
When drawdown exceeds the user-configured maximum percentage loss of account balance, all EA positions on the symbol and magic number are closed immediately.
Prevents significant account damage during adverse market conditions.
6. Trading Time Control
Operates only within specified server time hours (default 07:00 to 22:00).
Avoids trading during low liquidity or volatile overnight sessions.
7. Position Management
Controls maximum allowed open positions simultaneously (default 1).
Positions are opened/closed with proper ticket and magic number checks to avoid conflicts with manual or other expert trades.
Positions closed correctly with market execution orders.
8. Chart Visualization
Continuously shows swing high and swing low levels as horizontal lines on the chart.
Uses easily distinguishable colors for swing highs (green) and swing lows (red).
Helps traders to understand the current swing structure visually.
Input Parameters
Parameter
Type
Default
Description
inpLot
double
0.05
Fixed lot size per trade
useRiskPercent
bool
false
Enable risk % based lot sizing
riskPercent
double
1.0
Risk percent per trade (if enabled)
maxDrawdownPct
double
5.0
Max drawdown % before closing all EA trades (0 disables)
sl_atr_mult
int
3
Stop Loss multiplier based on ATR
r2r_ratio
double
2.0
Risk-to-Reward ratio for Take Profit
volatilityTF
ENUM_TIMEFRAMES
PERIOD_M5
Timeframe for ATR calculation
swingLookback
int
20
Bars to look back to find swing highs/lows on M1
maPeriod
int
50
EMA period for trend filter on M15
maTimeframe
ENUM_TIMEFRAMES
PERIOD_M15
Timeframe for EMA trend filter
tradeStartHour
int
7
Hour to start EA trading (server time)
tradeEndHour
int
22
Hour to stop EA trading (server time)
maxPositions
int
1
Maximum simultaneous positions allowed (0 = unlimited)
How It Works — Trading Logic in Detail
Trend Direction:
Each tick, the EA reads the current EMA (default 50-period on M15). If price is above EMA, the trend is up; below EMA is down.
Swing Detection:
It scans the last 20 M1 bars (default) to detect the highest high and lowest low, defining current market swing levels.
Break of Structure Confirmation:
For a Buy: The ask price breaks above the last swing high and the trend is up.
For a Sell: The bid price breaks below the last swing low and trend is down.
Volatility-Adjusted Stops & Targets:
The EA calculates the ATR (period 14 on M5) and multiplies it by a factor (default 3) to derive the SL distance in price.
The TP is set as SL distance times the Risk-to-Reward ratio (default 2).
Lot Size Calculation:
Either a fixed lot size or, if enabled, a risk % based lot size is computed, factoring in stop loss distance, tick value, and contract size.
Order Execution:
Opens buy/sell market order with calculated lot, SL, and TP, ensuring compliance with broker limits.
Drawdown Monitoring:
Checks total unrealized profit/loss from all EA positions for the symbol. If drawdown exceeds defined max %, closes all EA trades immediately.
System Requirements and Recommendations
Platform: MetaTrader 5 build 2520 or newer.
Symbol: Works on any symbol where tick value, contract size, and volume step can be retrieved.
Broker Requirements: Supports market orders, and volume step/sizing must be compatible.
Time Settings: EA uses server time for trading hours; verify broker time zone correspondence.
Chart timeframe: EA must be attached to the symbol chart intended to trade; chart timeframe can be any.
Usage Notes
This EA is designed for intraday trading, so adjust time filters accordingly.
The ATR multiplier and Risk-to-Reward ratio provide good starting defaults but can be tuned according to volatility and trading style.
When enabling risk-percentage lot sizing, ensure your SL calculation reflects realistic stop loss placement.
Always test the EA thoroughly on demo accounts before live deployment.
Drawdown protection is configurable and suitable for risk-averse traders.
Why Choose AdvancedBoS_EA_MT5?
Clear Trade Entries: Based on tested price action Break of Structure validated by trend EMA.
Dynamic Adaptive Risk: Lot sizing and SL/TP adjust to current volatility and risk profile.
Robust Position Management: Handles multiple positions properly with full drawdown protection.
Visual Swing Display: Keeps you informed about current market structure at all times.
Customizable & Flexible: Easily editable inputs tailor the EA for your personal trading preferences.
Future Enhancements Planned (Potential Roadmap)
Trailing stop loss to lock in profits while maintaining risk.
Partial position closing functionality.
Multi symbol portfolio management.
Alerts and notifications on new trades and drawdown events.
Enhanced graphical interface with swing patterns and statistics.
If you find this EA useful, please support the development with feedback or donations! For inquiries or support, contact: LucienWebP
Happy Trading & Stay Disciplined!
If you want, I can help you prepare concise publish-ready text versions or marketing blurbs as well. Let me know!
Then assign request.volume = cl_volume;.
2. Use current market prices suitable for position type
Add Print statements to output position volume, price, lot step, etc., before sending close order.
Test on other symbols to verify if error is only on XAUUSD or general.
Try opening a single position manually on XAUUSD in your demo and then use a minimal close request in script to isolate the issue.
Summary
The invalid request errors on close requests typically boil down to improper volume sizing or wrong price selection for the close order when hedging. By ensuring you close positions with correct normalized volume, proper bid or ask price, and verify symbol settings, you should fix these failures.
If you want, I can help generate a fully revised version of your close-all function with these safeguards added.
Feel free to provide your current full closing code snippet if you'd like me to review it line-by-line for improvements!
void CloseAllPositionsIfDrawdown(double maxDrawdownPercent)
{
if(maxDrawdownPercent <= 0)
return;
double totalUnrealized = 0.0;
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
// Sum unrealized profits/losses of all EA positions for this symbol
for(int i=PositionsTotal()-1; i>=0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == magic_number && PositionGetString(POSITION_SYMBOL) == _Symbol)
totalUnrealized += PositionGetDouble(POSITION_PROFIT);
}
}
if(totalUnrealized < 0)
{
double drawdownPercent = MathAbs(totalUnrealized)/balance*100.0;
if(drawdownPercent >= maxDrawdownPercent)
{
PrintFormat("Drawdown %.2f%% >= max %.2f%% — closing all EA positions on %s", drawdownPercent, maxDrawdownPercent, _Symbol);
for(int i=PositionsTotal()-1; i>=0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == magic_number && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
double pos_volume = PositionGetDouble(POSITION_VOLUME);
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double vol_min = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double vol_max = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
// Normalize volume to allowed step and range
double close_volume = MathFloor(pos_volume / lot_step) * lot_step;
close_volume = MathMax(close_volume, vol_min);
close_volume = MathMin(close_volume, vol_max);
// Defensive: do not proceed with zero or negative volume
if(close_volume <= 0)
{
PrintFormat("Position %I64d: volume after normalization invalid (%.2f), skipping close", ticket, close_volume);
continue;
}
// Use correct price for closing — bid for Buy position, ask for Sell position
double close_price = (pos_type == POSITION_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_BID) : SymbolInfoDouble(_Symbol, SYMBOL_ASK);
MqlTradeRequest close_req;
MqlTradeResult close_res;
ZeroMemory(close_req);
ZeroMemory(close_res);
close_req.action = TRADE_ACTION_DEAL;
close_req.position = ticket;
close_req.volume = close_volume;
close_req.price = close_price;
close_req.type = (pos_type == POSITION_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
close_req.deviation = 10;
close_req.magic = magic_number;
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)
{
// Provide detailed retcode info
PrintFormat("Closing position %I64d returned retcode %d — \"%s\"", ticket, close_res.retcode, EnumToString(close_res.retcode));
}
else
{
PrintFormat("Position %I64d closed due to drawdown protection", ticket);
}
}
}
}
}
}
}
How to Integrate
Replace your existing CloseAllPositionsIfDrawdown() with the above function in your EA code.
Compile and retest on XAUUSD D1 with hedging enabled.
Look at terminal Experts tab for detailed close status messages.
Why This Fix Works
Volume Normalization: ensures volume respects the broker’s allowed increments and limits.
Correct Close Price: bids asked appropriately based on position type avoids invalid price errors.
Error Handling: Prints detailed info for failed closes; helps diagnose if problem persists.
Safety Checks: prevents sending orders with invalid volume which commonly cause invalid requests.
If you want, I can also send you the full updated EA code snippet with this fix in context. Just ask!
By adding #include <Trade\Trade.mqh> at the top, the type ENUM_TRADE_RETCODE and the function EnumToString() recognizing that enum will be properly defined, resolving your errors.
Compile and test again, and you should no longer see those enum-related errors.
If you want help adding more features or refining the strategy, just ask!
The only change is in the CloseAllPositionsIfDrawdown() function when printing the retcode: it prints just the numeric value.
This avoids any ENUM_TRADE_RETCODE undefined errors.
You can still see the return codes as numbers to troubleshoot trades.
If you want me to later help you build a mapping from retcode int → string status for better logs, just let me know.
SYMBOL_VOLUME_STEP
SYMBOL_VOLUME_MAX
You may print all these along with the prices before sending close order to debug.
Modified snippet for close-all (focus on price):
mql5
double close_price = 0.0;
if(pos_type == POSITION_TYPE_BUY)
close_price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
else if(pos_type == POSITION_TYPE_SELL)
close_price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
else
{
PrintFormat("Unknown position type %d for position %I64d", pos_type, ticket);
continue; // skip if unknown
}
Summary
Change your close price logic in CloseAllPositionsIfDrawdown() as above.
This change should fix the error 4756 invalid request on XAUUSD hedging testing.
If you want, I can provide the full updated function with this fix and extra debug prints to track values before closing. Would you like that?
Close price fix:
Buy positions are closed with a sell order at the ASK price.
Sell positions closed with a buy order at the BID price.
This matches the proper market prices brokers expect and prevents invalid request errors.
Pre-close debug:
Prints ticket, volume, price, and position type before attempting close — useful for troubleshooting.
Rounding volumes as before, and ensuring volume and prices are valid.
Try compiling with this code and rerun your tests on XAUUSD D1 with hedging enabled. Errors 4756 should disappear, and positions should close correctly on drawdown.
If you want further assistance or enhancements, please ask!
mql5
close_req.price = 0;
Optional:
If you want to be very sure you are on the right price precision, verify the digits and normalize prices accordingly for order open (keep them as you did) but for close market orders price MUST be zero.
Summary of the fix:
Replace in CloseAllPositionsIfDrawdown():
mql5
close_req.price = close_price;
with
mql5
close_req.price = 0;
Why?
Setting price for market orders in MT5 is usually ignored, but setting a price different than zero triggers strict validation which can cause invalid request on some symbols (like XAUUSD).
Price 0 tells MT5 broker to execute at market price.
Complete critical snippet fix:
mql5
// Inside your position close loop in CloseAllPositionsIfDrawdown():
MqlTradeRequest close_req;
MqlTradeResult close_res;
ZeroMemory(close_req);
ZeroMemory(close_res);
close_req.action = TRADE_ACTION_DEAL;
close_req.position = ticket;
close_req.volume = close_volume;
// close_req.price = close_price; <-- REMOVE this
close_req.price = 0; // Set zero for market orders close
close_req.type = (pos_type == POSITION_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
close_req.deviation = 10;
close_req.magic = magic_number;
Try this fix and rerun your tests on XAUUSD hedging; position closes should succeed now.
If you want, I can provide the full EA code updated with this fix included. Would you like that?
//+------------------------------------------------------------------+
//| AdvancedBoS_EA_MT5.mq5 |
//| BoS EA with dynamic lot sizing, drawdown close, swing visualization |
//| and correct position closing for MT5 |
//+------------------------------------------------------------------+
#property copyright "LucienWebP"
#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 %, else fixed lot
input double riskPercent = 1.0; // Risk % per trade if risk mode enabled
input double maxDrawdownPct = 5.0; // Max drawdown % of balance before all close (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; // Timeframe for ATR calculation
input int swingLookback = 20; // Bars to look back for swing detection on M1
input int maPeriod = 50; // EMA period for trend filter M15
input ENUM_TIMEFRAMES maTimeframe = PERIOD_M15; // EMA timeframe
input int tradeStartHour = 7; // Trade start hour (server time)
input int tradeEndHour = 22; // Trade end hour (server time)
input int maxPositions = 1; // Max simultaneous positions (0=no limit)
input ulong magic_number = 123456; // Magic number for identifying positions
int ma_handle = INVALID_HANDLE;
int atr_handle = INVALID_HANDLE;
string swingHighLineName = "SwingHighLine";
string swingLowLineName = "SwingLowLine";
//+------------------------------------------------------------------+
int OnInit()
{
ma_handle = iMA(_Symbol, maTimeframe, maPeriod, 0, MODE_EMA, PRICE_CLOSE);
atr_handle = iATR(_Symbol, volatilityTF, 14);
if(ma_handle == INVALID_HANDLE)
{
Print("Failed to get EMA handle");
return INIT_FAILED;
}
if(atr_handle == INVALID_HANDLE)
{
Print("Failed to get ATR handle");
return INIT_FAILED;
}
if(!ObjectCreate(0, swingHighLineName, OBJ_HLINE, 0, 0, 0))
Print("Failed to create swing high line");
if(!ObjectCreate(0, swingLowLineName, OBJ_HLINE, 0, 0, 0))
Print("Failed to create swing low line");
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
ObjectDelete(0, swingHighLineName);
ObjectDelete(0, swingLowLineName);
if(ma_handle != INVALID_HANDLE)
IndicatorRelease(ma_handle);
if(atr_handle != INVALID_HANDLE)
IndicatorRelease(atr_handle);
}
//+------------------------------------------------------------------+
double CalculateLotSize(double sl_distance_points)
{
if(!useRiskPercent)
return(inpLot);
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
double riskMoney = balance * (riskPercent / 100.0);
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("Tick value or size zero - cannot calculate lot size");
return(inpLot);
}
double point_value = tick_value / tick_size;
double lot = riskMoney / (sl_distance_points * point_value * 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);
lot = MathFloor(lot / lot_step) * lot_step;
lot = MathMax(lot, min_lot);
lot = MathMin(lot, max_lot);
return lot;
}
//+------------------------------------------------------------------+
void CloseAllPositionsIfDrawdown(double maxDrawdownPercent)
{
if(maxDrawdownPercent <= 0)
return;
double totalUnrealized = 0.0;
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
for(int i=PositionsTotal()-1; i>=0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == magic_number && PositionGetString(POSITION_SYMBOL) == _Symbol)
totalUnrealized += PositionGetDouble(POSITION_PROFIT);
}
}
if(totalUnrealized < 0)
{
double drawdownPercent = MathAbs(totalUnrealized)/balance*100.0;
if(drawdownPercent >= maxDrawdownPercent)
{
PrintFormat("Drawdown %.2f%% >= max %.2f%% — closing all EA positions on %s", drawdownPercent, maxDrawdownPercent, _Symbol);
for(int i=PositionsTotal()-1; i>=0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == magic_number && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
double pos_volume = PositionGetDouble(POSITION_VOLUME);
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double vol_min = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double vol_max = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double close_volume = MathFloor(pos_volume / lot_step) * lot_step;
close_volume = MathMax(close_volume, vol_min);
close_volume = MathMin(close_volume, vol_max);
if(close_volume <= 0)
{
PrintFormat("Position %I64d: volume after normalization invalid (%.2f), skipping close", ticket, close_volume);
continue;
}
// Correct closing price logic per MT5 market order specs:
double close_price = 0; // Market close order price must be zero
// Debug prints before sending close order
PrintFormat("Closing position ticket=%I64d volume=%.2f positionType=%d using market price (price=0)", ticket, close_volume, pos_type);
MqlTradeRequest close_req;
MqlTradeResult close_res;
ZeroMemory(close_req);
ZeroMemory(close_res);
close_req.action = TRADE_ACTION_DEAL;
close_req.position = ticket;
close_req.volume = close_volume;
close_req.price = close_price; // MUST be zero for market close
close_req.type = (pos_type == POSITION_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
close_req.deviation = 10;
close_req.magic = magic_number;
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("Closing position %I64d returned retcode %d", ticket, close_res.retcode);
}
else
{
PrintFormat("Position %I64d closed due to drawdown protection", ticket);
}
}
}
}
}
}
}
//+------------------------------------------------------------------+
void OnTick()
{
CloseAllPositionsIfDrawdown(maxDrawdownPct);
int openPosCount = 0;
for(int i=PositionsTotal()-1; i>=0; i--)
{
ulong ticket=PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == magic_number && 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[], atr_buf[];
if(CopyBuffer(ma_handle, 0, 1, 1, ma_buf) <= 0)
{
Print("Failed copying EMA buffer ", GetLastError());
return;
}
if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0)
{
Print("Failed copying ATR buffer ", GetLastError());
return;
}
double ma = ma_buf[0];
double atr = atr_buf[0];
if(atr <= 0.0)
atr = 10.0 * _Point;
double sl_dist = atr * sl_atr_mult;
double tp_dist = sl_dist * r2r_ratio;
double last_swing_high = iHigh(_Symbol, PERIOD_M1, iHighest(_Symbol, PERIOD_M1, MODE_HIGH, swingLookback, 1));
double last_swing_low = iLow(_Symbol, PERIOD_M1, iLowest(_Symbol, PERIOD_M1, MODE_LOW, swingLookback, 1));
ObjectSetDouble(0, swingHighLineName, OBJPROP_PRICE, last_swing_high);
ObjectSetInteger(0, swingHighLineName, OBJPROP_COLOR, clrGreen);
ObjectSetDouble(0, swingLowLineName, OBJPROP_PRICE, last_swing_low);
ObjectSetInteger(0, swingLowLineName, OBJPROP_COLOR, clrRed);
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double price_htf = iClose(_Symbol, maTimeframe, 1);
bool is_uptrend = price_htf > ma;
bool is_downtrend = price_htf < ma;
double lot = CalculateLotSize(sl_dist);
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double lot_min = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double lot_max = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
lot = MathFloor(lot / lot_step) * lot_step;
lot = MathMax(lot, lot_min);
lot = MathMin(lot, lot_max);
if(lot < lot_min)
{
PrintFormat("Calculated lot size %.2f less than minimum allowed %.2f, skipping trade", lot, lot_min);
return;
}
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.symbol = _Symbol;
request.volume = lot;
request.deviation = 10;
request.magic = magic_number;
if(ask > last_swing_high && is_uptrend)
{
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 failed with error %d", GetLastError());
else
PrintFormat("Buy order opened @ %.5f lot %.2f SL %.5f TP %.5f", ask, lot, request.sl, request.tp);
}
else if(bid < last_swing_low && is_downtrend)
{
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 failed with error %d", GetLastError());
else
PrintFormat("Sell order opened @ %.5f lot %.2f SL %.5f TP %.5f", bid, lot, request.sl, request.tp);
}
}
//+------------------------------------------------------------------+
Notes:
Position close requests now have price = 0, meaning market close orders.
This is essential, otherwise the broker may reject close requests with error 4756 invalid request.
You will likely see the errors disappear and close orders execute correctly.
Please compile and test again with this code. Let me know if you need further assistance!