Constant Right Bar Margin Regardless of Zoom


As an illustration, when a chart is zoomed in, the number of visible bars is small (eg, 10 bars are showing) so the number of pixels required to draw the width of each bar is large. On the other end of the spectrum, when a chart is zoomed out, the number of visible bars is substantial (eg, 1000 bars are showing) so the number of pixels required to draw each bar's width is minimal.

The right bar margin appears to be controlled by the number of "bars." This means the right bar margin increases when the chart is zoomed in, and decreases when the chart is zoomed out. I'd like to specify a constant pixel width for the right bar margin...but alas, I've been unsuccessful so far.

Here's my latest attempt:

function ConvertPixelsToBars( value ) 
	// get extents of chart in "bars" and "pixels"

	lvb = Status("lastvisiblebar"); 
	fvb = Status("firstvisiblebar"); 
	pxchartleft = Status("pxchartleft"); 
	pxchartwidth = Status("pxchartwidth"); 

	// get pixels per bar
	barsOnChart = lvb - fvb + 1;
	pixsOnChart = pxchartwidth - pxchartleft;
	barsPerPix  = barsOnChart/pixsOnChart;
	barOutput = round( value * barsPerPix );
	return barOutput; 

barMargin = ConvertPixelsToBars(50);

SetChartOptions( 1, chartHideQuoteMarker, chartGridMiddle, 0, 0, barMargin );
Plot( C, "", colorDefault, styleCandle );

_TRACE( "DEBUG 50 pixels in bars: " + barMargin );

Any ideas?

Found a way to do this using the 'XShift' parameter of Plot(). The right edge of the last bar is not perfectly constant, but it's close enough. :slightly_smiling_face:

Using the code from my original post, replace:


Plot( C, "", colorDefault, styleCandle, 0, 0, -barMargin );

If there are other ways to achieve a constant right bar margin I'd still like to hear about them.


As an aside, RE: SetChartOptions( mode, flags, gridFlags, ymin, ymax, blankbars )

  1. the 'flags' and 'gridFlags' parameters can be changed on the fly by setting the 'mode' variable appropriately
  2. the 'ymin' & 'ymax' parameters can also be changed on the fly

However, I couldn't get the 'blankbars' parameter to change on the fly. If anyone has been able to accomplish this, I'd be grateful to hear from them.


Just a follow-up after using the above solution for a couple of weeks:

  1. dates and times are not offset with the bars (not surprising, after all, this method shifts the bars when plotted, not internally):
  • the datetime array doesn't align with the offset bars
  • the x-axis date & time labels don't match the bars' actual times
  • the tooltip bar times don't match the actual bar times (though the OHLC values appear to be correct)
  1. hand drawn studies do not remain anchored to the bars when the chart is zoomed.