Pillar Guide 03 · MetaTrader 4 & 5

MT4 & MT5 Indicators Guide: Categories, Repainting Checks & Installation

A technical reference for manual traders and Expert Advisor developers evaluating built-in oscillators, custom .ex4 and .ex5 binaries, buffer indexing, repainting behavior, and clean terminal setup.

12 min technical read

Direct Answer

MetaTrader 4 and 5 indicators transform historical OHLC price and tick volume into mathematical overlays or oscillators. Built-in tools read closed bars consistently, whereas custom .ex4 and .ex5 indicators can repaint if coded to reference future bars. Verifying buffer behavior before live deployment prevents distorted signals and misleading backtests.

1. Core MT4 & MT5 Indicator Categories

Technical indicators in MetaTrader 4 and MetaTrader 5 do not predict market direction on their own. Instead, every built-in or custom indicator applies a deterministic formula to open, high, low, close (OHLC) candle data and tick volume across a chosen timeframe. Grouping indicators by what market property they actually measure—trend persistence, short-term momentum, volatility expansion, or session price structure—prevents you from treating duplicate calculations as independent trade confirmations.

CategoryRepresentative ToolsPrimary InputsPractical EA / Chart RoleCore Limitation
TrendMoving Averages (SMA, EMA, LWMA), Ichimoku Kinko HyoHistorical Close/Median prices across N lookback barsRegime filtering (above/below slow MA), directional slope bias, dynamic support/resistance zonesInherent lag during rapid V-reversals; produces whipsaw cross signals inside sideways ranges
MomentumRSI, MACD, Stochastic OscillatorNormalized bar-to-bar close changes or high-low range positionPullback timing inside established trends, centerline crosses, divergence validationRemains pinned in overbought or oversold territory during strong impulsive currency trends
VolatilityAverage True Range (ATR), Bollinger BandsTrue Range (including session gaps) or rolling standard deviationVolatility-normalized stop-loss sizing, breakout squeeze detection, trailing distance scalingMeasures magnitude of price movement rather than trade direction on its own
Structure & VolumePivot Points (Classic/Fibonacci), Market Profile, Tick Volume / OBVPrior session H/L/C levels, time-price histograms, tick update countsObjective session targets, liquidity-hour gating, breakout confirmation filtersSpot forex lacks centralized exchange volume; MetaTrader tick volume reflects price updates, not lot contracts

Trend Overlays: Moving Averages & Ichimoku Kinko Hyo

Simple (SMA), Exponential (EMA), and Linear Weighted (LWMA) moving averages smooth noise by averaging recent closes over a lookback window. Faster EMAs react earlier to price turning points at the expense of more false crossovers; slower SMAs resist noise during pullbacks but introduce larger entry lag. Ichimoku combines five components into a complete directional framework: Tenkan-sen and Kijun-sen measure short- and medium-term equilibrium midpoints, while Senkou Span A and B project the Kumo cloud 26 bars forward. Because Senkou Span values are calculated strictly from past highs and lows and plotted ahead visually, the forward cloud is a projection, not a repainting bug—though reading the backward-shifted Chikou Span requires careful index alignment in automated scripts.

Momentum Oscillators: RSI, MACD & Stochastic

Momentum tools evaluate the velocity and relative positioning of recent closes. RSI compares average up-closes against down-closes on a 0–100 scale; Stochastic expresses where the current close sits within the N-period high-low range; MACD subtracts a 26-period EMA from a 12-period EMA and plots a 9-period signal line. In choppy, mean-reverting sessions, oscillator extremes align closely with swing turns. During sustained macro trends driven by central-bank rate surprises, RSI and Stochastic can remain pinned above 80 or below 20 for dozens of candles, making counter-trend oscillator shorts risky without a separate trend regime filter.

Volatility Engines: ATR & Bollinger Bands

Average True Range (ATR) captures the widest of current high-minus-low, high-minus-prior-close, or low-minus-prior-close, making it resilient to session open gaps. Algorithmic traders use ATR multiples (for example, 1.5x or 2.0x ATR) so stop-loss distances expand automatically during high-volatility London/New York overlaps and tighten during quiet Asian sessions. Bollinger Bands wrap a 20-period SMA inside upper and lower standard-deviation envelopes, highlighting volatility compression (“squeezes”) before expansion rather than signaling automatic reversals every time price touches an outer band.

Structure & Tick Volume: Pivots, Profiles & Broker Feeds

Because spot forex is decentralized, MetaTrader Tick Volume counts the number of bid/ask price updates within each bar rather than actual institutional lot volume. Tick activity still correlates well with intraday liquidity cycles—spiking at London open and U.S. data releases—but exact counts vary slightly across liquidity providers. Objective session levels such as Classic, Fibonacci, or Camarilla Pivot Points rely strictly on the prior completed day or week's OHLC values. You can pre-compute these reference zones with our Pivot Point Calculator and translate level distances into exact currency exposure using the Pip Calculator.

2. Custom Indicators in MT4 (.mq4/.ex4) vs MT5 (.mq5/.ex5) & iCustom Buffers

While built-in indicators are compiled directly into the MetaTrader terminal, custom indicators come as either human-readable source files (.mq4 for MT4, .mq5 for MT5) or compiled executable binaries (.ex4 and .ex5). Source code lets you inspect calculation math and recompile across terminal builds inside MetaEditor; compiled binaries protect commercial intellectual property but prevent independent line-by-line code audits.

Under the hood, MT5 indicators differ fundamentally from legacy MT4 code in three engineering areas: memory buffers, array indexing direction, and how Expert Advisors retrieve values via iCustom(). Understanding those differences explains why naive MQL4-to-MQL5 ports frequently plot upside-down lines or feed misaligned arrays to automated strategies.

MT4 Architecture (MQL4 / .ex4)

  • Timeseries Default Indexing: Built-in price arrays such as Close[0], High[1], and Time[i] index backwards from the present: 0 is the forming candle and 1 is the last closed candle.
  • Direct Scalar iCustom(): An MT4 Expert Advisor requests one value at a time with iCustom(Symbol(), Period(), "Name", inputs..., bufferIndex, shift).
  • Buffer Conventions: Legacy indicators typically expose up to 8 visible plot buffers (expanded in later builds up to 512 total), using EMPTY_VALUE (2147483647) when no arrow or signal exists on a bar.

MT5 Architecture (MQL5 / .ex5)

  • Chronological Indexing by Default: Inside OnCalculate(), price arrays default to ascending order where index 0 is the oldest historical bar and rates_total - 1 is the current bar, unless ArraySetAsSeries(buf, true) is called explicitly.
  • Handle + CopyBuffer() Pattern: An MT5 EA creates an indicator handle once inside OnInit(), reads bar arrays via CopyBuffer(handle, bufferNum, startPos, count, targetArray) in OnTick(), and calls IndicatorRelease() on shutdown.
  • Separated Plots & Calculations: MQL5 supports up to 512 buffers and clearly splits INDICATOR_DATA (plotted buffers readable by EAs) from INDICATOR_CALCULATIONS (internal intermediate arrays).

MQL5 Reference Pattern: Safe iCustom Buffer Read (Closed Bar)

int indHandle = INVALID_HANDLE;

int OnInit()
{
   // Create indicator handle once with explicit input parameters
   indHandle = iCustom(_Symbol, _Period, "CustomTrendOsc", 14, PRICE_CLOSE);
   if(indHandle == INVALID_HANDLE)
      return(INIT_FAILED);
   return(INIT_SUCCEEDED);
}

void OnTick()
{
   double signalBuf[];
   ArraySetAsSeries(signalBuf, true);

   // Copy 3 bars starting at shift 0; read closed bar index [1] and [2]
   if(CopyBuffer(indHandle, 0, 0, 3, signalBuf) < 3)
      return;

   double lastClosedValue = signalBuf[1];
   if(lastClosedValue != EMPTY_VALUE && lastClosedValue > 0.0)
   {
      // Evaluate entry logic only after bar close
   }
}

Always verify parameter count, parameter data types, and exact buffer_num indices against the Data Window (Ctrl+D in MetaTrader). Passing a string instead of an enum or reading a color-index buffer instead of a price buffer is one of the most common causes of silent EA integration errors. See our What Is an Expert Advisor? guide for how signal reads connect into full order-execution blocks.

3. How to Detect Repainting vs Non-Repainting Indicators

A visually spotless equity curve of buy and sell arrows on a static historical chart is one of the oldest pitfalls in retail trading. Many custom oscillators or “zero-lag” arrow systems look remarkably accurate when scrolled backward in history—only to erase missed signals or relocate arrows to better swing points as new candles print in real time. Before trusting any custom indicator manually or wiring it into an Expert Advisor, run a structured non-repainting audit.

Distinguish Normal Intrabar Movement from True Repainting

During an active 1-hour candle, bar 0 has not closed yet. A standard 14-period RSI or Moving Average line on bar 0 moves up and down until the 59th minute completes—that is normal live recalculation. True repainting happens when a closed candle (shift >= 1) changes its plotted buffer value or removes a signal arrow later.

Step 1: Strategy Tester Visual Mode Playback

Open the MetaTrader Strategy Tester (Ctrl+R), select any baseline EA (or an empty template EA), enable Visual mode, and drop the custom indicator directly onto the visual tester chart on M1 or M5. Slow down the playback slider, record the exact timestamps and prices of ten signal arrows or line crosses, advance the simulator by 40–60 candles, and pause. If past arrows vanished, jumped to a higher high three bars later, or flipped color on bars that had already closed, the indicator repaints.

Step 2: Inspect Source Loops for Future-Bar Indexing

When .mq4 or .mq5 source code is available, audit the main for loop inside OnCalculate():

  • In timeseries orientation (MT4 default): index i - 1 or Close[i - 2] reads newer candles relative to bar i. Any centered smoother, fractal confirmation without lag offset, or peak detector referencing i - 1 cannot know that value until future bars exist—creating look-ahead bias in history.
  • In non-timeseries orientation (MT5 default): chronological order reverses the sign—referencing high[i + 1] or close[i + 2] peeks ahead in time while the historical chart appears populated up to rates_total - 1.
  • Unbounded recalculation: loops that ignore prev_calculated and sweep backward writing Buffer[i + k] on every tick can rewrite previously fixed values.

Step 3: Watch for Chart Object Repositioning & MTF Delays

Some indicators hide repainting behavior from buffer checks by drawing labels or trendlines using ObjectCreate() and moving them later with ObjectMove(), leaving buffer arrays empty. Similarly, legitimate structural tools such as ZigZag or swing-fractal markers update unconfirmed legs until an opposite threshold is crossed, and Multi-Timeframe (MTF) overlays adjust the active higher-timeframe bucket across multiple lower-timeframe candles. Always confirm both visual object persistence and closed-bar locking inside your Strategy Tester backtesting workflow.

4. Avoiding Multicollinearity & Chart Overload

New MetaTrader users frequently load five or six oscillators below a chart, assuming that waiting for RSI, Stochastic, CCI, Williams %R, and MACD to align produces higher-probability trades. In quantitative finance, this problem is known as indicator multicollinearity: every one of those indicators transforms the exact same series of recent close prices. When price drops sharply and then ticks up, all five oscillators turn upward together—not because five independent forces confirmed a reversal, but because you plotted the same price derivative five different ways.

Multicollinearity damages Expert Advisors even more severely than manual charts. Every redundant indicator parameter adds extra optimization degrees of freedom. Optimizing 12 overlapping thresholds across historical price data makes it effortless to overfit past market noise—producing smooth backtest curves that immediately degrade out of sample.

Designing an Orthogonal 3-Layer Confirmation Stack

If your strategy uses indicators, restrict each component to a distinct informational dimension so filters genuinely complement one another:

Layer 1 · Regime / Trend

One slow moving average slope, ADX threshold, or higher-timeframe structural bias to separate trending vs ranging conditions.

Layer 2 · Trigger Timing

One momentum pullback trigger (e.g., RSI cross) or price-action breakout beyond a prior session Pivot/Donchian boundary.

Layer 3 · Volatility & Cost

One ATR stop-distance rule paired with a real-time spread filter so signal expectancy exceeds execution cost.

5. Step-by-Step Safe Installation in the MetaTrader Data Folder

Installing custom indicators inside the Windows Program Files directory rarely works on modern MetaTrader builds because user files are sandboxed inside the terminal's AppData workspace. Follow this exact installation sequence for both MT4 and MT5:

  1. 1. Open the Active Data Folder: Launch MetaTrader 4 or 5, open the top menu, and select File → Open Data Folder. This opens the exact terminal hash directory linked to your running instance.
  2. 2. Copy Files to the Platform-Specific Indicators Directory: Place .mq4 / .ex4 files inside MQL4\Indicators\ (MT4) or place .mq5 / .ex5 files inside MQL5\Indicators\ (MT5). Supporting header files (.mqh) belong in Include\, while compiled library dependencies belong in Libraries\.
  3. 3. Compile Source Files & Refresh Navigator: If you copied an .mq4 or .mq5 source file, open MetaEditor (F4), open the file, and press Compile (F7) to verify zero errors. Back in the terminal, open Navigator (Ctrl+N), right-click Indicators, and choose Refresh.
  4. 4. Attach to a Demo Chart & Audit Terminal Logs: Drag the indicator onto a demo chart, review its Inputs and Colors tabs, and inspect the Experts and Journal tabs at the bottom of the terminal for array out of range, zero divide, or UI freeze warnings caused by heavy per-tick loops.

Security Caution: “Allow DLL imports” & Unverified Binaries

Inside the indicator's Dependencies / Common tab, keep Allow DLL imports unchecked unless you explicitly need an audited local library and know why it is required. Standard mathematical indicators operate strictly inside MetaTrader's sandbox without native Windows DLLs or external WebRequest URLs. Enabling DLL imports grants native operating-system access under your Windows user account, which is unnecessary for chart overlays and oscillators.

Frequently Asked Questions

Can I run an MT4 .ex4 indicator inside MetaTrader 5?

No. MetaTrader 4 compiles indicators into .ex4 binaries using MQL4, whereas MetaTrader 5 requires .ex5 binaries compiled from MQL5. The two terminals use incompatible event models, indicator buffer structures, and standard library functions, so an .ex4 file must be rewritten and compiled from source as an .mq5 file to run in MT5.

What is the difference between live-bar recalculation and true repainting?

Every indicator that reads the current open candle (bar index 0) naturally updates while that candle is still forming because the current Close, High, and Low change with incoming ticks. True repainting occurs when values plotted on already-closed historical bars (shift 1 and older) move, disappear, or change color after subsequent candles print.

Why do multi-timeframe (MTF) indicators shift earlier bars on a lower timeframe chart?

When an H1 indicator is projected onto an M5 chart, all twelve 5-minute candles inside the active hour reference the same incomplete H1 candle. Until that H1 candle closes, all twelve sub-bars update together. An MTF indicator is only non-repainting if signals are evaluated strictly after the higher timeframe candle closes.

Should an Expert Advisor read shift 0 or shift 1 when calling iCustom()?

In almost all systematic strategies, reading shift 1 (the most recently closed candle) is safer than shift 0. Evaluating shift 0 inside OnTick() exposes the EA to intrabar spikes that can trigger a signal mid-candle and vanish before the bar closes, creating mismatches between historical backtests and live execution.

Why do standard MT4 and MT5 indicators not need Allow DLL imports enabled?

Pure technical indicators perform mathematical transformations solely on MetaTrader price arrays and chart objects inside the MQL sandbox. They only require DLL imports when bridging external C++ libraries, licensing servers, or third-party feeds. Leaving DLL imports disabled by default protects your workstation from untrusted native code execution.

How many indicators should a strategy combine on one chart?

Using two or three indicators from genuinely distinct categories—such as one trend filter, one volatility sizing tool like ATR, and one entry trigger—is typically far cleaner than stacking four oscillators. Combining multiple momentum indicators built from Close prices introduces multicollinearity, increasing false confidence and curve-fitting risk without adding independent signal information.

Related MetaTrader Tools & Pillar Guides