How to Create a Forex EA part 9 - The #1 Blog on trading, personal investing! Best Tips for Beginners

Header Ads

How to Create a Forex EA part 9

In this tutorial article, I’ll zoom in on the if-else compound operator with a few examples and its proper syntax so that you can apply it in your forex EA coding. As I’ve briefly mentioned in my overview on compound operators, the if-else statement gives a certain set of commands to be executed when specific conditions are met.
Its proper syntax goes:
If (conditions)
{
Expressions or functions to be executed;
}
Else
{
Expressions or functions to be executed;
}
For this compound operator to check if conditions are met, it could make use of relational and logical operations. Better dig up your notes on the 5 Basic Operations You Need in Building a Forex EA if you can’t remember how these work!
Let’s start off with a simple relational operation. For instance, say your risk management rules state that your system should have a maximum of five open trades at a time. Before you let your forex EA set orders or take new trades, you can use an if-else statement to check if the number of open positions is still within your limit like so:
If (OpenTrades < 5)
{
Create a new order or open a new trade;
}
As I’ve also discussed previously, the ‘else’ component can be excluded if you don’t really have any commands you’d like to execute if the conditions aren’t met.
Next up, logical operators make things more interesting, as these allow you to combine two or more conditions that must be met before executing the commands contained within the curly braces.
For example, if you’re working with a moving average crossover forex system and you’d like to open trades or set orders after a crossover takes place, you could use logical operators to make sure that BOTH conditions are met. In particular, to see if an upward crossover takes place, the forex EA should check if the previous value of the faster MA is below the previous value of the slower MA then the current value of the faster MA is above the current value of the slower MA.
If (PreviousFastMA < PreviousSlowMA && CurrentFastMA > CurrentSlowMA)
{
Open a long trade or set a buy limit order;
}
Similarly, the forex EA would ensure that a downward crossover would take place if the previous value of the faster MA is above the previous value of the slower MA then the current value of the faster MA is below the current value of the slower MA.
If (PreviousFastMA > PreviousSlowMA && CurrentFastMA < CurrentSlowMA)
{
Open a short trade or set a sell stop order;
}
Now you can also use logical operators to see if only one condition is met and run the expressions or functions in the curly brackets anyway. This can be applied for forex EAs with multiple technical indicators that only need one confirmation before buy or sell orders are created.