Undeclared identifier in MQL5 after a Pine Script conversion
Short answer
Error 256 means the code uses a name MQL5 never saw declared, usually a Pine built-in such as close outside OnCalculate, the ta namespace, na, hl2 or bar_index. Replace each with its MQL5 equivalent, and declare a variable before the if block, in the scope that reads it.
MetaEditor stops with undeclared identifier 'close' (error 256; older builds print the same thing as 'close' - undeclared identifier) when a name is used that MQL5 has never seen declared. In code ported from Pine Script the name is nearly always one of Pine's built-ins that MQL5 does not have: close outside OnCalculate, the ta namespace, na, hl2, bar_index, or a variable that was declared inside an if block and read after it.
Why it happens when converting Pine Script
Pine scripts live inside a large implicit environment. close, high, hl2, volume, bar_index, na and the whole ta.*, math.* and str.* namespaces exist on every line without a declaration, and a user function can read close as freely as the main script can. Variables are declared by assignment and the if block is an expression, so a name assigned inside a branch is usually hoisted to the outer scope by the way the script is written (x = if cond ... else ...).
MQL5 is C-like. Price data arrives only as the parameters of OnCalculate, so close is a local array in that one function and nothing else. There are no namespaces: ta.sma is the member sma of an object called ta, which does not exist. Every variable has a declaration with a type, and that declaration is visible only inside the braces it was written in. Names are case-sensitive, so Close (MQL4's old predefined array) is not close. Each of these differences gives the same error, and MetaEditor lists all of them in one compile, so one wrong habit repeated ten times reads as ten errors.
Fix
A port of ta.sma(hl2, len) with a candle-body check, written the way a Pine author would guess MQL5 works, produces nine errors at once. The file as it fails:
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_type1 DRAW_LINE
input int Length = 20;
double MaBuf[];
// Pine: f(len) => ta.sma(close, len)
double Ma(int len)
{
return ta.sma(close, len);
}
int OnInit()
{
SetIndexBuffer(0, MaBuf, INDICATOR_DATA);
return INIT_SUCCEEDED;
}
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[])
{
for(int i = prev_calculated > 0 ? prev_calculated - 1 : 0; i < rates_total; i++)
{
if(Close[i] > open[i])
{
double body = Close[i] - open[i];
}
MaBuf[i] = bar_index < Length ? na : Ma(Length) + hl2 * 0.0 + body * 0.0;
}
return rates_total;
}MetaEditor 5 (build 6140) reports:
undeclared identifier 'Close' (line 28: if(Close[i] > open[i]))
'[' - array required (line 28: the follow-on from the unknown name)
undeclared identifier 'Close' (line 30)
'[' - array required (line 30)
undeclared identifier 'bar_index' (line 32)
undeclared identifier 'na' (line 32)
undeclared identifier 'hl2' (line 32)
undeclared identifier 'body' (line 32: declared inside the if block above)
undeclared identifier 'ta' (line 13: return ta.sma(close, len))Two of those lines deserve a closer look. On line 13 the compiler reports ta and stops; once ta.sma is replaced, close inside the helper becomes the next error (undeclared identifier 'close' followed by '[' - array required), because a user function has no price arrays unless you pass them in. The second '[' - array required is noise: once the name is fixed the index error goes with it.
The corrected indicator. Every Pine built-in has become something MQL5 can see:
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots 1
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDodgerBlue
input int Length = 20; // Pine: len = input.int(20)
double MaBuf[];
double Hl2[]; // Pine's hl2 is a built-in series; here it is a buffer we fill
// Pine: f(src, len) => ta.sma(src, len)
// MQL5 has no implicit 'close': the series and the bar index are parameters.
double Sma(const double &src[], const int i, const int len)
{
if(i < len - 1)
return EMPTY_VALUE; // Pine: na on the warm-up bars
double sum = 0.0;
for(int k = 0; k < len; k++)
sum += src[i - k];
return sum / len;
}
int OnInit()
{
SetIndexBuffer(0, MaBuf, INDICATOR_DATA);
SetIndexBuffer(1, Hl2, INDICATOR_CALCULATIONS);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
return INIT_SUCCEEDED;
}
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++)
{
Hl2[i] = (high[i] + low[i]) / 2.0; // Pine: hl2
double body = 0.0; // declared in the scope that reads it
if(close[i] > open[i])
body = close[i] - open[i];
MaBuf[i] = Sma(Hl2, i, Length); // Pine: ta.sma(hl2, len); i plays bar_index
if(i == rates_total - 1) // Pine: barstate.islast
Comment("body: ", DoubleToString(body, _Digits));
}
return rates_total;
}It compiles with no errors or warnings. What changed, name by name:
ta.sma(src, len)became a plain functionSma(src, i, len). There is nota; you write the function or call a native one (iMAwith a handle andCopyBuffer).closeinside the helper became a parameterconst double &src[], with the bar indexipassed alongside. A Pine function closes over the chart's series; an MQL5 function does not.hl2became a calculation buffer filled on every bar. Pine'shl2,hlc3,ohlc4have no MQL5 counterpart; computing the expression inline is fine when it is used once, but a function that needs the history ofhl2needs an array.bar_indexis the loop variableiwhen the arrays are oldest-first (the default in MQL5).naisEMPTY_VALUEin a plot buffer and a guarded return elsewhere; it is not a keyword.bodyis declared before theif, in the scope that reads it, and only assigned inside the branch.Closeisclose. MQL5 identifiers are case-sensitive and the predefined MQL4 arrays do not exist.
Other causes of the same message
- MQL4 habits.
Bid,Ask,Bars,Point,DigitsandOrderSendwith the MQL4 signature are gone or renamed in MQL5. UseSymbolInfoDouble(_Symbol, SYMBOL_BID),_Point,_Digits, andCTradefrom<Trade\Trade.mqh>. See MQL4 vs MQL5. - Missing include.
CTrade,CPositionInfoandCSymbolInfoare undeclared until the header is included. The error names the class, not the header. - Using a variable before its declaration line. MQL5 reads top to bottom. A global used in
OnInitbut declared further down the file is undeclared at that point; move the declaration up. - A typo the Pine editor would have caught.
Lenght,prev_calulated. The error text quotes the misspelt name, so read it literally. - Loop variable used after the loop.
for(int i = 0; ...)declaresifor the loop body only; aniafter the closing brace is undeclared. Declare it before the loop if the final value matters. - Converted code. The Stratlate converter does not emit any of these names raw. The script body becomes a per-bar function that receives the
OnCalculatearrays, socloseis in scope;ta.sma(close, len)is emitted aspine_sma(close, __pineBar, (int)(len)),bar_indexas__pineBar,naas thePINE_NAconstant,barstate.islastas__pineBar == __pineLastBarandclose[1]aspine_hist(close, __pineBar, 1), which returns na instead of reading before bar 0. Script variables are declared once at file scope, so theif-scope error cannot occur. If a generated file does not compile, check first thatPineRuntime.mqhsits next to the.mq5: without it MetaEditor stops withfile '...\PineRuntime.mqh' not foundbefore it reaches any identifier. An undeclared identifier in a generated file is usually a name you added while editing it.
Pitfalls
- Declaring globals named
close,openortimeto make the errors go away. The names then shadow theOnCalculateparameters inside that function (MetaEditor warnsdeclaration of 'close' hides global variable) and your helper reads an empty array. Pass arrays as parameters instead. - Fixing the first error and recompiling once. MetaEditor may stop analysing a line at its first problem, as it did at
taabove. Expect a second round of errors on the same line, and fix the whole line, not the first name on it. - Replacing
nawith0. Zero is a valid price difference and a valid oscillator value. A plot buffer wantsEMPTY_VALUE; an intermediate value wants a guard. The na guide covers the full set of cases. - Using
iasbar_indexafterArraySetAsSeries(close, true). With series indexing, index 0 is the newest bar, soicounts backwards andbar_indexisrates_total - 1 - i. Pick one orientation per file. - Expecting
#includeto give you ataobject. No standard header provides Pine's namespaces. The functions you need are listed one by one in the cheat sheet, each with its MQL5 counterpart.
FAQ
Why does MetaEditor say undeclared identifier 'close' when close is right there in OnCalculate?
Because the name is used outside OnCalculate, usually in a helper function. The price arrays are parameters of OnCalculate and exist only inside it. Pass the array (const double &src[]) and the bar index to the helper, or read prices with iClose(_Symbol, _Period, shift) which works from any function.
What is the MQL5 equivalent of the ta namespace?
There is none. Each ta.* function maps to either a native indicator handle (iMA, iRSI, iATR with CopyBuffer) or a short function you write yourself. The results are not always identical on early bars, so compare the two on the same bars before trusting a port.
Why is 'body' undeclared when it was assigned a few lines earlier?
It was declared inside the braces of an if block, and MQL5 scopes a declaration to those braces. Declare it before the if with a default value and assign inside the branch, which is also how Pine's own var-less variables behave when you write x = cond ? a : b.
Let the converter do the mechanical part
Paste the original script and get a conversion that compiles, with every construct that could not be carried over reported instead of hidden. Review, compile and backtest the result before trading.
Open the converter