MQL5 — Guaranteed Timeout and Cancellation of Blocking File Operations
@Maher Al-mashharawi, there is no such official guaranteed timeout. You have to write some custom code. I prompted this to the MQL5 AI Assistant:
Why a wrapper is needed
FileClose() in MQL5 is declared as void FileClose(int file_handle) — it has no return value and no timeout parameter. So a "custom timeout" is really a bounded retry/poll wrapper that:
- flushes buffered data,
- calls FileClose() ,
- verifies the handle actually became invalid ( FileGetInteger(handle, FILE_SIZE) → -1 with ERR_INVALID_HANDLE ),
- gives up after timeout_ms and tells the caller.
Snippet (drop-in, EA context)
//+------------------------------------------------------------------+ //| Sample: bounded FileClose() with a return status for an EA | //| No file is edited by this sample - it is illustrative code only. | //+------------------------------------------------------------------+ #define FILE_CLOSE_RETRY_PAUSE_MS 10 // poll interval between attempts // Status codes returned by the wrapper (EA-visible result) enum ENUM_FILE_CLOSE_RESULT { FILE_CLOSE_OK = 0, // handle released FILE_CLOSE_TIMEOUT = 1, // handle still open after timeout_ms FILE_CLOSE_BAD_HANDLE= 2 // INVALID_HANDLE passed in }; //+------------------------------------------------------------------+ //| True while the handle still points to an open file. | //| FileClose() is void, so validity is checked through the handle. | //+------------------------------------------------------------------+ bool IsFileHandleOpen(const int file_handle) { if(file_handle == INVALID_HANDLE) return(false); ResetLastError(); const long size = FileGetInteger(file_handle, FILE_SIZE); // A released handle yields -1 with ERR_INVALID_HANDLE (5002). if(size < 0 && GetLastError() == ERR_INVALID_HANDLE) return(false); return(true); } //+------------------------------------------------------------------+ //| FileCloseTimeout: flush, close, then wait up to timeout_ms for | //| the handle to be released. Always returns a result to the EA. | //+------------------------------------------------------------------+ ENUM_FILE_CLOSE_RESULT FileCloseTimeout(const int file_handle, const uint timeout_ms = 5000) { if(file_handle == INVALID_HANDLE) return(FILE_CLOSE_BAD_HANDLE); if(!IsFileHandleOpen(file_handle)) return(FILE_CLOSE_OK); // already closed: nothing to do FileFlush(file_handle); // push buffered rows to disk first const uint started = GetTickCount(); // ms since program start while(true) { FileClose(file_handle); // void -> verify below if(!IsFileHandleOpen(file_handle)) return(FILE_CLOSE_OK); // released in time if(GetTickCount() - started >= timeout_ms) { PrintFormat("FileCloseTimeout: handle %d still open after %u ms (err=%d)", file_handle, timeout_ms, GetLastError()); return(FILE_CLOSE_TIMEOUT); // caller decides what to do } Sleep(FILE_CLOSE_RETRY_PAUSE_MS); // bounded, small block } } //+------------------------------------------------------------------+ //| EA state | //+------------------------------------------------------------------+ int g_log_handle = INVALID_HANDLE; // trade/log CSV handle //+------------------------------------------------------------------+ int OnInit() { g_log_handle = FileOpen("ea_trades.csv", FILE_WRITE | FILE_CSV | FILE_ANSI, ','); if(g_log_handle == INVALID_HANDLE) { PrintFormat("OnInit: FileOpen failed, err=%d", GetLastError()); return(INIT_FAILED); // early return: do not trade } FileWrite(g_log_handle, "time", "symbol", "side", "volume", "price"); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ void OnTick() { // Guard-style return: never write into a handle that is not open. if(g_log_handle == INVALID_HANDLE) { Print("OnTick: log handle is not open, tick skipped"); return; } // ... signal + execution logic here ... } //+------------------------------------------------------------------+ void OnDeinit(const int reason) { if(g_log_handle == INVALID_HANDLE) return; // nothing to release const ENUM_FILE_CLOSE_RESULT res = FileCloseTimeout(g_log_handle, 3000); if(res == FILE_CLOSE_TIMEOUT) PrintFormat("OnDeinit: file not released within timeout, reason=%d", reason); else if(res == FILE_CLOSE_BAD_HANDLE) Print("OnDeinit: invalid handle state, nothing to close"); g_log_handle = INVALID_HANDLE; // invalidate regardless }Optional: pure bool variant
If you prefer a single boolean return instead of an enum:
bool FileCloseTimeoutBool(const int file_handle, const uint timeout_ms = 5000) { return(FileCloseTimeout(file_handle, timeout_ms) == FILE_CLOSE_OK); }Notes and caveats
- No async I/O in MQL5. Terminal file access is a synchronous sandboxed API; there is no OS-level close callback. The "timeout" therefore bounds a retry/poll loop, it cannot cancel a stuck kernel operation.
- Sleep() context. Sleep() is allowed in EAs and scripts, but is not allowed in indicators. The wrapper above is EA/script-only.
- Verification method. Because FileClose() returns void , success is inferred from the handle state ( FileGetInteger(handle, FILE_SIZE) + ERR_INVALID_HANDLE ). If you prefer no polling at all, the minimal alternative is FileFlush(handle) (which does return bool ) followed by an unconditional FileClose(handle) and a true return.
- Strategy Tester. In the tester GetTickCount() and Sleep() behave differently from live trading (delay emulation, non-visual mode), so a timeout branch may trigger far less often — do not tune thresholds on backtest timings alone.
- This is illustrative logic only; it has not been compiled or backtested here, and passing compilation does not imply correct trading behavior. If you want, I can place it in MQL5\Experts\... and run compile_file to confirm 0 errors / 0 warnings.
@Maher Al-mashharawi, there is no such official guaranteed timeout. You have to write some custom code. I prompted this to the MQL5 AI Assistant:
Why a wrapper is needed
FileClose() in MQL5 is declared as void FileClose(int file_handle) — it has no return value and no timeout parameter. So a "custom timeout" is really a bounded retry/poll wrapper that:
- flushes buffered data,
- calls FileClose() ,
- verifies the handle actually became invalid ( FileGetInteger(handle, FILE_SIZE) → -1 with ERR_INVALID_HANDLE ),
- gives up after timeout_ms and tells the caller.
Snippet (drop-in, EA context)
Optional: pure bool variant
If you prefer a single boolean return instead of an enum:
Notes and caveats
- No async I/O in MQL5. Terminal file access is a synchronous sandboxed API; there is no OS-level close callback. The "timeout" therefore bounds a retry/poll loop, it cannot cancel a stuck kernel operation.
- Sleep() context. Sleep() is allowed in EAs and scripts, but is not allowed in indicators. The wrapper above is EA/script-only.
- Verification method. Because FileClose() returns void , success is inferred from the handle state ( FileGetInteger(handle, FILE_SIZE) + ERR_INVALID_HANDLE ). If you prefer no polling at all, the minimal alternative is FileFlush(handle) (which does return bool ) followed by an unconditional FileClose(handle) and a true return.
- Strategy Tester. In the tester GetTickCount() and Sleep() behave differently from live trading (delay emulation, non-visual mode), so a timeout branch may trigger far less often — do not tune thresholds on backtest timings alone.
- This is illustrative logic only; it has not been compiled or backtested here, and passing compilation does not imply correct trading behavior. If you want, I can place it in MQL5\Experts\... and run compile_file to confirm 0 errors / 0 warnings.
Hi Ryan,
Thank you for taking the time to respond and share the example.
Our main concern is a file operation that never returns control to the caller, rather than a retry loop that takes too long.
If FileFlush() or FileClose() itself blocks, the proposed wrapper cannot check the timeout until that function returns. So it does not appear to enforce a strict wall-clock deadline.
I also noticed a few details in the official MQL5 documentation:
-
FileFlush() returns void, not bool.
-
ERR_INVALID_FILEHANDLE is 5007; error 5002 refers to an invalid filename.
-
OnDeinit() has a documented execution limit of 2.5 seconds.
My key question is:
Is there any officially documented mechanism that can enforce a 14,400-second deadline even when an MQL5 file operation has not returned, while also preventing partial output from being treated as a successful result?
If not, would it be correct to say that this guarantee cannot be established using the proposed synchronous wrapper alone?
Any official MetaQuotes documentation or developer clarification would be greatly appreciated.
Thank you again!
Is there any officially documented mechanism that can enforce a 14,400-second deadline even when an MQL5 file operation has not returned, while also preventing partial output from being treated as a successful result?
Forum on trading, automated trading systems and testing trading strategies
MQL5 — Guaranteed Timeout and Cancellation of Blocking File Operations
Ryan L Johnson, 2026.10.11 16:20
[T]here is no such official guaranteed timeout.
If not, would it be correct to say that this guarantee cannot be established using the proposed synchronous wrapper alone?
Yes.
Forum on trading, automated trading systems and testing trading strategies
MQL5 — Guaranteed Timeout and Cancellation of Blocking File Operations
Ryan L Johnson, 2026.10.11 16:20
- No async I/O in MQL5. Terminal file access is a synchronous sandboxed API; there is no OS-level close callback. The "timeout" therefore bounds a retry/poll loop, it cannot cancel a stuck kernel operation.
Hi Ryan,
Thank you for taking the time to respond and share the example.
Our main concern is a file operation that never returns control to the caller, rather than a retry loop that takes too long.
If FileFlush() or FileClose() itself blocks, the proposed wrapper cannot check the timeout until that function returns. So it does not appear to enforce a strict wall-clock deadline.
I also noticed a few details in the official MQL5 documentation:
-
FileFlush() returns void, not bool.
-
ERR_INVALID_FILEHANDLE is 5007; error 5002 refers to an invalid filename.
-
OnDeinit() has a documented execution limit of 2.5 seconds.
My key question is:
Is there any officially documented mechanism that can enforce a 14,400-second deadline even when an MQL5 file operation has not returned, while also preventing partial output from being treated as a successful result?
If not, would it be correct to say that this guarantee cannot be established using the proposed synchronous wrapper alone?
Any official MetaQuotes documentation or developer clarification would be greatly appreciated.
Thank you again!
That seems an XY problem. The real issue is most probably : how do you come to "block" file operations with MQL5 ? Check your MQL5 code, don't try to impose a solution by "force".
That seems an XY problem. The real issue is most probably : how do you come to "block" file operations with MQL5 ? Check your MQL5 code, don't try to impose a solution by "force".
Hi Alain,
Thank you for your feedback. I understand your point about this potentially being an XY problem.
To clarify, we are not claiming that we have conclusively identified an MQL5 file operation that blocks indefinitely. We are investigating a strict worst-case requirement for a long-running data-processing operation.
The requirement is to enforce a 14,400-second wall-clock deadline, including the case where an individual synchronous file API call has not returned control to the caller.
We agree that examining our MQL5 code and identifying the actual causes of observed stalls is important, and we are treating that as a separate investigation.
However, my question is specifically about the platform's documented guarantees:
If an MQL5 file operation does not return, is there any officially supported mechanism that guarantees the running operation can be interrupted or otherwise brought to a safe conclusion before the deadline?
Or should we conclude that such a guarantee has not been established by the documented synchronous MQL5 APIs alone?
I am not asking for a forced workaround, only for clarification of the platform's supported behavior and limits.
Thank you again for your guidance.
Hi Alain,
Thank you for your feedback. I understand your point about this potentially being an XY problem.
To clarify, we are not claiming that we have conclusively identified an MQL5 file operation that blocks indefinitely. We are investigating a strict worst-case requirement for a long-running data-processing operation.
The requirement is to enforce a 14,400-second wall-clock deadline, including the case where an individual synchronous file API call has not returned control to the caller.
We agree that examining our MQL5 code and identifying the actual causes of observed stalls is important, and we are treating that as a separate investigation.
However, my question is specifically about the platform's documented guarantees:
If an MQL5 file operation does not return, is there any officially supported mechanism that guarantees the running operation can be interrupted or otherwise brought to a safe conclusion before the deadline?
Or should we conclude that such a guarantee has not been established by the documented synchronous MQL5 APIs alone?
I am not asking for a forced workaround, only for clarification of the platform's supported behavior and limits.
Thank you again for your guidance.
Obviously there is no such "officially supported mechanism".
Only real and practical usage can lead to real and practical solution.
Hello MetaQuotes Support,
We need to determine whether an MQL5 Expert Advisor can enforce a strict 14,400-second wall-clock deadline when an in-progress file operation does not return.
Could you please clarify:
Are FileOpen, FileWriteString, FileFlush, FileClose, FileMove, FileCopy, FileReadArray, FileReadString, and FileIsEnding guaranteed to return within a documented maximum duration?
Can an MQL5 file operation that has not returned be interrupted or cancelled safely?
Does the documented forced completion after a stop command guarantee that the blocked call returns to its caller? What guarantees exist regarding partially written files?
Is there an officially supported mechanism for enforcing a strict deadline in this situation?
Please provide official documentation references where available.
Thank you.