Introduction
In our last lesson, you learned the powerful technique of creating your own custom functions, and we built a practical CalculateLotSize function. You saw how functions can package a specific task into a reusable block, making your code cleaner and more efficient.
This lesson builds directly on that foundation by exploring a crucial concept: variable scope. We will answer the question, "Where in my code can I access a particular variable?" You will learn to distinguish between local variables, which live only inside a specific function, and global variables, which are accessible throughout your entire program. Understanding this difference is essential for preventing bugs and building reliable trading bots, as it governs how data is stored and shared within your code.
Where Does a Variable "Live"? Understanding Scope
In programming, "scope" refers to the region of your code where a variable is visible and can be used. Think of your program as a house. Some items belong in a specific room (like a toothbrush in the bathroom), while others are available to everyone in the house (like the thermostat in the hallway).
- A local variable is like the toothbrush. It exists and is used only within one specific room (a function).
- A global variable is like the thermostat. It can be seen and adjusted from any room in the house (any function in your program).
Let's formalize this idea slightly.
Context, scope, and lifetime of variables - Programming fundamentals - MQL5 Programming for Traders
This text from the official MQL5 book introduces the idea of code blocks and context, which are the foundations of variable scope.
Read the entire section. Pay attention to how curly braces {} create a local context (a "room") and how the area outside of all functions is the global context (the "house").
Local Variables: The Temporary Helpers
A local variable is declared inside a function's curly braces {}. Its existence is tied to that function.
Key Characteristics:
- Visibility: It is only accessible from within the function where it is defined.
- Lifetime: It is created when the function is called and destroyed as soon as the function finishes its job.
In the previous lesson, all the variables inside our CalculateLotSize function—like accountBalance, riskAmount, and lotSize—were local variables. They were created to help with the calculation and then discarded.
The video below gives a very clear explanation of this concept.
MQL5 Programming Tutorial 1.04 - Core Building Blocks Part 1 - Variables and Comments
The presenter in this "Toolkit for Traders" video provides an excellent summary of the difference between local and global variables.
Watch the segment from this timestamp. The speaker explains how a local variable, like the spread variable he created in his function, is temporary. It is created, used, and then disappears when the function is done. This isolation is a key feature.
Attempting to use a local variable outside its function will result in a compiler error because, from the outside, the variable simply doesn't exist.
Global Variables: The Shared State
A global variable is declared outside of all functions, typically at the very top of your script file.
Key Characteristics:
- Visibility: It can be accessed and modified from any function in your program (
OnStart,OnTick, or any custom function you create). - Lifetime: It is created when the program starts and exists until the program stops.
This makes global variables useful for storing information that needs to be shared or maintained across different parts of your code, such as user settings, a running count, or a trade's magic number.
The image below shows a perfect example of the distinction in code.

Let's see this in a more practical context for building an Expert Advisor (EA).
Range Breakout Expert Advisor Coding Tutorial for MT5 (mql5 Class)
In this video, developer René Balke builds an EA and uses global variables to manage its settings. This directly relates to your goal of building bots.
First, watch from this section, where he creates input variables. He explicitly states that they must be declared outside of the functions. These input variables are a special type of global variable that you can change from the EA's settings panel. Then, watch this part, where he creates more variables and again notes that because they are outside any function, they are automatically global variables that can be used anywhere.
A Practical Demonstration
Let's write a script to solidify this difference. Open MetaEditor and create a new script named ScopeTest.
-
Declare a Global Variable: At the very top of the file, before
OnStart(), declare a global counter.// Global variable - accessible everywhere int g_tradeCounter = 0;(Note: Prefixing global variables with "g_" is a common convention to make them easy to identify. It's good practice, but not a requirement of the language.)
-
Define a Custom Function: Below the
OnStart()function, create a function that simulates executing a trade.void SimulateTrade() { // Local variable - only exists inside this function string tradeResult = "Success"; // Modify the global variable g_tradeCounter = g_tradeCounter + 1; // Print both variables Print("SimulateTrade: Trade result is ", tradeResult, ". Total trades: ", g_tradeCounter); }Notice that
SimulateTradecan both define its own local variable (tradeResult) and access the global variable (g_tradeCounter). -
Use Them in
OnStart(): Now, update yourOnStart()function to call your new function and see what happens.void OnStart() { Print("OnStart: Starting trade simulation. Initial count: ", g_tradeCounter); SimulateTrade(); SimulateTrade(); Print("OnStart: Simulation finished. Final count: ", g_tradeCounter); // The following line will cause an error if you uncomment it! // Print(tradeResult); // Error: 'tradeResult' - undeclared identifier }The variable
tradeResultis local toSimulateTrade(), soOnStart()has no idea it exists. If you were to remove the//and compile, you would get an error. However,g_tradeCounteris global, so its value is preserved between the calls toSimulateTrade().
Compile and run your script. In the "Experts" tab, you will see the g_tradeCounter incrementing and persisting, demonstrating its global nature.
When to Use Which? A Core Principle
The distinction between local and global scope is not just academic; it's fundamental to writing good code.
MQL5 Variables: Choosing the Right Type for Algorithmic Trading - Trade Pretty
This article from Trade Pretty offers a concise summary and a crucial piece of advice.
First, read the section "Variable Scope" for a clear, side-by-side definition of global and local variables. Then, jump to the "Best Practices" section and read the point on limiting global variables.
As the article states, you should prefer local variables whenever possible. This practice, known as limiting scope, keeps your functions self-contained and prevents one part of your program from accidentally changing a value used by another part. Overusing global variables can make your code difficult to debug because it becomes hard to track where and when a variable's value is being modified.
Use global variables only when you have a clear reason for data to be shared across your entire bot, such as:
- User-configurable settings (
inputvariables). - A magic number to identify your EA's trades.
- Information that needs to persist between ticks, like the ticket number of an open trade.
Conclusion
In this lesson, you've grasped one of the most important organizational principles in programming: variable scope.
Key Takeaways:
- Scope determines where a variable can be accessed.
- Local variables are declared inside a function. They are temporary and private to that function, which is generally a good thing.
- Global variables are declared outside all functions. They are permanent and accessible everywhere in your program.
- As a best practice, you should always default to using local variables and only use global variables when you specifically need to share data across different functions.
This knowledge will be invaluable as you start building more complex logic. In our next lesson, we will continue expanding your toolkit by learning how to call MQL5's powerful built-in functions to retrieve account information, market data, and more.