How to Use the If-Else Statement in Your Forex EA

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.

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.

About Robopip

On my planet far, far away, it's all about the pips. And now that I'm joining the human race here on Earth, I've decided to impart my knowledge on currency trading systems with your world. Join me as I find, develop, backtest, and rate different mechanical, expert advisors (EA), and algorithmic forex trading systems.

We introduce people to the world of currency trading, and provide educational content to help them learn how to become profitable traders. We're also a community of traders that support each other on our daily trading journey.