What's wrong with this MQL4 code? - mql4

I wanted to make a generic code, where I could set a pricepoint and have the program buy and sell on my demo account.
{
double pricepoint = 1.36900;
if ( Bid < pricepoint )
{
int ticket;
ticket = OrderSend( "EURUSD", OP_BUY, 1.0, Ask, 0, 0, 0, "My 1st Order!" );
}
else if ( ticket != -1 ) & ( Ask > pricepoint )
{
OrderClose( ticket, 1.0, Bid, 0 );;
}

As others mentioned, first you need to declare ticket outside the if() statement. If you want to close the order later, when it's in profit, you can't do it straight inside the else{...} block - the price cannot be lower than pricepoint and higher than pricepoint at the same time.
Since your EA will run with each tick, the variable ticket will contain your new ticket number only for one cycle. If that's what you want your code would look like this:
double pricepoint = 1.36900;
int ticket = -1;
// buy condition is met
if (Bid < pricepoint)
{
// you should consider using Symbol() to get the chart symbol
ticket = OrderSend("EURUSD", OP_BUY, 0.01, Ask, 0, 0, 0, "My 1st Order!");
if (ticket < 0)
{
Print("OrderSend failed with error #", GetLastError());
}
else
Print("OrderSend placed successfully");
}
// ... later in code
// if you want to close specifically the ticket that was opened in the same tick cycle
if (ticket > 0)
{
if (OrderSelect(ticket, SELECT_BY_TICKET) == true)
{
// use OrderTicket(), OrderLots() and other Order functions to get the ticket properties
OrderClose(OrderTicket(), OrderLots(), Bid, 0, clrNONE);
}
else
Print("OrderSelect returned the error of ",GetLastError());
}
I don't recommend working with tickets this way though. It will take some time before your orders are in profit (if ever). You can loop through all open tickets and close those that are in profit like this:
for (int i = 0; i < OrdersTotal(); i++)
{
if (OrderSelect(i, SELECT_BY_POS) == true)
{
// we only care about opened market orders, not pendings
if (OrderType() > OP_SELL)
continue;
// we only want to close orders that are in profit
if (OrderProfit() < 0)
continue;
if (OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 0, clrNONE) == false)
Print("OrderClose returned the error of ",GetLastError());
// we need to adjust the control variable for the order we just closed
else
i--;
}
else
Print("OrderSelect returned the error of ",GetLastError());
}

The variable ticket needs to be declared ( and obtain a value )outside of the if(){...}else{...} block,and where does the Ask variable come from?

A: a commented inventory of errors for [ What's wrong with this code ]:
While MQL4 code is syntactically trivial, some care has to be taken for details:
{ // -<BegOfBlock>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double pricepoint = 1.36900; // =OK: .DEFs a variable visible/known till the <EndOfBlock> "}"
if ( Bid < pricepoint ) // ERR: <pricepoint> refers to something not known yet, the compiler will object ( <Bid> is a known system-state variable of the code-execution platform [ MetaTrader Terminal 4] )
{ // -<BegOfBlock>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int ticket; // =OK: .DEFs a variable visible/known till the <EndOfBlock> "}" with an implicit value assignment of 0
ticket = OrderSend( "EURUSD",
OP_BUY,
1.0,
Ask,
0,
0,
0,
"My 1st Order!"
); // =OK: .SET a value { -1 onFailure | <aTicketNUMBER> onSuccess }
}
// ^------<EndOfBlock>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// INF: ##<EndOfBlock> .UNDEF: <ticket>
//
else
if ( ticket != -1 ) & ( Ask > pricepoint )
// ^--------------|------------------------------ ERR: <ticket> refers to something not known here, the compiler will object
// ^------------------------------ ERR: "&" operator does not conform to syntax-rules, use "&&" and/or "||" for { .AND. | .OR. } boolean-constructions
{ // -<BegOfBlock>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
OrderClose( ticket, 1.0, Bid, 0 );;
// ^---------------------^--------------ERR: <ticket> refers to something not known here, the compiler will object
// ^--------------ERR: remove the 2nd ";"
}
// ^------<EndOfBlock>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ^------<EndOfBlock>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ERR: an<EndOfBlock> "}" missing
// INF: ##<EndOfBlock> .UNDEF: <pricepoint>

Related

crash while reading the socket data - recv() - in objective-c

I'm trying to read data from the socket and it works fine most of the time.
When I run the app for longer duration - app crashes and crashlytics points the crash to readingSocket() - this function just reads raw data from socket.
Below is code of readingSocket()
-(bool) readingSocket:(NSMutableData*)dataIn readBytes:(ssize_t)quantity error:(NSError **)error {
ssize_t readBytesNow = 0;
ssize_t grossRead= 0;
[dataIn setLength:0];
if (error != nil) {
*error = nil;
}
char *buffer = new char[6144];
do {
ssize_t readBytes = (quantity - grossRead);
readBytesNow = recv((int)raw_Socket, buffer, readBytes , MSG_DONTWAIT);
if (readBytesNow == 0) {
NSLog(#" read error");
delete[] buffer;
return false;
}
Else if (bytesRead < 0) {
if (errno == EAGAIN) {
[NSThread sleepForTimeInterval:0.5f];
NSLog(#" EAGAIN error");
continue;
}
else {
// if error != nil
delete[] buffer;
return false;
}
}
else if (readBytesNow > 0) {
grossRead += readBytesNow;
// doing some operations
}
} while (grossRead < quantity);
delete[] buffer;
return true;
}
I'm already doing so many checks after reading but not sure where could the probable cause for the crash or exception ??
any other better way to handle exception in my above code ?
I can't comment without 50 reputation (new user here), so here goes my comment as an answer.
Warning: I have no idea of the language your code is written, but I'm using my instincts as a C++ programmer (and probably mediocre one at it).
First thing I noticed was this piece of code:
if (error != nil) {
*error = nil;
}
In C world, this would be similar to checking if a pointer is null, but assigning null as its value afterwards.
Second thing to note is this construct:
-(bool) readingSocket:(NSMutableData*)dataIn readBytes:(ssize_t)quantity error:(NSError **)error {
...
char *buffer = new char[6144];
...
ssize_t readBytes = (quantity - grossRead);
When quantity > 6144 i.e. once in a blue moon, your network stack might read more than 6144 bytes which would result in a buffer overflow.
Tangential comments:
1) I think you should note that EAGAIN and EWOULDBLOCK may be the same value but not guaranteed. You might consider checking for both of them if you are not certain that your platform behaves exactly as you think.
An example link to Linux documentation
2) Your logic,
if (readBytesNow == 0) {
...
} Else if (bytesRead < 0) {
...
} else if (readBytesNow > 0) {
...
}
although being verbose, is unnecessary. You can use
if (readBytesNow == 0) {
...
} Else if (bytesRead < 0) {
...
} else {
...
}
to be sure you are not getting an additional comparison. This comparison might get optimised out anyway, but writing this way makes more sense. I had to look again to see "if I am missing something".
Hope these help.

how to use getBytes:length?

- (int) compareCBUUID:(CBUUID *) UUID1 UUID2:(CBUUID *)UUID2 {
char b1[128];
char b2[128];
[UUID1.data getBytes:b1];
[UUID2.data getBytes:b2];
if (memcmp(b1, b2, UUID1.data.length) == 0)return 1;
else return 0;
}
How I can convert above method to use getBytes:length in above method ?
Thanks
Why so hard? Just:
- (int)compareCBUUID:(CBUUID *) UUID1 UUID2:(CBUUID *)UUID2 {
return (int)(UUID1 == UUID2 || [UUID1 isEqual:UUID2]);
}

Not able to hear 'noise' when writing random values AudioBuffer in iOS

I am using EZAudio and trying to write some samples generated by my softaware to an AudioBuffer provided by this library https://github.com/syedhali/EZAudio as seen in the example "Playback By Manual Override".
My code looks like this...
// Completely override the output callback function
- (void)
output:(EZOutput *)output
callbackWithActionFlags:(AudioUnitRenderActionFlags *)ioActionFlags
inTimeStamp:(const AudioTimeStamp *)inTimeStamp
inBusNumber:(UInt32)inBusNumber
inNumberFrames:(UInt32)inNumberFrames
ioData:(AudioBufferList *)ioData {
//grab latest sample from sample queue
if (currentAudioPiece == nil || currentAudioPiece.duration >= currentAudioPieceIndex) {
self.currentAudioPiece = sampleQueue.dequeue;
}
AudioBuffer audioBuffer = ioData->mBuffers[0];
if (true) {
for (int i = 0; i < audioBuffer.mDataByteSize; i++) {
uint8_t rofl[2048];
arc4random_buf(&rofl, 2048);
audioBuffer.mData = rofl;
}
return;
}
//... more code that I'll debug later...'
Essentially I am unable to get a sanity check that a random bunch of memory playing back should make some noise. I think the problem is with "audioBuffer.mData = rofl;". I'm rather confused about working with memory at void*.
jn_pdx is correct, you need to copy/fill mData instead of reassigning it.
- (void)
output:(EZOutput *)output
callbackWithActionFlags:(AudioUnitRenderActionFlags *)ioActionFlags
inTimeStamp:(const AudioTimeStamp *)inTimeStamp
inBusNumber:(UInt32)inBusNumber
inNumberFrames:(UInt32)inNumberFrames
ioData:(AudioBufferList *)ioData {
//grab latest sample from sample queue
if (currentAudioPiece == nil || currentAudioPiece.duration >= currentAudioPieceIndex) {
self.currentAudioPiece = sampleQueue.dequeue;
}
AudioBuffer audioBuffer = ioData->mBuffers[0];
if (true) {
arc4random_buf(audioBuffer.mData, audioBuffer.mDataByteSize);
return;
}

Control may reach end of non-void function error if-statement

I'm getting the error Control may reach end of non-void function on this code:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (changeData.selectedSegmentIndex == 0) {
return self.tweets.count;
} else if (changeData.selectedSegmentIndex == 1) {
return self.tweets1.count;
} else if (changeData.selectedSegmentIndex == 2) {
return self.tweets2.count;
}
}
Why?
Because when your all if condition fails, you are not returning anything from the function.
Also multiple return statement in a function is not a good practice.
Do it like:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int count = 0;
if (changeData.selectedSegmentIndex == 0)
{
count = self.tweets.count;
}
elset if (changeData.selectedSegmentIndex == 1)
{
count = self.tweets1.count;
}
else if (changeData.selectedSegmentIndex == 2)
{
count = self.tweets2.count;
}
return count;
}
Midhun MP has your answer and better code style. I would strongly advice replacing all those nested else-ifs with a switch-statement as, well you don't really want else-ifs if you can avoid them...
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSInteger count = 0;
switch (changeData.selectedSegmentIndex)
{
case 0:
count = self.tweets.count;
break;
case 1:
count = self.tweets1.count;
break;
case 2:
count = self.tweets2.count;
break;
default:
break;
}
return count;
}
If you think its ok disable it:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger count = 0;
if (changeData.selectedSegmentIndex == 0) {
count = self.tweets.count;
} else if (changeData.selectedSegmentIndex == 1) {
count = self.tweets1.count;
} else {
count = self.tweets2.count;
}
return count;
}
or
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger count = 0;
if (changeData.selectedSegmentIndex == 0) {
count = self.tweets.count;
} else if (changeData.selectedSegmentIndex == 1) {
count = self.tweets1.count;
}
else if (changeData.selectedSegmentIndex == 2){
count = self.tweets2.count;
}
return count;
}
While I agree with most answers that suggest to avoid multiple returns in the general, on occasions multiple returns is nice and useful. For instance dispatching on an enum:
#include <iostream>
#include <string>
enum direction { north, east, south, west };
std::string to_string(direction d)
{
switch (d)
{
#define CASE(C) case C: return #C
CASE(north);
CASE(east);
CASE(south);
CASE(west);
#undef CASE
}
}
int main()
{
std::cout << to_string(west) << '\n';
}
If you compile with GCC, you get (C or C++, it's the same):
$ g++-4.9 -Wall foo.cc
foo.cc: In function 'std::string to_string(direction)':
foo.cc:17:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
Clang does not complain. Which is not so nice, actually, since it also compiles this without warnings:
int main()
{
std::cout << to_string(direction(666)) << '\n';
}
which results in:
$ clang++-3.5 -Wall foo.cc
$ ./a.out
zsh: illegal hardware instruction ./a.out
So one has to "fight" GCC's warning. One wrong approach would be to add say
default: abort();
to the switch. Sure, it cures the symptom, but now GCC will no longer complain if I add a new direction, say zenith, but forget to cover it in to_string. So really, never use a default case when switching on an enum.
Then you can leave an abort after the switch (which is clumsy to do without using inner returns).

iOS: Is this an audio-session simulator bug? keywords: kAudioSessionProperty_AudioRoute kAudioSessionUnsupportedPropertyError

can someone confirm whether this is indeed a bug? ( If so I will go off and file it with Apple ).
attempting to fetch kAudioSessionProperty_AudioRoute is returning error code kAudioSessionUnsupportedPropertyError on any version of the simulator prior to 4.3 ( which is the latest version at time of writing ).
this one is dead easy to reproduce.
Start a new project ( I am using Xcode 4.0.2 Build 4A2002a, that is the standard build ), window-based project "AudioSessionBug"
include AudioToolbox framework
replace the application delegate's .m file with the following:
//
// AudioSessionBugAppDelegate.m
// AudioSessionBug
//
// Created by Pi on 02/07/2011.
// Copyright 2011 Pi. All rights reserved.
//
#import "AudioSessionBugAppDelegate.h"
#import <AudioToolbox/AudioToolbox.h>
#define SET_PROPERTY( prop, type, val ) \
{ \
OSStatus ret = AudioSessionSetProperty( prop, sizeof( type ), &(type){ val } ); \
if ( ret != kAudioSessionNoError ) \
{ \
NSLog( #"AudioSessionSETProperty failed for: %s!", #prop ); \
return; \
} \
}
enum {
kNo = 0,
kYes = 1
};
// - - -
#interface AudioSessionBugAppDelegate ( )
- (void) setupSession;
#end
// - - -
#implementation AudioSessionBugAppDelegate
#synthesize window=_window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
[self.window makeKeyAndVisible];
[self setupSession];
return YES;
}
- (void) setupSession
{
OSStatus result = AudioSessionInitialize( NULL, NULL, NULL, NULL );
assert( result == kAudioSessionNoError );
SET_PROPERTY( kAudioSessionProperty_AudioCategory, UInt32, kAudioSessionCategory_PlayAndRecord );
// make sure headphones are plugged in!
{
// http://stackoverflow.com/questions/2753562/what-kind-of-routes-could-i-get-back-from-kaudiosessionproperty-audioroute-proper
CFStringRef state = nil;
UInt32 propertySize = sizeof(CFStringRef);
OSStatus status = AudioSessionGetProperty( kAudioSessionProperty_AudioRoute, &propertySize, &state );
if ( status == kAudioSessionUnsupportedPropertyError )
{
NSLog( #" WTF? GETTING kAudioSessionProperty_AudioRoute GIVES kAudioSessionUnsupportedPropertyError ?!?!? " );
}
NSLog( #" OK - done! " );
exit( 1 );
}
}
- (void)dealloc
{
[_window release];
[super dealloc];
}
#end
check that it works.
now change deployment target to anything prior to 4.3. say 4.2.
run it again on iPad simulator 4.3 -- OK
run it again on iPad simulator 4.2 -- FAIL
I just received the following confirmation from Apple:
This was a bug that was fixed in 4.3 and we currently have no plans to fix bugs in earlier builds of the simulator.

Resources