MQL4 beginner tutorial

MQL4 programming for beginners

Start by choosing the correct MQL4 program type: an Expert Advisor reacts to market and terminal events, an indicator calculates chart output, and a script performs a bounded task through OnStart. Then add inputs, guard every series access, and compile before testing.

Open the Coding Agent, then choose MQL4 from the language menu.

BeginnerRangeScript.mq4.mq4
#property strict
#property script_show_inputs

input int Lookback = 20;

void OnStart()
  {
   if(Lookback < 1 || Bars <= Lookback)
     {
      Print("Not enough bars for the requested lookback.");
      return;
     }

   int high_shift = iHighest(NULL, 0, MODE_HIGH, Lookback, 1);
   int low_shift  = iLowest(NULL, 0, MODE_LOW, Lookback, 1);

   if(high_shift < 0 || low_shift < 0)
     {
      Print("Series lookup failed. Error ", GetLastError());
      return;
     }

   Print("Highest: ", DoubleToString(High[high_shift], Digits));
   Print("Lowest: ", DoubleToString(Low[low_shift], Digits));
  }
  • Choose EA, indicator, or script first
  • Use the event handler for that program type
  • Treat bar 0 as the current bar
  • Compile before runtime testing

Pick the MQL4 program type before writing logic

Program type determines which events the terminal sends. Expert Advisors can receive NewTick and Timer events. Custom indicators calculate buffers through OnCalculate. Scripts run OnStart once for a bounded chart task.

Using the wrong handler is not a style issue. OnTick is not generated for indicators or scripts, and OnCalculate belongs to custom indicators. Decide the runtime first, then write the handler signature exactly as documented.

ProgramPrimary handlerTypical job
Expert AdvisorOnTickMonitor conditions and manage orders
Custom indicatorOnCalculateCalculate and draw chart values
ScriptOnStartRun one bounded task on demand

Learn series indexing before building signals

Price series use reverse indexing. Shift 0 is the current, still-forming bar; shift 1 is the most recently closed bar. A beginner signal often becomes unstable because it reads shift 0 without intending to react intrabar.

Check that enough bars exist before reading an index or requesting a lookback. Array and series bounds are runtime constraints, and an out-of-range access can stop the program.

  • Use shift 1 for a closed-bar decision when intrabar updates are not intended
  • Check Bars, rates_total, ArraySize, or a function return value before indexing
  • Keep symbol, timeframe, and applied-price choices explicit
  • Log failures with GetLastError instead of treating zero as valid data

Compilation is the first check, not the final test

MetaEditor catches invalid syntax, missing identifiers, wrong signatures, and compiler warnings. It cannot prove that a strategy rule is sensible, a broker accepts an order, history is complete, or a backtest models execution correctly.

After compilation, run the source in the matching MT4 program folder and inspect the Experts or Journal output. Trading code needs Strategy Tester and demo-account verification with explicit spread, symbol, and broker assumptions.

Review the complete example

This script introduces an input, OnStart, history guards, timeseries lookup, return-value checks, and formatted output without placing trades. Save it under MQL4/Scripts, compile it, and run it on a chart with enough history.

The example reads chart history and writes to the log. It does not place orders. Any later trading logic still needs broker-specific compilation, backtesting, and demo testing.

BeginnerRangeScript.mq4.mq4
#property strict
#property script_show_inputs

input int Lookback = 20;

void OnStart()
  {
   if(Lookback < 1 || Bars <= Lookback)
     {
      Print("Not enough bars for the requested lookback.");
      return;
     }

   int high_shift = iHighest(NULL, 0, MODE_HIGH, Lookback, 1);
   int low_shift  = iLowest(NULL, 0, MODE_LOW, Lookback, 1);

   if(high_shift < 0 || low_shift < 0)
     {
      Print("Series lookup failed. Error ", GetLastError());
      return;
     }

   Print("Highest: ", DoubleToString(High[high_shift], Digits));
   Print("Lowest: ", DoubleToString(Low[low_shift], Digits));
  }
Where Pineify fits

Move from the rule to editable MQL4 source

Pineify can generate or revise one self-contained .mq4 file with MQL4-specific reference context. Its independent static checker returns MetaEditor diagnostics so you can repair source issues before testing in your own MT4 environment.

Open MQL4 Coding Agent

Static diagnostics do not prove runtime behavior, backtest results, broker compatibility, or live-trading safety.

Pineify MQL4 Coding Agent with MQL4 selected and an editable MetaTrader 4 code artifact

A practical workflow

  1. 1

    Choose the program type

    Decide whether the job belongs in an Expert Advisor, custom indicator, or script.

  2. 2

    Define inputs and data

    List parameters, symbol, timeframe, bar shift, and minimum history before writing the calculation.

  3. 3

    Write one event handler

    Use the documented signature and keep the first example small enough to inspect completely.

  4. 4

    Compile and test

    Resolve diagnostics, then test runtime behavior in the correct MT4 folder and environment.

Frequently asked questions

Is MQL4 difficult for beginners?

MQL4 becomes manageable when you learn program types, event handlers, series indexing, and return-value checks first. Trading logic should come after those runtime basics.

Should a beginner start with an EA or a script?

Start with a script when learning syntax because OnStart runs a bounded task. Move to an EA when the requirement truly needs tick, timer, or trade management events.

What does shift 0 mean in MQL4?

Shift 0 identifies the current bar in a timeseries. Its price and volume can change until the bar closes, so closed-bar rules commonly use shift 1.

Can one .mq4 file contain helper functions?

Yes. A single .mq4 file can contain inputs, event handlers, helper functions, classes, and indicator buffers as long as it does not depend on external includes, libraries, DLLs, or resources.

Does clean compilation mean an EA is safe?

No. Compilation checks source rules. It does not validate strategy logic, prices, fills, broker limits, backtest assumptions, or live-trading risk.

Last verified against the linked official references on . Compile and test the final source in the MetaTrader 4 build, broker, symbol, and account environment you plan to use.

Continue with one reviewable MQL4 file

Define the requirement, inspect the generated source, repair diagnostics, and test the behavior in your own MT4 environment.

Open Coding Agent