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);
}


