Convert a Pine Script Indicator to MQL5, Step by Step
Short answer
Convert one indicator in an order that avoids rework, then fix the MetaEditor compile errors a Pine-to-MQL5 conversion typically produces. The worked example plots two EMAs and marks bullish crossovers, with each error message's exact text and fix.
You have a TradingView indicator and need it on a MetaTrader 5 chart. This guide converts one complete indicator by hand, in the order that avoids rework, and then lists the MetaEditor compile errors a Pine-to-MQL5 conversion typically produces, with the exact message text and the fix. It assumes you can read Pine and have MetaEditor installed.
The script we will convert plots two EMAs and marks bullish crossovers:
//@version=6
indicator("EMA Cross", overlay = true)
fastLen = input.int(9, "Fast")
slowLen = input.int(21, "Slow")
fast = ta.ema(close, fastLen)
slow = ta.ema(close, slowLen)
plot(fast, "Fast", color.blue)
plot(slow, "Slow", color.orange)
plotshape(ta.crossover(fast, slow), "Buy", shape.triangleup, location.belowbar, color.green)Step 1: Inventory the script
Before writing any MQL5, list what the Pine script uses. For each item you will make one decision:
- Declaration:
indicator()becomes an MQL5 indicator withOnCalculate();strategy()becomes an Expert Advisor withOnTick().overlay = truemeans the main chart window. - Inputs: two
input.intcalls. - Outputs: two
plot()lines and oneplotshape(), so three buffers. - Built-ins:
ta.ematwice andta.crossoveronce. - Anything harder:
request.security, drawings (line.new,label.new,box.new), alerts,barcolor. None here; if your script has them, budget extra time for each.
Step 2: Header properties and inputs
The #property lines replace the arguments of indicator() and the styling arguments of each plot(). Count every buffer: each plot needs at least one, and a per-bar colour needs a second (a colour-index buffer). Pine inputs become input variables; the trailing comment is what the user sees in the Inputs tab.
#property indicator_chart_window // overlay = true
#property indicator_buffers 3 // one per plotted series here
#property indicator_plots 3
#property indicator_label1 "Fast"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrBlue
input int InpFast = 9; // Fast <- the comment is the label in the Inputs tab
input int InpSlow = 21; // SlowStep 3: Write the bar loop
Pine runs your code once per bar; MQL5 calls OnCalculate() on every tick and hands you the whole price history. Write one loop that covers the bars not yet computed, plus the newest bar again because it is still forming:
int start = (prev_calculated > 0) ? prev_calculated - 1 : 0;
Inside the loop, index i is the bar Pine would be on. The arrays are oldest-first by default in MQL5, so Pine's x[k] is x[i - k], and i - k must not go below 0. Any value that a later bar reads from the past (here both EMAs) must live in a buffer, not a local variable.
Step 4: Translate the ta.* calls
You can use MetaTrader's iMA() handle with CopyBuffer(), but its first values are not guaranteed to match TradingView's, because the two platforms can start the average differently. Pine's ta.ema starts at the first source value and then applies alpha * src + (1 - alpha) * previous with alpha = 2 / (length + 1). (ta.rma, used by ta.rsi and ta.atr, is different: it is na for the first length - 1 bars and is seeded with their simple average.) Writing the recurrence out takes a few lines and removes the doubt. Note the 2.0: in MQL5, 2 / (len + 1) is integer division and evaluates to 0.
ta.crossover(a, b) is a > b on this bar and a <= b on the previous one. A comparison with na is false in Pine, so if your series can be empty (an SMA during warm-up, for example) the MQL5 version must also refuse to signal while either side is EMPTY_VALUE.
Step 5: Plots and shapes
A plot() line is a DRAW_LINE buffer. plotshape() becomes a DRAW_ARROW buffer that holds a price where the shape should appear and EMPTY_VALUE everywhere else; PLOT_ARROW picks a Wingdings symbol (233 is an up arrow) and PLOT_ARROW_SHIFT moves it a few pixels away from the bar, which approximates location.belowbar. Set PLOT_EMPTY_VALUE to EMPTY_VALUE for every plot so that bars without a value are not drawn at zero. The complete MQL5 indicator:
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots 3
#property indicator_label1 "Fast"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrBlue
#property indicator_label2 "Slow"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrOrange
#property indicator_label3 "Buy"
#property indicator_type3 DRAW_ARROW
#property indicator_color3 clrGreen
input int InpFast = 9; // Fast
input int InpSlow = 21; // Slow
double FastBuf[], SlowBuf[], BuyBuf[];
int OnInit()
{
SetIndexBuffer(0, FastBuf, INDICATOR_DATA);
SetIndexBuffer(1, SlowBuf, INDICATOR_DATA);
SetIndexBuffer(2, BuyBuf, INDICATOR_DATA);
PlotIndexSetInteger(2, PLOT_ARROW, 233); // Wingdings up arrow
PlotIndexSetInteger(2, PLOT_ARROW_SHIFT, 10); // pixels below the low
for(int p = 0; p < 3; p++)
PlotIndexSetDouble(p, PLOT_EMPTY_VALUE, EMPTY_VALUE);
return INIT_SUCCEEDED;
}
// Pine's ta.ema: starts at the first source value, then
// alpha * src + (1 - alpha) * previous, with alpha = 2 / (len + 1).
double EmaStep(const double &src[], const double &buf[], int i, int len)
{
if(i == 0)
return src[0];
double alpha = 2.0 / (len + 1);
return alpha * src[i] + (1.0 - alpha) * buf[i - 1];
}
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[])
{
int start = (prev_calculated > 0) ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++)
{
FastBuf[i] = EmaStep(close, FastBuf, i, InpFast);
SlowBuf[i] = EmaStep(close, SlowBuf, i, InpSlow);
BuyBuf[i] = EMPTY_VALUE;
// ta.crossover(fast, slow): fast > slow now, fast <= slow one bar ago
if(i > 0 && FastBuf[i] > SlowBuf[i] && FastBuf[i - 1] <= SlowBuf[i - 1])
BuyBuf[i] = low[i];
}
return rates_total;
}Step 6: Fix the MetaEditor compile errors
Press F7 in MetaEditor to compile. These are the errors a hand conversion from Pine produces most often; the messages are quoted as MetaEditor 5 prints them.
undeclared identifier 'close'together with'[' - array required: you usedcloseoutsideOnCalculate(), for example in a helper function. The price arrays are parameters ofOnCalculate(); pass them into the helper asconst double &src[], asEmaStepdoes.'InpLength' - constant cannot be modified: the Pine script reassigned an input. Copy the input into an ordinary variable inOnInit()and change that.wrong parameters counton aniMA,iRSIor similar line: you used the MQL4 signature with a trailingshift. In MQL5 these functions take no shift and return a handle; create it inOnInit()and read values withCopyBuffer().'}' - not all control paths return a value: a function ends with anif/else ifchain and no finalreturn. Pine's last expression is the return value, includingnawhen no branch matches; MQL5 needs an explicit return on every path.'price' - invalid array access: you assigned a whole array to a scalar. Index it:price[i].- Warning
possible loss of data due to type conversion from 'double' to 'int': for exampleint half = InpLength * 0.5;. Decide whether you want rounding ((int)MathRound(x)) or truncation ((int)x) and write it explicitly. - Warning
implicit conversion from 'int' to 'string': Pine'sstr.tostring()is explicit; in MQL5 useIntegerToString()orDoubleToString(x, digits).
One error appears only at run time, in the Experts tab: array out of range with a file name and line. It almost always means an index of i - k below zero during warm-up, or i + 1 on the newest bar.
Step 7: Check the result against TradingView
Attach the compiled indicator to the same symbol and timeframe you use on TradingView and open the Data Window (Ctrl+D) in MetaTrader. Pick a few bars well after warm-up and compare the EMA values; small differences can come from the broker's price feed rather than your code, so compare against bars whose OHLC values match first. Then check the arrows land on the same bars. For a strategy, run the Expert Advisor in the Strategy Tester and compare trade lists.
Stratlate's converter performs these steps automatically, writes a report naming every construct it approximated or could not convert, and checks each conversion with a differential verifier that runs both scripts on the same bars and compares their values. The output should still be compiled and tested on your own data.
Pitfalls
- Forgetting the newest bar is recomputed. Starting the loop at
prev_calculatedinstead ofprev_calculated - 1freezes the last value at the bar's first tick. - Wrong buffer counts. If
indicator_buffersis lower than the buffers you bind,SetIndexBuffer()fails for the extra ones, they stay empty arrays, and the first write raisesarray out of range. Check the counts whenever you add a plot. - Arrows drawn on every bar. The arrow buffer was not reset to
EMPTY_VALUEon bars without a signal. - A line starting at zero.
PLOT_EMPTY_VALUEwas not set, so warm-up values of 0 are drawn. - Signals that repaint on the live bar. This matches Pine: a crossover on the forming bar can appear and disappear until the bar closes. If you need confirmed signals, evaluate bar
i - 1.
FAQ
How long does it take to convert a Pine Script indicator to MQL5 by hand?
A small indicator with a few plots and standard ta.* functions takes an hour or two including testing. Scripts with request.security, drawings, tables or strategy logic take much longer, because each of those has to be redesigned for MetaTrader rather than translated line by line.
Should I use iMA and iRSI handles or calculate the values myself?
Handles are shorter to write and fine when approximate agreement is enough. If the MQL5 output must match TradingView bar for bar, compute the formula yourself using the seeding Pine documents, because built-in warm-up behaviour can differ in the first bars.
Why does my converted indicator show nothing on the chart?
Check the Experts tab for a runtime error such as array out of range, make sure indicator_buffers and indicator_plots match what you bind in OnInit, and confirm OnCalculate returns rates_total. A handle-based indicator also shows nothing until BarsCalculated reports enough bars.
Skip the manual steps
Paste the Pine Script and get MQL5 source with a report of anything approximated. Compile it in MetaEditor and compare it on your own chart.
Open the converter