Loading…

Global Variable Persistence

Terminal global variables are the only built-in way to carry a value across a chart being removed, an EA being recompiled, or the terminal itself restarting, without writing to a file. The raw API is easy to misuse: GlobalVariableGet() returns 0.0 both when the stored value genuinely is zero and when the variable was never set at all, so code that trusts the return value directly cannot tell "this never happened" from "this happened at zero" - a real source of "why did my EA think it already traded today" bugs. Every getter in this header takes an explicit default instead of silently assuming zero, and GvExists() is there for the moments an explicit default is not enough to disambiguate. Beyond the basic get/set, the header adds the state-tracking patterns that actually get reached for in practice: GvIncrement() for a counter that persists across restarts, GvSetFlag()/GvClearFlag()/GvIsFlagSet() for a boolean whose mere existence is the signal, GvCollect() to enumerate every variable under a namespace prefix, and GvDeleteAllWithPrefix() to clear a whole namespace in one call at the end of a test run. Only doubles are stored, because that is genuinely all the terminal API stores on either platform - this header does not pretend otherwise. Notes and limitations - A terminal holds a maximum of 1000 global variables in total across every program, on both platforms. GvSet() reports failure if that cap is hit; it does not raise it. - Global variables not accessed for 4 weeks (server time) are removed automatically by the terminal on both platforms. This header cannot change that; anything meant to persist longer needs a periodic touch or a file instead. - Values are shared by name across every chart and every program in the terminal. Namespace with a prefix specific to your EA, as the demo does, or two unrelated programs can silently overwrite each other's state. - GvCollect() reads GlobalVariablesTotal()/GlobalVariableName() at call time; it is a live snapshot, not a subscription - it will not notice variables created by another program after the call returns.

Script · MT4 · v1.0 · Free

About Global Variable Persistence

Global Variable Persistence is a script for MetaTrader 4. It has 1 setting, such as Prefix. MQL source code included.

Files in the download: GlobalVarStore.mqh, GlobalVarStore.txt, GlobalVarStoreDemo.mq4.

Settings

SettingDefaultWhat it does
PrefixDemoGV_Namespace for every variable this demo creates

How to install

  1. Download the ZIP from your PolyMaria library and unzip it.
  2. In MetaTrader 4 open File → Open Data Folder, then go to MQL4 → Scripts.
  3. Copy the .mq4 file(s) there. Put any .mqh files in MQL4 → Include.
  4. Open the .mq4 file in MetaEditor and press Compile (F7) if MetaTrader does not show it.
  5. Drag the script onto a chart to run it once.

Download the PDF guide

Tags: MT4 Script · MQL4 Source Code

MQL4 & MQL5 scripts · PolyMaria