2.2 How a robot is built
A robot is not a program that runs from top to bottom and stops. It waits for events – and the platform calls the right function when something happens.
The events
| Event | MetaTrader (MQL4/MQL5) | cTrader (C#) |
|---|---|---|
| The robot starts | OnInit() | OnStart() |
| New price | OnTick() | OnTick() |
| New candle | Must be checked yourself in OnTick() | OnBar() |
| The robot stops | OnDeinit() | OnStop() |
New candle in MetaTrader
MetaTrader has no separate event for a new candle. So we check ourselves whether the time of candle 0 has changed:
datetime lastBarTime = 0;
void OnTick()
{
datetime barTime = iTime(_Symbol, _Period, 0);
if(barTime == lastBarTime) return; // same candle as last time: do nothing
lastBarTime = barTime;
// here we look for new signals – once per candle
}return means “leave the function here”. So the code below only runs once per candle.
New candle in cTrader
In cTrader it is simpler. OnBar() is called automatically every time a new candle starts:
protected override void OnBar()
{
// here we look for new signals – once per candle
}What goes where?
- OnInit / OnStart: Create indicators and check settings.
- OnTick: Things that must happen continuously – for example a trailing stop.
- New candle: Read signals and open trades.
- OnDeinit / OnStop: Clean up.
Why not look for signals on every price?
There can be many price changes per second. If the robot looks for signals on every one of them, it can open several trades on the same signal – and the result depends on how many price changes arrived. By only looking for signals on a new candle, the robot becomes predictable, and the tests become more reliable.
In plain words
A trading robot is like a recipe. OnInit is getting the ingredients out, OnTick is checking the pot every moment, and OnDeinit is cleaning the kitchen afterwards.
Try it yourself
Find OnInit, OnTick and OnDeinit in an MQL5 robot. Write one sentence about what each part does.
Key takeaways
- A robot reacts to events: start, new price, new candle and stop.
- In MetaTrader you check yourself whether a new candle has started. In cTrader OnBar is used.
- Look for signals once per candle – that makes the robot predictable.
65% of retail investor accounts lose money when trading CFDs with this provider.