CopyRates and MqlRates in Pine Script: OHLCV built-ins

Short answer

Use the built-in series instead of a bar record: rates[i].close is close[i], tick_volume and real_volume both become volume, and time becomes time in milliseconds. spread has no equivalent.

CopyRates copies a block of bars into an array of MqlRates structures, each holding time, open, high, low, close, tick_volume, spread and real_volume. Pine Script has no bar record to copy: the fields are built-in series that always exist for the chart's symbol and timeframe. rates[i].close becomes close[i] (with the bar offset adjusted for an EA), tick_volume and real_volume both become volume, time becomes time in milliseconds, and spread has no equivalent.

What CopyRates computes

CopyRates(symbol, timeframe, start_pos, count, rates) returns the number of bars copied, or -1 on error, and fills rates with bars starting start_pos bars back from the forming bar. Two other overloads take a start time and a count, or a start and stop time. The destination array's direction decides the order: with ArraySetAsSeries(rates, true), rates[0] is the newest copied bar; without it, rates[0] is the oldest. If fewer bars are available than requested, the call copies what it has and returns a smaller number, which is why the result is always checked against count.

The fields: time is the bar's open time in seconds; tick_volume is the number of price changes during the bar (the only volume most forex brokers have); real_volume is exchange-traded volume and is zero on most CFD and forex feeds; spread is the bar's spread in points as recorded by the broker.

In Pine every one of these is already a series aligned to the current bar. close, open, high, low, volume and time on the current bar are the record; [n] gives any previous record. There is nothing to copy, nothing to check for availability, and for another symbol or timeframe a tuple from request.security returns several fields in one call.

The Pine Script equivalent

A bullish-engulfing entry with a tick-volume filter. The EA copies three bars into a series-ordered MqlRates array; the strategy reads the built-ins.

//@version=6
strategy("Engulfing with volume", overlay = true)

lots   = input.float(0.10, "Lots")
volMul = input.float(1.5, "Volume must exceed this x previous bar")

// No MqlRates array: open/high/low/close/volume/time ARE the bar record.
// The strategy runs at the close of each bar, so this bar is the EA's rates[1]
// and [1] is the EA's rates[2].
prevBear = close[1] < open[1]
lastBull = close > open
engulfs  = close >= open[1] and open <= close[1]
volumeUp = volume > volMul * volume[1]       // TradingView volume; MT5 tick_volume differs

if prevBear and lastBull and engulfs and volumeUp and strategy.position_size == 0
    strategy.entry("engulfing", strategy.long, qty = lots)
    strategy.exit("engulfing sl", "engulfing", stop = low)
#include <Trade\Trade.mqh>

input double InpLots   = 0.10;   // Lots
input double InpVolMul = 1.5;    // Volume must exceed this x previous bar

CTrade trade;

int OnInit()
{
   return(INIT_SUCCEEDED);
}

void OnTick()
{
   MqlRates rates[];
   ArraySetAsSeries(rates, true);                 // rates[0] = forming bar, rates[1] = last closed
   if(CopyRates(_Symbol, _Period, 0, 3, rates) < 3)
      return;                                     // history not ready yet

   static datetime lastBar = 0;
   if(rates[0].time == lastBar)
      return;                                     // act once per bar
   lastBar = rates[0].time;

   // Bullish engulfing on the two last closed bars, with a tick-volume filter.
   bool prevBear  = rates[2].close < rates[2].open;
   bool lastBull  = rates[1].close > rates[1].open;
   bool engulfs   = rates[1].close >= rates[2].open && rates[1].open <= rates[2].close;
   bool volumeUp  = rates[1].tick_volume > InpVolMul * rates[2].tick_volume;

   if(prevBear && lastBull && engulfs && volumeUp && !PositionSelect(_Symbol))
      trade.Buy(InpLots, _Symbol, 0.0, rates[1].low, 0.0, "engulfing");
}
MqlRates fieldPineNote
open, high, low, closeopen, high, low, closeSame prices if the data feed is the same
timetimeMilliseconds in Pine, seconds in MQL5; both bar open
tick_volumevolumeTradingView's volume for the feed, not MetaTrader's tick count
real_volumevolumeSame source
spreadNoneBars on TradingView carry no spread

Index mapping in an EA: the strategy evaluates on the close of the bar the EA calls rates[1], so rates[1] becomes offset 0 and rates[2] becomes [1]. rates[0], the forming bar, has no equivalent on historical bars; its open is the next bar's open, which is where a Pine market order fills. In an indicator that copies with CopyRates inside OnCalculate, use the plain mapping rates[n] → [n].

Where the two differ

Volume is a different quantity. MetaTrader's tick_volume on forex and CFDs counts quotes from that broker. TradingView's volume for the same symbol comes from whichever feed the chart uses (an exchange, a broker, or an aggregate) and can be orders of magnitude different, or zero. A volume filter with an absolute threshold will not transfer; ratios like the one in the example transfer better but still not exactly.

Bar boundaries. Daily and weekly bars start at the broker's server midnight in MetaTrader and at the exchange session start on TradingView, so a daily MqlRates record and Pine's daily close can describe different 24-hour windows.

No partial copies. MQL5 code must handle CopyRates returning fewer bars than asked. Pine's equivalent is na on the earliest bars: close[2] is na on the first two bars, and any comparison with it is false.

Gaps. Both platforms skip bars with no trades, so "two bars ago" may be hours ago after a weekend in both. Neither inserts empty records.

What the Stratlate converter emits

The MQL5 to Pine engine types MqlRates (and MqlTick) as a bar-record type and rewrites field reads through a field map in the Pine renderer: open, high, low, close to the built-ins, tick_volume and real_volume to volume, time to (time / 1000), and bid/ask/last to close. A CopyRates statement becomes a window offset computed by the f_rates_win runtime helper, and rates[n].close is read as close[rates__k + n]; in an EA the window is shifted one bar so rates[1] lands on Pine's current bar, as in the hand-written version. In expression position CopyRates is reported as an approximation ("Pine has no Rates struct"). In our conversion of the program above the OHLC and time reads were indexed correctly, but both tick_volume reads came out as the current bar's volume without their bar offset, so the volume filter compared a value with itself; check every volume field read in the output and add the offset by hand where it is missing. Compile and backtest the result against the original before relying on it.

Pitfalls

  • Keeping the EA's indices. rates[1].close written as close[1] in a strategy is one bar too old; every signal arrives a bar late. It should be close.
  • Porting an absolute tick_volume threshold. A filter like tick_volume > 500 may never or always be true on TradingView's feed. Use a ratio to a moving average of volume, and check that the symbol has volume at all (volume is na or 0 on some index and forex feeds).
  • Translating rates[i].time without dividing by 1000 when the result goes into seconds-based arithmetic. Symptom: time comparisons that are never true.
  • Building a Pine array of closes to imitate the MqlRates buffer. It works, but it duplicates history Pine already keeps and is slower; read close[n] directly.
  • Using spread for a filter. There is no spread on TradingView bars; replace it with a fixed cost in strategy(slippage = …) or drop the filter.

FAQ

How do I copy rates for another symbol or timeframe in Pine?

Request the fields you need as a tuple: [o, h, l, c] = request.security("FX:EURUSD", "60", [open, high, low, close]). Add [1] to each and lookahead = barmerge.lookahead_on to read the last completed bar without repainting.

Is TradingView volume the same as MetaTrader tick_volume?

No. Tick volume is a count of price updates from one broker; TradingView's volume depends on the chart's data source and is often exchange or aggregated volume. Patterns in the two can be similar, absolute values are not.

What replaces CopyRates with a start and stop time?

Pine has no time-range copy. Filter by time instead: compute a boolean such as inRange = time >= startMs and time <= stopMs and accumulate the values you need with var variables while it is true.

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 converter

Related