Cannot use plot in local scope: porting MQL5 to Pine Script

Short answer

Call plot() once at the top level of the script and move the condition into the value: plot(cond ? x : na). The same applies to plotshape, plotchar, hline, fill, bgcolor, barcolor and alertcondition, which also cannot run inside if blocks, loops or functions.

TradingView's Pine Editor refuses to compile a script with Cannot use 'plot' in local scope. when plot() is called inside an if block, a for or while loop, a switch branch or a user-defined function. The same message is given for plotshape, plotchar, plotarrow, plotcandle, plotbar, hline, fill, bgcolor, barcolor and alertcondition, with the function's name in the quotes. The fix is always the same: call the function once at the top level of the script and move the condition into the value, plot(cond ? x : na).

A note on the wording: the text above is TradingView's message as the Pine Editor prints it. Stratlate's own Pine parser does not reproduce this check (it is a rule of TradingView's compiler, not of the grammar), so the error here is quoted from TradingView rather than from a local run.

Why it happens when converting MQL5

An MQL5 indicator draws by writing numbers into buffers. Nothing is "drawn" at the moment of the write: SetIndexBuffer ties an array to a plot once, in OnInit, and from then on the code can write to it, or not, from anywhere in OnCalculate. Writing inside an if is ordinary MQL5, and so is filling three buffers from a loop. Here is a typical one: a moving average drawn green above the price and red below, plus an arrow on the bar where price crosses up.

#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots   3
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrSeaGreen
#property indicator_label1  "MA up"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrCrimson
#property indicator_label2  "MA down"
#property indicator_type3   DRAW_ARROW
#property indicator_color3  clrSeaGreen
#property indicator_label3  "Cross"

input int Length = 20;

double UpBuf[], DnBuf[], CrossBuf[];

int OnInit()
{
   SetIndexBuffer(0, UpBuf, INDICATOR_DATA);
   SetIndexBuffer(1, DnBuf, INDICATOR_DATA);
   SetIndexBuffer(2, CrossBuf, INDICATOR_DATA);
   for(int p = 0; p < 3; p++)
      PlotIndexSetDouble(p, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(2, PLOT_ARROW, 233);
   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++)
   {
      UpBuf[i] = EMPTY_VALUE;
      DnBuf[i] = EMPTY_VALUE;
      CrossBuf[i] = EMPTY_VALUE;
      if(i < Length)
         continue;
      double sum = 0.0;
      for(int k = 0; k < Length; k++)
         sum += close[i - k];
      double ma = sum / Length;
      double prevSum = sum - close[i] + close[i - Length];
      double prevMa  = prevSum / Length;

      if(close[i] > ma)                       // "plot" only on some bars
         UpBuf[i] = ma;
      else
         DnBuf[i] = ma;

      if(close[i] > ma && close[i - 1] <= prevMa)
         CrossBuf[i] = low[i];
   }
   return rates_total;
}

It compiles in MetaEditor 5 without warnings. The literal port keeps the shape of the code, and so keeps the if:

//@version=6
indicator("MA up/down with cross", overlay=true)
len = input.int(20, "Length")
ma = ta.sma(close, len)
if close > ma
    plot(ma, "MA up", color.teal)        // Cannot use 'plot' in local scope.
else
    plot(ma, "MA down", color.red)       // Cannot use 'plot' in local scope.
if ta.crossover(close, ma)
    plotshape(low, "Cross")              // Cannot use 'plotshape' in local scope.

Pine does not have buffers. A plot() call is a declaration: "this script has a plot, and here is the series it shows". TradingView counts the plots of a script when it compiles it, before any bar is processed, and gives each one its own entry in the Style tab of the settings dialog. A plot that exists on some bars and not on others has no meaning in that model, so the compiler requires every plot() to be reached unconditionally, once per bar, at the top level of the script.

Fix

Turn each MQL5 buffer into one Pine series, compute it at the top level, and plot it once. The value EMPTY_VALUE that MQL5 uses for "draw nothing here" is na in Pine:

//@version=6
indicator("MA up/down with cross", overlay=true)
len = input.int(20, "Length")

ma = ta.sma(close, len)
up = close > ma

// The condition moves INTO the series; plot() stays at global scope.
plot(up ? ma : na, "MA up", color.teal, style=plot.style_linebr)
plot(up ? na : ma, "MA down", color.red, style=plot.style_linebr)
plotshape(ta.crossover(close, ma), "Cross", shape.triangleup, location.belowbar, color.teal)

The three MQL5 buffers became three global calls. The if moved into the ternary: up ? ma : na is the green buffer, up ? na : ma is the red one. plot.style_linebr leaves gaps at the na bars instead of joining across them, which is how MetaTrader draws a DRAW_LINE buffer with empty values. The arrow buffer became a plotshape whose series is the boolean condition itself, drawn below the bar. Run through the Stratlate Pine parser, all three scripts on this page convert with status CLEAN, a quick check that they parse.

When the two MQL5 buffers only exist to colour one line, Pine has a shorter answer: one plot with a series colour.

//@version=6
indicator("MA one line, two colours", overlay=true)
len = input.int(20, "Length")
ma = ta.sma(close, len)
maColor = close > ma ? color.teal : color.red
plot(ma, "MA", maColor)

This is the Pine equivalent of MQL5's DRAW_COLOR_LINE with a colour-index buffer, and the line stays continuous. Use the two-plot form when the original really drew two separate lines, or when the user should be able to hide each one in the settings.

Plots filled in a loop

MQL5 code sometimes fills several buffers in a loop over buffer numbers, for example three "close N bars back" lines written by one for over N, through a helper that picks the buffer by index. Pine has no loop form for this, because the number of plots is fixed at compile time. Unroll it: one plot() per buffer, written out.

//@version=6
indicator("Three closes back", overlay=true)
// MQL5 filled three buffers in a for loop; Pine needs one plot() per series.
plot(close[1], "1 bar back", color.gray)
plot(close[2], "2 bars back", color.silver)
plot(close[3], "3 bars back", color.blue)

A loop is still fine for the calculation. Compute into variables inside the for, then plot the variables after it.

Other causes of the same message

  • A plot inside a user-defined function. A function body is a local scope. Return the value from the function and plot the result at the top level: v = myCalc(close) then plot(v).
  • bgcolor or barcolor inside an if. Same rule, same fix: bgcolor(cond ? color.new(color.green, 85) : na).
  • alertcondition inside an if. Pass the condition as the first argument instead: alertcondition(ta.crossover(close, ma), "Cross up"). alert(), by contrast, is allowed in local scope and is usually called inside an if.
  • Drawings are not affected. label.new, line.new, box.new and table.cell can be called anywhere, including inside if barstate.islast. If the MQL5 original used ObjectCreate conditionally, those translate to drawings, not plots; see drawings and objects.
  • Converted code. The Stratlate MQL5 → Pine converter does not produce this error: each SetIndexBuffer buffer becomes a series variable, the conditional writes in OnCalculate become a conditional expression that yields na where nothing was written, and all plot() calls are emitted together in a plots section at the end of the script. The result should still be compared with the original on the same bars, as every conversion should.

Pitfalls

  • Using 0 instead of na for "no value". The line then drops to zero on every bar where the condition is false, and on an overlay chart the price scale stretches to include zero. The MQL5 original wrote EMPTY_VALUE or nothing; the Pine equivalent is na.
  • Forgetting the gaps. With the default plot.style_line, Pine joins the last value before a run of na to the first value after it. If the original showed separate segments, use plot.style_linebr.
  • A var buffer that keeps the last value. MQL5 buffers keep what was written on earlier bars, so a port sometimes uses var float buf = na and assigns it in an if. That plots the last assigned value on every following bar, which is not what the MQL5 code drew if it reset the buffer each bar. Reset it, or compute it with the ternary.
  • Too many plots. Pine allows a limited number of plot outputs per script (64 at the time of writing, counting colour arguments). An MQL5 indicator with dozens of buffers may need some of them turned into drawings or dropped.
  • Calculation buffers plotted by mistake. INDICATOR_CALCULATIONS buffers are not drawn in MetaTrader. Port them as plain variables and do not plot them, or the Pine version shows extra lines.

FAQ

How do I plot only when a condition is true in Pine Script?

Plot a series that is na when the condition is false: plot(cond ? value : na). The call stays at the top level and runs on every bar; the na values are simply not drawn. Add style=plot.style_linebr if the gaps should not be bridged.

Can I call plot() inside a function in Pine Script v6?

No. A function body is local scope, so plot, plotshape, hline, fill, bgcolor and barcolor are rejected there. Return the value, or a tuple of values, from the function and plot them at the top level of the script.

What is the Pine equivalent of an MQL5 buffer that is filled only on some bars?

A series variable assigned on every bar, with na on the bars where MQL5 wrote EMPTY_VALUE or nothing, plotted once at the top level. If the buffer is a colour index for another plot, use a series colour in that plot's color argument instead.

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

Related