deinit() can't terminate the program ?

 
I wrote the following code:

//--------------------------------------------------------

int init()
  {
   return(0);
  }
int deinit()
  {
   return(0);
  }
  
  
  
int start()
  {
  
  Alert("deinit() called ! EA terminated in few seconds");
  sleep(5000);
  deinit();
   
  }

//--------------------------------------------------------

I ran it, but it didn't terminate at all !

Why deinit() function can't terminated the EA program ?
 
sonthanhthuytu:
Why deinit() function can't terminated the EA program ?

That is not its function and you are not supposed to call deinit, the system does.

An EA cannot terminate itself without nasty hacks using PostMessage windows calls.

It is easy and safe to put an abort flag test as the first line of the start function so that when you no longer want the EA to run it does minimal activity.

 
// Using any sort of PostMessage is a HACK and not recommended, but for otherwise unsupported functionality it can
// be useful. Just check it on your operating system and your MT4 version before committing to it - at your own risk.


//================================================================== THIS is the relevant code to post into your EA
#include <WinUser32.mqh>
#include <stdlib.mqh>


bool abort=false;

#define EA_KILL  33050

void SelfDestruct(){
   abort=true;       // don't put all our eggs in one basket; leave the known, trusted abort code in place as well!
   Print("Self-destruct initiated");

   // We send the message to this Window and let this window send it to its Parent
   // then the parent knows which Window it came from and therefore what to do
   int hWnd     = WindowHandle( Symbol(),0 );   
   
   PostMessageA( hWnd, WM_COMMAND, EA_KILL, 0 );
   return;
}
//=================================================================== THE stuff below is just a test harness

int  count = 0;
bool timeToDie = false;

//----------------------------------------------------------------------------
int init(){
   if( abort )
      return( 0 );
   
   // do some useful stuff here   
   count=0;   
   return(0);
}

//-----------------------------------------------------------------------------
int deinit(){

   return(0);
}

//------------------------------------------------------------------------------
int start(){
   if( abort )
      return( 0 );
   
   // do some useful stuff in here
   
   count++;
   if( count > 9 )     // we have to decide to self-destruct. This particular test is obviously just for testing
      timeToDie = true;
   
   Print(count);
      
   if( timeToDie ){
      SelfDestruct();
      return( 0 );
   }   

   return(0);
}
//------------------------------------------------------------------------------

from

https://www.mql5.com/en/forum/137428

keywords: SELF-DESTRUCT, SELF-TERMINATE, KILL EA

Reason: