OnInit in Pine Script: handles, buffers and properties
Short answer
Pine has no init handler; OnInit's work becomes declarative. Metadata goes in the indicator() or strategy() call, parameters and limits in input.* calls, and handles disappear because ta.ema(src, len) is called per bar.
OnInit runs once when an MQL5 program is attached: it binds buffers, creates indicator handles, sets the short name and digits, validates inputs and returns INIT_SUCCEEDED or a failure code. Pine Script has no init handler. Everything OnInit does is declarative in Pine: the indicator() or strategy() call carries the metadata, input.* calls carry the parameters and their limits, and indicator handles are simply not needed because ta.ema(src, len) is a function you call per bar.
What OnInit computes
An indicator's OnInit typically does four things. It calls SetIndexBuffer(i, array, INDICATOR_DATA) to turn global double arrays into drawn buffers, and PlotIndexSet* to adjust what #property lines did not cover. It creates handles with iMA, iRSI, iCustom and so on, which start a background calculation whose results are read later with CopyBuffer. It sets display metadata: IndicatorSetString(INDICATOR_SHORTNAME, …), IndicatorSetInteger(INDICATOR_DIGITS, …), levels for a separate window. And it validates inputs, returning INIT_PARAMETERS_INCORRECT to stop the program. An EA's OnInit additionally configures its CTrade object (magic number, deviation, filling mode) and may set a timer with EventSetTimer.
Pine's execution model has no "before the first bar" phase that you can code; the script body runs on the first bar like on any other. The declaration statement and the input functions are evaluated with constant arguments, so they act as the configuration layer. Anything that must happen only once is written with var (initialised on the first bar, kept afterwards) or inside if barstate.isfirst.
The Pine Script equivalent
An EMA indicator whose OnInit does all four jobs, and the Pine script in which each job has moved to a declaration.
//@version=6
// Everything OnInit did is declared here: title, window, precision, inputs.
indicator("EMA", shorttitle = "EMA", overlay = true, precision = 5)
len = input.int(50, "EMA length", minval = 1) // the InpLen < 1 check
src = input.source(close, "Applied price") // ENUM_APPLIED_PRICE
// No handle: the moving average is a function call, evaluated once per bar.
ema = ta.ema(src, len)
// The plot title is what PLOT_LABEL set (it must be a constant string in Pine);
// color and width are what the #property lines set.
plot(ema, title = "EMA", color = color.rgb(255, 215, 0), linewidth = 2)#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrGold
#property indicator_width1 2
input int InpLen = 50; // EMA length
input ENUM_APPLIED_PRICE InpPrice = PRICE_CLOSE; // Applied price
double EmaBuffer[];
int emaHandle = INVALID_HANDLE;
int OnInit()
{
if(InpLen < 1)
{
Print("EMA length must be at least 1");
return(INIT_PARAMETERS_INCORRECT);
}
SetIndexBuffer(0, EmaBuffer, INDICATOR_DATA);
PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpLen - 1);
PlotIndexSetString(0, PLOT_LABEL, "EMA(" + IntegerToString(InpLen) + ")");
IndicatorSetString(INDICATOR_SHORTNAME, "EMA " + IntegerToString(InpLen));
IndicatorSetInteger(INDICATOR_DIGITS, _Digits);
emaHandle = iMA(_Symbol, _Period, InpLen, 0, MODE_EMA, InpPrice);
if(emaHandle == INVALID_HANDLE)
return(INIT_FAILED);
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
if(emaHandle != INVALID_HANDLE)
IndicatorRelease(emaHandle);
}
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 toCopy = (prev_calculated == 0) ? rates_total : rates_total - prev_calculated + 1;
if(CopyBuffer(emaHandle, 0, 0, toCopy, EmaBuffer) <= 0)
return(0);
return(rates_total);
}| OnInit line | Pine |
|---|---|
#property indicator_chart_window | overlay = true |
IndicatorSetString(INDICATOR_SHORTNAME, …) | shorttitle = "…" (must be a constant) |
IndicatorSetInteger(INDICATOR_DIGITS, _Digits) | precision = n, or format = format.price to follow the symbol |
SetIndexBuffer + #property indicator_color1 | plot(series, color = …) |
PlotIndexSetString(0, PLOT_LABEL, …) | title = "…" on the plot |
if(InpLen < 1) return(INIT_PARAMETERS_INCORRECT) | minval = 1 on input.int, or runtime.error() for conditions an input range cannot express |
iMA(...) handle + CopyBuffer | ta.ema(src, len) |
OnDeinit / IndicatorRelease | Nothing; Pine has no teardown |
trade.SetExpertMagicNumber(...) | Nothing; a strategy identifies orders by string id |
Where the two differ
Failure codes. MQL5 can refuse to start. Pine cannot; the closest is runtime.error("message"), which stops the script with a red message on the chart and is evaluated per bar, so guard it so it fires once.
Constant metadata. title, shorttitle, precision, overlay and plot titles must be compile-time constants. The common MQL5 habit of building the short name from inputs ("EMA " + IntegerToString(InpLen)) does not translate; TradingView shows the input values next to the indicator name on its own.
Handles are calculations, not objects. An MQL5 handle computes the whole indicator once in the background and is read with CopyBuffer. A ta.* call in Pine is evaluated on every bar and keeps its own history. The practical consequence: the call must be reached on every bar (not hidden inside a condition) or its history breaks, which is the subject of the conditional-ta-calls guide linked below.
Input validation happens in the dialog. minval, maxval and step on input.int and input.float prevent bad values before the script runs; MQL5 inputs accept anything and must be checked in code.
Timers and events. EventSetTimer, OnTimer, OnChartEvent and OnTrade have no Pine equivalent at all; a script only runs when a bar or tick arrives.
What the Stratlate converter emits
The MQL5 to Pine engine does not emit a function for OnInit. An OnInit that only returns a status code is dropped as inert (StrategyLowering); one with real work has its statements lowered into the script body under an _on_init_extras marker. The #property indicator_chart_window / indicator_separate_window directive becomes overlay=true / overlay=false (IndicatorLowering), SetIndexBuffer is absorbed into a plot() per buffer and reported as such, and input declarations become input.int / input.float / input.bool / input.string with the trailing comment as the title; an ENUM_APPLIED_PRICE input is emitted as input.source(close, …). For the program above the iMA handle plus CopyBuffer was emitted as an inline EMA recurrence per bar (seeded with the first value), and a literal IndicatorShortName string becomes the indicator() title. IndicatorSetString / IndicatorSetInteger are reported as dropped (MQLW0500: no indicator() metadata is emitted for them), PlotIndexSet* calls are reported as styling that Pine sets at the plot() call, and a parameter check that returns a failure code becomes a log.info. Review the report's dropped list and add shorttitle / precision by hand if you need them.
Pitfalls
- Building
titleorshorttitlefrom an input. Pine rejects it: "Cannot call 'indicator' with argument 'shorttitle'… expected const string". Use a fixed string. - Putting the
ta.*call where the handle creation was (inside a guard that runs once). The function must execute on every bar; avar-guarded call returns a frozen value and the plot is a flat line. - Translating
INIT_FAILEDas a silentreturn. Pine has no script-level return; useruntime.error()or let the plot bena, and say so in the description so users understand why nothing draws. - Forgetting
precision. An oscillator that MQL5 showed with two digits defaults to the symbol's price precision in Pine; setprecision = 2onindicator(). - Carrying over
OnDeinitcleanup of chart objects. Pine deletes drawings automatically when the script is removed, and a loop that deletes objects on the last bar only removes your own work.
FAQ
Where do I put code that must run once, like OnInit?
Use var for variables that initialise once, or if barstate.isfirst for a block that should execute only on the first bar. Both are evaluated as part of the normal per-bar run; there is no separate phase.
How do I convert IndicatorSetDouble(INDICATOR_LEVELVALUE, …) levels?
Each level is an hline(value, "Title", color, hline.style_dashed) call. The value must be a constant or an input; fill() between two hline results reproduces a shaded zone.
Does strategy() need anything from an EA's OnInit?
Only the trading parameters: default_qty_type and default_qty_value for the lot size, pyramiding for stacked positions, commission_type / commission_value and slippage for costs, and initial_capital. Magic numbers, deviation and filling modes have no counterpart.
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