Understanding Variables in MQL4: A Practical Guide for MetaTrader Programmers
Camovia Tray Team · 2026-09-11
Have you ever attached an Expert Advisor to a chart, changed a single parameter in the input window, and wondered exactly how those values flow through your code? Or perhaps you've been confused by why a variable that should track your trade count keeps resetting to zero? Understanding how variables work in MQL4 is the foundation of writing reliable trading robots and indicators, yet it's one of the most common stumbling blocks for new MetaTrader programmers. Let's break down the variable types you'll encounter and—more importantly—how they behave at runtime.
The Two Fundamental Scopes: Global vs. Local
At the highest level, every variable in MQL4 belongs to one of two scopes: global or local. A variable declared outside all functions belongs to the global scope, making it accessible from anywhere in your program. These variables live in the global memory pool for the entire lifetime of your EA or indicator.
Local variables, by contrast, are declared inside a block of code (enclosed in curly braces). The most common example is variables declared within a function. These variables are only visible within that block, and they live on the stack—meaning their lifetime matches the function's execution. When the function exits, the variable disappears.
This might sound straightforward, but the real-world implications can be subtle. Consider this classic mistake:
int start()
{
int Tick = 0;
Tick++;
Comment("Received: tick No ", Tick);
} Every time the start() function executes, Tick is reinitialized to zero and then incremented to one. The comment will always display "1". If you want a counter that persists across function calls, you need a different approach.
Static Variables: Persistent Local Memory
The solution to the resetting counter problem is the static modifier. When you declare a local variable as static, the compiler places it in permanent program memory rather than on the stack. Its value is preserved between function calls, yet its scope remains limited to the function where it's declared—it's not visible to other parts of your program.
int start()
{
static int Tick = 0;
Tick++;
Comment("Received: tick No ", Tick);
} Now Tick will increment properly on each tick. Static variables are initialized only once, and if you don't provide an explicit initial value, they're set to zero by default.
The distinction matters for code clarity and reliability. Global variables are visible everywhere, which can lead to unintended interactions if you're not careful. Static variables give you persistence without the risk of other functions accidentally modifying the value.
Extern Variables: Making Parameters Adjustable
This is where MQL4 variables become genuinely practical for day-to-day trading. extern variables let you expose parameters to the user through the program properties window. When you attach an EA to a chart, any variable declared with the extern modifier appears as an adjustable input—and these values can be changed while the EA is running, not just at startup.
extern double Level = 1.2500;
extern int Points = 30; These declarations must appear outside all functions, typically near the top of your file. A user can modify these values in the program properties window, and the EA will use the new values without needing to be reattached.
The practical benefit here is straightforward: you can tune your EA's behavior based on market conditions without editing and recompiling code. A price level alert EA, for instance, might use extern variables to let traders adjust the trigger level and confirmation distance on the fly.
Global Variables at the Terminal Level
There's another category worth understanding: terminal-level global variables. These are accessed via functions like GlobalVariableCheck(), GlobalVariableSet(), and GlobalVariableGet(). Unlike the variables discussed above, these exist at the MetaTrader client terminal level and can be shared between multiple EAs running simultaneously.
The classic use case is a semaphore pattern for preventing two EAs from sending orders at the same moment:
while (GlobalVariableCheck("InTrade")) {
Sleep(1000);
}
GlobalVariableSet("InTrade", 1);
res = OrderSend(...);
GlobalVariableDel("InTrade"); This approach works across independent EAs on different charts—something ordinary global variables can't achieve.
Initialization Behavior: When Does a Global Variable Reset?
Here's a subtle point that trips up many developers: global variables are not reinitialized every time you open the program properties window. If you define:
int i = 0; ...you might expect i to reset to zero whenever the EA is initialized. But if you open properties, click OK, and the init() function is called, the global variable retains its old value. The initialization only happens when the EA is first loaded or recompiled, not on every property change.
This behavior can be surprising. If you need a variable to reset on each initialization, you should set it explicitly in the init() function. Understanding this nuance prevents those moments where your EA seems to "remember" something you expected it to forget.
Practical Implications for Your Workflow
So how does this knowledge apply when you're actively trading? If you're managing multiple EAs, testing different parameter sets, or monitoring open positions across several charts, you might find yourself frequently opening and closing the MetaTrader terminal, adjusting settings, and reattaching programs. Each time you do, variables behave according to these rules—and if you're not tracking which variables are persistent and which are transient, you might misinterpret your EA's behavior.
For traders who spend significant time fine-tuning EAs, having quick, convenient access to position data without opening the full terminal becomes a real workflow advantage. Being able to check your open orders, see current P&L, and confirm that your EA's variables are tracking as expected—all from the system tray—saves the cognitive overhead of navigating through multiple terminal windows. Tools that keep you connected to your trading state without demanding constant visual attention fit naturally into this kind of development and monitoring cycle.
Common Mistakes and Best Practices
The most frequent errors with variables in MQL4 involve scope confusion. Declaring variables at the wrong level, expecting persistence where none exists, or forgetting that extern parameters can be changed at runtime are all common.
A few practices that help:
- Use the
staticmodifier when you need persistence within a function but want to limit visibility - Place
externdeclarations near the top of your file for easy access - Initialize global variables explicitly in
init()if you need them to reset on each attachment - Use terminal-level global variables for coordination between separate EAs
If you're actively developing and testing EAs, you'll likely find yourself attaching and detaching programs frequently, adjusting extern parameters, and monitoring results. This is where having a lightweight way to keep an eye on your positions and orders—without constantly switching to the terminal window—makes the development loop smoother. It's not about replacing the terminal, but about staying focused on your code and strategy while still maintaining awareness of what's happening in the market.
Understanding variables in MQL4 isn't just about syntax—it's about knowing how your code will behave at runtime, in the real trading environment where market conditions, user interactions, and multiple programs all interact. That knowledge is what separates code that works from code that works reliably.
Turn MT5 / MT4 into a Tray Tool
Check quotes, manage positions, and hide in one click.
Download Camovia TrayFrequently Asked Questions
Is the MT4 bridge EA safe? What do I need to enable?
Yes. The bridge EA (CamoviaBridge) is bundled with the app - it only reads quotes/positions locally and executes close commands; no DLLs, no data uploads. Closing positions requires turning on AutoTrading in the MT4 toolbar.
How much does it cost? Is there a free trial?
Subscription pricing starts at $2.49/month (also $6.99/3 months, $13.49/6 months, $23.99/year), all plans with full features. New users can try it free before subscribing.
How do I restore the MT5/MT4 window after hiding it?
Choose "Show MT5/MT4" from the system tray menu and the window returns to its previous position. You can also hover the tray to check quotes and manage positions without opening the terminal.
Can it replace MT5/MT4 for trading?
No - Camovia Tray is a local shortcut tool. You can close positions right from the popup; all trading operations (opening, closing, etc.) are submitted by your local MT5/MT4 terminal to your own broker account. The app does not hold your funds or provide investment advice.
Popular Symbols Trading Hours
Open/close times, weekend hours & live market status:
Related Articles
Best MT5 Risk-Reward Tools: Beyond the Chart, Toward Seamless Trade Management
Discover how Camovia Tray transforms MT5/MT4 into a discreet tray tool for monitoring active risk-reward outcomes, managing open positions, and protecting your privacy.
MT5 Login Problem Explained: Why You Can't Log In and How to Fix It
Struggling with the MT5 login problem? Learn why you can't log in and how to fix it. Camovia Tray keeps you connected by turning MT5 into a tray tool—check quotes and manage positions without reopening the terminal.
MT4 vs MT5 for Beginners: Which Trading Platform Should You Start With?
Compare MT4 vs MT5 for beginners and find the right trading platform. Learn key differences, which one suits your goals, and how Camovia Tray helps you monitor both from the system tray.
Slippage Impact on Prop Trading Performance: Why Your Backtest Is Lying to You
Learn how slippage impacts prop trading performance and why backtests fail. Camovia Tray helps you monitor positions and manage risk from the system tray.
How to Track Drawdown in MT5/MT4 Without Ever Opening the Platform
Transform how you track drawdown in MT5/MT4. Camovia Tray lets you monitor open positions and floating drawdown from the system tray—no need to open the terminal. Real-time risk visibility, one-click position management, and total privacy. All data stays local.