Orders can fail for many reasons: requotes, invalid stops, insufficient margin, market closed. An EA that does not handle errors may retry endlessly, skip trades silently, or open duplicates.
A robust approach is to check the return code of every trade request and handle the main categories explicitly. For temporary issues such as requotes or busy servers, a limited number of retries with a short pause is reasonable. For permanent issues such as invalid stops, log the problem and stop retrying.
A worked example of a duplicate bug: an EA sends an order, the connection drops before confirmation, and the EA sends it again on reconnect. Checking open positions by magic number before sending prevents this.
It is also wise to verify stop distances against the broker's minimum stop level before sending, since this varies by broker and can change around news.
Testing error handling on demo by deliberately sending invalid orders helps confirm the logic works.
Which order errors have caused you the most trouble?
Handling requotes and order errors gracefully in MQL5
-
FXS London Scalper
- Posts: 1252
- Joined: Sun Oct 18, 2026 12:25 pm
Handling requotes and order errors gracefully in MQL5
FXS Official Team | London Session Desk
-
Amanhasnoname
- Posts: 2631
- Joined: Fri Oct 30, 2026 9:45 am
Re: Handling requotes and order errors gracefully in MQL5
The duplicate order case is the one that catches most people, and checking positions by magic number is a good fix as long as it also covers pending orders and the history of the last few seconds. After a reconnect, the terminal can take a moment to sync, so a position that was opened just before the drop may not yet appear in the list. A short wait and a second check, or storing a unique comment or request id in each order and searching for it, makes the guard much more reliable.
It also helps to separate the retcode categories in code rather than with a long chain of ifs. Requotes, price changed and off quotes are worth a refresh of the price and one or two retries. Invalid stops, invalid volume and not enough money should never be retried blindly, because the result will not change. Trade disabled and market closed should pause the EA until conditions change.
Logging the full request alongside the retcode, including price, stops, deviation and the symbol's current stop level and freeze level, saves a lot of guesswork later. Freeze level in particular is often forgotten and causes modify errors near the market.
It also helps to separate the retcode categories in code rather than with a long chain of ifs. Requotes, price changed and off quotes are worth a refresh of the price and one or two retries. Invalid stops, invalid volume and not enough money should never be retried blindly, because the result will not change. Trade disabled and market closed should pause the EA until conditions change.
Logging the full request alongside the retcode, including price, stops, deviation and the symbol's current stop level and freeze level, saves a lot of guesswork later. Freeze level in particular is often forgotten and causes modify errors near the market.
Re: Handling requotes and order errors gracefully in MQL5
Hi traders/scalpers,
i prepared this version of MQL 5 script, which can help you
SafeOrderExecutor (v1.00) – Production-Grade MQL5 Requote, Error & Duplicate Handling Script
To put the concepts discussed in this thread into practice, I built a clean, self-contained MQL5 Script and reusable OOP class (CSafeOrderExecutor) that compiles with zero errors and zero warnings in MetaEditor 5.
Most retail scalping EAs fail in live conditions because they either retry permanent errors endlessly (spamming the broker server until throttled with error 10024) or blindly resend orders after a brief disconnect and accidentally open duplicate positions. This utility solves both problems explicitly.
Key Technical Features
To reuse this in a live scalping Expert Advisor, copy the SExecReport struct and CSafeOrderExecutor class into an .mqh include file and call executor.ExecuteMarketOrder(...) from your entry logic.
Below is the complete source code for SafeOrderExecutor.mq5:
i prepared this version of MQL 5 script, which can help you
SafeOrderExecutor (v1.00) – Production-Grade MQL5 Requote, Error & Duplicate Handling Script
To put the concepts discussed in this thread into practice, I built a clean, self-contained MQL5 Script and reusable OOP class (CSafeOrderExecutor) that compiles with zero errors and zero warnings in MetaEditor 5.
Most retail scalping EAs fail in live conditions because they either retry permanent errors endlessly (spamming the broker server until throttled with error 10024) or blindly resend orders after a brief disconnect and accidentally open duplicate positions. This utility solves both problems explicitly.
Key Technical Features
- Explicit Return Code Classification (TRADE_RETCODE_*): Separates trade server responses into three buckets: Success (10009 Done, 10010 Partial, 10008 Placed), Retryable Transient Errors (10004 Requote, 10020 Price Changed, 10021 Price Off, 10012 Timeout, 10031 Connection Lost, 10024 Too Many Requests, 10028 Locked, 10029 Frozen), and Permanent Fatal Errors (10016 Invalid Stops, 10019 Insufficient Margin, 10018 Market Closed, 10017 Trade Disabled, etc.). Fatal errors abort immediately on the first attempt.
- Exponential Backoff with Fresh Ticks: On transient failures, the loop waits with exponential backoff (starting from InpBaseDelayMs, capped at 4000 ms, with an automatic 1000 ms floor if rate-limited) and fetches fresh Bid/Ask quotes via SymbolInfoTick() before every retry.
- Disconnect-Safe Duplicate Guard: Checks both open positions (PositionsTotal) and active pending orders (OrdersTotal) for the matching symbol and Magic Number before every retry attempt—not just before attempt #1. If the connection drops right after the broker fills the trade, the synced position is detected upon reconnect and a duplicate fill is blocked.
- Automatic Filling Policy Detection: Inspects SYMBOL_FILLING_MODE (IOC -> FOK -> RETURN) dynamically so the code runs across different ECN and standard MT5 brokers without throwing Error 10030 (Unsupported Filling Mode).
- Broker Stop-Level & Freeze-Level Protection: Validates Stop Loss and Take Profit distances against SYMBOL_TRADE_STOPS_LEVEL and SYMBOL_TRADE_FREEZE_LEVEL (plus a 2-point live tick buffer), with an option to auto-adjust stops to the minimum legal distance.
- Pre-Flight OrderCheck() & Latency Telemetry: Runs OrderCheck() locally before hitting the trade server and prints total execution latency (ms), attempt count, and exact retcode details both in the Experts log and directly on the chart.
- InpMode: Choose between MODE_NORMAL_EXECUTION (safe market entry) and MODE_TEST_INVALID_STOPS (deliberately places SL on the wrong side of the market on demo to verify instant abort on Error 10016).
- InpDirection / InpVolume: Market BUY or SELL and lot size (automatically normalized to broker min, max, and volume step).
- InpStopLossPts / InpTakeProfitPts: Stop Loss and Take Profit in points (set to 0 to disable).
- InpMagicNumber / InpDeviationPts: Magic number for duplicate isolation and maximum allowed slippage in points.
- InpMaxRetries / InpBaseDelayMs: Retry cap for transient errors and starting backoff delay in milliseconds.
- InpPreventDuplicate / InpAutoAdjustStops: Toggle duplicate-exposure protection and automatic stop-level adjustment.
- InpDemoAccountOnly: Built-in safety guard (true by default) that blocks execution on live accounts unless explicitly disabled.
- Save the code below as SafeOrderExecutor.mq5 inside MQL5\Scripts\ and compile it in MetaEditor 5.
- Drag the script onto any demo chart with InpMode = MODE_TEST_INVALID_STOPS and confirm in the Experts tab that OrderCheck immediately catches 10016 Invalid stops and aborts without retrying.
- Run it again with InpMode = MODE_NORMAL_EXECUTION to see normal fill confirmation and round-trip execution latency in milliseconds.
- Run it a second time right away to confirm that the duplicate guard detects the open position by Magic Number and blocks a second entry.
To reuse this in a live scalping Expert Advisor, copy the SExecReport struct and CSafeOrderExecutor class into an .mqh include file and call executor.ExecuteMarketOrder(...) from your entry logic.
Below is the complete source code for SafeOrderExecutor.mq5:
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Re: Handling requotes and order errors gracefully in MQL5
MQL5 version:
Code: Select all
//+------------------------------------------------------------------+
//| SafeOrderExecutor.mq5 |
//| Copyright 2026, PTtrader88 |
//| https://www.mql5.com/en/users/pttrader88 |
//+------------------------------------------------------------------+
#property copyright "PTtrader88"
#property link "https://www.mql5.com/en/users/pttrader88"
#property version "1.00"
#property description "Production-grade MQL5 market order execution utility."
#property description "Handles requotes, transient server errors with exponential backoff,"
#property description "duplicate-position protection after disconnects, and stop-level checks."
#property script_show_inputs
//+------------------------------------------------------------------+
//| Enums |
//+------------------------------------------------------------------+
enum ENUM_EXEC_DIRECTION
{
EXEC_BUY = 0, // Market BUY
EXEC_SELL = 1 // Market SELL
};
enum ENUM_SCRIPT_MODE
{
MODE_NORMAL_EXECUTION = 0, // Normal safe market execution
MODE_TEST_INVALID_STOPS = 1 // Demo test: deliberately send invalid SL (verify fatal abort)
};
enum ENUM_RETCODE_CLASS
{
RET_SUCCESS = 0, // Order executed or placed
RET_RETRYABLE = 1, // Temporary issue: safe to retry after refresh & pause
RET_PERMANENT = 2 // Permanent error: log and abort immediately
};
//+------------------------------------------------------------------+
//| Script Input Parameters |
//+------------------------------------------------------------------+
input group "=== Execution Parameters ==="
input ENUM_SCRIPT_MODE InpMode = MODE_NORMAL_EXECUTION; // Execution Mode
input ENUM_EXEC_DIRECTION InpDirection = EXEC_BUY; // Order Direction
input double InpVolume = 0.01; // Lot Size
input int InpStopLossPts = 150; // Stop Loss (points, 0 = none)
input int InpTakeProfitPts = 300; // Take Profit (points, 0 = none)
input ulong InpMagicNumber = 18011; // Magic Number
input ulong InpDeviationPts = 20; // Max Slippage / Deviation (points)
input string InpComment = "SafeExec_v1"; // Order Comment
input group "=== Error Handling & Safety ==="
input int InpMaxRetries = 5; // Max Retry Attempts (transient errors)
input int InpBaseDelayMs = 250; // Base Retry Delay (ms, exponential backoff)
input bool InpPreventDuplicate = true; // Prevent Duplicate Position/Order by Magic
input bool InpAutoAdjustStops = true; // Auto-adjust SL/TP to Broker Stops Level
input bool InpDemoAccountOnly = true; // Safety Guard: Block Execution on Real Account
//+------------------------------------------------------------------+
//| Execution Report Structure |
//+------------------------------------------------------------------+
struct SExecReport
{
bool success;
uint last_retcode;
string last_retcode_desc;
int attempts_used;
ulong order_ticket;
ulong deal_ticket;
double executed_price;
ulong total_latency_ms;
string summary;
};
//+------------------------------------------------------------------+
//| Reusable Class: CSafeOrderExecutor |
//| Copy this class directly into any MQL5 Expert Advisor |
//+------------------------------------------------------------------+
class CSafeOrderExecutor
{
private:
string m_symbol;
ulong m_magic;
ulong m_deviation;
int m_max_retries;
int m_base_delay_ms;
bool m_prevent_duplicate;
bool m_auto_adjust_stops;
//--- Determine decimal precision of volume step
int GetVolumeDigits(const double step) const
{
if(step <= 0.0) return 2;
int digits = 0;
double val = step;
while(digits < 8 && MathAbs(val - MathRound(val)) > 1e-8)
{
val *= 10.0;
digits++;
}
return digits;
}
//--- Normalize volume strictly to broker min/max/step constraints
double NormalizeVolume(const double raw_volume) const
{
double min_vol = SymbolInfoDouble(m_symbol, SYMBOL_VOLUME_MIN);
double max_vol = SymbolInfoDouble(m_symbol, SYMBOL_VOLUME_MAX);
double step_vol = SymbolInfoDouble(m_symbol, SYMBOL_VOLUME_STEP);
if(step_vol <= 0.0 || min_vol <= 0.0)
return 0.0;
double vol = MathFloor(raw_volume / step_vol + 1e-9) * step_vol;
if(vol < min_vol) vol = min_vol;
if(vol > max_vol) vol = max_vol;
return NormalizeDouble(vol, GetVolumeDigits(step_vol));
}
//--- Auto-detect broker-supported filling policy (prevents error 10030)
ENUM_ORDER_TYPE_FILLING ResolveFillingMode() const
{
long filling = SymbolInfoInteger(m_symbol, SYMBOL_FILLING_MODE);
if((filling & SYMBOL_FILLING_IOC) != 0)
return ORDER_FILLING_IOC;
if((filling & SYMBOL_FILLING_FOK) != 0)
return ORDER_FILLING_FOK;
return ORDER_FILLING_RETURN;
}
//--- Check both open positions and active orders for this symbol + magic
bool HasExistingExposure() const
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0) continue;
if(PositionGetString(POSITION_SYMBOL) == m_symbol &&
(ulong)PositionGetInteger(POSITION_MAGIC) == m_magic)
return true;
}
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
ulong ticket = OrderGetTicket(i);
if(ticket == 0) continue;
if(OrderGetString(ORDER_SYMBOL) == m_symbol &&
(ulong)OrderGetInteger(ORDER_MAGIC) == m_magic)
return true;
}
return false;
}
//--- Wait briefly for terminal reconnect when connection drops mid-flight
bool WaitForConnection(const int max_wait_ms) const
{
int waited = 0;
const int step_ms = 100;
while(!IsStopped() && waited < max_wait_ms)
{
if(TerminalInfoInteger(TERMINAL_CONNECTED) != 0)
return true;
Sleep(step_ms);
waited += step_ms;
}
return (TerminalInfoInteger(TERMINAL_CONNECTED) != 0);
}
//--- Validate and optionally adjust SL/TP distances against broker stops/freeze levels
bool BuildStops(const ENUM_ORDER_TYPE order_type,
const MqlTick &tick,
const int sl_pts,
const int tp_pts,
const bool force_invalid_sl,
double &out_sl,
double &out_tp,
string &err_msg) const
{
out_sl = 0.0;
out_tp = 0.0;
int digits = (int)SymbolInfoInteger(m_symbol, SYMBOL_DIGITS);
double point = SymbolInfoDouble(m_symbol, SYMBOL_POINT);
int stops_level = (int)SymbolInfoInteger(m_symbol, SYMBOL_TRADE_STOPS_LEVEL);
int freeze_level = (int)SymbolInfoInteger(m_symbol, SYMBOL_TRADE_FREEZE_LEVEL);
// Minimum safe buffer in points (+2 pts safety margin for live spread ticks)
int min_pts = MathMax(stops_level, freeze_level) + 2;
double min_dist = min_pts * point;
// Deliberate invalid-stop test mode (wrong side of market -> guaranteed error 10016)
if(force_invalid_sl)
{
out_sl = (order_type == ORDER_TYPE_BUY)
? NormalizeDouble(tick.ask + 50 * point, digits)
: NormalizeDouble(tick.bid - 50 * point, digits);
return true;
}
if(order_type == ORDER_TYPE_BUY)
{
if(sl_pts > 0)
{
double desired_sl = tick.ask - sl_pts * point;
double max_valid_sl = tick.bid - min_dist;
if(desired_sl > max_valid_sl)
{
if(!m_auto_adjust_stops)
{
err_msg = StringFormat("BUY SL too close (min stops/freeze level: %d pts)", min_pts);
return false;
}
desired_sl = max_valid_sl;
}
out_sl = NormalizeDouble(desired_sl, digits);
}
if(tp_pts > 0)
{
double desired_tp = tick.ask + tp_pts * point;
double min_valid_tp = tick.ask + min_dist;
if(desired_tp < min_valid_tp)
{
if(!m_auto_adjust_stops)
{
err_msg = StringFormat("BUY TP too close (min stops/freeze level: %d pts)", min_pts);
return false;
}
desired_tp = min_valid_tp;
}
out_tp = NormalizeDouble(desired_tp, digits);
}
}
else // ORDER_TYPE_SELL
{
if(sl_pts > 0)
{
double desired_sl = tick.bid + sl_pts * point;
double min_valid_sl = tick.ask + min_dist;
if(desired_sl < min_valid_sl)
{
if(!m_auto_adjust_stops)
{
err_msg = StringFormat("SELL SL too close (min stops/freeze level: %d pts)", min_pts);
return false;
}
desired_sl = min_valid_sl;
}
out_sl = NormalizeDouble(desired_sl, digits);
}
if(tp_pts > 0)
{
double desired_tp = tick.bid - tp_pts * point;
double max_valid_tp = tick.bid - min_dist;
if(desired_tp > max_valid_tp)
{
if(!m_auto_adjust_stops)
{
err_msg = StringFormat("SELL TP too close (min stops/freeze level: %d pts)", min_pts);
return false;
}
desired_tp = max_valid_tp;
}
out_tp = NormalizeDouble(desired_tp, digits);
}
}
return true;
}
public:
//--- Constructor
CSafeOrderExecutor(const string symbol,
const ulong magic,
const ulong deviation_pts = 20,
const int max_retries = 5,
const int base_delay_ms = 250,
const bool prevent_duplicate = true,
const bool auto_adjust_stops = true)
{
m_symbol = symbol;
m_magic = magic;
m_deviation = deviation_pts;
m_max_retries = MathMax(1, max_retries);
m_base_delay_ms = MathMax(50, base_delay_ms);
m_prevent_duplicate = prevent_duplicate;
m_auto_adjust_stops = auto_adjust_stops;
}
//--- Classify MQL5 trade server return codes explicitly
static ENUM_RETCODE_CLASS ClassifyRetcode(const uint retcode)
{
switch(retcode)
{
// Success states
case TRADE_RETCODE_DONE:
case TRADE_RETCODE_DONE_PARTIAL:
case TRADE_RETCODE_PLACED:
return RET_SUCCESS;
// Transient / retryable states
case TRADE_RETCODE_REQUOTE:
case TRADE_RETCODE_PRICE_CHANGED:
case TRADE_RETCODE_PRICE_OFF:
case TRADE_RETCODE_TIMEOUT:
case TRADE_RETCODE_CONNECTION:
case TRADE_RETCODE_TOO_MANY_REQUESTS:
case TRADE_RETCODE_LOCKED:
case TRADE_RETCODE_FROZEN:
case TRADE_RETCODE_ERROR:
return RET_RETRYABLE;
// Permanent / fatal states (never retry blindly)
default:
return RET_PERMANENT;
}
}
//--- Human-readable description for common MQL5 return codes
static string RetcodeToString(const uint retcode)
{
switch(retcode)
{
case TRADE_RETCODE_REQUOTE: return "10004 Requote";
case TRADE_RETCODE_REJECT: return "10006 Request rejected";
case TRADE_RETCODE_CANCEL: return "10007 Request canceled";
case TRADE_RETCODE_PLACED: return "10008 Order placed";
case TRADE_RETCODE_DONE: return "10009 Request completed";
case TRADE_RETCODE_DONE_PARTIAL: return "10010 Partial execution";
case TRADE_RETCODE_ERROR: return "10011 Request processing error";
case TRADE_RETCODE_TIMEOUT: return "10012 Request timeout";
case TRADE_RETCODE_INVALID: return "10013 Invalid request";
case TRADE_RETCODE_INVALID_VOLUME: return "10014 Invalid volume";
case TRADE_RETCODE_INVALID_PRICE: return "10015 Invalid price";
case TRADE_RETCODE_INVALID_STOPS: return "10016 Invalid stops";
case TRADE_RETCODE_TRADE_DISABLED: return "10017 Trade disabled";
case TRADE_RETCODE_MARKET_CLOSED: return "10018 Market closed";
case TRADE_RETCODE_NO_MONEY: return "10019 Insufficient funds/margin";
case TRADE_RETCODE_PRICE_CHANGED: return "10020 Price changed";
case TRADE_RETCODE_PRICE_OFF: return "10021 No quotes available";
case TRADE_RETCODE_INVALID_EXPIRATION:return "10022 Invalid expiration";
case TRADE_RETCODE_TOO_MANY_REQUESTS: return "10024 Too many requests (throttled)";
case TRADE_RETCODE_SERVER_DISABLES_AT:return "10026 AutoTrading disabled by server";
case TRADE_RETCODE_CLIENT_DISABLES_AT:return "10027 AutoTrading disabled by terminal";
case TRADE_RETCODE_LOCKED: return "10028 Request locked for processing";
case TRADE_RETCODE_FROZEN: return "10029 Order/position frozen";
case TRADE_RETCODE_INVALID_FILL: return "10030 Unsupported filling mode";
case TRADE_RETCODE_CONNECTION: return "10031 No connection to trade server";
case TRADE_RETCODE_LIMIT_ORDERS: return "10033 Pending orders limit reached";
case TRADE_RETCODE_LIMIT_VOLUME: return "10034 Volume limit reached";
case TRADE_RETCODE_LIMIT_POSITIONS: return "10040 Open positions limit reached";
case TRADE_RETCODE_LONG_ONLY: return "10042 Only long positions allowed";
case TRADE_RETCODE_SHORT_ONLY: return "10043 Only short positions allowed";
case TRADE_RETCODE_CLOSE_ONLY: return "10044 Only close orders allowed";
default: return StringFormat("Retcode %u", retcode);
}
}
//--- Main safe market execution method
SExecReport ExecuteMarketOrder(const ENUM_ORDER_TYPE order_type,
const double raw_volume,
const int sl_pts,
const int tp_pts,
const string comment,
const bool force_invalid_sl = false)
{
SExecReport report;
report.success = false;
report.last_retcode = 0;
report.last_retcode_desc = "Not sent";
report.attempts_used = 0;
report.order_ticket = 0;
report.deal_ticket = 0;
report.executed_price = 0.0;
report.total_latency_ms = 0;
report.summary = "";
ulong t_start = GetTickCount64();
// 1. Validate environment & permissions
if(order_type != ORDER_TYPE_BUY && order_type != ORDER_TYPE_SELL)
{
report.summary = "Aborted: Only market BUY/SELL orders are supported.";
return report;
}
if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) || !MQLInfoInteger(MQL_TRADE_ALLOWED))
{
report.summary = "Aborted: Algorithmic trading is disabled in terminal/script settings.";
return report;
}
if(!AccountInfoInteger(ACCOUNT_TRADE_ALLOWED))
{
report.summary = "Aborted: Trading is disabled for this account.";
return report;
}
ENUM_SYMBOL_TRADE_MODE trade_mode = (ENUM_SYMBOL_TRADE_MODE)SymbolInfoInteger(m_symbol, SYMBOL_TRADE_MODE);
if(trade_mode == SYMBOL_TRADE_MODE_DISABLED || trade_mode == SYMBOL_TRADE_MODE_CLOSEONLY)
{
report.summary = "Aborted: Symbol trading is disabled or close-only.";
return report;
}
if(order_type == ORDER_TYPE_BUY && trade_mode == SYMBOL_TRADE_MODE_SHORTONLY)
{
report.summary = "Aborted: Symbol permits short positions only.";
return report;
}
if(order_type == ORDER_TYPE_SELL && trade_mode == SYMBOL_TRADE_MODE_LONGONLY)
{
report.summary = "Aborted: Symbol permits long positions only.";
return report;
}
double volume = NormalizeVolume(raw_volume);
if(volume <= 0.0)
{
report.summary = "Aborted: Could not normalize lot size for symbol.";
return report;
}
ENUM_ORDER_TYPE_FILLING filling_mode = ResolveFillingMode();
int digits = (int)SymbolInfoInteger(m_symbol, SYMBOL_DIGITS);
// 2. Retry loop with fresh quotes & duplicate check on every iteration
for(int attempt = 1; attempt <= m_max_retries; attempt++)
{
if(IsStopped())
{
report.summary = "Aborted: Execution stopped by user.";
break;
}
report.attempts_used = attempt;
// Ensure connection before sending or retrying
if(!WaitForConnection(3000))
{
report.last_retcode = TRADE_RETCODE_CONNECTION;
report.last_retcode_desc = RetcodeToString(TRADE_RETCODE_CONNECTION);
PrintFormat("[SafeExec] Attempt %d/%d: No server connection.", attempt, m_max_retries);
continue;
}
// Crucial duplicate guard: runs BEFORE attempt 1 AND BEFORE every retry
// (protects against duplicate fills when connection drops before confirmation)
if(m_prevent_duplicate && HasExistingExposure())
{
report.summary = StringFormat("Blocked duplicate: Existing position/order detected for %s (Magic %I64u) on attempt %d.",
m_symbol, m_magic, attempt);
PrintFormat("[SafeExec] %s", report.summary);
break;
}
// Always fetch fresh quotes on each attempt
MqlTick tick;
if(!SymbolInfoTick(m_symbol, tick) || tick.ask <= 0.0 || tick.bid <= 0.0)
{
PrintFormat("[SafeExec] Attempt %d/%d: Failed to fetch fresh tick.", attempt, m_max_retries);
Sleep(m_base_delay_ms);
continue;
}
double sl = 0.0, tp = 0.0;
string stop_err = "";
if(!BuildStops(order_type, tick, sl_pts, tp_pts, force_invalid_sl, sl, tp, stop_err))
{
report.last_retcode = TRADE_RETCODE_INVALID_STOPS;
report.last_retcode_desc = RetcodeToString(TRADE_RETCODE_INVALID_STOPS);
report.summary = "Aborted pre-send: " + stop_err;
PrintFormat("[SafeExec] %s", report.summary);
break;
}
MqlTradeRequest req;
MqlTradeResult res;
MqlTradeCheckResult check;
ZeroMemory(req);
ZeroMemory(res);
ZeroMemory(check);
req.action = TRADE_ACTION_DEAL;
req.symbol = m_symbol;
req.volume = volume;
req.type = order_type;
req.price = NormalizeDouble((order_type == ORDER_TYPE_BUY) ? tick.ask : tick.bid, digits);
req.sl = sl;
req.tp = tp;
req.deviation = m_deviation;
req.magic = m_magic;
req.comment = comment;
req.type_filling = filling_mode;
// 3. Pre-flight check via OrderCheck (catches margin/stop/market-closed issues locally)
if(!OrderCheck(req, check))
{
report.last_retcode = check.retcode;
report.last_retcode_desc = RetcodeToString(check.retcode);
if(ClassifyRetcode(check.retcode) == RET_PERMANENT)
{
report.summary = StringFormat("Permanent error caught by OrderCheck: %s (Free margin: %.2f). Stopping retries.",
report.last_retcode_desc, check.margin_free);
PrintFormat("[SafeExec] %s", report.summary);
break;
}
PrintFormat("[SafeExec] Attempt %d/%d: Transient OrderCheck warning: %s",
attempt, m_max_retries, report.last_retcode_desc);
}
// 4. Send order to trade server
ResetLastError();
bool sent = OrderSend(req, res);
report.last_retcode = res.retcode;
report.last_retcode_desc = RetcodeToString(res.retcode);
ENUM_RETCODE_CLASS ret_class = ClassifyRetcode(res.retcode);
if(sent && ret_class == RET_SUCCESS)
{
report.success = true;
report.order_ticket = res.order;
report.deal_ticket = res.deal;
report.executed_price = res.price;
report.summary = StringFormat("SUCCESS (%s) | Order #%I64u | Deal #%I64u | Price: %.*f | Attempts: %d",
report.last_retcode_desc, res.order, res.deal, digits, res.price, attempt);
PrintFormat("[SafeExec] %s", report.summary);
break;
}
if(ret_class == RET_PERMANENT)
{
report.summary = StringFormat("PERMANENT ERROR on attempt %d: %s (LastError=%d). Aborted without further retries.",
attempt, report.last_retcode_desc, GetLastError());
PrintFormat("[SafeExec] %s", report.summary);
break;
}
// Retryable error: apply exponential backoff (extra pause if rate-limited)
int backoff_ms = m_base_delay_ms * (1 << (attempt - 1));
if(res.retcode == TRADE_RETCODE_TOO_MANY_REQUESTS)
backoff_ms = MathMax(backoff_ms, 1000);
if(backoff_ms > 4000)
backoff_ms = 4000;
PrintFormat("[SafeExec] Attempt %d/%d transient failure: %s | Retrying in %d ms...",
attempt, m_max_retries, report.last_retcode_desc, backoff_ms);
if(attempt < m_max_retries)
Sleep(backoff_ms);
else
report.summary = StringFormat("FAILED after %d/%d retries. Last server response: %s",
attempt, m_max_retries, report.last_retcode_desc);
}
report.total_latency_ms = GetTickCount64() - t_start;
return report;
}
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
// Safety guard against accidental execution on live accounts
if(InpDemoAccountOnly && AccountInfoInteger(ACCOUNT_TRADE_MODE) == ACCOUNT_TRADE_MODE_REAL)
{
string msg = "SafeOrderExecutor: Blocked on REAL account (set InpDemoAccountOnly=false to override).";
Print(msg);
Comment(msg);
return;
}
ENUM_ORDER_TYPE order_type = (InpDirection == EXEC_BUY) ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;
bool force_invalid = (InpMode == MODE_TEST_INVALID_STOPS);
CSafeOrderExecutor executor(_Symbol,
InpMagicNumber,
InpDeviationPts,
InpMaxRetries,
InpBaseDelayMs,
InpPreventDuplicate,
InpAutoAdjustStops);
PrintFormat("=== SafeOrderExecutor v1.00 | Symbol: %s | Mode: %s | Magic: %I64u ===",
_Symbol,
force_invalid ? "TEST_INVALID_STOPS" : "NORMAL_EXECUTION",
InpMagicNumber);
SExecReport rep = executor.ExecuteMarketOrder(order_type,
InpVolume,
InpStopLossPts,
InpTakeProfitPts,
InpComment,
force_invalid);
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
string panel = StringFormat(
"=== SafeOrderExecutor v1.00 ===\n"
"Symbol: %s | Magic: %I64u\n"
"Mode: %s\n"
"Status: %s\n"
"Retcode: %s\n"
"Attempts: %d/%d | Latency: %I64u ms\n"
"Order: #%I64u | Price: %.*f\n"
"Note: %s",
_Symbol, InpMagicNumber,
force_invalid ? "Deliberate Invalid SL Test" : "Safe Market Execution",
rep.success ? "EXECUTED" : "ABORTED / BLOCKED",
rep.last_retcode_desc,
rep.attempts_used, InpMaxRetries, rep.total_latency_ms,
rep.order_ticket, digits, rep.executed_price,
rep.summary
);
Comment(panel);
PrintFormat("[SafeExec] Total execution time: %I64u ms", rep.total_latency_ms);
}
//+------------------------------------------------------------------+Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.