Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 10

Understanding OnStart() in MQL5

Recommended resources

Introduction

Welcome to a new module! In the previous lessons, you mastered the fundamental building blocks of programming: variables, operators, if-else statements for decisions, and loops (for and while) for repetition. You now have the tools to write a sequence of commands to perform a task.

Now, we'll shift our focus to organizing that code. Instead of one long list of instructions, real-world programs group related code into logical, reusable blocks called functions. You've already been using them without even thinking about it—every script you've written has been inside a function called OnStart(), and you've used built-in functions like Print().

In this lesson, we will demystify this core component. We will explore the precise purpose of the OnStart() event handler and understand its unique role in MQL5. This is the first step toward structuring your code for the more complex trading bots you aim to build.


MQL5 Programs: More Than Just Bots

First, it's important to understand that MQL5 can create several different types of programs, each with a specific purpose. So far, we've been writing Scripts. Your ultimate goal is to build an Expert Advisor (EA), or a trading bot. These program types behave differently.

Let's clarify what distinguishes them.

Master MQL5 from beginner to pro (Part I): Getting started ...

This article from the official MQL5 site provides a clear breakdown of the different program types.

Start by reading the section "Main types of MQL5 programs". Then, carefully examine Table 1, which provides a side-by-side comparison of their capabilities. Pay special attention to the rows "Executed on every tick" and "Run while the chart window is open". Notice the key difference: Scripts run once, while Expert Advisors and Indicators run continuously.

As you can see, a Script is designed for a one-time execution. You run it, it performs its task from start to finish, and then it stops. This is perfect for tasks like placing a single complex order, closing all open positions, or running a quick calculation.

In contrast, an Expert Advisor is designed to run continuously on a chart, reacting to market events over and over again. This is what you need for a trading bot that constantly monitors prices.


OnStart(): The Entry Point for Scripts

Because scripts are designed to run once, the MQL5 environment needs to know where the program's instructions begin. This starting point is a special function called an event handler. It's a function that is automatically called by the MetaTrader platform in response to a specific event.

For scripts, the event is simple: "the user has started the script." The function that handles this event is OnStart().

Think of it as the main entrance to your program. When you run a script, MetaTrader looks for the OnStart() function and executes whatever code you've placed inside its curly braces {}.

This next resource from the official MQL5 book gives a concise, formal definition.

The main function of scripts and services: OnStart - Creating application programs - MQL5 Programming for Traders

This official documentation page explains the role of OnStart() directly.

Read the entire page. The key concept to grasp is that OnStart() serves as the entry point for a script. It's the designated beginning of your program's execution.


Anatomy of the OnStart() Function

Let's look at the structure you've seen in every script so far:

void OnStart()
{
  // Your code goes here
}

Let's break this down:

  • void: This keyword means the function doesn't return any value or report back to MetaTrader after it's done. It just performs its tasks and finishes.
  • OnStart: This is the special, reserved name that MetaTrader looks for when a script is launched. You cannot rename it.
  • (): The empty parentheses mean that this function doesn't require any information from the platform to run.
  • { ... }: The curly braces define the body of the function. All the code that you want to be executed when the script runs—variable declarations, loops, Print() calls—must be placed inside these braces.

Let's Build a Script... Again!

The best way to solidify this is to see it in action. You've done this before, but this time, pay close attention to the structure that MetaEditor creates for you.

Follow the steps in this guide to create a new script.

Master MQL5 from beginner to pro (Part I): Getting started ...

This part of the article walks you through the MQL5 Wizard to create a new script file.

Follow the steps under the heading "First script" to create a new script file. Name it OnStart_Test. When the wizard is done, look at the code it generated for you. Notice that it automatically creates the OnStart function, complete with a comment above it: //| Script program start function |. Now, add a single line of code inside the OnStart function, as shown in the article's Example 5: Print("Hello from OnStart!");

After you've added the Print() line, press the Compile button (or F7). If there are no errors, the log at the bottom will confirm the code was generated, just like in the image below.

This image shows a basic MQL5 script with the `OnStart()` function and the confirmation message in the compiler log indicating a successful build with "0 errors, 0 warnings".

Now, go to your MetaTrader 5 terminal, find your OnStart_Test script in the Navigator panel, and drag it onto a chart. Check the "Experts" tab in the Toolbox (Ctrl+T). You will see your "Hello from OnStart!" message printed once. The script has done its job and is no longer running.

This confirms the purpose of OnStart(): it's a container for a sequence of instructions that are executed exactly one time when the script is launched.


A Glimpse into Expert Advisors: OnTick()

To fully appreciate the role of OnStart(), it's helpful to contrast it with the main event handler used in Expert Advisors: OnTick().

  • OnStart() runs once when a script is started.
  • OnTick() runs repeatedly, every single time a new price update (a "tick") is received for the symbol on the chart.

This is the fundamental difference that makes EAs suitable for automated trading. Their logic isn't executed just once; it's re-evaluated with every flicker of the market.

Watch this brief explanation of the three main functions in an EA.

LEARN MQL5 TUTORIAL BASICS - 2 WHAT ARE FUNCTIONS

This video from MQL5 Tutorial introduces the key functions of an Expert Advisor.

Pay attention to the description of the three functions: OnInit: This is the EA's initialization function. It runs once when the EA starts, similar to OnStart(). OnDeinit: This runs once when the EA is stopped. OnTick: This is the most important one. Notice the presenter states it runs "whenever a price changes on the chart."

Understanding this distinction is critical. For a one-off task, you use a script with OnStart(). For a continuous trading strategy, you will use an Expert Advisor with OnInit() for setup and OnTick() for the core trading logic. We will dive deep into OnTick() in a later module.


Conclusion

In this lesson, you've taken your first step into creating structured, organized MQL5 programs. You now understand the specific and essential role of the OnStart() function.

Key Takeaways:

  • MQL5 has different program types, including Scripts (for one-time tasks) and Expert Advisors (for continuous trading).
  • Event handlers are special functions that are automatically run by MetaTrader in response to platform events.
  • OnStart() is the event handler for scripts. It serves as the entry point and its code is executed exactly once when the script is launched.
  • The OnStart() function is distinct from an EA's main logic function, OnTick(), which runs repeatedly with every new price update.

You now see that OnStart() isn't just some boilerplate code; it's the fundamental structure that defines how a script operates. In our next lesson, we will build on this foundation by learning how to define your own custom functions, giving you the power to create modular and efficient code.