Sporadic Pending Order function | MQL4 - mql4

So I have an EA which places a Pending Order at the opening price of the current candle, and expires at the end of the current candle.
My code is below, I have even printed an error function in order to diagnose any errors that may occur, however, according to the EA, a pending order is placed so no error appears.
Sometimes a pending order is actually successfully executed, and other times, it tells me a pending order has been placed successfully, but no pending order appears on the chart.
There are no error messages.
Clearly there are no errors, so it must be something to do with my coding. What am I missing here? Why does it sometimes placed a pending order on the chart, and others times it decided not to?
Many thanks.
if(<Conditions are met>){
int pendingExpiration = Period() * 60;
double candleOpenPrice = iOpen(Symbol(),0,0);
double pendingOrderExecPrice = NormalizeDouble(candleOpenPrice,Digits);
if(!OrderSend(Symbol(),OP_BUYSTOP,3,pendingOrderExecPrice,100,<sl>,<tp>,0,1,Time[0] + pendingExpiration,0)){
RefreshRates();
Print("Error on pending order "+IntegerToString(GetLastError(),0));
}
else {
<confirmaion email function>
}
}

Only thing I see is the Digits thing:
Yours: NormalizeDouble(candleOpenPrice,Digits);
What I know: NormalizeDouble(candleOpenPrice,_Digits);
Notice the underscore.
Although not sure whether this causes the errors.
Your call to candleOpenPrice just might sometimes return too many (or few) digits that can not be casted by the erratic call to _Digits.

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

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

Removing a GKTurnBasedMatch which is in an invalid state

I am doing some experimentation to try to learn about GameKit and I made a simple game and an interface which lists my player's matches. I am trying to add the ability to remove games using the removeWithCompletionHandler: method on the match, but I am having trouble removing a GKTurnBasedMatch which seems to have entered an invalid state.
A po of the match in question prints:
$0 = 0x1d590d20 <GKTurnBasedMatch 0x1d590d20 id:858d8257-cc49-4060-b1d8-38c09a929e3c status:Ended message: taken:2013-03-08 18:08:47 +0000 created:2013-03-08 03:24:14 +0000
current:<GKTurnBasedParticipant 0x1d58c020 - id:G:1717956303 (local player) status:Invited outcome:None lastTurn:(null)>
participants:
<GKTurnBasedParticipant 0x1d58bc90 - id:G:1717239488 status:Done outcome:Quit lastTurn:2013-03-08 18:08:47 +0000>
<GKTurnBasedParticipant 0x1d58c020 - id:G:1717956303 (local player) status:Invited outcome:None lastTurn:(null)>
>
Which seems to indicate that the match has been ended. However, one of the participants has the outcome:None, which I am led by the docs to believe is invalid for an ended game. Trying to simply remove the game gives:
The requested operations could not be completed because one or more parameters are invalid.
While trying to set the outcomes and end the game gives:
The requested operation could not be completed because the session is in an invalid state.
I thought perhaps I could not remove the game because the local player is the active participant, but both participantQuitInTurnWithOutcome:... and endTurnWithNextParticipants:... both give the error:
The requested operation could not be completed because the session is in an invalid state.
as well. Am I doing something wrong or did I somehow create an unremovable game?
P.S. I am also unable to remove the games through the Game Center provided interface, where they are listed under the "Game Over" section.
This is how I managed to remove all invalid matches.
I checked the status of the current participant, if it's invited, I called declineInviteWithCompletionHandler, otherwise I called participantQuitInTurnWithOutcome.
In both completion blocks, I then called removeWithCompletionHandler to remove the match.
This generated a few errors but the matches were still removed so my list is clean.
And here is a workaround on how to avoid getting to this state to begin with. This has the added benefit that the invitee never even get a notification if the inviter quits before finishing his/hers first turn.
In playerQuitForMatch, first end the turn and then in the completion handler, immediately quit the match. Like so,
[match endTurnWithNextParticipants:[NSArray arrayWithObject:nextParticipant]
turnTimeout:GKTurnTimeoutDefault
matchData:nil completionHandler:^(NSError *error) {
if (error) {
NSLog(#"%#", error);
}
[match participantQuitOutOfTurnWithOutcome:GKTurnBasedMatchOutcomeQuit
withCompletionHandler:^(NSError *error) {
if (error) {
NSLog(#"%#" ,error);
}
}];
}];
Unfortunately, I've run into the exact same error. To help others understand the problem, in hopes of researching a solution, you can recreate this by inviting a friend to a match, but then quitting the match during the first turn before you ever submit that turn to the invited player. Then, the hosting player removes the match from Game Center. On the invited player's device, they will have a match that looks like the one referenced above, that cannot be deleted. I've tried all types of workaround solutions.
I haven't had any luck yet, but I will update my answer with a solution if I find one. I'm currently trying to ship a Game Center game and so I have to find some way around this. I'll have a conclusion within the next day or two.
UPDATE:
I went over my non-deleteable matches, and they are almost the same as yours except my player with the Invited status also has the match outcome of Won. It seems the key to put the match into an invalid state is to have one player status be Invited instead of Done, but have the match status be Ended. That's the common element between our two cases, and it's an edge case in Apple's bizantine Game Center code. It wouldn't surprise me if they simply screwed up this edge case and expected you to "just know" that you weren't supposed to put the players in that state (undoubtedly if you read their docs closely enough you'll be able to piece this together eventually).
My conclusion is that Apple has an edge case on their hands that goes unnoticed easily because it only can happen if you quit a new match, and only if you invite a friend, two cases you might not test often. Also, if you aren't setting match outcomes improperly I'm guessing it will never happen so they just never caught it.
Since I haven't shipped yet, I'm going to configure my app to detect matches in this state and ignore them. I'm going to report to the console a count of how many matches are in this state, just so I can ensure its not growing past this point. Then, I'm going to analyze my quitting code and make sure that in this edge case that I simply can never put a match into this state again. I think given what we know we've got to be proactive, and just suck up the fact that some matches slipped through.
Hopefully you haven't shipped yet, so the error case matches will be localized to the Game Center Sandbox environment. Actually, the bad matches are just localized to your test user in the Sandbox, so you could just throw away that user and start with a new user once you've corrected your issue. If you implement my above suggestions you should be able to confirm your app is working properly before taking this step.
If anyone can actually find a way to remove these error matches once they exist, please let us know, but I hope my suggestions and identification of the actual cause will be enough to help you proceed with your project.
I found the solution. For invalid matches just use -participantQuitOutOfTurn method and then -removeWithCompletionHandler method. It will be completely removed.
I have a similar situation, if slightly different. I start a match, invite a second sandbox account to play, then the first player quits and deletes the game before the second player can respond. When the second player tries to then quit the game, they get this error:
Error quitting match in turn: Error Domain=GKErrorDomain Code=22 "The requested operation could not be completed because the specified participant is invalid."
UserInfo=0x1f5de800 {
GKServerStatusCode=5097,
NSUnderlyingError=0x1f58b610 "The operation couldn’t be completed.
status = 5097,
Invalid state: turn sent to playerId:1952436619 in slotIndex: 0 for sessionId: 698b074b-fa0b-4505-834f-1b4305b7eecb : expected slot state: Active but found: Inactive",
NSLocalizedDescription=The requested operation could not be completed because the specified participant is invalid.
}
So as far as I can tell, that's happening because the next participant to move already has a status of "Done," which I'm guessing is because they already quit:
<GKTurnBasedMatch 0x1f532b20 id:698b074b-fa0b-4505-834f-1b4305b7eecb status:Open message: taken:2013-03-30 19:53:47 +0000 created:2013-03-30 18:29:09 +0000
current:<GKTurnBasedParticipant 0x1f532b80 - id:G:1952433332 (local player) status:Active outcome:None lastTurn:2013-03-30 19:53:47 +0000>
participants:
<GKTurnBasedParticipant 0x1f532b70 - id:G:1952436619 status:Done outcome:Lost lastTurn:2013-03-30 18:29:10 +0000>
<GKTurnBasedParticipant 0x1f532b80 - id:G:1952433332 (local player) status:Active outcome:None lastTurn:2013-03-30 19:53:47 +0000>
>
Hopefully this will help others diagnose if nothing else. Would love to hear others' insights towards a workaround or solution. If this is a bug on Apple's part, it seems like it might be worth filing a radar.
Apple Technical Developer support confirmed the issue. Submitted bug report. Will keep you posted.

node.js process out of memory error

FATAL ERROR: CALL_AND_RETRY_2 Allocation Failed - process out of memory
I'm seeing this error and not quite sure where it's coming from. The project I'm working on has this basic workflow:
Receive XML post from another source
Parse the XML using xml2js
Extract the required information from the newly created JSON object and create a new object.
Send that object to connected clients (using socket.io)
Node Modules in use are:
xml2js
socket.io
choreographer
mysql
When I receive an XML packet the first thing I do is write it to a log.txt file in the event that something needs to be reviewed later. I first fs.readFile to get the current contents, then write the new contents + the old. The log.txt file was probably around 2400KB around last crash, but upon restarting the server it's working fine again so I don't believe this to be the issue.
I don't see a packet in the log right before the crash happened, so I'm not sure what's causing the crash... No new clients connected, no messages were being sent... nothing was being parsed.
Edit
Seeing as node is running constantly should I be using delete <object> after every object I'm using serves its purpose, such as var now = new Date() which I use to compare to things that happen in the past. Or, result object from step 3 after I've passed it to the callback?
Edit 2
I am keeping a master object in the event that a new client connects, they need to see past messages, objects are deleted though, they don't stay for the life of the server, just until their completed on client side. Currently, I'm doing something like this
function parsingFunction(callback) {
//Construct Object
callback(theConstructedObject);
}
parsingFunction(function (data) {
masterObject[someIdentifier] = data;
});
Edit 3
As another step for troubleshooting I dumped the process.memoryUsage().heapUsed right before the parser starts at the parser.on('end', function() {..}); and parsed several xml packets. The highest heap used was around 10-12 MB throughout the test, although during normal conditions the program rests at about 4-5 MB. I don't think this is particularly a deal breaker, but may help in finding the issue.
Perhaps you are accidentally closing on objects recursively. A crazy example:
function f() {
var shouldBeDeleted = function(x) { return x }
return function g() { return shouldBeDeleted(shouldBeDeleted) }
}
To find what is happening fire up node-inspector and set a break point just before the suspected out of memory error. Then click on "Closure" (below Scope Variables near the right border). Perhaps if you click around something will click and you realize what happens.

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