Overview
In MQL5, a script is a simple program designed to perform a single action and then terminate. Unlike Expert Advisors (EAs), which run continuously with every new market tick, a script executes its code only once when launched. Scripts are ideal for quick operations such as sending a message to the log, closing all trades, or performing calculations that do not require constant updates. This section will guide you through creating and running your first MQL5 script.
What You Will Be Able to Do
- Understand the structure and purpose of MQL5 scripts.
- Create a new script using MetaEditor.
- Compile and execute the script within MetaTrader 5.
- Read and verify the output message in the Experts log window.
Code Example
//+------------------------------------------------------------------+
//| MyFirstScript.mq5 |
//+------------------------------------------------------------------+
#property version "1.00"
#property strict
void OnStart()
{
// This function runs once when the script starts
Print("My first MQL5 script is running!");
}
Execution Steps
- Open MetaEditor from MetaTrader 5 (press F4).
- Select File → New → Script to start the MQL5 Wizard.
- Enter the script name
MyFirstScriptand click Finish. - Paste the sample code shown above into the editor window.
- Press F7 to compile the code. If successful, you will see “0 error(s), 0 warning(s)” in the Toolbox.
- In MetaTrader 5, open any chart and drag
MyFirstScriptfrom the Navigator → Scripts section onto the chart. - Check the Experts tab at the bottom of MetaTrader to confirm the message “My first MQL5 script is running!” appears.
Key Point
Scripts always begin execution with the OnStart() function and stop automatically once the code inside it finishes. They are best suited for one-time tasks, such as modifying trade positions, exporting data, or testing short pieces of code. As you progress, you’ll find scripts useful for both learning MQL5 and performing small maintenance operations in your trading workflow.


