MQL4 error diagnosis

MQL4 exit with error: stop work and clean up safely

For an MQL4 exit with error, record the failure where it occurs, return from the current handler, and let OnDeinit release resources when the terminal actually unloads or reinitializes the program. OnDeinit receives a reason code, but it is not a general exception handler and should not start new trades.

Open the Coding Agent, then choose MQL4 from the language menu.

SafeDeinitialization.mq4.mq4
#property strict

int OnInit()
  {
   Print("EA initialized.");
   return(INIT_SUCCEEDED);
  }

void OnDeinit(const int reason)
  {
   Print("EA deinitialized. reason=", reason,
         " last_error=", GetLastError());

   // Release files, timers, objects, and other owned resources here.
   // Do not start a new trade while the program is being removed.
  }

void OnTick()
  {
   if(Bars < 2)
      return;
  }
  • Log the original failure first
  • Return from the current handler
  • Use OnDeinit for owned resources
  • Do not open trades during shutdown

A function return is not program removal

Returning from OnTick, OnTimer, or a helper stops the current path only. The EA remains attached and can receive later events. Use a disabled state flag when a critical failure should block future work without removing the program.

Initialization can return INIT_FAILED when required inputs or resources are unavailable. That communicates failure through the documented lifecycle.

OnDeinit explains why the program is leaving

The terminal calls OnDeinit before reinitialization or unloading and supplies a reason such as chart change, input change, account change, template application, removal, or terminal close.

Keep the original runtime error in its own log. The deinitialization reason describes lifecycle state and is not a replacement for the earlier GetLastError value.

Cleanup only what the program owns

Kill timers, close valid file handles, release resources, and delete only objects created under the program’s own prefix. Cleanup should be idempotent because partial initialization is possible.

  • Track whether each resource was acquired
  • Allow cleanup to run after partial initialization
  • Do not wait in long loops during shutdown
  • Do not submit a new order from OnDeinit

Review the complete example

The EA has documented OnInit, OnTick, and OnDeinit signatures. OnDeinit records its reason and is reserved for resource cleanup, not recovery trading.

Shutdown paths should not change account exposure unexpectedly. Test lifecycle events on a demo setup and keep position management outside OnDeinit.

SafeDeinitialization.mq4.mq4
#property strict

int OnInit()
  {
   Print("EA initialized.");
   return(INIT_SUCCEEDED);
  }

void OnDeinit(const int reason)
  {
   Print("EA deinitialized. reason=", reason,
         " last_error=", GetLastError());

   // Release files, timers, objects, and other owned resources here.
   // Do not start a new trade while the program is being removed.
  }

void OnTick()
  {
   if(Bars < 2)
      return;
  }
Where Pineify fits

Move from the rule to editable MQL4 source

Pineify can generate or revise one self-contained .mq4 file with MQL4-specific reference context. Its independent static checker returns MetaEditor diagnostics so you can repair source issues before testing in your own MT4 environment.

Open MQL4 Coding Agent

Static diagnostics do not prove runtime behavior, backtest results, broker compatibility, or live-trading safety.

Pineify MQL4 Coding Agent with MQL4 selected and an editable MetaTrader 4 code artifact

A practical workflow

  1. 1

    Record the first failure

    Log the failed API, return, immediate error, and relevant state where it occurred.

  2. 2

    Stop the current operation

    Return or switch to a disabled state so later code cannot use invalid resources.

  3. 3

    Release owned resources

    Use OnDeinit for timers, handles, objects, and other lifecycle cleanup.

  4. 4

    Test each exit path

    Exercise removal, chart changes, input changes, failed initialization, and terminal shutdown.

Frequently asked questions

How do I exit an MQL4 EA with an error?

Log the failure and return from the current handler. Use INIT_FAILED for an initialization failure or a disabled state for a critical runtime condition.

Does return from OnTick unload the EA?

No. It ends only the current OnTick call. The EA can receive later events while it remains attached.

Is OnDeinit called after every runtime error?

Not as a general exception handler. It is called for program uninitialization or reinitialization events defined by the terminal.

Should OnDeinit close trades?

Do not start new trade work during shutdown. Any position-exit policy belongs in normal, testable trade-management logic with explicit risk rules.

What should cleanup code log?

Log the deinitialization reason and cleanup result separately from the original operation error.

Last verified against the linked official references on . Compile and test the final source in the MetaTrader 4 build, broker, symbol, and account environment you plan to use.

Continue with one reviewable MQL4 file

Define the requirement, inspect the generated source, repair diagnostics, and test the behavior in your own MT4 environment.

Open Coding Agent