CopyBuffer in Pine Script: the value is just the series
Short answer
No call is needed: a ta.* result such as ta.ema(close, 10) is already the series. A CopyBuffer(handle, 0, n, 1, buf) read of one value is series[n], and the BarsCalculated readiness check has no counterpart.
In MQL5 an indicator function such as iMA or iRSI returns a handle, and CopyBuffer copies its computed values into an array you own. Pine Script has neither step: ta.ema(close, 10) is already the value for the current bar, and older values are read with the history operator. A CopyBuffer(handle, 0, n, 1, buf) read of one value is series[n] in Pine, and the handle-readiness check BarsCalculated has no counterpart because a Pine series is always computed up to the bar being evaluated.
What CopyBuffer computes
The signature is int CopyBuffer(handle, buffer_num, start_pos, count, double &buffer[]) (overloads take a start time instead of a position). buffer_num picks the indicator's output, for example MAIN_LINE/SIGNAL_LINE for iMACD or 0–2 for iBands. start_pos counts bars from the present into the past: 0 is the forming bar, 1 the last closed bar. count values are copied, and the function returns how many were copied or −1 on failure, typically because the handle has not finished calculating. A dynamic destination array is resized to count. The copied values are stored oldest first, so without ArraySetAsSeries(buffer, true) the newest value is at buffer[count − 1]; with it, at buffer[0]. BarsCalculated(handle) returns how many bars the indicator has computed, or −1, and is the usual guard before copying.
The Pine Script equivalent
Map each copied element to a history index. The one subtlety is timing: an Expert Advisor typically runs on the first tick of a new bar and reads start_pos = 1, the bar that just closed. Pine evaluates a historical bar at its close, where that same value is the current one, series[0]. Restrict the logic to confirmed bars with barstate.isconfirmed so the realtime bar behaves the same way.
//@version=6
indicator("CopyBuffer replacement", overlay = true)
fastLen = input.int(10, "Fast MA", minval = 1)
slowLen = input.int(30, "Slow MA", minval = 1)
fast = ta.ema(close, fastLen) // the handle and the buffer are just this series
slow = ta.ema(close, slowLen)
// MQL5 on the first tick of a new bar: CopyBuffer(h, 0, 1, 2, buf) with
// ArraySetAsSeries(buf, true) gives buf[0] = bar just closed, buf[1] = the one before.
// Pine runs at the close of that same bar, where those values are fast and fast[1].
crossedUp = barstate.isconfirmed and fast[1] <= slow[1] and fast > slow
crossedDown = barstate.isconfirmed and fast[1] >= slow[1] and fast < slow
plot(fast, "Fast", color.rgb(30, 144, 255))
plot(slow, "Slow", color.orange)
plotshape(crossedUp, "Cross up", shape.triangleup, location.belowbar, color.green)
plotshape(crossedDown, "Cross down", shape.triangledown, location.abovebar, color.red)The MQL5 Expert Advisor this replaces. It copies two values from each moving-average handle, starting at the last closed bar, into series-ordered arrays and tests for a crossover:
input int InpFast = 10;
input int InpSlow = 30;
int fastHandle, slowHandle;
double fastBuf[], slowBuf[];
int OnInit()
{
fastHandle = iMA(_Symbol, _Period, InpFast, 0, MODE_EMA, PRICE_CLOSE);
slowHandle = iMA(_Symbol, _Period, InpSlow, 0, MODE_EMA, PRICE_CLOSE);
if(fastHandle == INVALID_HANDLE || slowHandle == INVALID_HANDLE)
return(INIT_FAILED);
ArraySetAsSeries(fastBuf, true); // index 0 = newest copied value
ArraySetAsSeries(slowBuf, true);
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
IndicatorRelease(fastHandle);
IndicatorRelease(slowHandle);
}
void OnTick()
{
if(BarsCalculated(fastHandle) <= InpFast || BarsCalculated(slowHandle) <= InpSlow)
return; // handles not ready yet
// start_pos 1 = last closed bar, count 2 = that bar and the one before it
if(CopyBuffer(fastHandle, 0, 1, 2, fastBuf) != 2) return;
if(CopyBuffer(slowHandle, 0, 1, 2, slowBuf) != 2) return;
bool crossedUp = fastBuf[1] <= slowBuf[1] && fastBuf[0] > slowBuf[0];
bool crossedDown = fastBuf[1] >= slowBuf[1] && fastBuf[0] < slowBuf[0];
if(crossedUp) Print("fast EMA crossed above slow EMA on the last closed bar");
if(crossedDown) Print("fast EMA crossed below slow EMA on the last closed bar");
}Where the two differ
| MQL5 | Pine Script |
|---|---|
h = iMA(…) in OnInit | ma = ta.ema(…) at script level, evaluated every bar |
CopyBuffer(h, 0, 0, 1, b), b[0] | ma (forming bar on realtime; the bar's final value on history) |
CopyBuffer(h, 0, 1, 1, b), b[0] on a new bar | ma at the close of that bar, or ma[1] one bar later |
CopyBuffer(h, 0, s, k, b) with ArraySetAsSeries(b, true), b[j] | ma[s + j] |
Same without ArraySetAsSeries, b[j] | ma[s + k − 1 − j] |
buffer_num | The matching tuple element or separate series |
Return value −1, BarsCalculated < bars | No such state; early bars are na instead |
IndicatorRelease(h) | Nothing to release |
What the Stratlate converter emits
The MQL5 → Pine engine resolves the handle to the producer call (for example ta.ema(close, int(InpFast))) and rewrites a statement-level CopyBuffer as an assignment of that series to the destination, honouring start_pos as a history offset and, for a non-zero literal buffer_num on a multi-line indicator, re-selecting the line. A small literal count (2 to 8) into an array becomes a loop of array.set calls; our probe of the EA above produced exactly that, with the bar alignment adjusted so the values are those of the closed bars. Such a multi-value copy from start_pos = 0 in an EA raises a warning that signals will fire one bar later than the original. Used inside an expression, CopyBuffer is reported as an approximation that evaluates to 0, and BarsCalculated becomes bar_index with an MQLW0501 warning. Compile the output and backtest it against the MT5 trade list.
Pitfalls
- Forgetting the array order. Without
ArraySetAsSeries,buf[0]after a two-value copy is the older value; porting it asma[0]inverts every crossover test. - Translating
start_pos = 1mechanically to[1]in a script that also usesbarstate.isconfirmed. That waits one more bar than the EA did; at a confirmed bar's close the EA's shift-1 value is[0]. - Reading the forming bar (
start_pos = 0) in an EA and expecting the same signals in Pine's backtest. History bars in Pine only exist at their close, so intrabar signals cannot be reproduced on history. - Ignoring a failed copy in MQL5. If the return value is not checked, the array keeps old values and the EA trades on stale data; there is no Pine analogue to port.
- Assuming
buffer_numorder equals plot order. It follows the called indicator'sSetIndexBuffercalls.
FAQ
What replaces BarsCalculated in Pine?
Nothing is needed: every series is computed through the current bar. To skip the warm-up, test na(ma) or bar_index >= length.
How do I read several past values at once?
Use the history operator for each one, ma[1], ma[2], and so on, or functions such as ta.highest(ma, 5) over a window. Pine has no array copy of a series because the history is already addressable.
Does CopyBuffer with a start time have an equivalent?
There is no time-keyed lookup in Pine. Store the value in a var variable when time reaches the bar you want, or compute the bar offset from bar_index.
Convert the whole program
Paste an MQL4 or MQL5 indicator or Expert Advisor and get Pine Script v6 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.
Open the converterRelated
- Pine close[1] vs MQL5 arrays: indexing and ArraySetAsSeries
- ArraySetAsSeries in Pine Script: index direction and []
- iMA in Pine Script: ta.sma, ta.ema, ta.rma or ta.wma by mode
- close[1] in MQL5: the history operator and array offsets
- Convert MQL5 to Pine Script (v6) — online MT5 to TradingView converter