MQL5: How to Use It to Build and Run MetaTrader Code
By FXNook Lab team
MQL5 is the programming language used to create programs for MetaTrader 5. To get started, open MetaEditor from MT5, create an Expert Advisor, add a few event functions, compile the file, and run it in the Strategy Tester. The example here prints the chart symbol and its bid price on each tick; it does not place trades.
What MQL5 Does in MetaTrader 5
MQL5 lets you write programs that run inside MetaTrader 5. You can use it to automate trading rules, calculate and display market data, or perform a one-time task. MetaEditor is the editor and compiler that comes with MT5, and it turns source files such as .mq5 into program files that the terminal can run.
Choose the program type based on how it should run. An Expert Advisor (EA) stays attached to a chart and responds to events such as new ticks. A script runs once when you launch it. A custom indicator calculates values for charts and can draw lines, arrows, or other output; it is not itself a trade-execution program.
| Program type | How it runs | Typical use |
|---|---|---|
| Expert Advisor | Stays active on a chart and handles events, commonly new ticks. | Monitoring conditions or automating a trading process. |
| Script | Runs its task once after you launch it. | Performing a one-time action or calculation. |
| Custom indicator | Calculates and displays values on a chart. | Showing a signal, line, or other visual analysis. |
These program types share the MQL5 language, but they do not share the same main event function. An EA commonly uses OnTick, a script uses OnStart, and a custom indicator calculates through OnCalculate. Selecting the right type in the creation wizard gives you a starting template with the appropriate structure.
Open MetaEditor and Create the Right Program
- Open MetaTrader 5 and start MetaEditor. Press
F4, or use the MetaEditor button in the terminal toolbar. - In MetaEditor, choose File > New to open the MQL Wizard.
- Select Expert Advisor (template) for this walkthrough, then continue.
- Enter a name such as
FirstTickLogger. The wizard may offer extra event handlers; keep the template simple for now. - Finish the wizard. MetaEditor creates an
.mq5source file in the terminal'sMQL5/Expertsfolder and opens it for editing.
The file name becomes the program name shown in MetaTrader, so use a clear name without changing the generated file extension. If you created a script or indicator by mistake, it is usually easier to create the correct program type from the wizard again than to turn one program type into another by renaming the file.
MetaEditor also creates an .ex5 file when compilation succeeds. That is the compiled program the MT5 terminal loads. Keep the .mq5 source file: you edit that file when you want to change the program.
Read the Basic MQL5 Program Structure
An EA is event-driven. Rather than running from the first line to the last line and then stopping, MT5 calls specific functions when the matching event occurs. The standard EA template includes initialization and shutdown handlers, and you add the logic you want to run while the EA is active.
OnInit()runs when the EA is loaded. It is where you can set up values or indicator handles. ReturningINIT_SUCCEEDEDtells MT5 initialization completed successfully.OnTick()runs when a new price tick arrives for the symbol of the chart where the EA is attached. This is where an EA commonly checks conditions and responds to market updates.OnDeinit(const int reason)runs when the EA is removed or unloaded, or when its chart context changes in a way that requires deinitialization. It is commonly used to release resources or print a shutdown message.
The handler signatures matter. For example, an EA's OnTick function has no parameters and returns no value. If you change the name or parameter list, MT5 will not treat that function as the expected event handler.
A script has an OnStart() entry point and runs its task once. An indicator normally initializes with OnInit() and calculates data in OnCalculate(), which receives price-series information. Indicators that use graphical output or indicator buffers have additional structure, so start from the custom indicator template rather than copying an EA template.
Build a Minimal EA and Understand Its Output
Replace the contents of the EA template with the following MQL5 code. It prints a startup message, then prints the current chart symbol and bid price when a tick arrives, and prints a shutdown message when it is unloaded.
#property version "1.00"
int OnInit()
{
Print("Started on ", _Symbol);
return INIT_SUCCEEDED;
}
void OnTick()
{
double bid = 0.0;
if(SymbolInfoDouble(_Symbol, SYMBOL_BID, bid))
{
Print(_Symbol, " bid: ", DoubleToString(bid, _Digits));
}
}
void OnDeinit(const int reason)
{
Print("Stopped. Reason: ", reason);
}
#property version sets version metadata for the program. _Symbol is the symbol for the chart context, while _Digits is that symbol's number of decimal places. SymbolInfoDouble requests a symbol property; here it writes the bid into the bid variable and returns whether the request succeeded.
The if statement prevents the EA from printing a value unless the bid request succeeds. DoubleToString formats the price using the symbol's digits, and Print sends the message to the terminal log. The code contains no trade function such as CTrade.Buy or OrderSend, so it cannot open or close a trade.
Because OnTick can run frequently, this example can produce many log lines during an active market or a long backtest. That is useful for learning how events work, but production programs usually avoid printing every update unless detailed logging is needed.
Compile the File and Fix Common First Errors
- Save the file in MetaEditor, then press
F7or choose the compile command. - Read the compilation result in the Toolbox or Errors panel. A successful build should report zero errors; warnings, if present, are listed separately.
- If there is an error, double-click its line in the panel to jump to the relevant code, correct it, save, and compile again.
Many first compile errors come from small editing mistakes. A missing semicolon at the end of a statement can make the next line appear to be the problem. A missing closing brace can cause an error near the end of the file, even though the opening brace that needs attention is much earlier.
Also compare the function names and signatures with the template. MQL5 is case-sensitive, so OnTick is not the same as ontick. If you see an undeclared identifier, make sure the name is spelled correctly and that the variable or function is available in that scope. If MetaEditor reports an unexpected end of program, count the opening and closing braces and parentheses.
A successful compile only tells you the source passed the compiler. It does not prove that the program behaves as intended, receives the events you expect, or sends valid orders. This example avoids order handling, so its first functional test is to see whether the expected log messages appear.
If you are working with an existing EA and MetaEditor errors are getting in the way, the FXNook Lab MQL4/MQL5 error fixer can compile uploaded code, identify causes, and show what changed. For a guided example of the broader EA workflow, see How to Create an EA in MQL5.
Test the EA Before Attaching It to a Chart
The MT5 Strategy Tester runs an EA against historical market data in a separate test environment. It is a good place to confirm that the EA initializes and responds to simulated ticks before you attach it to a live chart. For this logging example, you are testing event flow and output, not trading performance.
- Open the Strategy Tester in MT5, commonly with
Ctrl+R. - Select
FirstTickLoggeras the Expert Advisor and choose the symbol you want to test. - Choose a date range that has available history. Select a tick model supported by the terminal and suitable for the check; a more detailed tick model can produce more events and more log output.
- Start the test. Use the visual mode option if you also want to watch the chart update during the run.
- When the test finishes, inspect the tester's Experts and Journal tabs for the startup, tick, and shutdown messages or any runtime errors.
For a simple check, you do not need a complex date range or trading report. Look for the startup message and repeated bid messages. If the test has no tick data for the selected range, or the run does not receive price updates, there may be no tick messages to inspect; choose a symbol and period with available history.
Since this EA sends no orders, an empty trade list is expected. When you move on to an EA that trades, the tester setup needs more attention: inputs, trading rules, spread and execution assumptions, and the selected tick model can all affect what the test shows. Tested results do not guarantee future results.
For another worked example that includes a fuller EA workflow, see MT5 EA Source Code: Build and Test a Working Example.
Run an EA on a Chart and Check Its Status
- In MT5's Navigator, find your EA under Expert Advisors. If it does not appear after compilation, right-click the Navigator and choose refresh.
- Drag the EA onto a chart, or double-click its name. The chart symbol determines the symbol used by
_Symbolin this example. - Review the EA's inputs and the permissions shown in its properties. For this code, there are no trading permissions to enable because it does not place trades.
- Make sure the terminal's Algo Trading control permits automated programs to run, then look at the chart and terminal logs for initialization and tick messages.
When the EA is attached, MT5 shows its name on the chart, and the Experts and Journal logs show its messages or any runtime errors. If it prints the startup line but no bid lines, the EA may not be receiving ticks yet; wait for a new tick or try a symbol that is active. If the Experts log reports an error, use its text and time to narrow down what happened.
An attached EA is not necessarily a trading EA. The sample can run correctly while never creating a position because it contains no order logic. For an EA that does trade, also verify its inputs, trading permissions, order handling, and behavior in the tester before using it on a chart.
Choose Your Next MQL5 Step
If your goal is to automate a process that reacts to changing prices, continue with an EA and learn how it reads inputs, checks conditions, and manages trade requests. MQL5 provides trading classes such as CTrade, as well as trade functions, but order placement introduces separate requirements such as valid volume, price, stop levels, and broker execution settings. Learn those details before adding trade calls to a program.
If you want chart calculations or visual signals, start a custom indicator instead. If you want a one-off operation, create a script. Using the matching template gives you the right event structure and avoids adapting code that was designed to run differently.
For a guided build from a written strategy, the FXNook Lab AI EA builder turns a description into a confirmed specification before building an MT4 or MT5 EA or indicator, then compiles and checks the result. The Lab also has tools for conversion, code fixes, and code checks; see the FXNook Lab overview for the available workspace tools.
Your practical next step is to compile the sample, run it in the Strategy Tester, and make sure its messages match the events you expect. After that, choose an EA, script, or indicator template based on the job you want the program to do, and test each change before relying on it.
Questions
How do I start writing MQL5 code in MetaTrader 5?
Open MetaEditor from MT5 with F4, choose File > New, and select the template that matches your goal, such as Expert Advisor, script, or custom indicator. Save the generated .mq5 file, edit its code, and compile it with F7. Start by testing a small program that produces visible output before adding more behavior.
What is the difference between an MQL5 EA, script, and indicator?
An EA stays active on a chart and responds to events, often new price ticks. A script runs a task once when launched, while an indicator calculates and displays information on a chart. Use the program type whose event model matches the job you want to perform.
How do I compile and test an MQL5 program?
Save the .mq5 source in MetaEditor and press F7; use the Errors or Toolbox panel to locate and correct compile problems. Then open MT5's Strategy Tester, select the program, symbol, date range, and tick model, and start a run. Review the tester's Experts and Journal logs for runtime messages as well as the test result.