# 3D bars {free code}

**URL:** <https://discourse.ninjatrader.com/t/3d-bars-free-code/7878>\
**Category:** Desktop SDK - Indicators\
**Created:** [October 29, 2026, 3:06am UTC](https://discourse.ninjatrader.com/t/3d-bars-free-code/7878 "2026-10-29T03:06:18Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![BillMilton](https://discourse.ninjatrader.com/letter_avatar_proxy/v4/letter/b/c68b51/32.png) [@BillMilton](https://discourse.ninjatrader.com/u/BillMilton)\
**Post date:** [October 29, 2026, 3:06am UTC](https://discourse.ninjatrader.com/t/3d-bars-free-code/7878/1 "2026-10-29T03:06:18Z")

</div>

![image](https://discourse.ninjatrader.com/uploads/default/original/2X/5/5b0ade4b6b4392219daa76476ec21b9379d694e3.png)

3D candles with raised body and two color wicks. Brightness of each wick corresponds to the volume at the top or bottom x ticks of the bar and can be adjusted with a scroll wheel while hovering over any bar. Volume bars pictured.

Use open close candles, remove fill color (leave just the outline), apply the indicator.

```auto
#region Using declarations
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Data;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.NinjaScript;
#endregion
    public enum HLBandRenderMode
    {
        BandZones, // H: high down BandTicks, L: low up BandTicks
        MidToExtreme // H: mid to high, L: mid to low
    }
namespace NinjaTrader.NinjaScript.Indicators
{

    public class HLBandVolume : Indicator
    {
        // Immutable snapshot published to the render thread. Never modified after construction.
        private sealed class BandVol
        {
            public readonly long H;
            public readonly long L;
            public BandVol(long h, long l) { H = h; L = l; }
        }

        private const int WheelNotch = 120;
        private const int IdleMs = 700;

        // ---- Data-thread-only state ----
        private Dictionary<double, long> curProfile = new Dictionary<double, long>();
        private int curIdx = -1;
        private double curHi, curLo; // fallback extremes from the seconds data

        // ---- Published state: written by data thread, read lock-free by UI/render thread ----
        private readonly ConcurrentDictionary<int, BandVol> bands = new ConcurrentDictionary<int, BandVol>();

        // ---- UI-thread-only state (render + wheel handler) ----
        private SharpDX.Direct2D1.SolidColorBrush fillBrush;
        private SharpDX.Direct2D1.SolidColorBrush labelBg, labelFg;
        private SharpDX.DirectWrite.TextFormat labelFormat;
        private string lastError;

        private ChartScale lastScale; // cached from OnRender for hit testing
        private ChartPanel wheelPanel;
        private System.Windows.Threading.DispatcherTimer idleTimer;
        private bool wheelSession; // a wheel gesture is in progress
        private bool wheelHit; // the gesture's first tick landed on a rectangle
        private int wheelAccum;
        private double dpiX = 1, dpiY = 1;
        private float wheelX, wheelY; // cursor position in chart pixels
        private string wheelLabel;

        #region Properties
        [NinjaScriptProperty]
        [Range(1, 100)]
        [Display(Name = "Band ticks", GroupName = "Parameters", Order = 0)]
        public int BandTicks { get; set; }

        [NinjaScriptProperty]
        [Range(0.05, 1.0)]
        [Display(Name = "Fill opacity", GroupName = "Parameters", Order = 1)]
        public double FillOpacity { get; set; }

        [NinjaScriptProperty]
        [Display(Name = "Render mode", GroupName = "Parameters", Order = 2)]
        public HLBandRenderMode RenderMode { get; set; }

        [NinjaScriptProperty]
        [Display(Name = "Fixed volume mode", GroupName = "Fixed Volume", Order = 0)]
        public bool FixedVolumeMode { get; set; }

        [NinjaScriptProperty]
        [Range(2, 256)]
        [Display(Name = "Gradient steps", GroupName = "Fixed Volume", Order = 1)]
        public int GradientSteps { get; set; }

        [NinjaScriptProperty]
        [Range(1, int.MaxValue)]
        [Display(Name = "Volume per step", GroupName = "Fixed Volume", Order = 2)]
        public int VolumePerStep { get; set; }

        [XmlIgnore]
        [Display(Name = "Low volume color", GroupName = "Gradient", Order = 0)]
        public System.Windows.Media.Brush LowVolColor { get; set; }

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

        [XmlIgnore]
        [Display(Name = "High volume color", GroupName = "Gradient", Order = 1)]
        public System.Windows.Media.Brush HighVolColor { get; set; }

        [Browsable(false)]
        public string HighVolColorSerialize
        {
            get { return Serialize.BrushToString(HighVolColor); }
            set { HighVolColor = Serialize.StringToBrush(value); }
        }
        #endregion

        protected override void OnStateChange()
        {
            if (State == State.SetDefaults)
            {
                Name = "HLBandVolume";
                IsOverlay = true;
                Calculate = Calculate.OnBarClose;
                BandTicks = 5;
                FillOpacity = 0.65;
                RenderMode = HLBandRenderMode.BandZones;
                FixedVolumeMode = false;
                GradientSteps = 10;
                VolumePerStep = 100;
                LowVolColor = System.Windows.Media.Brushes.DodgerBlue;
                HighVolColor = System.Windows.Media.Brushes.Red;
                DisplayInDataBox = false;
                PaintPriceMarkers = false;
            }
            else if (State == State.Configure)
            {
                AddDataSeries(BarsPeriodType.Second, 1); // BarsInProgress == 1
            }
            else if (State == State.Historical)
            {
                if (ChartControl != null)
                {
                    ChartControl.Dispatcher.InvokeAsync(() =>
                    {
                        if (wheelPanel != null || ChartPanel == null) return;
                        wheelPanel = ChartPanel;
                        wheelPanel.PreviewMouseWheel += OnWheel; // tunneling: runs before the chart's own wheel handling
                    });
                }
            }
            else if (State == State.Terminated)
            {
                DetachWheel();
                DisposeResources();
            }
        }

        // ================= Data thread =================

        protected override void OnBarUpdate()
        {
            if (BarsInProgress != 1) return;

            int idx = BarsArray[0].GetBar(Times[1][0]);
            if (idx < 0) return;

            if (idx != curIdx)
            {
                curIdx = idx;
                curProfile = new Dictionary<double, long>();
                curHi = Highs[1][0];
                curLo = Lows[1][0];
            }
            else
            {
                if (Highs[1][0] > curHi) curHi = Highs[1][0];
                if (Lows[1][0] < curLo) curLo = Lows[1][0];
            }

            // Approximation: the whole second's volume is placed at the 1s close.
            double p = Instrument.MasterInstrument.RoundToTickSize(Closes[1][0]);
            long v;
            curProfile.TryGetValue(p, out v);
            curProfile[p] = v + (long)Volumes[1][0];

            // Use the chart bar's own high/low so the volume bands match what is drawn.
            // Fall back to the seconds extremes if the primary bar isn't available yet.
            double hi = curHi, lo = curLo;
            Bars primary = BarsArray[0];
            if (idx < primary.Count)
            {
                hi = primary.GetHigh(idx);
                lo = primary.GetLow(idx);
            }

            double band = BandTicks * TickSize;
            double mid = (hi + lo) * 0.5;
            double eps = TickSize * 0.001;
            double hCut = hi - band - eps;
            double lCut = lo + band + eps;

            // H/L totals are always the volume within BandTicks of the high / low,
            // regardless of render mode. Each price belongs to at most one band:
            // on short bars the bar is split at its midpoint.
            long h = 0, l = 0;
            foreach (var kv in curProfile)
            {
                if (kv.Key >= hCut && kv.Key > mid + eps) h += kv.Value;
                if (kv.Key <= lCut && kv.Key <= mid + eps) l += kv.Value;
            }

            bands[idx] = new BandVol(h, l);
        }

        // ================= Wheel handling (UI thread) =================

        private void OnWheel(object sender, MouseWheelEventArgs e)
        {
            if (!FixedVolumeMode || wheelPanel == null) return;

            try
            {
                if (!wheelSession)
                {
                    // First tick of a gesture: the only place a hit test happens.
                    wheelSession = true;
                    wheelAccum = 0;

                    var src = System.Windows.PresentationSource.FromVisual(wheelPanel);
                    if (src != null && src.CompositionTarget != null)
                    {
                        dpiX = src.CompositionTarget.TransformToDevice.M11;
                        dpiY = src.CompositionTarget.TransformToDevice.M22;
                    }

                    System.Windows.Point p = e.GetPosition(wheelPanel);
                    wheelHit = HitTest((float)(p.X * dpiX), (float)(p.Y * dpiY));
                }

                RestartIdleTimer();

                if (!wheelHit) return; // missed on the first tick: let the chart have the whole gesture

                System.Windows.Point pos = e.GetPosition(wheelPanel);
                wheelX = (float)(pos.X * dpiX);
                wheelY = (float)(pos.Y * dpiY);

                wheelAccum += e.Delta;
                int notches = wheelAccum / WheelNotch; // truncates toward zero; handles fine-grained wheels
                if (notches != 0)
                {
                    wheelAccum -= notches * WheelNotch;
                    int count = Math.Abs(notches);
                    for (int k = 0; k < count; k++)
                    {
                        long inc = Math.Max(1, VolumePerStep / 10); // ~10% per notch
                        long next = notches > 0 ? VolumePerStep + inc : VolumePerStep - inc;
                        VolumePerStep = (int)Math.Max(1, Math.Min(int.MaxValue / 2, next));
                    }
                }

                wheelLabel = "Volume / step: " + VolumePerStep.ToString("N0");
                e.Handled = true;
                ForceRefresh();
            }
            catch (Exception ex)
            {
                Print("HLBandVolume wheel error: " + ex.Message);
            }
        }

        private void RestartIdleTimer()
        {
            if (idleTimer == null)
            {
                idleTimer = new System.Windows.Threading.DispatcherTimer();
                idleTimer.Interval = TimeSpan.FromMilliseconds(IdleMs);
                idleTimer.Tick += OnIdle;
            }
            idleTimer.Stop();
            idleTimer.Start();
        }

        private void OnIdle(object sender, EventArgs e)
        {
            idleTimer.Stop();
            bool wasShowing = wheelSession && wheelHit;
            wheelSession = false;
            wheelHit = false;
            wheelLabel = null;
            if (wasShowing) ForceRefresh(); // hide the label
        }

        // Is (px, py), in chart pixels, inside a rectangle that is actually drawn?
        private bool HitTest(float px, float py)
        {
            if (ChartControl == null || ChartBars == null || lastScale == null) return false;
            Bars pb = ChartBars.Bars;
            if (pb == null || pb.Count == 0) return false;

            int i = ChartBars.GetBarIdxByX(ChartControl, (int)px);
            if (i < ChartBars.FromIndex || i > ChartBars.ToIndex || i < 0 || i >= pb.Count) return false;

            BandVol bv;
            if (!bands.TryGetValue(i, out bv) || (bv.H == 0 && bv.L == 0)) return false;

            float barW = (float)ChartControl.BarWidth * 2f;
            float x, hy1, hy2, ly1, ly2;
            GetBandRects(pb, ChartControl, lastScale, i, barW, out x, out hy1, out hy2, out ly1, out ly2);

            if (px < x || px > x + barW) return false;
            return (py >= hy1 && py <= hy2) || (py >= ly1 && py <= ly2);
        }

        private void DetachWheel()
        {
            ChartPanel panel = wheelPanel;
            wheelPanel = null;
            if (panel == null) return;

            panel.Dispatcher.InvokeAsync(() =>
            {
                panel.PreviewMouseWheel -= OnWheel;
                if (idleTimer != null)
                {
                    idleTimer.Stop();
                    idleTimer.Tick -= OnIdle;
                    idleTimer = null;
                }
            });
        }

        // ================= Rendering (UI thread) =================

        public override void OnRenderTargetChanged()
        {
            DisposeResources();
            if (RenderTarget == null) return;

            fillBrush = new SharpDX.Direct2D1.SolidColorBrush(RenderTarget, SharpDX.Color.Gray);

            labelBg = new SharpDX.Direct2D1.SolidColorBrush(RenderTarget, SharpDX.Color.Black);
            labelBg.Opacity = 0.85f;
            labelFg = new SharpDX.Direct2D1.SolidColorBrush(RenderTarget, SharpDX.Color.White);
            labelFormat = new SharpDX.DirectWrite.TextFormat(
                NinjaTrader.Core.Globals.DirectWriteFactory, "Arial", 12f);
        }

        private void DisposeResources()
        {
            if (fillBrush != null) { fillBrush.Dispose(); fillBrush = null; }
            if (labelBg != null) { labelBg.Dispose(); labelBg = null; }
            if (labelFg != null) { labelFg.Dispose(); labelFg = null; }
            if (labelFormat != null) { labelFormat.Dispose(); labelFormat = null; }
        }

        private static void BrushToRgb(System.Windows.Media.Brush brush, out float r, out float g, out float b)
        {
            var sb = brush as System.Windows.Media.SolidColorBrush;
            if (sb == null) { r = g = b = 0.5f; return; }
            System.Windows.Media.Color c = sb.Color;
            r = c.R / 255f;
            g = c.G / 255f;
            b = c.B / 255f;
        }

        // Screen geometry of the H and L rectangles for primary bar i (shared by drawing and hit testing).
        // H rect: top is pinned at the bar's HIGH.
        // L rect: bottom is pinned at the bar's LOW.
        // BandZones: H extends down BandTicks, L extends up BandTicks (neither crosses the midpoint).
        // MidToExtreme: H extends down to the midpoint, L extends up to the midpoint.
        // The 1px minimum height grows inward, so the pinned edges never move off the price.
        private void GetBandRects(Bars pb, ChartControl cc, ChartScale cs, int i, float barW,
            out float x, out float hy1, out float hy2, out float ly1, out float ly2)
        {
            double hi = pb.GetHigh(i);
            double lo = pb.GetLow(i);
            double mid = (hi + lo) * 0.5;

            double hBottom, lTop;
            if (RenderMode == HLBandRenderMode.MidToExtreme)
            {
                hBottom = mid;
                lTop = mid;
            }
            else
            {
                double band = BandTicks * TickSize;
                hBottom = Math.Max(hi - band, mid); // never below the midpoint
                lTop = Math.Min(lo + band, mid); // never above the midpoint
            }

            x = cc.GetXByBarIndex(ChartBars, i) - barW / 2f;

            hy1 = cs.GetYByValue(hi); // pinned: top at the high
            hy2 = Math.Max(cs.GetYByValue(hBottom), hy1 + 1f);

            ly2 = cs.GetYByValue(lo); // pinned: bottom at the low
            ly1 = Math.Min(cs.GetYByValue(lTop), ly2 - 1f);
        }

        // Volume -> gradient position in [0,1]
        private float GradientT(long vol, long maxVol)
        {
            if (FixedVolumeMode)
            {
                int steps = Math.Max(2, GradientSteps);
                long step = vol / Math.Max(1, VolumePerStep);
                if (step > steps - 1) step = steps - 1;
                return (float)step / (steps - 1);
            }
            return (float)Math.Sqrt((double)vol / maxVol);
        }

        protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
        {
            if (ChartBars == null || chartControl == null || chartScale == null) return;
            if (RenderTarget == null || RenderTarget.IsDisposed) return;
            if (fillBrush == null || fillBrush.IsDisposed) return;

            lastScale = chartScale; // used by the wheel hit test (same UI thread)

            try
            {
                DrawBands(chartControl, chartScale);
                DrawLabel();
            }
            catch (Exception ex)
            {
                if (ex.Message != lastError)
                {
                    lastError = ex.Message;
                    Print("HLBandVolume OnRender error: " + ex);
                }
            }
        }

        private void DrawBands(ChartControl chartControl, ChartScale chartScale)
        {
            Bars pb = ChartBars.Bars;
            if (pb == null || pb.Count == 0) return;

            int from = Math.Max(0, ChartBars.FromIndex);
            int to = Math.Min(ChartBars.ToIndex, pb.Count - 1);
            if (to < from) return;

            float barW = (float)chartControl.BarWidth * 2f;

            float loR, loG, loB, hiR, hiG, hiB;
            BrushToRgb(LowVolColor, out loR, out loG, out loB);
            BrushToRgb(HighVolColor, out hiR, out hiG, out hiB);

            BandVol bv;

            // Pass 1 (dynamic mode only): max volume among visible bands
            long maxVol = 1;
            if (!FixedVolumeMode)
            {
                for (int i = from; i <= to; i++)
                {
                    if (!bands.TryGetValue(i, out bv)) continue;
                    if (bv.H > maxVol) maxVol = bv.H;
                    if (bv.L > maxVol) maxVol = bv.L;
                }
            }

            fillBrush.Opacity = (float)FillOpacity;

            // Pass 2: draw
            for (int i = from; i <= to; i++)
            {
                if (!bands.TryGetValue(i, out bv)) continue;
                if (bv.H == 0 && bv.L == 0) continue;

                float x, hy1, hy2, ly1, ly2;
                GetBandRects(pb, chartControl, chartScale, i, barW, out x, out hy1, out hy2, out ly1, out ly2);

                float th = GradientT(bv.H, maxVol);
                fillBrush.Color = new SharpDX.Color(
                    loR + (hiR - loR) * th,
                    loG + (hiG - loG) * th,
                    loB + (hiB - loB) * th,
                    1f);
                RenderTarget.FillRectangle(new SharpDX.RectangleF(x, hy1, barW, hy2 - hy1), fillBrush);

                float tl = GradientT(bv.L, maxVol);
                fillBrush.Color = new SharpDX.Color(
                    loR + (hiR - loR) * tl,
                    loG + (hiG - loG) * tl,
                    loB + (hiB - loB) * tl,
                    1f);
                RenderTarget.FillRectangle(new SharpDX.RectangleF(x, ly1, barW, ly2 - ly1), fillBrush);
            }
        }

        // Volume-per-step label next to the cursor, shown only while a wheel gesture that hit a rectangle is active
        private void DrawLabel()
        {
            if (!wheelSession || !wheelHit || wheelLabel == null) return;
            if (labelBg == null || labelFg == null || labelFormat == null) return;

            float w = wheelLabel.Length * 7.5f + 14f;
            float h = 22f;
            float x = wheelX + 16f;
            float y = wheelY + 16f;

            if (ChartPanel != null)
            {
                if (x + w > ChartPanel.W) x = wheelX - w - 8f; // keep inside the panel
                if (y + h > ChartPanel.H) y = wheelY - h - 8f;
            }

            RenderTarget.FillRectangle(new SharpDX.RectangleF(x, y, w, h), labelBg);
            RenderTarget.DrawText(wheelLabel, labelFormat,
                new SharpDX.RectangleF(x + 7f, y + 3f, w - 7f, h - 3f), labelFg);
        }
    }
}

```

---

<div class="post-metadata">

**Author:** ![BillMilton](https://discourse.ninjatrader.com/letter_avatar_proxy/v4/letter/b/c68b51/32.png) [@BillMilton](https://discourse.ninjatrader.com/u/BillMilton)\
**Post date:** [October 29, 2026, 12:20pm UTC](https://discourse.ninjatrader.com/t/3d-bars-free-code/7878/2 "2026-10-29T12:20:48Z")

</div>

![3dVol.gif](https://discourse.ninjatrader.com/uploads/default/original/2X/4/4e89d63f44f9f0ea3f75eafe4230ef77909ae7bd.gif)

I’ll leave rounded corners as a task for your favorite AI:

 ![image](https://discourse.ninjatrader.com/uploads/default/original/2X/6/6a5a70849fe8f931d98fd93519c07ffce60b6b5b.png)
