Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Modify bollinger band

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Modify bollinger band

    Hi, I tried to modify the Bollinger band code to color the candle "Blue" when there are two consecutive candle that close above the midline. When there are two consecutive candle that close below the midline, color the candle magenta. I have the following code, but it is not updating the color of the candles on my chart.

    Code:
    //
    // Copyright (C) 2024, NinjaTrader LLC <www.ninjatrader.com>.
    // NinjaTrader reserves the right to modify or overwrite this NinjaScript component with each release.
    //
    #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.Data;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Core.FloatingPoint;
    using NinjaTrader.NinjaScript.DrawingTools;
    #endregion
    
    // This namespace holds indicators in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Indicators
    {
        /// <summary>
        /// Bollinger Bands are plotted at standard deviation levels above and below a moving average.
        /// Since standard deviation is a measure of volatility, the bands are self-adjusting:
        /// widening during volatile markets and contracting during calmer periods.
        /// </summary>
        public class Bollinger : Indicator
        {
            private SMA        sma;
            private StdDev    stdDev;
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description                 = NinjaTrader.Custom.Resource.NinjaScriptIndicatorDescriptionBollinger;
                    Name                        = NinjaTrader.Custom.Resource.NinjaScriptIndicatorNameBollinger;
                    IsOverlay                   = true;
                    IsSuspendedWhileInactive    = true;
                    NumStdDev                   = 2;
                    Period                      = 14;
                    Calculate                   = Calculate.OnEachTick;
    
                    AddPlot(Brushes.Goldenrod, NinjaTrader.Custom.Resource.BollingerUpperBand);
                    AddPlot(Brushes.Goldenrod, NinjaTrader.Custom.Resource.BollingerMiddleBand);
                    AddPlot(Brushes.Goldenrod, NinjaTrader.Custom.Resource.BollingerLowerBand);
                }
                else if (State == State.DataLoaded)
                {
                    sma     = SMA(Period);
                    stdDev  = StdDev(Period);
                }
            }
    
            protected override void OnBarUpdate()
            {
                // Ensure we have a previous bar to compare
                if (CurrentBar < 1)
                {
                    BarBrush = null;
                    CandleOutlineBrush = null;
                    return;
                }
    
                double sma0    = sma[0];
                double stdDev0 = stdDev[0];
    
                Upper[0] = sma0 + NumStdDev * stdDev0;
                Middle[0] = sma0;
                Lower[0] = sma0 - NumStdDev * stdDev0;
    
                // Determine if current and previous candles are green (bullish) and above midline
                bool currentGreen = (Close[0] > Open[0]) && (Close[0] > Middle[0]);
                bool previousGreen = (Close[1] > Open[1]) && (Close[1] > Middle[1]);
    
                // Determine if current and previous candles are red (bearish) and below midline
                bool currentRed = (Close[0] < Open[0]) && (Close[0] < Middle[0]);
                bool previousRed = (Close[1] < Open[1]) && (Close[1] < Middle[1]);
    
                // Apply blue color when two consecutive green candles above the midline occur
                if (currentGreen && previousGreen)
                {
                    BarBrush = Brushes.Blue;
                    CandleOutlineBrush = Brushes.Blue;
                }
                // Apply magenta color when two consecutive red candles below the midline occur
                else if (currentRed && previousRed)
                {
                    BarBrush = Brushes.Magenta;
                    CandleOutlineBrush = Brushes.Magenta;
                }
                else
                {
                    // Reset to default if conditions are not met
                    BarBrush = null;
                    CandleOutlineBrush = null;
                }
            }
    
            #region Properties
            [Browsable(false)]
            [XmlIgnore()]
            public Series<double> Lower
            {
                get { return Values[2]; }
            }
    
            [Browsable(false)]
            [XmlIgnore()]
            public Series<double> Middle
            {
                get { return Values[1]; }
            }
    
            [Range(0, int.MaxValue), NinjaScriptProperty]
            [Display(ResourceType = typeof(Custom.Resource), Name = "NumStdDev", GroupName = "NinjaScriptParameters", Order = 0)]
            public double NumStdDev
            { get; set; }
    
            [Range(1, int.MaxValue), NinjaScriptProperty]
            [Display(ResourceType = typeof(Custom.Resource), Name = "Period", GroupName = "NinjaScriptParameters", Order = 1)]
            public int Period
            { get; set; }
    
            [Browsable(false)]
            [XmlIgnore()]
            public Series<double> Upper
            {
                get { return Values[0]; }
            }
            #endregion
        }
    }
    
    #region NinjaScript generated code. Neither change nor remove.
    
    namespace NinjaTrader.NinjaScript.Indicators
    {
        public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
        {
            private Bollinger[] cacheBollinger;
            public Bollinger Bollinger(double numStdDev, int period)
            {
                return Bollinger(Input, numStdDev, period);
            }
    
            public Bollinger Bollinger(ISeries<double> input, double numStdDev, int period)
            {
                if (cacheBollinger != null)
                    for (int idx = 0; idx < cacheBollinger.Length; idx++)
                        if (cacheBollinger[idx] != null && cacheBollinger[idx].NumStdDev == numStdDev && cacheBollinger[idx].Period == period && cacheBollinger[idx].EqualsInput(input))
                            return cacheBollinger[idx];
                return CacheIndicator<Bollinger>(new Bollinger(){ NumStdDev = numStdDev, Period = period }, input, ref cacheBollinger);
            }
        }
    }
    
    namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
    {
        public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
        {
            public Indicators.Bollinger Bollinger(double numStdDev, int period)
            {
                return indicator.Bollinger(Input, numStdDev, period);
            }
    
            public Indicators.Bollinger Bollinger(ISeries<double> input , double numStdDev, int period)
            {
                return indicator.Bollinger(input, numStdDev, period);
            }
        }
    }
    
    namespace NinjaTrader.NinjaScript.Strategies
    {
        public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
        {
            public Indicators.Bollinger Bollinger(double numStdDev, int period)
            {
                return indicator.Bollinger(Input, numStdDev, period);
            }
    
            public Indicators.Bollinger Bollinger(ISeries<double> input , double numStdDev, int period)
            {
                return indicator.Bollinger(input, numStdDev, period);
            }
        }
    }
    
    #endregion
    ​

    #2
    It seems to be working on my end. I just copy/pasted your code and it works. Maybe you need to hit F5 to refresh it?​
    Attached Files

    Comment


      #3
      Hi

      Did you modify the existing indicator from Ninjatrader or did you created a new indicator and reloaded it?

      Comment


        #4
        I modified an existing 'test' template I use and copied the private variables and replaced the relevant code.I did need to refresh at first to see it. Although, at first I was simply testing the BarBrush and CandleOutlineBrush, so that's probably why I needed to refresh it.

        Comment


          #5
          Would you upload your working indicator file so I can import it into my system?

          Thank you.

          Comment


            #6
            Hello. I have modified the Properties window a bit, so you can select colors for each of the band, adjust Opacity if you want, and adjust the colors for your Green and Red candles. Everything should be set to the defaults you provided. Let me know if you run into any problems and I'll check it.
            Attached Files

            Comment


              #7
              Got it. thank you. Your file working for me and I see where I went wrong in creating the file.

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by Geovanny Suaza, 02-11-2026, 06:32 PM
              0 responses
              557 views
              0 likes
              Last Post Geovanny Suaza  
              Started by Geovanny Suaza, 02-11-2026, 05:51 PM
              0 responses
              324 views
              1 like
              Last Post Geovanny Suaza  
              Started by Mindset, 02-09-2026, 11:44 AM
              0 responses
              101 views
              0 likes
              Last Post Mindset
              by Mindset
               
              Started by Geovanny Suaza, 02-02-2026, 12:30 PM
              0 responses
              545 views
              1 like
              Last Post Geovanny Suaza  
              Started by RFrosty, 01-28-2026, 06:49 PM
              0 responses
              547 views
              1 like
              Last Post RFrosty
              by RFrosty
               
              Working...
              X