Introduction
Every experienced MetaTrader developer eventually hits the wall where two Expert Advisors need to talk to each other, or a script needs to remember something from last week's run. That's where Global Variables come in. Unlike regular MQL variables that vanish when your program stops, Global Variables persist in the MetaTrader terminal's memory and are accessible by any EA, script, or indicator running on the same platform instance.
In this guide, you'll learn what Global Variables are, how to set, read, and delete them from MQL4/MQL5 code, how to use them for cross-EA coordination, and how to avoid the common pitfalls that cause headaches. By the end, you'll be able to implement reliable inter-program communication in your automated trading setup.
Prerequisites
- MetaTrader 4 or 5 (any build, but build 1200+ for MT4 is preferred for best compatibility)
- MetaEditor installed (comes with the platform; open via F4 in MT4/MT5)
- At least one running EA or script to test with — ideally two EAs on different charts for cross-communication testing
- Basic MQL knowledge (knowing how to compile and attach an EA, and basic syntax like
ifstatements and loops)
No special accounts or files are needed — Global Variables are a built-in feature of the terminal itself. You can also view all current Global Variables directly in the terminal: in MT4, go to Tools → Global Variables; in MT5, it's under Tools → Options → Expert Advisors → Global Variables tab (or use the Navigator panel's "Global Variables" section).
What Are Global Variables in MetaTrader?
Global Variables (often abbreviated as GV in MQL communities) are name-value pairs stored in the MetaTrader terminal's memory. They are not saved to disk by default in MT4, meaning they disappear when you close the terminal. However, you can use the GlobalVariableSave() function in MQL4 to persist them. In MT5, Global Variables are always persistent across terminal restarts — they're automatically saved to the file global_variables.dat in the \MQL5\Files\ folder of your terminal data directory.
Each Global Variable has a unique string name (case-insensitive) and a double-precision floating-point value. The name can be up to 255 characters and can include any ASCII characters except the null character. Common naming conventions include prefixes like "EA_MyEA_LastTradeTime" to avoid collisions. The value is stored as a double (8-byte floating point), which means you can store integers, timestamps, prices, or any numeric data. For boolean flags, use 1.0 for true and 0.0 for false.
Key Differences: MT4 vs MT5
| Feature | MT4 | MT5 |
|---|---|---|
| Persistence | Only when saved via GlobalVariableSave() |
Always persistent across restarts |
| Maximum number | 1024 (hard limit) | Unlimited (memory-based) |
| Temporary variables | GlobalVariableTemp() available |
Not needed (all persist) |
| Atomic compare-and-swap | GlobalVariableSetOnCondition() supports double values |
Same function, but only compares by exact double value |
| Viewing in terminal | Tools → Global Variables | Tools → Options → Expert Advisors → Global Variables tab |
Step-by-Step: Working with Global Variables in MQL4/MQL5
Step 1: Setting a Global Variable
To create or update a Global Variable, use the GlobalVariableSet() function. The syntax is identical in MQL4 and MQL5:
bool GlobalVariableSet(
string name, // variable name
double value // value to set
);
The function returns true if successful, false if it fails (e.g., if the name is empty or too long).
Example: Set a variable that records the timestamp of the last trade:
if(OrderSelect(0, SELECT_BY_POS, MODE_TRADES))
{
GlobalVariableSet("MyEA_LastTradeTime", TimeCurrent());
}
This creates a Global Variable named "MyEA_LastTradeTime" with the current server time as its value. If the variable already exists, its value is overwritten.
Step 2: Reading a Global Variable
Use GlobalVariableGet() to retrieve the value:
double lastTradeTime = GlobalVariableGet("MyEA_LastTradeTime");
if(lastTradeTime > 0)
{
Print("Last trade was at ", TimeToString((datetime)lastTradeTime));
}
If the variable does not exist, GlobalVariableGet() returns 0.0. Always check the return value or use GlobalVariableCheck() first to see if it exists — especially if 0.0 is a valid value in your logic (e.g., tracking a price level of 0.0).
Step 3: Checking if a Global Variable Exists
if(GlobalVariableCheck("MyEA_LastTradeTime"))
{
Print("Variable exists with value: ", GlobalVariableGet("MyEA_LastTradeTime"));
}
else
{
Print("Variable does not exist yet.");
}
GlobalVariableCheck() returns true if a variable with that name exists, false otherwise. It's a simple boolean check that doesn't retrieve the value, so it's efficient for validation.
Step 4: Deleting a Global Variable
Clean up after yourself to avoid cluttering the terminal:
GlobalVariableDel("MyEA_LastTradeTime");
To delete all variables (use with extreme caution — it affects all programs running on that terminal):
GlobalVariablesDeleteAll();
In MT4, you can also delete a single variable and immediately save the change with GlobalVariableDel("name"); GlobalVariableSave("name"); — but note that GlobalVariableSave() on a deleted variable will not restore it; it simply removes it from the persistent file.
Step 5: Saving Global Variables (MT4 Only)
In MT4, Global Variables are lost when you close the terminal unless you explicitly save them:
GlobalVariableSave("MyEA_LastTradeTime");
This saves the variable to the file global_variables.dat in the terminal's data folder (typically C:\Users\[YourUsername]\AppData\Roaming\MetaQuotes\Terminal\[InstanceID]\). The variable is automatically reloaded when the terminal starts. In MT5, this function exists but is effectively a no-op because persistence is automatic.
Pro tip: In MT4, save your critical variables in the OnDeinit() function of your EA to ensure they persist even if the EA is removed from the chart:
void OnDeinit(const int reason)
{
GlobalVariableSave("MyEA_LastTradeTime");
GlobalVariableSave("MyEA_ConsecutiveLosses");
}
Step 6: Listing All Global Variables
To programmatically list all Global Variables (useful for debugging or cleanup):
int total = GlobalVariablesTotal();
for(int i = 0; i < total; i++)
{
string name = GlobalVariableName(i);
double value = GlobalVariableGet(name);
Print("GV[", i, "]: ", name, " = ", value);
}
Note: GlobalVariableName() returns the name at index i in the internal list. The order is not guaranteed and may change when variables are added or deleted.
Practical Use Cases
Cross-EA Communication
Suppose you have one EA that opens trades and another that manages risk. The risk manager can read a Global Variable set by the trade opener to know the current position size:
// In TradeOpener EA:
GlobalVariableSet("RiskManager_CurrentLotSize", currentLotSize);
// In RiskManager EA:
double lotSize = GlobalVariableGet("RiskManager_CurrentLotSize");
if(lotSize > maxAllowedLot)
{
// Take corrective action: close the trade or reduce lot size
Print("Risk limit exceeded: ", lotSize, " > ", maxAllowedLot);
}
You can extend this to share multiple parameters — for example, a "master" EA that sets trading signals, and "slave" EAs that execute them on different symbols:
// Master EA sets a signal
GlobalVariableSet("Signal_EURUSD", 1.0); // 1 = buy, -1 = sell, 0 = neutral
// Slave EA on EURUSD chart reads it
double signal = GlobalVariableGet("Signal_EURUSD");
if(signal == 1.0) OpenBuy();
else if(signal == -1.0) OpenSell();
Persistent State Across Chart Changes
If your EA needs to remember something even after being removed and reattached to a chart, Global Variables are the solution. For example, tracking the number of consecutive losing trades:
if(tradeResult == LOSS)
{
int consecutiveLosses = (int)GlobalVariableGet("MyEA_ConsecutiveLosses");
consecutiveLosses++;
GlobalVariableSet("MyEA_ConsecutiveLosses", consecutiveLosses);
Print("Consecutive losses: ", consecutiveLosses);
}
else if(tradeResult == WIN)
{
GlobalVariableSet("MyEA_ConsecutiveLosses", 0); // reset
}
This counter survives EA removal, terminal restart (if saved in MT4), and is accessible by other programs.
Coordinating Multiple Instances
If you run the same EA on multiple charts (different symbols or timeframes), Global Variables can prevent duplicate trades. For example, a "global lock" variable ensures only one instance executes a trade at a time:
if(!GlobalVariableCheck("Global_TradeLock"))
{
GlobalVariableSet("Global_TradeLock", 1);
// Open trade logic
// ...
GlobalVariableDel("Global_TradeLock");
}
else
{
Print("Another instance is trading, skipping.");
}
For more robust coordination, use GlobalVariableSetOnCondition() to atomically check and set the lock:
// Try to acquire lock (only if it's 0)
if(GlobalVariableSetOnCondition("Global_TradeLock", 1.0, 0.0))
{
// We got the lock — proceed with trade
// ...
GlobalVariableSet("Global_TradeLock", 0.0); // release
}
else
{
Print("Could not acquire lock, another instance is active.");
}
Sharing Indicator Values Between Programs
An indicator can expose its latest value to an EA via Global Variables. For example, a custom RSI indicator writes its value to a GV every tick:
// In indicator's OnCalculate()
double rsiValue = iRSI(NULL, 0, 14, PRICE_CLOSE, 0);
GlobalVariableSet("MyRSI_Value", rsiValue);
Then an EA reads it without needing to recalculate:
double rsi = GlobalVariableGet("MyRSI_Value");
if(rsi < 30) Print("Oversold condition detected");
Tips and Best Practices
- Use descriptive names with prefixes to avoid conflicts. For example,
"MyEA_LastSignal"instead of just"Signal". Include your EA name, purpose, and maybe a version number:"MyEA_v2_LastTradeTime". - Always check existence before reading to avoid interpreting a 0 value as meaningful data. Use
GlobalVariableCheck()or compare the return ofGlobalVariableGet()against 0 only if 0 is not a valid value. - Delete variables when no longer needed to
Frequently Asked Questions
Can Global Variables be used to pass data between MT4 and MT5 instances?
No. Global Variables are stored per terminal instance. MT4 and MT5 are separate programs and cannot share Global Variables. For cross-platform communication, consider using files, the Windows registry, or a network-based solution.
What happens if I exceed the 1024 variable limit in MT4?
The
GlobalVariableSet()function will return false and fail to create the variable. You must delete unused variables usingGlobalVariableDel()orGlobalVariablesDeleteAll()to free up space. Monitor the count withGlobalVariablesTotal().Are Global Variables thread-safe in MQL5?
Yes, MQL5's Global Variable functions are thread-safe for reading and writing. However, you still need to handle race conditions when multiple EAs write to the same variable. Use
GlobalVariableSetOnCondition()for atomic operations.Can I see Global Variables from the MetaTrader interface without coding?
Yes. In MT4, go to Tools → Global Variables (or press Ctrl+F7). In MT5, go to Tools → Global Variables (or press Ctrl+F7). This opens a window listing all current variables, their values, and last modified time. You can also delete variables from this interface.






