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

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;
}

Related

MQL Program unexpectedly terminated

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);
}
}

How to test if Xamarin Android app closes

I am writing my first Android app, using Xamarin. I have an Exit button that, when clicked, closes the app. I want a test in Xamarin UITest that verifies clicking the button closes the app. I messed around with it for a while and finally found something that allows the test to pass.
In the app:
exitButton.Click += (o, e) =>
{
int pid = Android.OS.Process.MyPid();
Android.OS.Process.KillProcess(pid);
};
In UITest:
[Test]
public void ExitButtonClosesTheScreen()
{
try
{
app.Tap(c => c.Button("exitButton"));
Assert.Fail("App remains open.");
}
catch (System.Exception e)
{
Assert.AreEqual("The underlying connection was closed: The connection was closed unexpectedly.", e.InnerException.InnerException.InnerException.Message);
}
}
The test now passes so I guess I'm happy. My question is, is this really the best way to do this? Or is there a better way that I wasn't able to find?
Edit: Unfortunately, this is not the answer. This method allows the test to pass in VS but fails when I run it in App Center. Is there another way to run this test? Or is this something that is simply not testable with UITest? Thank you.
First of all the right code for closing the Application as per me is using finish affinity
In an Activity:
this.FinishAffinity();
In a Fragment:
this.Activity.FinishAffinity();
After doing this AppCenter should be able to figure that your app is closed.
I did a brief read up on this the other day for something similar and I am certain that the ActivityManager class would be the best way to go about this.
https://developer.xamarin.com/api/type/Android.App.ActivityManager/
There is a method within this class called RunningAppProcesses which returns a list of application processes that are running on the device - and from there I guess you can assert if your app process is on the list or not.
Hope this helps
After almost 4 years, i've encountered with the same issue.
I will do it this way in your case:
[Test]
public void ExitButtonClosesTheScreen()
{
app.Tap(c => c.Marked("exitButton"));
/** I asume exitButton click action will just exit,
no popups or alerts appear before exiting. **/
app.WaitForNoElement(q => q.Marked("exitButton"),
"Timeout waiting for element exitButton",
new TimeSpan(0, 0, 30));
AppResult[] result = app.Query();
Assert.IsTrue(result.Length == 0);
}
app.Query() returns all views visible by default, unless a query is especified by a lambda expression, as you should alredy know.
If the Application is gone, the Views visible will be 0, and as such, app.query() will return and array lenght of 0.
For WaitForNoElement's timeout I use a TimeSpan of 30 seconds, but you can use whatever timeout you prefer for this operation, i just considered 30 seconds will be ok.

Is there any function for testing Candle Bar closed in MQL5?

I have tried the following code in MQL5 but getting errors. This code was I guess from MQL4.
Code:
int OnInit()
{
// if you don't want to execute on the first tick
IsBarClosed(-1,false);
return(1);
if(!IsBarClosed(0,true)) // true/false here allows to keep old bar for check again later in the code and reset
return(0);
}
//+------------------------------------------------------------------+
//| check if new bar has formed
//+------------------------------------------------------------------+
bool IsBarClosed(int timeframe,bool reset)
{
static datetime lastbartime;
if(timeframe==-1)
{
if(reset)
lastbartime=0;
else
lastbartime=iTime(NULL,timeframe,0);
return(true);
}
if(iTime(NULL,timeframe,0)==lastbartime) // wait for new bar
return(false);
if(reset)
lastbartime=iTime(NULL,timeframe,0);
return(true);
}
Output:
'iTime' - function not defined testing lines and trdae.mq5 243 25
'iTime' - function not defined testing lines and trdae.mq5 246 8
'iTime' - function not defined testing lines and trdae.mq5 249 21
3 error(s), 0 warning(s) 4 1
Kindly, help me in getting it done correctly with MQL5. I am trying to detect the candle Bar closing time and not opening time. I just want to attempt when the bar closes.
iTime() function does not exist in MQl5, only in MQL4. Use CopyRates() or SeriesInfoInteger(_Symbol,_Period,SERIES_LASTBAR_DATE).
static is a keyword in MQL4/5 with very specific properties. Many versions it worked in the following way: if you attach ea to the chart, static is zero and then updates. if you reattach - from zero to actual. if you change timeframe or settings of the ea/ind - static remains same (it doesnt deinitialize, doesnt become zero and then actual value). The earliest 1000+ build of MT4 worked like that (two updates back from now). Maybe someone find this keyword useful in mql4 that allows to keep variables together with their functions and not in the globals; of course keeping in mind the problem above or ignoring it. But there is no reason to use this word in MQL5. if you need a set of functions - create a class and keep all variables related to it. Then you wont have problems with static variables that havent been reinitialized.
Bar close time is an interesting concept, I am not sure what you mean. if you have a bar (e.g., using MqlRates), you can get its open time. close time is not reported. you may count it yourself of course (open time + PeriodSeconds(_Period)-1).
IsNewBar() function/ class has an important function - it checks each tick and says whether a new bar has started or not. It is possible to tell that a new bar starts because TimeCurrent() or Time of the last tick >= Time of the last known bar + 60*Period(). At the same time, it is not possible to tell whether a bar is closed or not (ok, it is possible to tell that a bar is closed if a new bar is created, and that's the only way) because many ticks may arrive after that (even at the last second of the bar).
I do not know why you need to reset parameters in your code, try the following:
datetime iTime=(datetime)(SeriesInfoInteger(_Symbol,Period(),SERIES_LASTBAR_DATE)/PeriodSeconds()*PeriodSeconds());
and then replace iTime() in your code with iTime variable, that may help

Forcebly stop EA in OnTick()

I am making a EA for backTest.
Normally program works like this.
Ontick() is called until the end of certain period.
OnDeinit() OnTester() are called.
However now I want to stop in OnTick() and goto 2).
like this,
void OnTick()
{
if (cnt > 100) {OnTick();OnTester();//Finish program here}
}
I think I could stop in OnInit() (to check user's initial setup etc...)
However can I stop EA in OnTick()???
In summary, what I want to do is,
Call OnTester() from inside of the OnTick() and finish the program.
Yes, this is also possible:
syntax is:
void ExpertRemove();
The Expert Advisor is not stopped immediately as you call ExpertRemove(); just a flag to stop the EA operation is set. That is, any next event won't be processed, OnDeinit() will be called and the Expert Advisor will be unloaded and removed from the chart.
So the OnDeinit(){...}-handler is activated "automatically", once a first call to the ExpertRemove() system function has raised the pre-termination flag.
If your logic requires, put this call into a "manually" called OnTester() handler, relying on it being invoked as posted aboveif( cnt > 100 ) { OnTester(); // having the "killer"-ExpertRemove() there ... }
and you are done.
You might have noticed, there should not be the posted OnTick()-call inside the if(){...}-code-block, as it would never let the code-execution reach the manually-pre-scribed call to the OnTester(), but will remain in a lethal never ending loop of manually-injected endless diving of re-entries into the OnTick(){...}-handler, having no way to exit from.

Silverlight 3 IncreaseQuotaTo fails if I call AvailableFreeSpace first

The following code throws an exception...
private void EnsureDiskSpace()
{
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForSite())
{
const long NEEDED = 1024 * 1024 * 100;
if (file.AvailableFreeSpace < NEEDED)
{
if (!file.IncreaseQuotaTo(NEEDED))
{
throw new Exception();
}
}
}
}
But this code does not (it displays the silverlight "increase quota" dialog)...
private void EnsureDiskSpace()
{
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForSite())
{
const long NEEDED = 1024 * 1024 * 100;
if (file.Quota < NEEDED)
{
if (!file.IncreaseQuotaTo(NEEDED))
{
throw new Exception();
}
}
}
}
The only difference in the code is that the first one checks file.AvailableFreeSpace and the second checks file.Quota.
Are you not allowed to check the available space before requesting more? It seems like I've seen a few examples on the web that test the available space first. Is this no longer supported in SL3? My application allows users to download files from a server and store them locally. I'd really like to increase the quota by 10% whenever the user runs out of sapce. Is this possible?
I had the same issue. The solution for me was something written in the help files. The increase of disk quota must be initiated from a user interaction such as a button click event. I was requesting increased disk quota from an asynchronous WCF call. By moving the space increase request to a button click the code worked.
In my case, if the WCF detected there was not enough space, the silverlight app informed the user they needed to increase space by clicking a button. When the button was clicked, and the space was increased, I called the WCF service again knowing I now had more space. Not as good a user experience, but it got me past this issue.
There is a subtle bug in your first example.
There may not be enough free space to add your new storage, triggering the request - but the amount you're asking for may be less than the existing quota. This throws the exception and doesn't show the dialog.
The correct line would be
file.IncreaseQuotaTo(file.Quota + NEEDED);
I believe that there were some changes to the behavior in Silverlight 3, but not having worked directly on these features, I'm not completely sure.
I did take a look at this MSDN page on the feature and the recommended approach is definitely the first example you have; they're suggesting:
Get the user store
Check the AvailableFreeSpace property on the store
If needed, call IncreaseQuotaTo
It isn't ideal, since you can't implement your own growth algorithm (grow by 10%, etc.), but you should be able to at least unblock your scenario using the AvailableFreeSpace property, like you say.
I believe reading the amount of total space available (the Quota) to the user store could be in theory an issue, imagine a "rogue" control or app that simply wants to fill every last byte it can in the isolated storage space, forcing the user eventually to request more space, even when not available.
It turns out that both code blocks work... unless you set a break point. For that matter, both code blocks fail if you do set a break point.

Resources