Pine User-Defined Types, Methods and Libraries in MQL5

Short answer

MQL5 has structs, classes, member functions and include files, but Pine objects are references while MQL5 structs are values. That one difference breaks most hand conversions of object-based Pine indicators, so keep reference semantics when you port them.

Modern Pine scripts are built from type declarations, methods, arrays of objects and imported libraries. MQL5 has all of the ingredients (structs, classes, member functions and include files) but the semantics differ in one place that breaks most hand conversions: Pine objects are references, MQL5 structs are values. This guide is for developers converting object-based Pine indicators who want the result to behave the same bar by bar.

A Pine type with a method

An indicator that records a zone every time price makes a 20-bar high, marks it broken when a close goes above it, and plots how many zones are still intact:

//@version=6
indicator("Breakout zones")
type Zone
    float top
    float bottom
    bool  broken = false

method update(Zone this, float price) =>
    if price > this.top
        this.broken := true
    this.broken

var zones = array.new<Zone>()
if high > ta.highest(high, 20)[1]
    zones.push(Zone.new(high, low))
    if zones.size() > 50
        zones.shift()

int active = 0
for z in zones
    if not z.update(close)
        active += 1
plot(active, "Active zones")

Three things happen here that MQL5 needs to reproduce: Zone has a default field value; update changes the object it is called on; and var zones keeps its contents from bar to bar.

The MQL5 version with a struct

A type maps to a struct, and a method whose first parameter is the type maps to a member function. MQL5 structs cannot take default member values, so an Init function (or a constructor) sets them. array<Zone> is a dynamic array of structs; push is ArrayResize plus assignment and shift is ArrayRemove(zones, 0, 1).

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_label1  "Active zones"

input int InpLookback = 20;  // breakout lookback
input int InpMaxZones = 50;  // zones kept

struct Zone
  {
   double            top;
   double            bottom;
   bool              broken;
   void              Init(const double t, const double b) { top = t; bottom = b; broken = false; }
   // Pine: method update(Zone this, float price)
   bool              Update(const double price)
     {
      if(price > top)
         broken = true;
      return broken;
     }
  };

double Active[];
Zone   zones[];
int    processed = 0;   // closed bars already folded into zones[]

int OnInit()
  {
   SetIndexBuffer(0, Active, INDICATOR_DATA);
   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[])
  {
   if(prev_calculated == 0)
     {
      ArrayResize(zones, 0);
      processed = 0;
     }
   // closed bars only: zones[] is state, and the forming bar is re-run on
   // every tick, which would push the same zone again and again
   for(int i = processed; i < rates_total - 1; i++)
     {
      if(i >= InpLookback
         && high[i] > high[ArrayMaximum(high, i - InpLookback, InpLookback)])
        {
         const int n = ArraySize(zones);
         ArrayResize(zones, n + 1);
         zones[n].Init(high[i], low[i]);
         if(ArraySize(zones) > InpMaxZones)
            ArrayRemove(zones, 0, 1);
        }
      int active = 0;
      for(int k = 0; k < ArraySize(zones); k++)
         if(!zones[k].Update(close[i]))   // updates the element in place
            active++;
      Active[i] = active;
     }
   processed = MathMax(processed, rates_total - 1);
   Active[rates_total - 1] = EMPTY_VALUE;
   return rates_total;
  }

Two details carry the behaviour. zones[k].Update(close[i]) calls the member function on the array element itself, so the change sticks. And the loop only processes closed bars: zones[] is state, and OnCalculate runs the newest bar again on every tick. Pine rolls var variables back before each realtime update, so the zone is pushed once; an MQL5 loop that includes the forming bar would push it on every tick.

References vs values

In Pine, assigning an object copies the reference:

a = Zone.new(1.10, 1.09)
b = a              // b and a are the SAME object
b.broken := true   // a.broken is now true too
c = a.copy()       // an independent copy

In MQL5, assigning a struct copies it:

Zone a;
a.Init(1.10, 1.09);
Zone b = a;          // b is a COPY of a
b.broken = true;     // a.broken is still false

Zone tmp = zones[k]; // copy: tmp.Update() would not change zones[k]
zones[k].Update(close[i]);   // in place: changes the element

If your Pine code takes an object out of an array, changes it and expects the array to see the change, a struct copy will silently lose the update. Either always work through the array index, as above, or use a class and pointers, which have Pine's sharing behaviour:

class CZone
  {
public:
   double            top, bottom;
   bool              broken;
                     CZone(const double t, const double b) : top(t), bottom(b), broken(false) {}
   bool              Update(const double price) { if(price > top) broken = true; return broken; }
  };

CZone *a = new CZone(1.10, 1.09);
CZone *b = a;        // same object, as in Pine
b.broken = true;     // a.broken is true
// Pine na(a)  ->  a == NULL ;  every new needs a delete (OnDeinit)
delete a;

Pine's na object maps naturally to a NULL pointer. The cost is memory management: every object created with new must be deleted, usually in OnDeinit and when you remove it from a collection.

Methods and built-in method syntax

Pine's z.update(close) is sugar for update(z, close). In MQL5 you can write either a member function or a free function that takes the struct by reference (bool update(Zone &z, double price)); MQL5 passes structs to functions by reference only, so both change the original. Built-in method calls on collections translate to the array functions: zones.size() to ArraySize(zones), zones.get(i) to zones[i], zones.pop() to reading the last element and ArrayResize(zones, n - 1).

Libraries

A Pine library exports types and functions for other scripts to import:

//@version=6
// @description Zone helpers shared by several indicators
library("ZoneLib")

export type Zone
    float top
    float bottom
    bool  broken = false

// @function True while price is inside the zone
export method contains(Zone this, float price) =>
    price <= this.top and price >= this.bottom

The MQL5 counterpart is an include file in MQL5\Include, pulled in with #include at compile time:

// MQL5\Include\ZoneLib.mqh
struct Zone
  {
   double            top;
   double            bottom;
   bool              broken;
   bool              Contains(const double price) const { return price <= top && price >= bottom; }
  };

// in the indicator:   #include <ZoneLib.mqh>

There is no versioning in an include: import user/ZoneLib/1 pins a library version, while #include takes whatever file is on disk when you compile. Keep a copy per project if the library changes.

What Stratlate does with types and libraries

Stratlate turns each type into an MQL5 struct. A type that is stored in an array, holds a drawing, or is passed around as a value is kept in a pool and referenced by index, so a change made through one variable is visible through the others, as in Pine. Methods become functions that take the receiver as their first argument. A type with a map or matrix field is reported as not converted. var state, including arrays and pooled objects, is saved at the start of the forming bar and restored before each re-run, which reproduces Pine's rollback. Imports of public libraries whose licence allows redistribution, such as TradingView's own, are bundled and inlined when they convert in full, and only the functions the script uses are brought in. For any other import, paste the library functions you use into the script and convert again. Compile the output in MetaEditor and test it before use.

Pitfalls

  • Modifying a copy. Zone z = zones[k]; z.Update(c); changes the copy only. Symptom: zones never become broken.
  • State changed on the forming bar. Pushing objects or counting inside a loop that includes the newest bar. Symptom: correct history, but values that grow with every tick on the live bar.
  • Missing defaults. MQL5 does not reliably zero-initialise local structs. Symptom: random values in fields that Pine defaulted to na or false.
  • Leaking class objects. Pointers created with new and never deleted are reported as leaked memory when the indicator is removed.
  • Unbounded arrays. Pine scripts usually cap their arrays (shift past 50, 500 and so on). Keep the cap; otherwise the per-bar loop slows down over long histories.
  • Library licences. Copying a library's code into your EA is covered by its licence; check it before you distribute the result.

FAQ

Should a Pine type become an MQL5 struct or a class?

Use a struct when objects are only stored in variables and arrays and you index them directly; it needs no memory management. Use a class with pointers when objects are shared between several variables or arrays, because that is how Pine objects behave, and delete them when done.

Can I import a TradingView library into MQL5?

No. MQL5 cannot download TradingView code. Copy the functions and types you use into an MQL5 include file, or paste them into the Pine script before converting it. Respect the library's licence when you copy it.

Why does my converted indicator create the same object many times on the live bar?

OnCalculate re-runs the newest bar on every tick, and Pine resets var state between those runs while MQL5 does not. Only change persistent state on closed bars, or save the state at the start of the bar and restore it before each re-run.

Convert object-based Pine code

Stratlate converts Pine types, methods and arrays of objects to MQL5 and resolves imports of bundled public libraries.

Open the converter

Related guides