MQL Program unexpectedly terminated - mql4

I'm new to MQL language, so please correct me if I described something wrong.
I made an script by the script editor to place orders automatically. The program should be never stopped unless by manually termination. My code looks like that:
void onStart()
{
While(true)
{
Sleep(10000);
MakeOrder(....);//of course actual code is much more complicated
}
}
The only preset functions I use are trade functions, math functions and time functions.
The code works well for most of the times that can continue running at least for 48 hours, but sometimes it might unexpectedly stopped reporting deinit reason 4(which is the same exit code if I click stop button when debugging) within one hour after starting. It looks that MQL doesn't have try...catch module, and getting error in some coding lines won't stop it. I wonder what might have happened behind the termination? Or how can I ignore it, so at least the program can automatically restart?

You should check the OnTimer and OnTick functions.
And recommended to use IsStopped() in the While loop.
void onStart()
{
while(!IsStopped())
{
Sleep(10000);
MakeOrder(....);//of course actual code is much more complicated
}
}

Uninitialization Reason 4 is : chart has been closed. In MT4, you always need to run a script on a chart (window), so of course if this chart is close for any reason, your script will terminate. There is nothing you can do to prevent that.
As suggested, adding IsStopped() will terminate your loop (and script), so what you can do is to add some code after your loop to notify you the script is being terminated.
For example :
void OnStart()
{
//---
while(!IsStopped())
{
Sleep(10000);
//MakeOrder(....);//of course actual code is much more complicated
}
//---
if(UninitializeReason()==REASON_CHARTCLOSE)
{
string msg="Chart is closed and the script is terminated.";
Alert(msg);
SendNotification(msg);
}
}

Related

AccountInfo() and SymbolInfo() return 0 on MT4 startup

When I attach a custom indicator to a chart, close MT4 and reopen it, the indicator initialises normally but every instance of AccountInfo() or SymbolInfo() in the first run of start() returns 0.0, causing several functions to throw a 'zero divide' error. When I reinitialise the indicator (without closing MT4), AccountInfo() and SymbolInfo() return the values they usually do.
If I comment out all functions that are dependent on these two, the indicator initialises without throwing errors after restarting MT4.
Has anybody had a similar issue?
To clarify: the problem only arises when I attach the indicator to the chart, close MT4 and reopen it again; when I attach it when MT4 is already open, AccountInfo() and SymbolInfo() return normal values.
Additional information:
using #property strict
using start() instead of OnCalculate() (so I can run the main function manually without waiting for a new tick)
the requested account or symbol property has no influence on the problem
It happens quite often that some data is not available in MT4 at some moment of time. The best thing you can do is to check whether the result is accepted (>0 if you call time, quotes, other data that cannot be zero) or to check the last error, then Sleep(50) and try again. Most likely 2-5th attempt is successful so you need that in a loop.
It is possible that you need to know at least Account Number that cannot be zero. After you receive succesful result, all other data seems to loaded correctly.
int OnInit()
{
if(!initializeAccountInfo())
return(INIT_FAILED);
// ... other checks that you need
return(INIT_SUCCEEDED);
}
bool initializeAccountInfo()
{
int accountNumber=0, attempt=0, ATTEMPTS=50, SLEEP(50);
while(attempt<ATTEMPTS)
{
accountNumber=AccountInfoInteger(ACCOUNT_LOGIN);
attempt++;
if(accountNumber==0)
Sleep(SLEEP);
else
break;
}
return accountNumber>0;
}

How to terminate a long running isolate #2

I am trying to understand how I shall port my Java chess engine to dart.
So I have understood that I should use an Isolates to run my engine in parallell with the GUI but how can I force the engine to terminate the search.
In java I just set some boolean that where shared between the engine thread and the gui thread.
Answer I got:
You should send a message to the isolate, telling it to stop. You can simply do something like:
port.send('STOP');
My request
Thanks for the clarification. What I don't understand is that if the chess engine isolate is busy due to a port.send('THINK') command how can it respond to a port.send('STOP') command
Each isolate is single-threaded. As long as your program is running nobody else will have the means to interfere with your execution.
If you want to be able to react to outside events (including messages from other isolates) you need to split your long running execution into smaller parts. A chess-engine probably has already some state to know where to look for the next move (assuming it's built with something like A*). In this case you could just periodically interrupt your execution and resume after a minimal timeout.
Example:
var state;
var stopwatch = new Stopwatch()..run();
void longRunning() {
while (true) {
doSomeWorkThatUpdatesTheState();
if (stopwatch.elapsedMilliseconds > 200) {
stopwatch.reset();
Timer.run(longRunning);
return;
}
}
}
The new API will contain a
isolate.kill(loopForever ? Isolate.IMMEDIATE : Isolate.AS_EVENT);
See https://code.google.com/p/dart/issues/detail?id=21189#c4 for a full example.

How to cancel a #Background task with AndroidAnnotations

My use case is that whenever an user types something an EditText, the input data is used for performing operations on the background. These operations might take long enough to cause an ANR. #TextChange together with #Background works fine if the operation is done quicly enough. But is the operation takes long enough, so that the user inputs more data, I will get threading issues as there will be multiple background tasks that will command the update of same UI component.
I think I achieve the wanted behaviour with AsyncTask API, but wanted to look for AndroidAnnotations based solutions as well, as it simplifies the code a lot. Great lib by the way.
Below are some code snippets that'll hopefully illustrate my point. Thanks for at least reading, comments/answers appreciated :)
#TextChange
void onUserInput(...) {
// This will start a new thread on each text change event
// thus leading to a situation that the thread finishing
// last will update the ui
// the operation time is not fixed so the last event is
// not necessary the last thread that finished
doOperation()
}
#Background
void doOperation() {
// Sleep to simulate long taking operation
Thread.sleep( 6000 );
updateUi()
}
#UiThread
void updateUi() {
// Update text field etc content based on operations
}
UPDATE: This is not possible at the moment, see DayS' answer below.
It's possible since AA 3.0. Read this thread.
#Override
protected void onStop() {
super.onStop();
boolean mayInterruptIfRunning = true;
BackgroundExecutor.cancelAll("longtask", mayInterruptIfRunning);
}
#Background(id="longtask")
public void doSomethingLong() {
// ...
}
There already was this kind of request on Android Annotations but it was closed because no solution was proposed. But if you have any idea about it, go ahead and re-open this issue ;)

How could i make this function sleep for a certain amount of time?

So here's my problem. I have code set up that calls a function whenever my player is over its last destination in the a* pathfinding array...
public function rakeSoil(e:Event):void {
var:Cell = Grid.getCellAt(player.x/50, player.y/50);
if (cell.isWalkable == false) {
return;
else {
//here is where i want to do the sleep code so this doesnt happen straight away? If possible.
target.sprites = [grass];
}
}
thanks guys :)
Generally, the "right" way to delay execution of something is to use a Timer.
Hacking up some kind of a sleep function could cause problems, since Flash runs in a single thread, so you won't be able to do anything else while your function is running, including refreshing the screen (making your game appear as if it crashed, or at least started lagging).
If you're absolutely, positively sure you want to do this, you could call the getTimer() function in a loop to see if a certain amount of miliseconds has passed.

C builder RAD 2010 RTL/VCL Application->Terminate() Function NOT TERMINATING THE APPLICATION

I have a problem also described here: http://www.delphigroups.info/3/9/106748.html
I have tried almost all forms of placing Application->Terminate() func everywhere in the code, following and not 'return 0', 'ExitProcess(0)', 'ExitThread(0)', exit(0). No working variant closes the app. Instead the code after Application->Terminate() statement is running.
I have two or more threads in the app. I tried calling terminate func in created after execution threads and in main thread.
Also this is not related (as far as I can imagine) with CodeGuard / madExcept (I have turned it off and on, no effect). CodeGuard turning also did not do success.
The only working code variant is to place Application->Terminate() call to any of any form button's OnClick handler. But this does not fit in my needs. I need to terminate in any place.
What I should do to terminate all the threads in C++ Builder 2010 application and then terminate the process?
Application->Terminate() does not close application immediately, it only signals you want to close the application.
Terminate calls the Windows API
PostQuitMessage function to perform an
orderly shutdown of the application.
Terminate is not immediate.
In your functions call Application->ProcessMessages() then check if the Application->Terminated property is true.
For applications using
calculation-intensive loops, call
ProcessMessages periodically, and
also check Terminated to determine
whether to abort the calculation and
allow the application to terminate
For example:
void Calc()
{
for (int x = 0; x < 1000000; ++x)
{
// perform complex calculation
// check if need to exit
Application->ProcessMessages();
if (Application->Terminated)
{
break;
} // end if
} // end for
// clean up
}

Resources