In this video we want to talk about simple calculations, obviously when you use an Expert Advisor like this one to do automated trading you need to do some calculations.

For example, in my case I have calculated the max number of positions that are allowed and you see that the currency pair profit is calculated, so let’s find out how to do some basic calculations!

To do that please click on the little icon here or press F4 to open your Metaeditor window and here you want to click on: “File/ New/ Expert Advisor (template)” from template, “Continue”, I will call this file: ”SimpleCalculations”, click on “Continue”, “Continue” and “Finish” and now you can delete everything above the “OnTick” function here, let’s also remove the two comment lines.

First we need two “int” variables; “a” equals 5 and “b” equals 3, we use “Comment” to output the result from “a” plus “b”.

Let’s click the “Compile” button here, we don’t have any errors so now we can click here or press F4 to go back to Metatrader.

In Metatrader we click on: “View/ Strategy Tester”, let’s pick the new “SimpleCalculations.ex5” file, enable the visualization mode and start your test, and here is the output, the result is 8 because 5 plus 3 is 8, so let’s use the next one; “a” minus “b”, recompile, start a new test and this time our result is 2 because 5 minus 3 is 2. 

Let’s multiply the two values; 5 times 3, recompile and this time the result is 15.  We can also divide, “a” divided by “b”, what do you think? 

Oh, the result is 1! – and the reason is: 5 divided by 3 is 1 because we used integer variables! So we have no floating type values here and that’s where most people get crazy because results don’t match what they expect, so let’s use “double” as a data type, recompile and this time the result is 1.6666666667, that is better!

What would you think is the results if you calculate “a” plus “a” times “b”?

“a” is 5, so “a” plus “a” would be 10, “b” is 3, so 3 times 10 would be 30.

Let’s compile it and our result is 20! – and the reason is that multiplication or division is always calculated first! If you want to change that you need to use brackets because what’s inside the brackets is calculated even before multiplication or division and this time our result is 30! 

If you press F1 and open the MQL5 Reference you will find lots of other math functions and I would suggest that you write little programs like this one to find out how they work because in the future you will have more complicated calculations and that makes it even harder to find out what is working and why, but in this short video you have learned how to do very basic math calculations and you have done it yourself with a few lines of MQL5 code.


SimpleCalculations.mq5 – Downloaded 53 times – 115.00 B