how to automate process of rebooting MT4

 

I just had an issue with several open live positions in my IBFX MT4 account where after many attempts over several minutes I was unable to modify the SL and TP of several open positions. I consistently received the "Trade Context Is Busy" error. The only way out of this was to reboot MT4 after which I was immediately able to modify the orders. I spoke with a rep. at IBFX who recommended rebooting MT4 once a day as this is a general problem with MT4.

I'm in the process of building an EA for unattended automated trading and now I'm concerned.

Is their a Windows program/routine all of you use to automatically restart MT4 each day?

How do you wrestle with this issue to achieve 100% unattended operation?

 
I have that problem too . . . hopefully someone will have an answer

 

Windows Scheduled Task might help.

 

modify the EA to use one of the reliable order libraries such as libOderReliable.mqh [sp?] or common_functions.mqh to avoid the "trade context busy" problem in the first place instead of trying to find a cure for the symptoms. MT4 can run an entire week while making dozens of trades per day from multiple EAs without any need for a reboot.

 
7bit:

modify the EA to use one of the reliable order libraries such as libOderReliable.mqh [sp?] or common_functions.mqh to avoid the "trade context busy" problem in the first place instead of trying to find a cure for the symptoms. MT4 can run an entire week while making dozens of trades per day from multiple EAs without any need for a reboot.



As I mentioned, I get the error even with manual trading. So, EAs and their code have nothing to do with causing or preventing the problem. And, running an entire week without rebooting is nothing really to brag about. I mean, this platform is "sold" as a viable/robust solution for automated trading. Having to manually reboot every x days just doesn't cut it in my book. Does anyone know it MT5 is plagued with similar problems?
 
billworld:

As I mentioned, I get the error even with manual trading. So, EAs and their code have nothing to do with causing or preventing the problem. And, running an entire week without rebooting is nothing really to brag about. I mean, this platform is "sold" as a viable/robust solution for automated trading. Having to manually reboot every x days just doesn't cut it in my book. Does anyone know it MT5 is plagued with similar problems?

Well I see I didn't explicity mention "manual" trading in my original post, but, that's what I meant.
 
ubzen:

Windows Scheduled Task might help.


The Windows Task Scheduler has an action to "Start A Program" but not "Quit A Program".

Any other ideas?

 
billworld:


The Windows Task Scheduler has an action to "Start A Program" but not "Quit A Program".

Any other ideas?


Did you try it? I'm on windows Xp and when I had issues reconnecting automatically using a particular broker, that was the method I implemented. I've since done restoring my computer and I'm not gonna create a user profile to prove or dis-prove that. I'm pretty sure, it allowed me to specify the duration the task would have ran. Example: Start@ 12:01 Am ---> (Duration=24hrs) ---> End@11:59pm. Around that same time period, I looked at autohotkey pretty slick macro creator that, you can start and close anything and create .exe files. Anyways, I can't help but say, the major source of your problem is likely the Broker or your Net-Service. Since moving to another broker, I never had that problem....ever and stopped using the hot fixes above. btw: 100% unattended operation - Nothing's that stable IMO.

 

What does the MT4 progam update do and how can a programmer do it?

 
billworld:


The Windows Task Scheduler has an action to "Start A Program" but not "Quit A Program".

Any other ideas?

Be creative. Use it so start "taskkill /im teminal.exe" and then start terminal.exe again. Or use it to start a script (or a batch file) that does these two steps.
 
  1. 7bit:
    Be creative. Use it so start "taskkill /im teminal.exe" and then start terminal.exe again. Or use it to start a script (or a batch file) that does these two steps.
    Exactly. I would have the EA periodically write a file to say it's alive. and have a scheduled (or always running) batch file check if the file exists and delete or if not exists, kill and restart. (handling the week end/holidays would be a problem.)
  2. I consistently received the "Trade Context Is Busy" error.
    Your EA's should use a semaphore to prevent these.
            if (GetTradeContext() < TC_LOCKED){
                                            CallAgain(Bid); break;  }
            oo.ticket = OrderSend(  Symbol(),   op.code,    size,
                    now.open,       Slippage.Pips*pips2points,
                    NO_SL,          NO_TP,          order.comment,
                    magic.number,   NO_EXPIRATION,  op.color);
            if (oo.ticket < 0){     Alert( "OrderSend(type=",   op.code,
                " (",   op.text,    "), lots=", size,
                ", price=", PriceToStr(now.open),
                " (", DeltaToPips(now.open-Bid),
                "), SL=0, TP=0, '", order.comment, "', ...) failed: ",
                                                    GetLastError() );
                RelTradeContext();      // After GetLastError
                if(!IsTradeAllowed()) Alert("Trading NOT allowed!");
                EA.status="OrderSend Failed"; return; }
            RelTradeContext();          // After GetLastError
    ...
    //+------------------------------------------------------------------+
    //| Trade context semaphore.                                         |
    //+------------------------------------------------------------------+
    void    RelTradeContext(){         // Set global variable for GetTradeContext = 0.
    /*bool  need2refresh;           // Export=T to GetTradeContext=R|T|F,
                                    // SetDIR=R|F, start=F, ModifyStops=R|F */
        need2refresh = true;        // Assume caller did a OrderSend/Modify/Close.
        while( !(IsTesting() || IsStopped()) ){
            GlobalVariableSet(TC.GV.Name, 0.0); // Unlock the trade context.
            int _GetLastError = GetLastError();
            if (_GetLastError == 0) break;
            Comment("RelTradeContext: GlobalVariableSet('",
                    TC.GV.Name,"',0.0)-Error #", _GetLastError );   Sleep(1000);
        }
    }   // void RelTradeContext()
    int  Random(int min, int max){  return( MathRand()/32768.0*(max-min+1)+min );  }
    #define ERR_146_MIN_WAIT_MSEC    1000   // Trade context busy random delay min
    #define ERR_146_MAX_WAIT_MSEC    5000   // Trade context busy random delay max
    void RandomSleep(){ Sleep(Random(ERR_146_MIN_WAIT_MSEC,ERR_146_MAX_WAIT_MSEC));}
    #define ERR_146_TIMEOUT_MSEC    60000   // Trade context busy maximum delay
    #include <stderror.mqh>                 // ERR_GLOBAL_VARIABLE_NOT_FOUND
    int     GetTradeContext(int maxWaitMsec = ERR_146_TIMEOUT_MSEC){
    //  bool    need2refresh;               // Import from RelTradeContext
        /*Return codes:*/{
            #define TC_LOCKED        0  //  Success. The global variable TC.GV.Name
        //                                  was set to 1, locking out others.
            #define TC_REFRESH      +1  //  Success. The trade context was initially
        //                                  busy, but became free. The market info
        //                                  needed to be refreshed. Recompute trade
        //                                  values if necessary.
            #define TC_ERROR        -1  //  Error, interrupted by the user. The
        //                                  expert was removed from the chart, the
        //                                  terminal was closed, the chart period
        //                                  and/or symbol was changed, etc.)
            #define TC_TIMEOUT      -2  //  Error, the wait limit was exceeded.
        /*************************************************************************/}
        if ( IsTesting() ){                     // Only one EA runs under the tester
            if (need2refresh)   Refresh();
            return(TC_LOCKED);                  // Context always available.
        }
        /* If there is no global variable, create it. If the variable == 1 wait
         * until another thread sets it back to 0. Set it to 1. */
        int     startWaitingTime    = GetTickCount(),   // Remember start time.
                GTCreturn           = TC_LOCKED;        // Assume an idle context.
        bool    TC_locked           = false;            // Not yet.
        while(true){
            if ( IsStopped() ){     // The expert was terminated by the user, abort.
                Print("GTC: The expert was terminated by the user!");
                if (TC_locked)  RelTradeContext();
                return(TC_ERROR);
            }
            if (!TC_locked) {                           // Set the semaphore.
                if (GlobalVariableSetOnCondition( TC.GV.Name, 1.0, 0.0 )){
                    TC_locked=true;                     // Semaphore now set.
                    continue;                           // Check for non-sema EAs.
                }
                int _GetLastError   = GetLastError();   switch(_GetLastError){
                case 0:                             // Variable exists but is
                    break;                          // already set. Need to wait.
                case ERR_GLOBAL_VARIABLE_NOT_FOUND:
                    GlobalVariableSet(TC.GV.Name, 0.0); // Create it.
                    _GetLastError   = GetLastError();
                    if (_GetLastError == 0) continue;
                    Print(  "GetTradeContext: GlobalVariableSet(", TC.GV.Name,
                                ", 0.0) Failed: ",  _GetLastError );    // Error
                    return(TC_ERROR);
                default:
                    Print(  "GetTradeContext:GlobalVariableSetOnCondition('",
                            TC.GV.Name, "',1.0,0.0)-Error #", _GetLastError);
                    break;                      // Exit switch, wait and retry.
                }   // switch(_GetLastError)
            }   // Set the semaphore.
            else if (!IsTradeContextBusy()){            // Cleanup and return.
                if (GTCreturn == TC_REFRESH){           // Clear the Wait comment
                    Comment(WindowExpertName(),": ", VERSION);
                    need2refresh=true;
                }
                if (need2refresh)   Refresh();
                return(GTCreturn);
            }
            int delay = GetTickCount() - startWaitingTime ;
            if (delay > maxWaitMsec){                   // Abort.
                Print("Waiting time (", maxWaitMsec/1000, " sec) exceeded!");
                if (TC_locked)  RelTradeContext();
                return(TC_TIMEOUT);
            }
            Comment("Wait until another expert finishes trading... ", delay/1000.);
            RandomSleep();
            GTCreturn = TC_REFRESH;                     // Will need to refresh.
        }   // while
        /*NOTREACHED*/
    }   // GetTradeContext
    

Reason: