2.1 Basics: variables, conditions and functions
You do not need to be a programmer to build a simple robot. You need four building blocks. The examples are in MQL5, but they look almost the same in MQL4 and C#.
1. Variables and types
A variable is a named box that holds a value. Each variable has a type that says what kind of value it can hold.
int period = 14; // whole number
double price = 1.08452; // decimal number
bool isBuy = true; // true or false
string name = "My Algo"; // textEverything after // is a comment. It is for humans – the computer skips it.
2. Input parameters
The word input turns a variable into a setting you can change in the platform without touching the code. In cTrader you do the same with [Parameter].
input int InpFastPeriod = 10; // Fast MA
input double InpRiskPercent = 1.0; // Risk per trade in %3. Conditions
With if the robot decides what to do. && means “and”, || means “or”, and ! means “not”.
if(fast1 > slow1 && fast2 <= slow2)
{
// fast MA has crossed above slow MA: buy
}
else if(fast1 < slow1 && fast2 >= slow2)
{
// crossed below: sell
}4. Functions
A function is a named block of code that does one job. It can take values in and give an answer back.
double PipsToPrice(double pips)
{
return(pips * 10 * _Point); // on a 5-decimal currency pair
}Semicolons and curly brackets
- Every instruction ends with a semicolon
;. - Curly brackets
{ }group several lines into one block. - Upper and lower case matter:
Priceandpriceare two different variables.
The most common mistakes
Almost all errors beginners get when they compile are caused by a missing semicolon, a curly bracket that is not closed, or a typo in a variable name. The error message says which line it is – start there, and look at the line above.
Try it yourself
Find one variable, one condition and one function in the code from the algo builder. What does each of them do?
Key takeaways
- Variables hold values, and the type says what kind of value.
- input (MQL) and [Parameter] (cTrader) turn variables into settings.
- if decides what the robot does, and functions group code that does one job.
65% of retail investor accounts lose money when trading CFDs with this provider.