Pine barcolor and bgcolor in MetaTrader 5
Short answer
MetaTrader 5 has no direct equivalent of barcolor() or bgcolor(). Recolour bars by drawing your own coloured candles, and paint the background by placing rectangles behind the bars.
barcolor() and bgcolor() are one-liners in Pine Script, and many indicators use them as the main way to show a signal. MetaTrader 5 has no direct equivalent for either. This guide is for anyone porting such an indicator to MQL5 who needs the highlighted bars to survive the move, and it shows the two techniques that work: drawing your own coloured candles, and placing background rectangles.
Why there is no one-line equivalent
In TradingView, barcolor(c) recolours the chart's own candle on that bar, and bgcolor(c) paints the full height of the pane behind it. Pine allows both from any script; a barcolor call in an indicator that lives in its own pane still recolours the candles on the main chart.
In MetaTrader the price candles belong to the terminal. An indicator can change the chart-wide colours with ChartSetInteger(0, CHART_COLOR_CANDLE_BULL, clr) and its siblings, but that recolours every candle, not one. There is no per-bar candle colour and no per-bar background property. What an indicator can do is draw on top of the chart: its own candles through buffers, and its own shapes through chart objects. Both only work in the window the drawing lives in, so an MQL5 indicator in a separate window cannot recolour the main chart's candles. If the Pine script is a pane indicator that also calls barcolor, the usual answer is a second, small chart-window indicator that does the colouring.
The Pine example
This indicator flags bars whose volume is more than twice its 20-bar average: the candle turns yellow or orange, and the background turns pale yellow.
//@version=6
indicator("Volume spike highlight", overlay = true)
len = input.int(20, "Average length")
spike = volume > 2 * ta.sma(volume, len)
barcolor(spike ? (close >= open ? color.yellow : color.orange) : na)
bgcolor(spike ? color.new(color.yellow, 85) : na)barcolor: draw coloured candles over the chart
A chart-window indicator with a DRAW_COLOR_CANDLES plot draws a full candle from four buffers (open, high, low, close) plus a colour index buffer. On bars where Pine's colour is na, write EMPTY_VALUE to all four buffers and nothing is drawn, so the terminal's normal candle shows. On highlighted bars, copy the bar's OHLC into the buffers and choose the colour index. The terminal's candle is still there underneath, but yours covers it exactly. For bar charts rather than candles, DRAW_COLOR_BARS works the same way.
bgcolor: rectangles behind the price
For a background, create an OBJ_RECTANGLE that spans the bar's time range from time[i] to time[i] + PeriodSeconds(), with a price range taller than any price the chart will show. Set OBJPROP_BACK so it sits behind the candles and OBJPROP_FILL so it is solid. Chart objects do not take part in the price scale, so a tall rectangle does not squash the chart. Object colours are plain RGB with no transparency, so translate color.new(color.yellow, 85) into a dark or muted shade that suits the chart background rather than full yellow.
Objects cost far more than buffer values, so limit them: draw only the most recent few hundred bars, or merge a run of consecutive highlighted bars into one rectangle.
The complete MQL5 version of the example, using both techniques:
#property indicator_chart_window
#property indicator_buffers 5
#property indicator_plots 1
#property indicator_label1 "Spike bars"
#property indicator_type1 DRAW_COLOR_CANDLES
#property indicator_color1 clrYellow,clrOrange
input int InpLen = 20; // Average length
input int InpBgBars = 500; // Bars that get a background (objects)
double O[], H[], L[], C[], Clr[];
const string BG = "spike_bg_";
int OnInit()
{
SetIndexBuffer(0, O, INDICATOR_DATA);
SetIndexBuffer(1, H, INDICATOR_DATA);
SetIndexBuffer(2, L, INDICATOR_DATA);
SetIndexBuffer(3, C, INDICATOR_DATA);
SetIndexBuffer(4, Clr, INDICATOR_COLOR_INDEX);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
ObjectsDeleteAll(0, BG);
}
void Background(const datetime t, const double top, const bool on)
{
string nm = BG + IntegerToString((long)t);
if(!on) { ObjectDelete(0, nm); return; }
if(ObjectFind(0, nm) < 0)
{
ObjectCreate(0, nm, OBJ_RECTANGLE, 0, t, 0.0, t + PeriodSeconds(), top);
ObjectSetInteger(0, nm, OBJPROP_COLOR, C'60,60,20');
ObjectSetInteger(0, nm, OBJPROP_FILL, true);
ObjectSetInteger(0, nm, OBJPROP_BACK, true);
ObjectSetInteger(0, nm, OBJPROP_SELECTABLE, false);
}
}
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) ObjectsDeleteAll(0, BG); // full recalculation
int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++)
{
O[i] = H[i] = L[i] = C[i] = EMPTY_VALUE; // na: the normal candle shows
Clr[i] = 0;
bool spike = false;
if(i >= InpLen - 1)
{
double sum = 0.0;
for(int k = 0; k < InpLen; k++) sum += (double)tick_volume[i - k];
spike = tick_volume[i] > 2.0 * sum / InpLen;
}
if(spike)
{
O[i] = open[i]; H[i] = high[i]; L[i] = low[i]; C[i] = close[i];
Clr[i] = close[i] >= open[i] ? 0 : 1;
}
if(i >= rates_total - InpBgBars)
Background(time[i], high[i] * 10.0, spike);
}
return rates_total;
}The rectangle for a bar is created once and deleted if the live bar stops qualifying, which mirrors how TradingView repaints the realtime bar's colours on each tick. OnDeinit removes every object by prefix, otherwise the rectangles stay on the chart after the indicator is removed.
bgcolor in a separate window
When the Pine indicator lives in its own pane, a buffer is simpler than objects. Fix the window's scale, then draw a DRAW_COLOR_HISTOGRAM that reaches the top of the scale on highlighted bars. Declare it as the first plot so the oscillator lines are drawn over it.
// bgcolor in a separate-window indicator: full-height columns behind the oscillator
#property indicator_separate_window
#property indicator_minimum 0
#property indicator_maximum 100
#property indicator_type1 DRAW_COLOR_HISTOGRAM
#property indicator_color1 clrDarkSlateGray,clrMaroon
// in OnCalculate, per bar:
BgBuf[i] = condition ? 100.0 : EMPTY_VALUE; // reach the top of the fixed scale
BgColor[i] = bullish ? 0 : 1;This only works when the oscillator has a known range, such as RSI or stochastic. For an unbounded oscillator, use rectangles in the subwindow instead; pass the subwindow number from ChartWindowFind() to ObjectCreate.
What Stratlate does with barcolor and bgcolor
Stratlate's converter does not draw barcolor or bgcolor at present. A constant colour is dropped with a cosmetic note in the conversion report. A colour chosen per bar, such as barcolor(signal ? color.yellow : na), is reported as an approximation, because it usually is how the script shows a signal; the condition itself is still computed in the generated code, so you can attach one of the techniques above to it. Read the report for these lines, and compile and check the indicator on a chart before relying on it.
Pitfalls
- Using
volumeon forex or CFDs. MT5 fills thevolumearray only where the broker supplies exchange volume; otherwise it is zero. Symptom: the condition never fires. Usetick_volume, and expect its values to differ from TradingView's feed. - Writing 0 instead of
EMPTY_VALUEforna. Symptom: flat candles drawn at price zero, and the chart scale collapses to include them. - Drawing the candles in a separate window. Symptom: a second copy of the price chart appears in the subwindow and the main candles are unchanged.
- "Chart on foreground" switched on. With
CHART_FOREGROUNDenabled the terminal's candles are drawn over indicator plots. Symptom: your coloured candles are hidden. - One object per bar over the whole history. Symptom: the terminal slows down on long charts. Limit the range or merge runs.
- Objects not cleaned up. Symptom: highlighted backgrounds remain after the indicator is removed or its inputs change. Delete by prefix in
OnDeinit, and clear and redraw whenprev_calculatedis 0.
FAQ
Can an MQL5 indicator change the colour of a single candle?
Not the terminal's own candle. It can draw its own candle over it with a DRAW_COLOR_CANDLES plot in a chart-window indicator, which looks the same. ChartSetInteger can only change the colours of all candles at once.
Can a separate-window indicator colour the main chart's bars?
No. Buffers and objects draw in the indicator's own window. Put the bar colouring in a second, chart-window indicator.
Does Stratlate convert barcolor and bgcolor?
Not at present. A constant colour is dropped with a cosmetic note, and a colour chosen per bar is reported as an approximation while its condition is still computed, so you can add the drawing by hand.
Convert the rest of the indicator
Let the converter handle the calculations, plots and inputs, then add the bar and background colours with the techniques above. The report tells you exactly which colour calls it left out.
Open the converter