Table of Contents
Differences from MQL Tools
Smart Compile Targets for Header FilesWhen editing
Commands:
IntelliSense & Semantic SupportThis extension now uses clangd to provide state-of-the-art IntelliSense, code completion, and navigation for MQL4/5.
Symbol Visibility Inside Headersclangd parses each translation unit once, top-down — unlike the MetaEditor compiler, which concatenates all sources and resolves names multi-pass. By itself this would make symbols declared in the parent To solve this transparently,
You can safely add
Quick Setup Guide
💡 Windows Tip: Open MQL5 from Your Projects FolderMetaTrader stores MQL files deep inside
This creates a zero-cost pointer — no duplication, files exist only once. You can now open Important Notes
MetaEditor on macOS / Linux (Wine)On non-Windows platforms you can run MetaEditor through Wine while keeping the same workflow.
When
Auto-Reload EA After Compile (MT5 Service)On Wine/macOS (and any setup where MetaTrader doesn't auto-reload the running EA after compile) you can close the loop with a tiny MT5 Service that watches for flag files written by the post-compile task hook. A ready-to-use service ships under Command Palette: How it works
Service inputs
Notes
Live Runtime LogMonitor your MQL4/MQL5 terminal logs in real-time directly within VS Code—no need to switch to MetaTrader or open external log files. Features:
Log Modes
Why multiple modes?
MetaTrader's Setting up LiveLog (Real-time) Mode
Commands:
Notes:
Trade Report DashboardAnalyze your Strategy Tester results directly in VS Code. The Trade Report parses MT5 tester log files and displays trades, P&L, and log entries in an interactive dashboard. Command: Features:
Source Code Navigation (Click-to-Source)When using LiveLog Setup: Just use LiveLog's level-prefixed functions — source tags are embedded automatically:
The Trade Report will show:
Source SnapshotsEditing your EA after a test run can break Enable it:
When a snapshot exists the Trade Report shows two clickable badges per source location:
The dashboard also marks runs that have a snapshot with a small snapshot label.
Run BacktestLaunch an MT5 Strategy Tester run for your EA directly from VS Code — without touching the MetaTrader UI. Requires: TradeReportServer running (or auto-started) and a How to use:
Settings:
Notes:
Backtest Setup
|
| Field | Description | Example |
|---|---|---|
Expert |
EA name (without .ex5 extension) |
MyEA |
Symbol |
Trading symbol | EURUSD |
FromDate |
Start date (format: YYYY.MM.DD) |
2025.01.01 |
ToDate |
End date (format: YYYY.MM.DD) |
2025.01.31 |
Period |
Timeframe (optional, defaults to M1) |
M5 |
Date format: All dates must use the YYYY.MM.DD format (e.g., 2025.01.31).
Example tester.ini:
[Tester]
Expert=MyEA
Symbol=EURUSD
Period=M5
Model=0
ExecutionMode=0
Optimization=0
FromDate=2025.01.01
ToDate=2025.01.31
[Inputs]
RiskPercentage=1.0||1||0.1||10||Y
VS Code Settings for Backtesting
| Setting | Description |
|---|---|
mql_tools.Backtest.PromptForParameters |
If true, prompts for symbol and date before running. If false, uses tester.ini defaults silently. |
mql_tools.Backtest.TesterLogDir |
Optional path to MT5's tester agent log directory. Only set if auto-detection fails. |
mql_tools.Backtest.VisualMode |
Force visual mode on (true) or off (false) for every launch. null (default) respects the EA's INI. |
mql_tools.Backtest.KeepTerminalOpen |
Keep MT5 open after the test (true → ShutdownTerminal=0). null (default) respects the EA's INI. |
mql_tools.Terminal.Terminal5Dir |
Path to terminal64.exe. Required on all platforms. Auto-detects common locations on Windows. |
mql_tools.Metaeditor.Include5Dir |
Path to MQL5 data folder (contains Include, Experts, Logs, etc.). |
How MT5 Writes the Tester Log
When a backtest runs, MT5's Strategy Tester agent writes logs to a specific directory. The runner finds these logs as follows:
Windows:
%APPDATA%\MetaQuotes\Tester\<terminal-id>\Agent-127.0.0.1-3000\logs
Linux/macOS (Wine):
<Wine_prefix>/drive_c/users/<user>/AppData/Roaming/MetaQuotes/Tester/<terminal-id>/Agent-127.0.0.1-3000/logs
The extension:
- Auto-detects the log directory based on the terminal identity (derived from
Include5Dir) - Monitors the latest
*.logfile for the completion marker (MetaTester 5 stopped) - Copies the completed log to the EA's
runs/folder:MQL5/Experts/<YourEA>/runs/<timestamp>.log
If auto-detection fails, set mql_tools.Backtest.TesterLogDir to the full path of the agent logs directory.
Important Notes
- Each Run Backtest command overwrites
<MQL5>/tester.iniwith your EA'stester.iniplus any parameters chosen for the run. Back up your hand-tuned<MQL5>/tester.inifirst if you need to preserve it. - Backtest logs are stored in
MQL5/Experts/<YourEA>/runs/— each run creates a timestamped.logfile. - The Trade Report Dashboard opens automatically after test completion (controlled by
mql_tools.Backtest.AutoOpenReport).
Arrange MT5 Charts
Tile your MetaTrader 5 chart windows into saved layouts from VS Code. Charts docked inside the terminal snap into a grid; charts you undock (right-click → uncheck Docked) spread across your other monitors.
Command: MQL: Arrange MT5 Charts — pick a named preset. Or click the Charts button in the status bar for fast switching (toggle with mql_tools.ChartLayout.ShowStatusBarButton).
Define presets in mql_tools.ChartLayout.Presets. Each has a required docked grid and an optional floating grid for undocked charts. Monitors are numbered 1-based (Windows enumeration order).
"mql_tools.ChartLayout.Presets": [
// All charts docked, tiled 2×4 inside MT5 on monitor 1.
{ "name": "wall", "docked": { "monitor": 1, "rows": 2, "cols": 4 } },
// Docked charts on monitor 1; undocked charts side-by-side on monitor 2.
{ "name": "split", "docked": { "monitor": 1, "rows": 2, "cols": 3 },
"floating": { "monitor": 2, "rows": 1, "cols": 2 } }
]
Charts are matched by SYMBOL,TIMEFRAME title, so panels (Market Watch, Navigator) are never touched.
Beyond uniform grids: a docked/floating block can use a CSS grid-template-areas template for spans (one chart wider or taller than the rest), and naming the cells after timeframes (M5, H1, …) places charts by timeframe, bound to the active chart's symbol (others minimized).
"mql_tools.ChartLayout.Presets": [
// Letters = spans: A wide on top, B tall down the right, C wide on the bottom.
{ "name": "tall-right", "docked": { "monitor": 1, "areas": ["A A B", "C C B"] } },
// Timeframe names = match by timeframe: M5 wide top, H1 tall right, M15 bottom,
// all from the active chart's symbol; charts of other symbols are minimized.
{ "name": "scalp", "docked": { "monitor": 1, "areas": ["M5 M5 H1", "M15 M15 H1"] } }
]
See the full guide for the rules (rectangular regions, empty . cells, timeframe tokens).
⚠️ Windows only (for now) — it moves native MT5 windows via the Win32 API; a no-op on macOS / Linux / Wine.
Full guide: docs/chart-layout.md.
MQL Debugger (Real-Time Variable Inspection)
Debug your MetaTrader Expert Advisors and Scripts directly from VS Code. The extension injects telemetry at your breakpoints, compiles an instrumented build, and streams variable states to a live debug dashboard — no MetaEditor debugger needed.
How to use:
- Open the
.mq5,.mq4, or.mqhfile you want to debug. - Place breakpoints in the editor margin (click to the left of the line numbers) where you want to inspect variables.
- Click the Start Debugging (bug icon) button in the editor title bar, or press
Ctrl+Alt+D, or runMQL: Start Debuggingfrom the Command Palette.- Starting from an
.mqhfile automatically resolves dependencies and asks which main EA to instrument.
- Starting from an
- The extension will automatically:
- Deploy
MqlDebug.mqhto your MetaTraderInclude/folder (always up to date). - Instrument all relevant source files (main EA + included headers with breakpoints).
- Compile a temporary
*.mql_dbg_build.ex5file without touching your original.ex5. - Start watching the debug log file.
- Open the MQL Debug panel in VS Code.
- Deploy
- In MetaTrader, attach the newly compiled EA/Script to a chart.
- As the EA executes and hits breakpoints, variables populate and update in real-time in the debug dashboard.
- When finished, click Stop Session in the notification or run
MQL: Stop Debugging.
What variables are automatically watched
At each breakpoint the extension automatically collects variables into two tiers depending on the mql_tools.Debug.DetailLevel setting:
Default mode (always active):
| Source | Example |
|---|---|
| Function parameters | double price, int magic |
| Local variables declared before the breakpoint | int bar = 0; |
| Member access expressions used in the function | g_timers.lastTime, this.m_count, a.b.c |
| Implicit class members referenced near the breakpoint | m_lotSize used inside a class method |
Deep Analysis mode (mql_tools.Debug.DetailLevel: deepAnalysis) — additionally:
| Source | Example |
|---|---|
| Global primitive variables referenced within ±15 lines | g_spread, g_signal |
input / sinput parameter variables (always, no proximity filter) |
InpLotSize, InpMaxOrders |
| Primitive fields of local class-typed variables | order.lots, order.openPrice |
Supported types: int, uint, short, ushort, char, uchar, long, ulong, double, float, string, bool, datetime, color, common ENUM_* types, and arrays of numeric types.
Manual watch annotations
Add a // @watch comment near any breakpoint to explicitly name variables that should be watched, even if the auto-detector would miss them:
// @watch myVar otherVar
SomeFunction(); // ← breakpoint here
Multiple variables can be listed on one line. Annotated variables are always watched first.
Breakpoint conditions
VS Code conditional breakpoints are fully supported. Set a condition in the breakpoint editor and the injected code wraps the telemetry in an if block — the EA only pauses when the condition is true.
Pause / Continue (blocking breakpoints)
Each breakpoint injects a MQL_DBG_PAUSE call that spin-waits until you press Continue or Stop in VS Code. This lets you inspect a frozen state before the EA resumes.
Warning: The EA thread is fully blocked while paused. No
OnTick/OnTimerevents fire. Use only on demo accounts or in the Strategy Tester. Auto-resumes after 120 seconds as a safety failsafe.
Call stack tracking
Functions containing breakpoints automatically get ENTER/EXIT instrumentation injected, so the debug dashboard shows a live call stack as functions are entered and returned.
Settings
| Setting | Default | Description |
|---|---|---|
mql_tools.Debug.DetailLevel |
default |
default: locals + member access. deepAnalysis: also global primitives, input vars, and class field expansion. |
mql_tools.ShowButton.StartDebugging |
true |
Show/hide the toolbar bug button on MQL files. |
Notes:
- Class-typed variables are not serialized directly (would cause compile errors). Only their primitive/enum fields are watched.
- If an injection point is unsafe (e.g. inside a braceless single-line block), the debugger warns and skips that line. Use
// @watchor add a statement to create a safe injection point. - The instrumented build uses
.mql_dbg_buildin the filename — never commit or deploy these files.
Troubleshooting clangd diagnostics (MQL-specific)
If you open built-in examples like MQL5/Experts/Examples/MACD/MACD Sample.mq5 and see a large number of clangd errors, work through the steps below.
Make sure the workspace is configured
- Run
MQL: Create configuration(from the Command Palette) once per workspace root. - This command:
- Updates
.vscode/settings.jsonwith the requiredclangd.fallbackFlags. - Generates a
.clangdfile in the workspace to suppress many MQL-specific false positives.
- Updates
- Run
Verify include paths
- The extension adds
-Iflags for your MQL4/MQL5 root and itsIncludedirectory based on your MetaEditor path. - If your MetaTrader installation lives in a non-standard location, set the appropriate
mql_tools.Metaeditor.*settings (for exampleMetaeditor5DirandInclude5Dir), then runMQL: Create configurationagain. - Advanced: you can manually extend
clangd.fallbackFlagsin.vscode/settings.jsonwith extra-I...or-include...flags; MQL Clangd merges its own flags with your existing ones instead of overwriting them.
- The extension adds
Add forced includes for framework / library headers
- For additional frameworks or helper headers that define lots of types or functions used by your project, prefer:
mql_tools.Clangd.ForcedIncludes(global, for all MQL projects), or#ifdef __clang__includes inside specific.mq4/.mq5files (per-file).
- This is often enough to fix "unknown type/function" diagnostics without changing how MetaEditor compiles your code.
- For additional frameworks or helper headers that define lots of types or functions used by your project, prefer:
Tuning diagnostics via the generated
.clangdfile- The
.clangdfile generated by the extension already suppresses many diagnostics that are known to be noisy for MQL (preprocessor directives, array peculiarities, overload resolution differences, and so on). - If you still hit a clangd-only warning that is harmless in MQL, you can:
- Open the
.clangdfile at the workspace root. - Add the diagnostic ID to the
Diagnostics: Suppress:list.
- Open the
- This gives you fine-grained control over which clangd checks remain active.
Tip: Intentional assignment in conditions
If you see "Possible assignment in condition" for intentional code like
if(ticket = OrderSend(...)), you can silence it by adding extra parentheses:// Warning: assignment in condition if (ticket = OrderSend(...)) { } // No warning: extra parentheses signal intent if ((ticket = OrderSend(...))) { }- The
Cleaning up old configuration
- Leftover
clangd.fallbackFlagsfrom other extensions (e.g. the original MQL Tools) can cause issues. Remove stale flags from.vscode/settings.json, then re-runMQL: Create configuration.
- Leftover
FAQ: Common Questions
How can I make clang-format more relaxed for MQL code?
If clang-format is reformatting your MQL code in ways you don't like, you have several options:
Disable formatting entirely for MQL files (recommended for MQL): Add this to your
.clangdfile:--- If: PathMatch: .*\.(mq4|mq5|mqh) Diagnostics: # ... your existing suppressions Style: # Disable clang-format for MQL files DisableFormat: trueCustomize clang-format style: Create a
.clang-formatfile in your workspace root with relaxed settings:BasedOnStyle: LLVM IndentWidth: 3 ColumnLimit: 0 AllowShortFunctionsOnASingleLine: All AllowShortIfStatementsOnASingleLine: true AllowShortLoopsOnASingleLine: true BreakBeforeBraces: Attach SpaceAfterCStyleCast: falseUse MetaEditor's formatting instead: Since MetaEditor has its own formatting rules, you might prefer to format MQL code in MetaEditor and disable clang-format in VS Code entirely.
Is it risky to suppress so many diagnostics?
Short answer: For MQL code, it's necessary and safe.
Why we suppress diagnostics:
- MQL is not standard C++. It has different syntax, keywords, and semantics.
- clangd is a C++ language server that doesn't natively understand MQL-specific features like:
#propertyand#importdirectivesinputandsinputkeywordsexportmodifier- Flexible arrays in classes
- Different type conversion rules
- Different overload resolution
- MQL's custom string type
What we suppress:
- False positives: Errors that clangd reports but are valid MQL code
- MQL-specific syntax: Features that don't exist in standard C++
- Type system differences: MQL is more permissive with conversions
What we DON'T suppress:
- Logic errors in your code
- Undefined variables (that aren't MQL built-ins)
- Type mismatches that would also fail in MQL
- Most code completion and IntelliSense features
The trade-off:
- ✅ You get excellent IntelliSense, code completion, and navigation
- ✅ You avoid hundreds of false-positive errors
- ⚠️ You might miss some edge-case C++ errors (but MetaEditor will catch them during compilation)
Best practice: Use both tools together:
- Use VS Code + clangd for editing, navigation, and IntelliSense
- Use MetaEditor for final compilation and testing
- If you see a real error, add it to your
.clangdsuppressions only if it's a false positive and report an issue to this repository.
Can I add more diagnostic suppressions?
Yes! If you encounter additional false positives:
Identify the diagnostic code:
- Hover over the error in VS Code
- Look for the diagnostic code in brackets, e.g.,
[unknown_typename]or[-Wunused-variable]
Add it to
.clangd: Open the.clangdfile in your workspace root and add the code to theSuppresslist:Diagnostics: Suppress: # ... existing suppressions - your_diagnostic_code_hereSave and reload: The changes should take effect immediately. If not, reload the VS Code window.
Preserving Custom Diagnostic Suppressions
The .clangd file is generated by the "MQL: Create configuration" command. If you have added custom diagnostic suppressions, you can preserve them when re-running the command.
Configuration option: mql_tools.Clangd.PreserveSuppressions
- prompt (default): Ask whether to merge suppressions each time
- always: Automatically merge existing suppressions
- never: Always overwrite the
.clangdfile
Merging combines your custom suppressions with the defaults, deduplicating automatically. Set this in your VS Code settings (.vscode/settings.json or global settings):
{
"mql_tools.Clangd.PreserveSuppressions": "always"
}
If set to "prompt", you'll see a choice dialog when an existing .clangd is found.