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

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

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

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

Passing Data through the Stack

I wanted to see if you could pass struct through the stack and I manage to get a local var from a void function in another void function.
Do you guys thinks there is any use to that and is there any chance you can get corrupted data between the two function call ?
Here's the Code in C (I know it's dirty)
#include <stdio.h>
typedef struct pouet
{
int a,b,c;
char d;
char * e;
}Pouet;
void test1()
{
Pouet p1;
p1.a = 1;
p1.b = 2;
p1.c = 3;
p1.d = 'a';
p1.e = "1234567890";
printf("Declared struct : %d %d %d %c \'%s\'\n", p1.a, p1.b, p1.c, p1.d, p1.e);
}
void test2()
{
Pouet p2;
printf("Element of struct undeclared : %d %d %d %c \'%s\'\n", p2.a, p2.b, p2.c, p2.d, p2.e);
p2.a++;
}
int main()
{
test1();
test2();
test2();
return 0;
}
Output is :
Declared struct : 1 2 3 a '1234567890'
Element of struct undeclared : 1 2 3 a '1234567890'
Element of struct undeclared : 2 2 3 a '1234567890'
Contrary to the opinion of the majority, I think it can work out in most of the cases (not that you should rely on it, though).
Let's check it out. First you call test1, and it gets a new stack frame: the stack pointer which signifies the top of the stack goes up. On that stack frame, besides other things, memory for your struct (exactly the size of sizeof(struct pouet)) is reserved and then initialized. What happens when test1 returns? Does its stack frame, along with your memory, get destroyed?
Quite the opposite. It stays on the stack. However, the stack pointer drops below it, back into the calling function. You see, this is quite a simple operation, it's just a matter of changing the stack pointer's value. I doubt there is any technology that clears a stack frame when it is disposed. It's just too costy a thing to do!
What happens then? Well, you call test2. All it stores on the stack is just another instance of struct pouet, which means that its stack frame will most probably be exactly the same size as that of test1. This also means that test2 will reserve the memory that previously contained your initialized struct pouet for its own variable Pouet p2, since both variables should most probably have the same positions relative to the beginning of the stack frame. Which in turn means that it will be initialized to the same value.
However, this setup is not something to be relied upon. Even with concerns about non-standartized behaviour aside, it's bound to be broken by something as simple as a call to a different function between the calls to test1 and test2, or test1 and test2 having stack frames of different sizes.
Also, you should take compiler optimizations into account, which could break things too. However, the more similar your functions are, the less chances there are that they will receive different optimization treatment.
Of course there's a chance you can get corrupted data; you're using undefined behavior.
What you have is undefined behavior.
printf("Element of struct undeclared : %d %d %d %c \'%s\'\n", p2.a, p2.b, p2.c, p2.d, p2.e);
The scope of the variable p2 is local to function test2() and as soon as you exit the function the variable is no more valid.
You are accessing uninitialized variables which will lead to undefined behavior.
The output what you see is not guaranteed at all times and on all platforms. So you need to get rid of the undefined behavior in your code.
The data may or may not appear in test2. It depends on exactly how the program was compiled. It's more likely to work in a toy example like yours than in a real program, and it's more likely to work if you turn off compiler optimizations.
The language definition says that the local variable ceases to exist at the end of the function. Attempting to read the address where you think it was stored may or may produce a result; it could even crash the program, or make it execute some completely unexpected code. It's undefined behavior.
For example, the compiler might decide to put a variable in registers in one function but not in the other, breaking the alignment of variables on the stack. It can even do that with a big struct, splitting it into several registers and some stack — as long as you don't take the address of the struct it doesn't need to exist as an addressable chunk of memory. The compiler might write a stack canary on top of one of the variables. These are just possibilities at the top of my head.
C lets you see a lot behind the scenes. A lot of what you see behind the scenes can completely change from one production compilation or run to the next.
Understanding what's going on here is useful as a debugging skill, to understand where values that you see in a debugger might be coming from. As a programming technique, this is useless since you aren't making the computer accomplish any particular result.
Just because this works for one compiler doesn't mean that it will for all. How uninitialized variables are handled is undefined and one computer could very well init pointers to null etc without breaking any rules.
So don't do this or rely on it. I have actually seen code that depended on functionality in mysql that was a bug. When that was fixed in later versions the program stopped working. My thoughts about the designer of that system I'll keep to myself.
In short, never rely on functionality that is not defined. If you knowingly use it for a specific function and you are prepared that an update to the compiler etc can break it and you keep an eye out for this at all times it might be something you could explain and live with. But most of the time this is far from a good idea.

Monodroid - free memory when activity finished

Here can be found a sample code
https://github.com/PVoLan/TestActivityDispose
We have two activities. One has a button leading to second activity. Second activity has 30 TextViews (simulating a complex UI) and a back button.
Switching between activities forward and back causes GREF quantity growing quickly. It requires about 60 times to click forward and back to overflow 2k limit and crash application.
Android log can be found in repository. As you can see from log, GREF overflow occurs most because of TextViews (1543 GREFs). Another GREFS are:
Button (55 GREFs) - backButton, obviously
OnClickListenerImplementor (55 GREFs) - backButton.Click listenters
Activity2 (54 GREFs)
Intent (54 GREFs) - activity starters
So, as we can see, activity resources are not freed when activity finishes (although OnDestroy is called)
How can I free all this GREFs properly?
The problem is that there are two GCs in the process (Dalvik & Mono), and neither knows how much memory the other is using. For example, all Mono sees for TextView instances is a really small object (largely an IntPtr and other supporting fields from Java.Lang.Object):
namespace Java.Lang {
public class Object {
IntPtr handle;
// ...
}
}
namespace Android.Widget {
public class TextView : Java.Lang.Object {
// ...
}
}
That is, for most of the bound types, there are no data members of consequence, and the C# wrappers are quite tiny. Mono doesn't know -- and can't know -- that there's a Java object associated with Object.handle, and (more importantly) how much memory that object is referencing.
Consequently, you occasionally need to help it:
// https://github.com/PVoLan/TestActivityDispose/blob/master/Test/Activity2.cs
public class Activity2 {
// ...
protected override void OnDestroy ()
{
Android.Util.Log.Info("----------", "Destroy");
base.OnDestroy ();
GC.Collect ();
}
}
The added GC.Collect() call will give Mono's GC a chance to execute and collect the garbage objects. After adding that line, repeatedly tapping "Hello World, Click Me!" and "Back" levels out at 93-126 grefs (depending on which activity you're on).

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