Your First MQL Script: Reading the Chart
Write your first real MQL program. We'll read price, compute a moving average, and print a signal — the building blocks every trading bot is made of.
MQL (MetaQuotes Language) is the C-like language that powers MetaTrader bots. You don't need to be a programmer to start — you need to understand three ideas: events, series, and functions. We'll use all three in a few lines.
Events: code that runs when something happens#
An MQL program hooks into events the platform fires. The most important is OnTick() —
called every time the price updates:
// Runs once when the program starts
void OnInit()
{
Print("Script started on ", _Symbol);
}
// Runs on every new price tick
void OnTick()
{
double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
Print("Current bid: ", price);
}
Load that onto a chart and it prints the live price on every tick. That's a working MQL program — no magic.
Series: price is an array#
Historical prices are arrays indexed from the most recent bar backwards. Close[0] is the
current bar, Close[1] the one before, and so on. Indicators work the same way.
Putting it together: a moving-average signal#
void OnTick()
{
// 20-period and 50-period moving averages on the current symbol
double fast = iMA(_Symbol, PERIOD_CURRENT, 20, 0, MODE_EMA, PRICE_CLOSE, 0);
double slow = iMA(_Symbol, PERIOD_CURRENT, 50, 0, MODE_EMA, PRICE_CLOSE, 0);
if (fast > slow)
Print("Uptrend: fast EMA above slow EMA");
else
Print("Downtrend: fast EMA below slow EMA");
}
This is the heartbeat of a trend-following bot. Swap the Print calls for order commands
and you have an Expert Advisor — but never do that before you've
backtested the logic.
What you just learned#
- Code runs in response to events (
OnInit,OnTick). - Price and indicators are series you index from the current bar back.
- Built-in functions like
iMA()do the heavy lifting.
From here, every trading bot is just more rules stacked on these same bones. For more, browse the MetaTrader articles and our latest writing.