Blog / Code & convert EAs · Pine Script · MQL5 · Indicators
Converting Pine Script Indicators (Not Strategies) to MQL5
Learn how to convert TradingView Pine Script indicators into MQL5 custom indicators, including calculations, chart plots, buffers, signals, and alerts.
· 5 min read
Converting a Pine Script indicator into MQL5 is different from converting a strategy.
An indicator calculates market data and displays information on a chart. It may draw lines, colour candles, mark signals or trigger alerts. It does not need to open or close trades.
In MT5, the equivalent is usually a custom indicator written in MQL5.
The main challenge is reproducing both the calculations and the visual output. An indicator that compiles but plots values on the wrong candles or produces different signals is not a successful conversion.
1. Identify What the Pine Indicator Does
Start by breaking the original indicator into its main components.
Consider this simple Pine Script example:
//@version=6
indicator("EMA Indicator", overlay=true)
emaValue = ta.ema(close, 20)
plot(emaValue, title="20 EMA", color=color.blue, linewidth=2)It calculates a 20-period exponential moving average using closing prices and displays it as a blue line on the main chart.
Before converting it, identify:
- Inputs: Periods, price sources and adjustable settings.
- Calculations: Moving averages, oscillators and mathematical formulas.
- Plots: Lines, histograms, coloured candles and arrows.
- Signals: Conditions that identify market events.
- Alerts: Notifications triggered by specific conditions.
- Display settings: Main chart or separate indicator window.
This gives you a clear conversion checklist and helps prevent missing features.
2. Map Pine Script Functions to MQL5
Pine Script has built-in functions for calculations and chart displays. MQL5 uses indicator functions, buffers and drawing properties to achieve similar results.
| Pine Script | MQL5 equivalent or approach |
|---|---|
ta.sma() |
iMA() with MODE_SMA |
ta.ema() |
iMA() with MODE_EMA |
ta.rsi() |
iRSI() |
ta.macd() |
iMACD() |
plot() |
Indicator buffers and drawing styles |
hline() |
Indicator levels or horizontal chart objects |
plotshape() |
Arrow buffers or chart objects |
barcolor() |
Candle-colouring indicator plots |
alertcondition() |
Custom alert logic using Alert() |
These are functional mappings, not automatic replacements. Some Pine Script features require additional MQL5 code to reproduce their appearance and behaviour.
For example, Pine's plot() displays a series directly. In MQL5, you normally store the calculated values in an indicator buffer and configure how MT5 draws them.
3. Create an MQL5 Custom Indicator
A basic MQL5 custom indicator needs:
- Indicator properties to define its display.
- One or more buffers to store calculated values.
OnInit()to initialise the indicator.OnCalculate()to calculate or update its values.
The following example converts the 20-period EMA from Section 1.
First, define the indicator properties and output buffer:
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_label1 "20 EMA"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDodgerBlue
#property indicator_width1 2
input int EMAPeriod = 20;
double EMABuffer[];
int emaHandle = INVALID_HANDLE;The indicator is configured to draw one blue line on the main chart.
Create the EMA handle in OnInit():
int OnInit()
{
if(EMAPeriod < 1)
return INIT_PARAMETERS_INCORRECT;
if(!SetIndexBuffer(0, EMABuffer, INDICATOR_DATA))
return INIT_FAILED;
ArraySetAsSeries(EMABuffer, true);
emaHandle = iMA(
_Symbol,
_Period,
EMAPeriod,
0,
MODE_EMA,
PRICE_CLOSE
);
if(emaHandle == INVALID_HANDLE)
{
Print("Failed to create EMA handle.");
return INIT_FAILED;
}
PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, EMAPeriod - 1);
IndicatorSetString(
INDICATOR_SHORTNAME,
"EMA (" + IntegerToString(EMAPeriod) + ")"
);
return INIT_SUCCEEDED;
}Notice that iMA() creates an indicator handle. It does not directly return the EMA value. You retrieve the calculated values using CopyBuffer() (Indicator Handles and CopyBuffer Explained covers this in detail).
4. Calculate and Display the EMA
MQL5 uses OnCalculate() to update custom indicator values.
For this example, retrieve the EMA values from the built-in indicator and store them in EMABuffer:
int OnCalculate(
const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[]
)
{
if(rates_total < EMAPeriod)
return 0;
ArraySetAsSeries(EMABuffer, true);
int calculated = BarsCalculated(emaHandle);
if(calculated < rates_total)
return prev_calculated;
int copied = CopyBuffer(
emaHandle,
0,
0,
rates_total,
EMABuffer
);
if(copied != rates_total)
{
Print("Failed to copy EMA values. Error: ", GetLastError());
return prev_calculated;
}
return rates_total;
}The important parts are:
BarsCalculated()checks whether the underlying EMA has enough calculated data.CopyBuffer()retrieves the EMA values.EMABufferstores the values MT5 displays as a line.ArraySetAsSeries()makes index0refer to the current candle.
For this straightforward example, the entire EMA history is copied on each calculation. More advanced indicators can optimise this using prev_calculated.
Release the handle when the indicator is removed:
void OnDeinit(const int reason)
{
if(emaHandle != INVALID_HANDLE)
IndicatorRelease(emaHandle);
}Save the file as EMA_Indicator.mq5 in the MQL5/Indicators directory and compile it in MetaEditor.
5. Convert Arrows and Visual Signals
Not every Pine indicator displays a simple line.
If the original script uses plotshape() to mark buy signals, you can reproduce them using an additional MQL5 indicator buffer with an arrow drawing style.
For example, Pine Script might use:
buySignal = ta.crossover(close, emaValue)
plotshape(
buySignal,
style=shape.triangleup,
location=location.belowbar,
color=color.green
)Add a second plot and buffer to the MQL5 indicator:
#property indicator_buffers 2
#property indicator_plots 2
#property indicator_label2 "Buy Signal"
#property indicator_type2 DRAW_ARROW
#property indicator_color2 clrLimeGreen
double BuyArrowBuffer[];In OnInit(), bind the buffer and configure its arrow:
SetIndexBuffer(1, BuyArrowBuffer, INDICATOR_DATA);
ArraySetAsSeries(BuyArrowBuffer, true);
PlotIndexSetInteger(1, PLOT_ARROW, 233);
PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);You must also populate the buffer when the buy condition is true.
For a confirmed-candle crossover, the relevant calculation is:
// Index the price arrays like the buffers: 0 = current candle.
ArraySetAsSeries(close, true);
ArraySetAsSeries(low, true);
// Clear old arrow values before recalculating.
ArrayInitialize(BuyArrowBuffer, EMPTY_VALUE);
for(int i = 1; i < rates_total - 1; i++)
{
bool buySignal =
close[i] > EMABuffer[i] &&
close[i + 1] <= EMABuffer[i + 1];
if(buySignal)
BuyArrowBuffer[i] = low[i] - 10 * _Point;
}The ArraySetAsSeries() calls give the price arrays the same series indexing as the buffers, where index 0 is the current candle. The loop checks completed candles and rebuilds the historical arrow signals.
For indicators with multiple plots, you may need several buffers. A MACD-style indicator, for example, can require separate buffers for its main line, signal line and histogram.
6. Reproduce Pine Script Alerts
Some indicators use alertcondition() to notify users when a signal appears.
For example:
alertcondition(
ta.crossover(close, emaValue),
title="Price crossed above EMA",
message="Price crossed above the 20 EMA"
)MQL5 does not have Pine's alertcondition() function. You can implement equivalent notifications using Alert().
For example, declare a timestamp globally:
datetime lastAlertTime = 0;Then check the most recently completed candle (with time[] also set as series):
if(buySignal &&
time[1] != lastAlertTime)
{
Alert("Price crossed above the EMA on ", _Symbol);
lastAlertTime = time[1];
}This prevents the same completed-candle signal from generating repeated alerts on every tick.
For a complete implementation, evaluate the alert condition on the latest completed candle and update the timestamp only after the alert is triggered. Also check whether the original TradingView alert uses intrabar or confirmed-bar signals.
7. Check Repainting and Historical Calculations
Matching the indicator's formula does not guarantee matching signals.
Pine indicators can update as realtime prices or volumes change. Their current-candle calculations may therefore change before the candle closes.
Pay particular attention to indicators that use:
- Current-candle high, low or close.
- Pivot highs and lows requiring future bars for confirmation.
- Higher-timeframe data.
- Intrabar conditions.
- Calculations that depend on previous values or persistent variables.
For example, a signal may appear when the current candle crosses above a moving average and disappear before the candle closes.
If the MQL5 version only checks completed candles, its signals may be more stable but will not necessarily appear at the same time as the original TradingView indicator.
Decide whether the conversion should reproduce the original intrabar behaviour or use confirmed-candle signals. Don't silently change the behaviour during conversion.
8. Compare the Converted Indicator with TradingView
After compiling the MQL5 indicator, compare it with the original Pine Script version.
Use the same:
- Symbol and timeframe.
- Historical date range.
- Indicator parameters.
- Applied price and calculation method.
- Candle data, where available.
Then compare the actual indicator values at matching timestamps.
If the lines differ, check the price source, indicator settings, available history and array indexing.
For signals, compare the exact candles where arrows and alerts appear. A timing difference may indicate a problem with bar indexing or confirmation rules.
Differences in broker price history and candle construction can also produce different indicator values.
Final Checklist
Before delivering a converted indicator, confirm that:
- All original inputs are available in MT5.
- Calculations use equivalent formulas and price sources.
- Indicator buffers are correctly configured.
- Lines, arrows and histograms appear in the intended locations.
- Alerts trigger under the correct conditions.
- Historical and realtime behaviour have been checked.
- Repainting and confirmation differences are understood.
A good conversion reproduces the original indicator's calculations and chart behaviour, not just its appearance.
Rather not convert it by hand? PositionAlpha's Pine Script to MQL5 converter converts a TradingView indicator (Pine Script v4, v5 or v6) into an MT5 indicator and reports what it changed or couldn't convert. Compile it in MetaEditor and compare it with the original on a chart, as described above, before you rely on it.
Build a bot from your idea
Describe your trading idea and the AI writes MT4 or MT5 code for you to review and test, with a plain-English explanation and setup steps. Your first bot is free.