MidLine (50% line) drawing tool {free code}

Here’s a simple drawing tool (MidLine) code that draws a mid line between two anchors. Line stays at current bar. Line and anchors can be moved up down freely. Mid line has a menu to change it’s color, stop it from being moved (lock). Clicking on MSet sets anchors preset tick distance from the line. It works well for me so I share the code here. Made with AI, may have bugs.

// 
//
#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
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;
#endregion

namespace NinjaTrader.NinjaScript.DrawingTools
{
	public class MidLine : DrawingTool
	{
		private const double	AnchorSensitivity	= 15;
		private const double	LineTolerance		= 8;
		private const double	MarkerLength		= 20;
		private const double	MarkerInset			= 15;
		private const float		MinLineFallback		= 200f;

		private	ChartAnchor		editingAnchor;

		private	SharpDX.DirectWrite.TextFormat	textFormat;
		private	float							builtTextSize	= -1f;
		private	readonly DeviceBrush			textBrushDevice	= new();
		private	Color							builtTextColor;
		private	readonly DeviceBrush			markerBrushDevice		= new();
		private	Color							builtMarkerColor;
		private	readonly DeviceBrush			markerTextBrushDevice	= new();
		private	Color							builtMarkerTextColor;

		private	const int						MenuToggleCells		= 2;
		private	const int						MenuActionCells		= 1;
		private	const int						MenuColorCells		= 4;
		private	const int						MenuCells			= MenuToggleCells + MenuActionCells + MenuColorCells;
		private	const int						MenuColorOffset		= MenuToggleCells + MenuActionCells;
		private	const int						MenuActionCell		= MenuToggleCells;
		private	static	readonly string[]		MenuLabels			= { "Marks", "Lock", "MSet", " ", " ", " ", " " };
		private	static	readonly Color[]		DefaultLinePresets	= { Colors.DodgerBlue, Colors.ForestGreen, Colors.Crimson, Colors.Gold };
		private	readonly SharpDX.RectangleF[]	menuCellRects	= new SharpDX.RectangleF[MenuCells];
		private	readonly DeviceBrush[]			menuColorBrushDevices	= new DeviceBrush[MenuColorCells];
		private	readonly Color[]				builtMenuPresetColors	= new Color[MenuColorCells];
		private	SharpDX.DirectWrite.TextLayout[]	cachedMenuLayouts;
		private	SharpDX.DirectWrite.TextFormat		cachedMenuFormat;
		private	readonly float[]					cachedMenuWidths	= new float[MenuCells];
		private	float							cachedMenuCellHeight;
		private	SharpDX.DirectWrite.TextLayout	cachedLabelLayout;
		private	string							cachedLabelText;
		private	SharpDX.DirectWrite.TextFormat	cachedLabelFormat;
		private	SharpDX.DirectWrite.TextLayout	cachedMarkerLayout;
		private	string							cachedMarkerText;
		private	SharpDX.DirectWrite.TextFormat	cachedMarkerFormat;
		private	Brush							linePreset1;
		private	Brush							linePreset2;
		private	Brush							linePreset3;
		private	Brush							linePreset4;

		[Display(Order = 1)]
		public ChartAnchor	StartAnchor	{ get; set; }

		[Display(Order = 2)]
		public ChartAnchor	EndAnchor	{ get; set; }

		[Display(Name = "Line", Description = "Color, width and dash style of the mid line", GroupName = "NinjaScriptGeneral", Order = 3)]
		public Stroke		Stroke		{ get; set; }

		[Display(Name = "Show Label", Description = "Show the price label above the line", GroupName = "NinjaScriptGeneral", Order = 4)]
		public bool			ShowLabel	{ get; set; }

		[Display(Name = "Show Price Marker", Description = "Show the price tag at the right end of the line", GroupName = "NinjaScriptGeneral", Order = 5)]
		public bool			ShowPriceMarker	{ get; set; }

		[Range(6f, 24f)]
		[Display(Name = "Text Size", Description = "Font size of the label and axis marker", GroupName = "NinjaScriptGeneral", Order = 6)]
		public float		TextSize	{ get; set; }

		[Range(50, 2000)]
		[Display(Name = "Line Length", Description = "Length of the mid line in pixels, extending left from the current bar", GroupName = "NinjaScriptGeneral", Order = 7)]
		public int			LineLength	{ get; set; }

		[Display(Name = "Show Anchor Markers", Description = "Show 20 pixel horizontal markers at anchor price levels, ending 15 pixels left of the line's right edge", GroupName = "NinjaScriptGeneral", Order = 8)]
		public bool			ShowAnchorMarkers	{ get; set; }

		[Display(Name = "Lock Line", Description = "When enabled, the line cannot be dragged up or down. Moving anchors to relocate the midline is always possible", GroupName = "NinjaScriptGeneral", Order = 9)]
		public bool			LockLine	{ get; set; }

		[Range(1, 1000)]
		[Display(Name = "Marker Tick Distance", Description = "Tick distance from the mid line at which MSet places each anchor", GroupName = "NinjaScriptGeneral", Order = 10)]
		public int			MarkerTickDistance	{ get; set; }

		[XmlIgnore]
		[Display(Name = "Line Preset 1", Description = "First line color swatch in the selection menu", GroupName = "NinjaScriptGeneral", Order = 11)]
		public Brush LinePreset1
		{
			get => linePreset1;
			set => SetPresetBrush(ref linePreset1, value);
		}

		[Browsable(false)]
		public string LinePreset1Serialize
		{
			get => Serialize.BrushToString(LinePreset1);
			set => LinePreset1 = Serialize.StringToBrush(value);
		}

		[XmlIgnore]
		[Display(Name = "Line Preset 2", Description = "Second line color swatch in the selection menu", GroupName = "NinjaScriptGeneral", Order = 12)]
		public Brush LinePreset2
		{
			get => linePreset2;
			set => SetPresetBrush(ref linePreset2, value);
		}

		[Browsable(false)]
		public string LinePreset2Serialize
		{
			get => Serialize.BrushToString(LinePreset2);
			set => LinePreset2 = Serialize.StringToBrush(value);
		}

		[XmlIgnore]
		[Display(Name = "Line Preset 3", Description = "Third line color swatch in the selection menu", GroupName = "NinjaScriptGeneral", Order = 13)]
		public Brush LinePreset3
		{
			get => linePreset3;
			set => SetPresetBrush(ref linePreset3, value);
		}

		[Browsable(false)]
		public string LinePreset3Serialize
		{
			get => Serialize.BrushToString(LinePreset3);
			set => LinePreset3 = Serialize.StringToBrush(value);
		}

		[XmlIgnore]
		[Display(Name = "Line Preset 4", Description = "Fourth line color swatch in the selection menu", GroupName = "NinjaScriptGeneral", Order = 14)]
		public Brush LinePreset4
		{
			get => linePreset4;
			set => SetPresetBrush(ref linePreset4, value);
		}

		[Browsable(false)]
		public string LinePreset4Serialize
		{
			get => Serialize.BrushToString(LinePreset4);
			set => LinePreset4 = Serialize.StringToBrush(value);
		}

		public override object Icon => "\u2500";

		public override IEnumerable<ChartAnchor> Anchors
		{
			get
			{
				yield return StartAnchor;
				yield return EndAnchor;
			}
		}

		private double MidPrice => (StartAnchor.Price + EndAnchor.Price) / 2d;

		public override void OnCalculateMinMax()
		{
			MinValue = double.MaxValue;
			MaxValue = double.MinValue;

			if (!IsVisible || StartAnchor == null || EndAnchor == null)
				return;

			if ((StartAnchor != null && !StartAnchor.IsEditing) || (EndAnchor != null && !EndAnchor.IsEditing))
			{
				MinValue = MidPrice;
				MaxValue = MidPrice;
			}
		}

		protected override void Dispose(bool disposing)
		{
			base.Dispose(disposing);
			textBrushDevice.RenderTarget			= null;
			markerBrushDevice.RenderTarget			= null;
			markerTextBrushDevice.RenderTarget		= null;
			for (int i = 0; i < menuColorBrushDevices.Length; i++)
				if (menuColorBrushDevices[i] != null)
					menuColorBrushDevices[i].RenderTarget = null;
			textFormat?.Dispose();
			textFormat		= null;
			builtTextSize	= -1f;
			DisposeCachedText();
		}

		private void DisposeMenuLayouts()
		{
			if (cachedMenuLayouts != null)
			{
				for (int i = 0; i < cachedMenuLayouts.Length; i++)
					cachedMenuLayouts[i]?.Dispose();
				cachedMenuLayouts = null;
			}
			cachedMenuFormat		= null;
			cachedMenuCellHeight	= 0f;
		}

		private void DisposeCachedText()
		{
			DisposeMenuLayouts();
			cachedLabelLayout?.Dispose();
			cachedLabelLayout	= null;
			cachedLabelText		= null;
			cachedLabelFormat	= null;
			cachedMarkerLayout?.Dispose();
			cachedMarkerLayout	= null;
			cachedMarkerText	= null;
			cachedMarkerFormat	= null;
		}

		public override void OnRender(ChartControl chartControl, ChartScale chartScale)
		{
			geoValid = false;
			if (StartAnchor == null || EndAnchor == null)
				return;
			if (DrawingState == DrawingState.Building && StartAnchor.IsEditing)
				return;
			if (!TryGetLinePixels(chartControl, chartScale, out ChartPanel panel, out double leftX, out double rightX, out double lineY, out double mid))
				return;

			SharpDX.Direct2D1.AntialiasMode oldAntialiasMode = RenderTarget.AntialiasMode;
			RenderTarget.AntialiasMode = SharpDX.Direct2D1.AntialiasMode.PerPrimitive;
			try
			{
				EnsureStrokeTarget();

				float	width	= Stroke != null ? Stroke.Width : 2f;
				double	yAdj	= width % 2 == 0 ? 0.5d : 0d;
				double	lineLen	= Math.Max(50d, LineLength > 0 ? LineLength : MinLineFallback);
				double	effLeft	= rightX - lineLen;
				var		p0		= new SharpDX.Vector2((float)effLeft, (float)(lineY + yAdj));
				var		p1		= new SharpDX.Vector2((float)rightX, (float)(lineY + yAdj));

				if (IsInHitTest)
				{
					RenderTarget.DrawLine(p0, p1, chartControl.SelectionBrush, width + 12f, Stroke != null ? Stroke.StrokeStyle : null);
					if (ShowAnchorMarkers)
						RenderAnchorMarkers(panel, chartScale, rightX, true, chartControl, width);
					return;
				}

				if (Stroke != null && Stroke.BrushDX != null)
					RenderTarget.DrawLine(p0, p1, Stroke.BrushDX, width, Stroke.StrokeStyle);

				Color lineColor = (Stroke != null ? Stroke.Brush as SolidColorBrush : null)?.Color ?? Colors.DodgerBlue;

				if (ShowAnchorMarkers)
					RenderAnchorMarkers(panel, chartScale, rightX, false, null, 0f);

				if (lineY < panel.Y || lineY > panel.Y + panel.H)
					return;

				if (ShowLabel || ShowPriceMarker)
				{
					NinjaTrader.Cbi.MasterInstrument mi = GetMasterInstrument(chartControl);
					if (ShowLabel)
						RenderLabel(panel, effLeft, rightX, lineY, FormatLabelText(mi, mid), lineColor);
					if (ShowPriceMarker)
						RenderPriceMarker(panel, chartScale, lineY, lineColor, FormatMidPrice(mi, mid));
				}

				RenderMenu(panel, effLeft, rightX, lineY, lineColor);

				geoValid	= true;
				geoRightX	= rightX;
				geoLineY	= lineY;
				CacheAnchorPixels(chartControl, panel, chartScale);
			}
			finally
			{
				RenderTarget.AntialiasMode = oldAntialiasMode;
			}
		}

		private bool TryGetLinePixels(ChartControl chartControl, ChartScale chartScale, out ChartPanel panel, out double leftX, out double rightX, out double lineY, out double mid)
		{
			panel = null;
			leftX = rightX = lineY = mid = 0;
			try
			{
				panel = chartControl.ChartPanels[PanelIndex];
				Point sp	= StartAnchor.GetPoint(chartControl, panel, chartScale);
				Point ep	= EndAnchor.GetPoint(chartControl, panel, chartScale);
				mid			= MidPrice;
				if (double.IsNaN(mid) || double.IsInfinity(mid))
					return false;
				lineY	= chartScale.GetYByValue(mid);
				leftX	= Math.Min(sp.X, ep.X);

				ChartBars	bars	= GetPrimaryChartBars(chartControl);
				double		endX	= Math.Max(sp.X, ep.X);
				if (bars != null)
				{
					int endIdx = bars.ToIndex;
					try
					{
						if (bars.Bars != null && bars.Bars.Count > 0)
							endIdx = bars.Bars.Count - 1;
					}
					catch { }
					try { endX = chartControl.GetXByBarIndex(bars, endIdx); } catch { }
				}
				rightX	= Math.Max(endX, leftX);
				return true;
			}
			catch { return false; }
		}

		private void CacheAnchorPixels(ChartControl chartControl, ChartPanel panel, ChartScale chartScale)
		{
			try
			{
				Point sp	= StartAnchor.GetPoint(chartControl, panel, chartScale);
				Point ep	= EndAnchor.GetPoint(chartControl, panel, chartScale);
				geoStartX	= sp.X;
				geoStartY	= sp.Y;
				geoEndX		= ep.X;
				geoEndY		= ep.Y;
			}
			catch
			{
				geoValid = false;
			}
		}

		private bool IsWithinCachedHoverBand(Point pt)
		{
			if (!geoValid)
				return true;
			double lineLen	= Math.Max(50d, LineLength > 0 ? LineLength : MinLineFallback);
			double effLeft	= geoRightX - lineLen;
			double minX		= Math.Min(effLeft - 4, Math.Min(geoRightX - MarkerInset - MarkerLength - 4, Math.Min(geoStartX, geoEndX) - AnchorSensitivity));
			double maxX		= Math.Max(geoRightX + 12, Math.Max(geoStartX, geoEndX) + AnchorSensitivity);
			if (pt.X < minX || pt.X > maxX)
				return false;
			double tol	= Math.Max(LineTolerance, AnchorSensitivity);
			bool nearLineY	= Math.Abs(pt.Y - geoLineY) <= tol;
			bool nearStartY	= Math.Abs(pt.Y - geoStartY) <= tol;
			bool nearEndY	= Math.Abs(pt.Y - geoEndY) <= tol;
			return nearLineY || nearStartY || nearEndY;
		}

		private bool IsNearLine(Point pt, double lineY, double leftX, double rightX)
		{
			double	lineLen	= Math.Max(50d, LineLength > 0 ? LineLength : MinLineFallback);
			double	effLeft	= rightX - lineLen;
			return Math.Abs(pt.Y - lineY) <= LineTolerance && pt.X >= effLeft - 4 && pt.X <= rightX + 12;
		}

		private string FormatMidPrice(NinjaTrader.Cbi.MasterInstrument mi, double mid)
		{
			if (mi != null)
			{
				try { return mi.FormatPrice(mid); } catch { }
			}
			return mid.ToString();
		}

		private string FormatMidPrice(ChartControl chartControl, double mid)
		{
			return FormatMidPrice(GetMasterInstrument(chartControl), mid);
		}

		private NinjaTrader.Cbi.MasterInstrument GetMasterInstrument(ChartControl chartControl)
		{
			try
			{
				ChartBars	bars	= GetPrimaryChartBars(chartControl);
				var			mi		= bars != null && bars.Bars != null && bars.Bars.Instrument != null ? bars.Bars.Instrument.MasterInstrument : null;
				if (mi != null)
					cachedInstrument = mi;
				return mi ?? cachedInstrument;
			}
			catch { return cachedInstrument; }
		}

		private string FormatLabelText(ChartControl chartControl, double mid)
		{
			NinjaTrader.Cbi.MasterInstrument mi = GetMasterInstrument(chartControl);
			return FormatLabelText(mi, mid);
		}

		private string FormatLabelText(NinjaTrader.Cbi.MasterInstrument mi, double mid)
		{
			string priceText = FormatMidPrice(mi, mid);

			double halfRange = Math.Abs(StartAnchor.Price - EndAnchor.Price) / 2d;
			if (double.IsNaN(halfRange) || double.IsInfinity(halfRange))
				return priceText;

			string ptsText;
			string dolText = string.Empty;
			try
			{
				if (mi != null && mi.TickSize > 0)
				{
					long ticks = (long)Math.Round(halfRange / mi.TickSize);
					ptsText = string.Format("{0}T", ticks);
				}
				else
					ptsText = string.Format("{0:F2} pts", halfRange);
				if (mi != null && mi.PointValue > 0)
					dolText = string.Format(" / ${0:F2}", halfRange * mi.PointValue);
			}
			catch
			{
				ptsText = string.Format("{0:F2} pts", halfRange);
			}
			return string.Format("{0} / {1}{2}", priceText, ptsText, dolText);
		}

		private void EnsureTextFormat()
		{
			float size = TextSize > 0f ? TextSize : 11f;
			if (textFormat != null && builtTextSize == size)
				return;
			textFormat?.Dispose();
			builtTextSize	= size;
			textFormat		= new SharpDX.DirectWrite.TextFormat(
				Core.Globals.DirectWriteFactory, "Consolas",
				SharpDX.DirectWrite.FontWeight.Bold,
				SharpDX.DirectWrite.FontStyle.Normal,
				SharpDX.DirectWrite.FontStretch.Normal,
				size)
			{
				TextAlignment		= SharpDX.DirectWrite.TextAlignment.Leading,
				ParagraphAlignment	= SharpDX.DirectWrite.ParagraphAlignment.Near,
				WordWrapping		= SharpDX.DirectWrite.WordWrapping.NoWrap,
			};
			DisposeCachedText();
		}

		private void EnsureMenuLayouts()
		{
			EnsureTextFormat();
			if (textFormat == null)
				return;
			if (cachedMenuLayouts != null && ReferenceEquals(cachedMenuFormat, textFormat))
				return;
			DisposeMenuLayouts();
			cachedMenuFormat	= textFormat;
			cachedMenuLayouts	= new SharpDX.DirectWrite.TextLayout[MenuCells];
			cachedMenuCellHeight = 0f;
			for (int i = 0; i < MenuCells; i++)
			{
				var layout = new SharpDX.DirectWrite.TextLayout(Core.Globals.DirectWriteFactory, MenuLabels[i], cachedMenuFormat, 200f, 100f);
				cachedMenuLayouts[i]	= layout;
				cachedMenuWidths[i]		= layout.Metrics.Width + layout.Metrics.Left + 12f;
				if (IsMenuColorCell(i) && cachedMenuWidths[i] < 24f)
					cachedMenuWidths[i] = 24f;
				if (layout.Metrics.Height > cachedMenuCellHeight)
					cachedMenuCellHeight = layout.Metrics.Height;
			}
			cachedMenuCellHeight += 6f;
		}

		private SharpDX.DirectWrite.TextLayout EnsureLabelLayout(string text)
		{
			EnsureTextFormat();
			if (textFormat == null || string.IsNullOrEmpty(text))
				return null;
			if (cachedLabelLayout != null && cachedLabelText == text && ReferenceEquals(cachedLabelFormat, textFormat))
				return cachedLabelLayout;
			cachedLabelLayout?.Dispose();
			cachedLabelText		= text;
			cachedLabelFormat	= textFormat;
			cachedLabelLayout	= new SharpDX.DirectWrite.TextLayout(Core.Globals.DirectWriteFactory, text, textFormat, 1000f, 100f);
			return cachedLabelLayout;
		}

		private SharpDX.DirectWrite.TextLayout EnsureMarkerLayout(string text)
		{
			EnsureTextFormat();
			if (textFormat == null || string.IsNullOrEmpty(text))
				return null;
			if (cachedMarkerLayout != null && cachedMarkerText == text && ReferenceEquals(cachedMarkerFormat, textFormat))
				return cachedMarkerLayout;
			cachedMarkerLayout?.Dispose();
			cachedMarkerText	= text;
			cachedMarkerFormat	= textFormat;
			cachedMarkerLayout	= new SharpDX.DirectWrite.TextLayout(Core.Globals.DirectWriteFactory, text, textFormat, 1000f, 100f);
			return cachedMarkerLayout;
		}

		private SharpDX.Direct2D1.Brush EnsureSolidBrush(DeviceBrush device, ref Color built, Color color)
		{
			if (device.Brush == null || color.R != built.R || color.G != built.G || color.B != built.B || color.A != built.A)
			{
				built			= color;
				device.Brush	= new SolidColorBrush(color);
			}
			device.RenderTarget = RenderTarget;
			return device.BrushDX;
		}

		private static Color ContrastColor(Color color)
		{
			double luminance = (color.R * 0.299 + color.G * 0.587 + color.B * 0.114) / 255d;
			return luminance > 0.55 ? Colors.Black : Colors.White;
		}

		private void RenderLabel(ChartPanel panel, double leftX, double rightX, double lineY, string text, Color lineColor)
		{
			SharpDX.DirectWrite.TextLayout layout = EnsureLabelLayout(text);
			if (layout == null)
				return;
			SharpDX.Direct2D1.Brush brush = EnsureSolidBrush(textBrushDevice, ref builtTextColor, lineColor);
			if (brush == null)
				return;

			float w	= layout.Metrics.Width + layout.Metrics.Left;
			float h	= layout.Metrics.Height;

			double visLeft	= Math.Max(leftX, panel.X);
			double visRight	= Math.Min(rightX, panel.X + panel.W);
			float	x		= (float)((visLeft + visRight) / 2d - w / 2d);
			x				= Math.Max((float)panel.X, Math.Min(x, (float)(panel.X + panel.W - w)));
			float	y		= (float)lineY - h - 6f;
			if (y < panel.Y)
				y = (float)lineY + 6f;

			RenderTarget.DrawTextLayout(new SharpDX.Vector2(x, y), layout, brush);
		}
		private void RenderPriceMarker(ChartPanel panel, ChartScale chartScale, double lineY, Color lineColor, string label)
		{
			SharpDX.DirectWrite.TextLayout layout = EnsureMarkerLayout(label);
			if (layout == null)
				return;
			SharpDX.Direct2D1.Brush fill = EnsureSolidBrush(markerBrushDevice, ref builtMarkerColor, lineColor);
			SharpDX.Direct2D1.Brush text = EnsureSolidBrush(markerTextBrushDevice, ref builtMarkerTextColor, ContrastColor(lineColor));
			if (fill == null || text == null)
				return;

			float scaleW = 0f;
			try { scaleW = (float)chartScale.Width; } catch { }
			if (scaleW < 30f)
				scaleW = 60f;
			float tagW = scaleW - 2f;

			float	th		= layout.Metrics.Height;
			float	h		= th + 4f;
			float	y		= (float)lineY - h / 2f;
			var		tagRect	= new SharpDX.RectangleF((float)(panel.X + panel.W + 1d), y, tagW, h);

			RenderTarget.PopAxisAlignedClip();
			try
			{
				RenderTarget.FillRectangle(tagRect, fill);
				RenderTarget.DrawRectangle(tagRect, text, 1f);
				RenderTarget.DrawTextLayout(new SharpDX.Vector2(tagRect.X + 4f - layout.Metrics.Left, tagRect.Y + 2f), layout, text);
			}
			finally
			{
				RenderTarget.PushAxisAlignedClip(
					new SharpDX.RectangleF((float)panel.X, (float)panel.Y, (float)panel.W, (float)panel.H),
					SharpDX.Direct2D1.AntialiasMode.PerPrimitive);
			}
		}

		private void RenderAnchorMarkers(ChartPanel panel, ChartScale chartScale, double rightX, bool hitTest, ChartControl chartControl, float hitWidth)
		{
			if (!hitTest && (Stroke == null || Stroke.BrushDX == null))
				return;
			if (!hitTest)
				EnsureStrokeTarget();
			float	w		= Stroke != null ? Stroke.Width : 2f;
			double	yAdj	= w % 2 == 0 ? 0.5d : 0d;
			double	x1		= rightX - MarkerInset;
			double	x0		= x1 - MarkerLength;
			RenderAnchorMarker(StartAnchor, panel, chartScale, x0, x1, yAdj, w, hitTest, chartControl, hitWidth);
			RenderAnchorMarker(EndAnchor, panel, chartScale, x0, x1, yAdj, w, hitTest, chartControl, hitWidth);
		}

		private void RenderAnchorMarker(ChartAnchor anchor, ChartPanel panel, ChartScale chartScale, double x0, double x1, double yAdj, float w, bool hitTest, ChartControl chartControl, float hitWidth)
		{
			if (anchor == null)
				return;
			try
			{
				double anchorY = chartScale.GetYByValue(anchor.Price);
				if (double.IsNaN(anchorY) || double.IsInfinity(anchorY))
					return;
				if (anchorY < panel.Y || anchorY > panel.Y + panel.H)
					return;
				var p0 = new SharpDX.Vector2((float)x0, (float)(anchorY + yAdj));
				var p1 = new SharpDX.Vector2((float)x1, (float)(anchorY + yAdj));
				if (hitTest)
					RenderTarget.DrawLine(p0, p1, chartControl.SelectionBrush, hitWidth + 12f, Stroke != null ? Stroke.StrokeStyle : null);
				else
					RenderTarget.DrawLine(p0, p1, Stroke.BrushDX, w, Stroke.StrokeStyle);
			}
			catch { }
		}

		private bool IsNearMarker(Point pt, ChartScale chartScale, double rightX, out ChartAnchor hitAnchor)
		{
			hitAnchor = null;
			if (!ShowAnchorMarkers)
				return false;
			try
			{
				double	x1		= rightX - MarkerInset;
				double	x0		= x1 - MarkerLength;
				if (pt.X < x0 - 4 || pt.X > x1 + 4)
					return false;
				double	startDy	= MarkerDy(StartAnchor, chartScale, pt);
				double	endDy	= MarkerDy(EndAnchor, chartScale, pt);
				if (startDy <= LineTolerance && startDy <= endDy)
				{
					hitAnchor = StartAnchor;
					return true;
				}
				if (endDy <= LineTolerance)
				{
					hitAnchor = EndAnchor;
					return true;
				}
				return false;
			}
			catch { hitAnchor = null; return false; }
		}

		private static double MarkerDy(ChartAnchor anchor, ChartScale chartScale, Point pt)
		{
			if (anchor == null)
				return double.MaxValue;
			double anchorY = chartScale.GetYByValue(anchor.Price);
			if (double.IsNaN(anchorY) || double.IsInfinity(anchorY))
				return double.MaxValue;
			return Math.Abs(pt.Y - anchorY);
		}

		private	bool			moveActive;
		private	bool			markerDragActive;
		private	double			moveStartMousePrice;
		private	double			moveStartStartPrice;
		private	double			moveStartEndPrice;

		private	NinjaTrader.Cbi.MasterInstrument	cachedInstrument;
		private	object							strokeTarget;

		private	bool			geoValid;
		private	double			geoRightX;
		private	double			geoLineY;
		private	double			geoStartX;
		private	double			geoStartY;
		private	double			geoEndX;
		private	double			geoEndY;

		private void EnsureStrokeTarget()
		{
			if (Stroke == null)
				return;
			if (!ReferenceEquals(strokeTarget, RenderTarget))
			{
				Stroke.RenderTarget	= RenderTarget;
				strokeTarget		= RenderTarget;
			}
		}

		private	bool IsMenuColorCell(int cell)
		{
			return cell >= MenuColorOffset && cell < MenuColorOffset + MenuColorCells;
		}

		private static bool ColorsEqual(Color a, Color b)
		{
			return a.R == b.R && a.G == b.G && a.B == b.B && a.A == b.A;
		}

		private static float MenuGap(int index)
		{
			if (index <= 0)
				return 0f;
			return index == MenuColorOffset ? 12f : 4f;
		}

		private Color GetPresetColor(int slot)
		{
			Brush preset = null;
			switch (slot)
			{
				case 0: preset = linePreset1; break;
				case 1: preset = linePreset2; break;
				case 2: preset = linePreset3; break;
				case 3: preset = linePreset4; break;
			}
			Color color = (preset as SolidColorBrush)?.Color ?? Colors.Transparent;
			if (color == Colors.Transparent && slot >= 0 && slot < DefaultLinePresets.Length)
				color = DefaultLinePresets[slot];
			return color;
		}

		private void SetPresetBrush(ref Brush field, Brush value)
		{
			field = value;
			if (field != null)
			{
				if (field.IsFrozen)
					field = field.Clone();
				field.Freeze();
			}
		}

		private SharpDX.Direct2D1.Brush EnsureMenuColorBrush(int cell)
		{
			int slot = cell - MenuColorOffset;
			if (slot < 0 || slot >= MenuColorCells)
				return null;
			if (menuColorBrushDevices[slot] == null)
			{
				menuColorBrushDevices[slot] = new DeviceBrush();
				builtMenuPresetColors[slot] = Colors.Transparent;
			}
			Color preset = GetPresetColor(slot);
			DeviceBrush device = menuColorBrushDevices[slot];
			if (device.Brush == null || !ColorsEqual(preset, builtMenuPresetColors[slot]))
			{
				builtMenuPresetColors[slot] = preset;
				device.Brush = new SolidColorBrush(preset);
			}
			device.RenderTarget = RenderTarget;
			return device.BrushDX;
		}

		private void ApplyPresetColor(int slot)
		{
			Color color = GetPresetColor(slot);
			Brush fill = new SolidColorBrush(color);
			fill.Freeze();
			if (Stroke != null)
				Stroke = new Stroke(fill, Stroke.DashStyleHelper, Stroke.Width) { RenderTarget = Stroke.RenderTarget };
			else
				Stroke = new Stroke(fill, DashStyleHelper.Solid, 2f);
		}

		private bool IsLineColorActive(Color color)
		{
			Color current = (Stroke != null ? Stroke.Brush as SolidColorBrush : null)?.Color ?? Colors.Transparent;
			return ColorsEqual(current, color);
		}

		private void RenderMenu(ChartPanel panel, double leftX, double rightX, double lineY, Color lineColor)
		{
			Array.Clear(menuCellRects, 0, menuCellRects.Length);

			if (!IsSelected || DrawingState == DrawingState.Building)
				return;

			EnsureMenuLayouts();
			if (cachedMenuLayouts == null)
				return;
			SharpDX.Direct2D1.Brush textBrush = EnsureSolidBrush(textBrushDevice, ref builtTextColor, lineColor);
			if (textBrush == null)
				return;
			EnsureStrokeTarget();
			SharpDX.Direct2D1.Brush activeFill	= Stroke != null ? Stroke.BrushDX : null;
			SharpDX.Direct2D1.Brush activeText	= EnsureSolidBrush(markerTextBrushDevice, ref builtMarkerTextColor, ContrastColor(lineColor));
			if (activeText == null)
				return;

			float[]		widths		= cachedMenuWidths;
			float		cellHeight	= cachedMenuCellHeight;

			float totalWidth = 0f;
			for (int i = 0; i < MenuCells; i++)
				totalWidth += widths[i] + MenuGap(i);
			float menuY = (float)lineY + 10f;
			if (menuY + cellHeight > panel.Y + panel.H)
				menuY = (float)lineY - 10f - cellHeight;
			float visibleRight	= (float)Math.Min(rightX, panel.X + panel.W);
			float menuX			= visibleRight - totalWidth;
			if (menuX < panel.X)
				menuX = (float)panel.X;

			float x = menuX;
			for (int i = 0; i < MenuCells; i++)
			{
				var		rect	= new SharpDX.RectangleF(x, menuY, widths[i], cellHeight);
				bool	active	= IsMenuCellActive(i);

				if (IsMenuColorCell(i))
				{
					SharpDX.Direct2D1.Brush swatch = EnsureMenuColorBrush(i);
					if (swatch != null)
						RenderTarget.FillRectangle(rect, swatch);
				}
				else if (active && activeFill != null)
					RenderTarget.FillRectangle(rect, activeFill);
				RenderTarget.DrawRectangle(rect, textBrush, active ? 2f : 1f);
				RenderTarget.DrawTextLayout(
					new SharpDX.Vector2(rect.X + 6f - cachedMenuLayouts[i].Metrics.Left, rect.Y + 3f),
					cachedMenuLayouts[i],
					active ? activeText : textBrush);

				menuCellRects[i] = rect;
				x += widths[i] + MenuGap(i + 1);
			}
		}

		private bool IsMenuCellActive(int cell)
		{
			switch (cell)
			{
				case 0: return ShowAnchorMarkers;
				case 1: return LockLine;
				default:
					if (IsMenuColorCell(cell))
						return IsLineColorActive(GetPresetColor(cell - MenuColorOffset));
					return false;
			}
		}

		private bool IsMenuActionCell(int cell)
		{
			return cell == MenuActionCell;
		}

		public override void OnMouseDown(ChartControl chartControl, ChartPanel chartPanel, ChartScale chartScale, ChartAnchor dataPoint)
		{
			if (DrawingState == DrawingState.Building)
			{
				if (StartAnchor.IsEditing)
				{
					SetAnchorPrice(chartControl, StartAnchor, dataPoint.Price);
					StartAnchor.IsEditing = false;
				}
				else if (EndAnchor.IsEditing)
				{
					SetAnchorPrice(chartControl, EndAnchor, dataPoint.Price);
					EndAnchor.IsEditing = false;
				}

				if (!StartAnchor.IsEditing && !EndAnchor.IsEditing)
				{
					PinAnchorsToCurrentBars(chartControl);
					DrawingState	= DrawingState.Normal;
					IsSelected		= false;
				}
				return;
			}

			if (IsSelected && HandleMenuClick(chartControl, chartPanel, chartScale, dataPoint))
				return;

			if (IsLocked)
			{
				IsSelected = false;
				return;
			}

			Point anchorPoint = dataPoint.GetPoint(chartControl, chartPanel, chartScale);
			if (!IsWithinCachedHoverBand(anchorPoint))
			{
				IsSelected = false;
				return;
			}
			if (!TryGetLinePixels(chartControl, chartScale, out _, out double leftX, out double rightX, out double lineY, out _))
			{
				IsSelected = false;
				return;
			}
			if (IsNearMarker(anchorPoint, chartScale, rightX, out ChartAnchor markerAnchor))
			{
				editingAnchor			= markerAnchor;
				editingAnchor.IsEditing	= true;
				markerDragActive		= true;
				DrawingState			= DrawingState.Editing;
				IsSelected				= true;
				return;
			}
			ChartAnchor closest = GetClosestAnchor(chartControl, chartPanel, chartScale, AnchorSensitivity, anchorPoint);
			if (closest == null)
				closest = GetClosestAnchorByPixels(chartControl, chartPanel, chartScale, anchorPoint);
			if (closest != null)
			{
				editingAnchor			= closest;
				editingAnchor.IsEditing	= true;
				DrawingState			= DrawingState.Editing;
				IsSelected				= true;
				return;
			}

			if (IsNearLine(anchorPoint, lineY, leftX, rightX))
			{
				IsSelected = true;
				if (!LockLine)
				{
					moveActive			= true;
					moveStartMousePrice	= dataPoint.Price;
					moveStartStartPrice	= StartAnchor.Price;
					moveStartEndPrice	= EndAnchor.Price;
					DrawingState		= DrawingState.Moving;
				}
				chartControl.InvalidateVisual();
				return;
			}

			IsSelected = false;
		}

		private ChartAnchor GetClosestAnchorByPixels(ChartControl chartControl, ChartPanel chartPanel, ChartScale chartScale, Point point)
		{
			try
			{
				Point	sp	= StartAnchor.GetPoint(chartControl, chartPanel, chartScale);
				Point	ep	= EndAnchor.GetPoint(chartControl, chartPanel, chartScale);
				double	sd	= (sp - point).Length;
				double	ed	= (ep - point).Length;
				double	best	= Math.Min(sd, ed);
				if (best > AnchorSensitivity)
					return null;
				return sd <= ed ? StartAnchor : EndAnchor;
			}
			catch { return null; }
		}

		private bool HandleMenuClick(ChartControl chartControl, ChartPanel chartPanel, ChartScale chartScale, ChartAnchor dataPoint)
		{
			if (dataPoint == null)
				return false;

			Point point = dataPoint.GetPoint(chartControl, chartPanel, chartScale);
			for (int i = 0; i < menuCellRects.Length; i++)
			{
				SharpDX.RectangleF r = menuCellRects[i];
				if (r.Width <= 0f || r.Height <= 0f)
					continue;
				if (point.X < r.X || point.X > r.X + r.Width || point.Y < r.Y || point.Y > r.Y + r.Height)
					continue;

				ApplyMenuAction(chartControl, i);
				return true;
			}
			return false;
		}

		private void ApplyMenuAction(ChartControl chartControl, int cell)
		{
			switch (cell)
			{
				case 0:
					ShowAnchorMarkers = !ShowAnchorMarkers;
					break;
				case 1:
					LockLine = !LockLine;
					break;
				default:
					if (cell == MenuActionCell)
						ApplyMarkerPreset(chartControl);
					else if (IsMenuColorCell(cell))
						ApplyPresetColor(cell - MenuColorOffset);
					break;
			}

			if (chartControl != null)
				chartControl.InvalidateVisual();
		}

		private void ApplyMarkerPreset(ChartControl chartControl)
		{
			try
			{
				NinjaTrader.Cbi.MasterInstrument mi = GetMasterInstrument(chartControl);
				if (mi == null || mi.TickSize <= 0)
					return;
				int ticks = Math.Max(1, MarkerTickDistance);
				double offset = ticks * mi.TickSize;
				double mid = MidPrice;
				if (double.IsNaN(mid) || double.IsInfinity(mid))
					return;
				StartAnchor.Price	= mid + offset;
				EndAnchor.Price		= mid - offset;
				PinAnchorsToCurrentBars(chartControl);
			}
			catch { }
		}

		private void PinAnchorsToCurrentBars(ChartControl chartControl)
		{
			try
			{
				int lastSlot = GetLastBarSlot(chartControl);
				if (lastSlot < 1)
					return;

				SetAnchorSlot(chartControl, StartAnchor, lastSlot - 1);
				SetAnchorSlot(chartControl, EndAnchor, Math.Max(0, lastSlot - 2));
			}
			catch { }
		}

		private void SetAnchorPrice(ChartControl chartControl, ChartAnchor anchor, double price)
		{
			if (anchor == null || double.IsNaN(price) || double.IsInfinity(price))
				return;
			anchor.Price = price;
		}

		private static int GetLastBarSlot(ChartControl chartControl)
		{
			ChartBars bars = GetPrimaryChartBars(chartControl);
			if (bars == null)
				return -1;

			try
			{
				if (bars.Bars != null && bars.Bars.Count > 0)
					return Math.Max(0, bars.Bars.Count - 1);
			}
			catch { }
			return Math.Max(0, bars.ToIndex);
		}

		private static void SetAnchorSlot(ChartControl chartControl, ChartAnchor anchor, int slot)
		{
			anchor.SlotIndex = slot;
			try { anchor.Time = chartControl.GetTimeBySlotIndex(slot); } catch { }
		}

		public override void OnMouseMove(ChartControl chartControl, ChartPanel chartPanel, ChartScale chartScale, ChartAnchor dataPoint)
		{
			if (IsLocked && DrawingState != DrawingState.Building)
				return;

			if (DrawingState == DrawingState.Building)
			{
				if (EndAnchor.IsEditing)
					SetAnchorPrice(chartControl, EndAnchor, dataPoint.Price);
			}
			else if (DrawingState == DrawingState.Editing)
			{
				if (editingAnchor != null)
					SetAnchorPrice(chartControl, editingAnchor, dataPoint.Price);
			}
			else if (DrawingState == DrawingState.Moving)
			{
				if (moveActive)
				{
					if (!double.IsNaN(dataPoint.Price) && !double.IsInfinity(dataPoint.Price)
						&& !double.IsNaN(moveStartMousePrice) && !double.IsInfinity(moveStartMousePrice))
					{
						double shift = dataPoint.Price - moveStartMousePrice;
						StartAnchor.Price	= moveStartStartPrice + shift;
						EndAnchor.Price		= moveStartEndPrice + shift;
					}
				}
				else
				{
					double priceDelta = 0d;
					try { priceDelta = dataPoint.Price - InitialMouseDownAnchor.Price; } catch { }
					StartAnchor.Price	+= priceDelta;
					EndAnchor.Price		+= priceDelta;
				}
			}
		}

		public override void OnMouseUp(ChartControl chartControl, ChartPanel chartPanel, ChartScale chartScale, ChartAnchor dataPoint)
		{
			if (DrawingState == DrawingState.Building)
				return;

			if (editingAnchor != null)
			{
				try { editingAnchor.IsEditing = false; } catch { }
				editingAnchor = null;
			}
			markerDragActive = false;
			if (moveActive)
				moveActive = false;
			PinAnchorsToCurrentBars(chartControl);
			DrawingState = DrawingState.Normal;
		}

		public override Cursor GetCursor(ChartControl chartControl, ChartPanel chartPanel, ChartScale chartScale, Point point)
		{
			if (DrawingState == DrawingState.Building)
				return Cursors.Pen;

			if (DrawingState == DrawingState.Moving)
				return IsLocked ? Cursors.No : (moveActive ? Cursors.SizeNS : Cursors.SizeAll);

			if (DrawingState == DrawingState.Editing)
				return IsLocked ? Cursors.No : (markerDragActive ? Cursors.SizeNS : Cursors.SizeNESW);

			if (IsLocked || IsInHitTest)
				return null;

			try
			{
				if (!IsWithinCachedHoverBand(point))
					return null;

				if (!TryGetLinePixels(chartControl, chartScale, out _, out double leftX, out double rightX, out double lineY, out _))
					return null;

				if (IsNearMarker(point, chartScale, rightX, out _))
					return Cursors.SizeNS;
				if (IsNearLine(point, lineY, leftX, rightX))
					return LockLine ? Cursors.Hand : Cursors.SizeNS;

				if (GetClosestAnchor(chartControl, chartPanel, chartScale, AnchorSensitivity, point) != null)
					return Cursors.SizeNESW;
			}
			catch { }
			return null;
		}

		public sealed override Point[] GetSelectionPoints(ChartControl chartControl, ChartScale chartScale)
		{
			try
			{
				ChartPanel	panel	= chartControl.ChartPanels[PanelIndex];
				Point		sp		= StartAnchor.GetPoint(chartControl, panel, chartScale);
				Point		ep		= EndAnchor.GetPoint(chartControl, panel, chartScale);
				if (Math.Abs(sp.X - ep.X) < 4d || Math.Abs(sp.Y - ep.Y) < 4d)
					ep.Offset(8d, 8d);
				return new[] { sp, ep };
			}
			catch { return new Point[0]; }
		}

		public override bool IsVisibleOnChart(ChartControl chartControl, ChartScale chartScale, DateTime firstTimeOnChart, DateTime lastTimeOnChart)
		{
			if (base.IsVisibleOnChart(chartControl, chartScale, firstTimeOnChart, lastTimeOnChart))
				return true;

			try
			{
				double leftX;
				double rightX;
				if (geoValid)
				{
					double lineLen	= Math.Max(50d, LineLength > 0 ? LineLength : MinLineFallback);
					rightX			= geoRightX;
					leftX			= rightX - lineLen;
				}
				else if (!TryGetLinePixels(chartControl, chartScale, out _, out leftX, out rightX, out _, out _))
					return false;

				DateTime leftTime	= chartControl.GetTimeByX((int)leftX);
				DateTime rightTime	= chartControl.GetTimeByX((int)Math.Max(leftX, rightX));

				return leftTime <= lastTimeOnChart && rightTime >= firstTimeOnChart;
			}
			catch { return false; }
		}

		private static ChartBars GetPrimaryChartBars(ChartControl chartControl)
		{
			try
			{
				if (chartControl == null || chartControl.BarsArray == null || chartControl.BarsArray.Count == 0)
					return null;
				return chartControl.BarsArray[0];
			}
			catch { return null; }
		}

		protected override void OnStateChange()
		{
			if (State == State.SetDefaults)
			{
				Name				= "MidLine";
				StartAnchor			= new() { DisplayName = "Start", IsEditing = true, DrawingTool = this };
				EndAnchor			= new() { DisplayName = "End", IsEditing = true, DrawingTool = this };
				DrawingState		= DrawingState.Building;
				Stroke				= new(Brushes.DodgerBlue, DashStyleHelper.Solid, 2f);
				ShowLabel			= true;
				ShowPriceMarker		= true;
				TextSize			= 14f;
				LineLength			= 300;
				ShowAnchorMarkers	= true;
				LockLine			= false;
				MarkerTickDistance	= 80;
				LinePreset1			= new SolidColorBrush(Colors.DodgerBlue);
				LinePreset2			= new SolidColorBrush(Colors.ForestGreen);
				LinePreset3			= new SolidColorBrush(Colors.Crimson);
				LinePreset4			= new SolidColorBrush(Colors.Gold);
			}
			else if (State == State.Terminated)
				Dispose();
		}
	}
}

EMA ? and volume candles?

heh, I forgot to switch to regular candles. These are custom candles and… yes, EMA.

1 Like

What is the most technically challenging and complex candlestick indicator you have ever developed?

It is probably order management indicator. Not finished yet.

EDIT: you asked about candlestick indicator. None of my candlestick indicators are complex. My custom candlestick indicator are just noise filters mostly.

This is probably my most successful:

1 Like

This look like you have your hands full , yikes

do some of the highlighted candles depend based on the size if the candle itself ?

Each dimension, color, width and when new candle sprouts are independent of each other.