Maintain fixed bar height indicator

Adjusts price scale so visible bars have fixed number of pixels per tick (user defined). Also shows deviation from defined height that works in manual scaling as well. Of course the auto scaling only works if other indicators are not affecting the scale (autoscale should be off for other indicators)

It only changes the scale when bars are off the screen to minimize bars moving up and down as one scrolls.

#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.DrawingTools;
using DX = SharpDX;
using D2D = SharpDX.Direct2D1;
#endregion



namespace NinjaTrader.NinjaScript.Indicators
{
	public class PixelsPerTickScaler : Indicator
	{
		private volatile int cachedPanelHeight;
		private double cachedAbsMargin = double.NaN;
		private AutoScaleMarginType cachedMarginType;
		private double cachedMarginUpper = double.NaN;
		private double cachedMarginLower = double.NaN;
		private double stickyMin = double.NaN;
		private double stickyMax = double.NaN;
		private double stickyHeight = double.NaN;
		private bool stickyValid;

		private bool resourcesValid;
		private D2D.Brush desiredBrush;
		private D2D.Brush actualBrush;
		private System.Windows.Media.Brush resDesiredColor;
		private System.Windows.Media.Brush resActualColor;
		private int resOpacity = -1;

		public override string DisplayName
		{
			get { return string.IsNullOrEmpty(Name) ? base.DisplayName : Name; }
		}

		protected override void OnStateChange()
		{
			if (State == State.SetDefaults)
			{
				Description = @"Keeps a fixed pixels-per-tick vertical scale centered on the last visible close. Expands only to keep visible highs/lows on screen.";
				Name = "Pixels per tick scaler";
				Calculate = Calculate.OnPriceChange;
				IsOverlay = true;
				IsAutoScale = true;
				DisplayInDataBox = false;
				DrawOnPricePanel = true;
				PaintPriceMarkers = false;
				ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
				IsSuspendedWhileInactive = true;
				PixelsPerTick = 2;
				ShowScaleBars = true;
				DesiredScaleColor = Brushes.LimeGreen;
				ActualScaleColor = Brushes.Red;
				ReferenceTicks = 40;
				ScaleBarWidth = 10;
				ScaleBarOpacity = 80;
			}
			else if (State == State.DataLoaded)
			{
				stickyValid = false;
				stickyMin = double.NaN;
				stickyMax = double.NaN;
				stickyHeight = double.NaN;
				cachedAbsMargin = double.NaN;
				cachedMarginUpper = double.NaN;
				cachedMarginLower = double.NaN;
			}
			else if (State == State.Terminated)
			{
				DisposeBrushes();
			}
		}

		public override void OnRenderTargetChanged()
		{
			DisposeBrushes();
		}

		protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
		{
			if (ChartPanel != null && ChartPanel.H > 0)
			{
				cachedPanelHeight = ChartPanel.H;
				try
				{
					var props = chartScale.Properties;
					bool marginSettingsChanged =
						props.AutoScaleMarginType != cachedMarginType
						|| props.AutoScaleMarginUpper != cachedMarginUpper
						|| props.AutoScaleMarginLower != cachedMarginLower;
					cachedMarginType = props.AutoScaleMarginType;
					cachedMarginUpper = props.AutoScaleMarginUpper;
					cachedMarginLower = props.AutoScaleMarginLower;
					if (marginSettingsChanged)
					{
						stickyValid = false;
						cachedAbsMargin = double.NaN;
					}
					else if (stickyValid && stickyHeight > 0)
					{
						double tick = ResolveTickSize();
						double tol = tick > 0 ? tick : 0;
						double rendered = chartScale.MaxMinusMin;
						double totalExcess = rendered - stickyHeight;
						double lowerExcess = stickyMin - chartScale.MinValue;
						double upperExcess = chartScale.MaxValue - stickyMax;
						double cap = stickyHeight * 0.25;
						if (!double.IsNaN(rendered) && !double.IsInfinity(rendered)
							&& totalExcess >= -tol && totalExcess <= stickyHeight * 0.3
							&& lowerExcess >= -tol && upperExcess >= -tol
							&& lowerExcess <= cap && upperExcess <= cap)
							cachedAbsMargin = Math.Max(0, totalExcess);
					}
				}
				catch { }
			}

			if (!ShowScaleBars)
				return;
			if (IsInHitTest || RenderTarget == null || chartControl == null || chartScale == null || ChartPanel == null)
				return;

			if (!resourcesValid || !ResourcesUpToDate())
				CreateResources();
			if (desiredBrush == null || desiredBrush.IsDisposed || actualBrush == null || actualBrush.IsDisposed)
				return;

			double tickSize = 0;
			try
			{
				Bars b = ChartBars != null ? ChartBars.Bars : null;
				if (b != null && b.Instrument != null && b.Instrument.MasterInstrument != null)
					tickSize = b.Instrument.MasterInstrument.TickSize;
			}
			catch { }
			if (!(tickSize > 0))
			{
				try { tickSize = TickSize; }
				catch { }
			}
			if (!(tickSize > 0) || !(PixelsPerTick > 0))
				return;

			if (!(ReferenceTicks > 0))
				return;

			float actualBarH = 0;
			try
			{
				actualBarH = chartScale.GetPixelsForDistance(ReferenceTicks * tickSize);
			}
			catch
			{
				return;
			}
			if (!(actualBarH >= 0) || float.IsNaN(actualBarH) || float.IsInfinity(actualBarH))
				return;

			double desiredBarH = ReferenceTicks * PixelsPerTick;
			if (!(desiredBarH > 0) || double.IsNaN(desiredBarH) || double.IsInfinity(desiredBarH))
				return;

			int maxBarH = ChartPanel.H > 0 ? ChartPanel.H - 16 : (int)desiredBarH;
			if (maxBarH < 20)
				return;

			int barW = ScaleBarWidth > 0 ? ScaleBarWidth : 10;
			const int margin = 8;
			const int gap = 4;

			float bottom = (float)Math.Round((double)(ChartPanel.Y + ChartPanel.H - margin));
			float x0 = (float)Math.Round((double)(ChartPanel.X + margin));
			float x1 = (float)Math.Round(x0 + barW + gap);

			double desiredF = Math.Min(desiredBarH, (double)maxBarH);
			float frameH = (float)Math.Round(desiredF);
			if (frameH < 1 && desiredF > 0)
				frameH = 1;

			bool actualOverflow = actualBarH > (double)maxBarH;
			double actualF = Math.Min(actualBarH, (double)maxBarH);
			float fillH = (float)actualF;
			if (fillH < 1 && actualF > 0)
				fillH = 1;

			float top = (float)Math.Round(bottom - frameH);

			D2D.AntialiasMode oldAA = RenderTarget.AntialiasMode;
			RenderTarget.AntialiasMode = D2D.AntialiasMode.Aliased;
			try
			{
				RenderTarget.FillRectangle(new DX.RectangleF(x0, top, barW, frameH), desiredBrush);
				RenderTarget.DrawRectangle(new DX.RectangleF(x0, top, barW, frameH), desiredBrush);
				if (actualOverflow)
					RenderTarget.FillRectangle(new DX.RectangleF(x1, top - 3, barW, 3), actualBrush);
				if (fillH > 0)
					RenderTarget.FillRectangle(new DX.RectangleF(x1, bottom - fillH, barW, fillH), actualBrush);
				RenderTarget.DrawRectangle(new DX.RectangleF(x1, top, barW, frameH), actualBrush);
			}
			finally
			{
				RenderTarget.AntialiasMode = oldAA;
			}
		}

		public override void OnCalculateMinMax()
		{
			if (!IsAutoScale || ChartBars == null || ChartBars.Bars == null)
				return;

			Bars bars = ChartBars.Bars;
			int count = bars.Count;
			int from;
			int to;
			try
			{
				from = Math.Max(ChartBars.FromIndex, 0);
				to = Math.Min(ChartBars.ToIndex, count - 1);
			}
			catch
			{
				return;
			}
			if (count == 0 || to < from)
				return;

			double tmpMin = double.MaxValue;
			double tmpMax = double.MinValue;
			try
			{
				for (int index = from; index <= to; index++)
				{
					double h = High.GetValueAt(index);
					double l = Low.GetValueAt(index);
					if (l < tmpMin) tmpMin = l;
					if (h > tmpMax) tmpMax = h;
				}
			}
			catch
			{
				return;
			}
			if (!(tmpMin <= tmpMax))
				return;

			double anchor;
			try
			{
				anchor = Close.GetValueAt(to);
			}
			catch
			{
				MinValue = tmpMin;
				MaxValue = tmpMax;
				return;
			}
			if (double.IsNaN(anchor) || double.IsInfinity(anchor))
			{
				MinValue = tmpMin;
				MaxValue = tmpMax;
				return;
			}

			double tickSize = 0;
			try
			{
				if (bars.Instrument != null && bars.Instrument.MasterInstrument != null)
					tickSize = bars.Instrument.MasterInstrument.TickSize;
			}
			catch { }
			if (!(tickSize > 0))
			{
				try { tickSize = TickSize; }
				catch { }
			}
			if (!(tickSize > 0))
			{
				MinValue = tmpMin;
				MaxValue = tmpMax;
				return;
			}

			int panelH = cachedPanelHeight;
			if (panelH <= 0 && ChartPanel != null)
			{
				try { panelH = ChartPanel.H; }
				catch { }
			}
			if (panelH <= 0 || !(PixelsPerTick > 0))
			{
				MinValue = tmpMin;
				MaxValue = tmpMax;
				return;
			}

			double absMargin = !(double.IsNaN(cachedAbsMargin) || double.IsInfinity(cachedAbsMargin)) && cachedAbsMargin > 0
				? cachedAbsMargin
				: 0;
			double desiredHeight = ((double)panelH - (absMargin / tickSize) * PixelsPerTick) / PixelsPerTick * tickSize;
			if (!(desiredHeight > 0))
				desiredHeight = (double)panelH / PixelsPerTick * tickSize;
			if (!(desiredHeight > 0) || double.IsNaN(desiredHeight) || double.IsInfinity(desiredHeight))
			{
				MinValue = tmpMin;
				MaxValue = tmpMax;
				return;
			}

			double visibleRange = tmpMax - tmpMin;
			if (visibleRange >= desiredHeight)
			{
				stickyValid = false;
				cachedAbsMargin = double.NaN;
				MinValue = tmpMin;
				MaxValue = tmpMax;
				return;
			}

			bool fitsSticky = stickyValid && tmpMin >= stickyMin && tmpMax <= stickyMax;
			bool heightOk = stickyValid && FuzzyEqual(stickyHeight, desiredHeight);
			if (fitsSticky && heightOk)
			{
				MinValue = stickyMin;
				MaxValue = stickyMax;
				return;
			}

			double half = desiredHeight * 0.5;
			double minIdeal = anchor - half;
			double maxIdeal = anchor + half;

			if (maxIdeal < tmpMax)
			{
				double shift = tmpMax - maxIdeal;
				minIdeal += shift;
				maxIdeal += shift;
			}
			if (minIdeal > tmpMin)
			{
				double shift = minIdeal - tmpMin;
				minIdeal -= shift;
				maxIdeal -= shift;
			}

			stickyMin = minIdeal;
			stickyMax = maxIdeal;
			stickyHeight = desiredHeight;
			stickyValid = true;
			MinValue = minIdeal;
			MaxValue = maxIdeal;
		}

		private bool ResourcesUpToDate()
		{
			return resourcesValid
				&& object.ReferenceEquals(resDesiredColor, DesiredScaleColor)
				&& object.ReferenceEquals(resActualColor, ActualScaleColor)
				&& resOpacity == ScaleBarOpacity;
		}

		private void CreateResources()
		{
			DisposeBrushes();
			if (RenderTarget == null)
				return;
			double alpha = Math.Max(0, Math.Min(100, ScaleBarOpacity)) / 100.0;
			try
			{
				if (DesiredScaleColor != null)
				{
					desiredBrush = DesiredScaleColor.ToDxBrush(RenderTarget);
					if (desiredBrush != null && !desiredBrush.IsDisposed)
						desiredBrush.Opacity = (float)alpha;
				}
				if (ActualScaleColor != null)
				{
					actualBrush = ActualScaleColor.ToDxBrush(RenderTarget);
					if (actualBrush != null && !actualBrush.IsDisposed)
						actualBrush.Opacity = (float)alpha;
				}
			}
			catch { }
			resourcesValid = desiredBrush != null || actualBrush != null;
			resDesiredColor = DesiredScaleColor;
			resActualColor = ActualScaleColor;
			resOpacity = ScaleBarOpacity;
		}

		private void DisposeBrushes()
		{
			resourcesValid = false;
			DisposeBrush(ref desiredBrush);
			DisposeBrush(ref actualBrush);
		}

		private double ResolveTickSize()
		{
			try
			{
				Bars b = ChartBars != null ? ChartBars.Bars : null;
				if (b != null && b.Instrument != null && b.Instrument.MasterInstrument != null
					&& b.Instrument.MasterInstrument.TickSize > 0)
					return b.Instrument.MasterInstrument.TickSize;
			}
			catch { }
			try
			{
				if (TickSize > 0)
					return TickSize;
			}
			catch { }
			return 0;
		}

		private static bool FuzzyEqual(double a, double b)
		{
			if (a == b)
				return true;
			if (double.IsNaN(a) || double.IsNaN(b) || double.IsInfinity(a) || double.IsInfinity(b))
				return false;
			double diff = Math.Abs(a - b);
			double largest = Math.Max(Math.Abs(a), Math.Abs(b));
			return diff <= largest * 1e-9;
		}

		private static void DisposeBrush(ref D2D.Brush brush)
		{
			if (brush != null)
			{
				try
				{
					if (!brush.IsDisposed)
						brush.Dispose();
				}
				catch { }
				brush = null;
			}
		}

		[NinjaScriptProperty]
		[Range(0.1, 100)]
		[Display(Name = "Pixels per tick", Description = "Fixed vertical scale in screen pixels per tick.", Order = 100, GroupName = "Parameters")]
		public double PixelsPerTick { get; set; }

		[NinjaScriptProperty]
		[Display(Name = "Show scale bars", Description = "Show desired vs actual scale bars in the bottom left corner.", Order = 200, GroupName = "Parameters")]
		public bool ShowScaleBars { get; set; }

		[NinjaScriptProperty]
		[XmlIgnore]
		[Display(Name = "Desired scale color", Description = "Color of the full-height bar representing the desired scale.", Order = 300, GroupName = "Parameters")]
		public System.Windows.Media.Brush DesiredScaleColor { get; set; }

		[Browsable(false)]
		public string DesiredScaleColorSerializable
		{
			get { return Serialize.BrushToString(DesiredScaleColor); }
			set { DesiredScaleColor = Serialize.StringToBrush(value); }
		}

		[NinjaScriptProperty]
		[XmlIgnore]
		[Display(Name = "Actual scale color", Description = "Color of the bar representing the actual scale.", Order = 400, GroupName = "Parameters")]
		public System.Windows.Media.Brush ActualScaleColor { get; set; }

		[Browsable(false)]
		public string ActualScaleColorSerializable
		{
			get { return Serialize.BrushToString(ActualScaleColor); }
			set { ActualScaleColor = Serialize.StringToBrush(value); }
		}

		[NinjaScriptProperty]
		[Range(1, 1000)]
		[Display(Name = "Reference ticks", Description = "Number of ticks the reference bar represents.", Order = 500, GroupName = "Parameters")]
		public int ReferenceTicks { get; set; }

		[NinjaScriptProperty]
		[Range(4, 30)]
		[Display(Name = "Scale bar width", Description = "Width in pixels of each scale bar.", Order = 600, GroupName = "Parameters")]
		public int ScaleBarWidth { get; set; }

		[NinjaScriptProperty]
		[Range(0, 100)]
		[Display(Name = "Scale bar opacity", Description = "Opacity of both scale bars (0 - 100%).", Order = 700, GroupName = "Parameters")]
		public int ScaleBarOpacity { get; set; }
	}
}

1 Like