Our partnerSkilling
  • Spreads from 0.1 pips
  • 1,000+ instruments
  • Free demo account

65% of retail investor accounts lose money when trading CFDs with this provider.

Open account
Module 2 · Programming for traders

2.1 Basics: variables, conditions and functions

Lesson 4 of 19Reading time: 2 min

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.

MQL5
int    period = 14;        // whole number
double price  = 1.08452;   // decimal number
bool   isBuy  = true;      // true or false
string name   = "My Algo"; // text

Everything 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].

MQL5
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”.

MQL5
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.

MQL5
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: Price and price are 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.
Practise what you have learned – without riskTry it on a free demo account with Skilling, with real prices and virtual money.
Open a free demo account

65% of retail investor accounts lose money when trading CFDs with this provider.