Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Moving average color change when slow ma crosses above or below

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

    Moving average color change when slow ma crosses above or below

    Hi, I need some help here...

    I have tried programming an indicator that changes the color of an EMA depending on whether another MA crosses above or below it.

    Cross above = green

    cross below = red

    At the moment I have managed to change the color of the exact area where the crossing occurs, however I also need it to maintain the color until a crossing occurs again and change to red or green depending on the case. Please see the code below.


    I attach a photo so that it is better understood.​ I also have an NT7 indicator that performed this function but I don't know how to convert it to Ninjatrader 8...

    Any help will be very appreciated!




    Code:
    namespace NinjaTrader.NinjaScript.Indicators
    {
    public class MovingAverageColorChange : Indicator
    {
    private EMA ema;
    private HMA hma;
    private SMA sma;
    private TEMA tema;
    private TMA tma;
    private WMA wma;
    private bool SlopeColor = true;
    
    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Change color of Moving Average.";
    Name = "MovingAverageColorChange";
    Calculate = Calculate.OnBarClose;
    IsOverlay = true;
    DisplayInDataBox = true;
    DrawOnPricePanel = true;
    DrawHorizontalGridLines = true;
    DrawVerticalGridLines = true;
    PaintPriceMarkers = true;
    ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
    //Disable this property if your indicator requires custom values that cumulate with each new market data event.
    //See Help Guide for additional information.
    IsSuspendedWhileInactive = true;
    MAType = 1;
    Period = 20;
    Up = Brushes.Green;
    Down = Brushes.Red;
    AddPlot(Brushes.Transparent, "MA");
    }
    else if (State == State.Configure)
    {
    }
    else if (State == State.DataLoaded)
    {
    ema = EMA(Inputs[0], Period);
    hma = HMA(Inputs[0], Period);
    sma = SMA(Inputs[0], Period);
    tma = TMA(Inputs[0], Period);
    tema = TEMA(Inputs[0], Period);
    wma = WMA(Inputs[0], Period);
    }
    }
    
    protected override void OnBarUpdate()
    {
    switch (MAType)
    {
    case 1:
    {
    MA[0] = ema[0];
    break;
    }
    case 2:
    {
    MA[0] = hma[0];
    break;
    }
    case 3:
    {
    MA[0] = sma[0];
    break;
    }
    case 4:
    {
    MA[0] = tma[0];
    break;
    }
    case 5:
    {
    MA[0] = tema[0];
    break;
    }
    case 6:
    {
    MA[0] = wma[0];
    break;
    }
    }
    
    if(SlopeColor == true)
    if(CrossAbove(EMA(8), MA, 1)) {PlotBrushes[0][0] = Up;}
    else if(CrossBelow(EMA(8), MA, 1)) {PlotBrushes[0][0] = Down;}
    
    }
    
    [HASHTAG="t3322"]region[/HASHTAG] Properties
    [Range(1, 6), NinjaScriptProperty]
    [Display(ResourceType = typeof(Custom.Resource), Name = "MAType", GroupName = "Parameters", Order = 0)]
    public int MAType
    { get; set; }
    
    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="Period", Order=1, GroupName="Parameters")]
    public int Period
    { get; set; }
    
    [NinjaScriptProperty]
    [XmlIgnore]
    [Display(Name="Up", Order=2, GroupName="Parameters")]
    public Brush Up
    { get; set; }
    
    [Browsable(false)]
    public string UpSerializable
    {
    get { return Serialize.BrushToString(Up); }
    set { Up = Serialize.StringToBrush(value); }
    }
    
    [NinjaScriptProperty]
    [XmlIgnore]
    [Display(Name="Down", Order=3, GroupName="Parameters")]
    public Brush Down
    { get; set; }
    
    [Browsable(false)]
    public string DownSerializable
    {
    get { return Serialize.BrushToString(Down); }
    set { Down = Serialize.StringToBrush(value); }
    }
    
    [Browsable(false)]
    [XmlIgnore]
    public Series<double> MA
    {
    get { return Values[0]; }
    }
    #endregion
    
    }
    }​
    Click image for larger version

Name:	MA CROSS.png
Views:	847
Size:	56.4 KB
ID:	1271921

    #2
    Hello tradingnasdaqprueba,

    Thanks for your post.

    The EMACrossColor script for NinjaTrader 7 that you shared checks if one EMA is greater than another EMA and assigns a value to a green plot, otherwise a value is assigned to a separate red plot.

    In your script you could consider using a 'Greater than'/'Less than' comparison in your script instead of a CrossAbove()/CrossBelow() condition.

    By doing so, the condition to color the plot green would be true anytime the EMA(8) is greater than MA and the plot would be set to green for each bar this condition is true. The plot color would be red anytime the EMA(8) is less than MA and the plot would be set to red for each bar this condition is true.

    Please let us know if we may assist further.
    <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

    Comment


      #3
      Hello BrandonH,

      Thanks for your help, now it maintains the color, but the color change does not occur where the MAs crosses... What I need is for the color to change after the crossing occurs, in the next bar.

      Please see the attached image, here I have drawn with a BLUE vertical line, where the indicator makes the color change and in YELLOW where the color change should occur when the EMA(8)[0] < MA[0].

      See also the orange circle, Is there any condition I can apply so that this little cross remains green in cases like this?

      What should I need to make this change, Why is the condition EMA(8)[0] < MA[0] not currently met?



      Code:
      if(SlopeColor == true)
      if(EMA(8)[0] > MA[0]) {PlotBrushes[0][0] = Up;}
      
      if(EMA(8)[0] < MA[0]) {PlotBrushes[0][0] = Down;}
      ​

      Click image for larger version

Name:	MACROSS.png
Views:	654
Size:	58.0 KB
ID:	1272208



      Thanks!

      Comment


        #4
        Hello tradingnasdaqpruebra,

        Thanks for your notes.

        To understand exactly how the condition in your logic is evaluating, you would need to add debugging prints to the script and monitor the print output in the NinjaScript Output window (New > NinjaScript Output).

        Note that if you want both of your if conditions that determine when the plot color is changed to occur when SlopeColor == true, you would need to wrap the if conditions in curly braces. For example:

        if(SlopeColor == true)
        {
        if(EMA(8)[0] > MA[0]) {PlotBrushes[0][0] = Up;}

        if(EMA(8)[0] < MA[0]) {PlotBrushes[0][0] = Down;}
        }


        Add prints one line above each condition that prints out the EMA(8)[0] and MA[0] to understand how those conditions are evaluating in the script.

        Below is a link to a forum post that demonstrates how to use prints to understand behavior.
        https://ninjatrader.com/support/foru...121#post791121
        <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

        Comment


          #5
          Thanks Brandon!!! now works fine!

          Comment


            #6
            Hello Again Brandon,

            I would like to improve the indicator a little bit more by showing green when the cross between MAs is too little or to parallel, see image as example, What would be the procedure here?

            Click image for larger version

Name:	image.png
Views:	655
Size:	30.4 KB
ID:	1272538


            Thanks!​

            Comment


              #7
              Hello tradingnasdqpruebra,

              Thanks for your notes.

              I am not entirely certain I understand what you mean by "when the cross between MAs is too little or to parallel".

              Do you want to check if one plot is a certain number of ticks below the other plot?

              If so, you could offset the EMA(8)[0] or MA[0] by a certain number of ticks.

              For example, the code below would check if the EMA(8)[0] is less than the MA[0] minus 5 ticks.

              if(EMA(8)[0] < (MA[0] - 5 * TickSize))
              {
              //do something
              }


              See this help guide documentation about TickSize: https://ninjatrader.com/support/help...ize.htm​
              <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

              Comment


                #8
                Originally posted by tradingnasdaqprueba View Post
                Hi, I need some help here...

                I also have an NT7 indicator that performed this function but I don't know how to convert it to Ninjatrader 8...
                Could you post the NT7 indicator so that members in this forum can give the conversion a try.

                lolu

                Comment


                  #9
                  Hello Brandon,

                  The thing is I am trying to copy one indicator that I have from a 3rd Party. What happens here is that sometimes this indicator doesn't color some little MA crosses... but other times it does... and I don't understand the logic here...



                  Hello Omololu,

                  I atached the indicator for NT7 so maybe somebody can convert it to NT8.

                  Thanks!

                  Attached Files
                  Last edited by tradingnasdaqprueba; 10-20-2023, 06:33 AM.

                  Comment


                    #10
                    Hello tradingnasdaqprueba,

                    Thanks for your notes.

                    The NinjaTrader 7 script is assigning the current bar value to the plot of the current bar and assigns the previous plot value to the previous bar as seen below.

                    MyEMAGreen.Set(EMA(Input, fastPeriod)[0]);
                    MyEMAGreen.Set(1, EMA(Input, fastPeriod)[1]);


                    You could try changing the plot color of the current bar and previous bar using PlotBrushes[][] when the condition is true.​

                    If you are converting this script and want it to function the exact same way in NinjaTrader 8 as it does in NinjaTrader 7, you could use the same logic seen in the NinjaTrader 7 compatible script within your NinjaTrader 8 script.

                    For example, create two plots in your NinjaTrader 8 script since the NinjaTrader 7 script uses two plots.

                    Then, copy the OnBarUpdate() logic from the NinjaTrader 7 script over to the NinjaTrader 8 script and resolve any errors that appear.

                    Note that instead of calling MyEMAGreen.Set() to assign a value to the plot, you would call MyEMAGreen[0] = X, where X is the value you are assigning to the plot. Instead of calling MyEMAGreen.Set(1, EMA(Input, fastPeriod)[1] you could assign the previous EMA value to the previous plot value.

                    Below I am including a link to a list of the code-breaking changes from NinjaTrader 7 to NinjaTrader 8. The help guide will be the best way to see how things have changed from NinjaTrader 7 to NinjaTrader 8.
                    http://ninjatrader.com/support/helpG...ng_changes.htm
                    <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                    Comment


                      #11
                      Hello Brandon,

                      Could you be more specific with this:

                      Code:
                      protected override void OnBarUpdate()
                      {
                      //Add your custom indicator logic here.
                      if (CurrentBar == 0) return;
                      
                      if(EMA(Input, fastPeriod)[0] > EMA(Input,slowPeriod)[0])
                      {
                      MyEMAGreen.Set(EMA(Input, fastPeriod)[0]);
                      MyEMAGreen.Set(1, EMA(Input, fastPeriod)[1]);
                      }
                      else
                      {
                      MyEMARed.Set(EMA(Input, fastPeriod)[0]);
                      MyEMARed.Set(1, EMA(Input, fastPeriod)[1]);
                      }



                      What should I do exactly? Do you mean this?


                      Code:
                      protected override void OnBarUpdate()
                              {
                                  //Add your custom indicator logic here.
                                  if (CurrentBar == 0) return;
                      
                                  if(EMA(Input, fastPeriod)[0] > EMA(Input,slowPeriod)[0]);
                                  {
                                  MyEMAGreen[0] = EMA(Input, fastPeriod)[0]);
                                  MyEMAGreen[1] = EMA(Input, fastPeriod)[1]);
                                  }
                                  else
                                  {
                                  MyEMARed[0] = EMA(Input, fastPeriod[0]);
                                  MyEMARed[1] = EMA(Input, fastPeriod[1]);
                                  }
                      ​

                      I become an error C0115 with this code, I think this should be like you told me with the PlotBrushes[][] but I don't understand how... Could you be more especific with this?

                      Click image for larger version

Name:	image.png
Views:	599
Size:	88.1 KB
ID:	1272718

                      ​​​Thanks!!

                      Comment


                        #12
                        Hello tradingnasdaqprueba,

                        It looks like you have a couple problems in that code. The first item is that if statements never have semi colons at the end. Please see the examples below, your original code and then the modification that just removes the semi colon ; from the end

                        This:

                        Code:
                        if(EMA(Input, fastPeriod)[0] > EMA(Input,slowPeriod)[0]);

                        should be this:

                        Code:
                        if(EMA(Input, fastPeriod)[0] > EMA(Input,slowPeriod)[0])



                        You also have some extra parenthesis at the end that are not needed. The code should look like the following, I removed the closing ) at the end of each line. Here is one example and then the full block of code below.

                        This:

                        Code:
                        MyEMAGreen[0] = EMA(Input, fastPeriod)[0]);

                        should be:

                        Code:
                        MyEMAGreen[0] = EMA(Input, fastPeriod)[0];



                        Code:
                        if(EMA(Input, fastPeriod)[0] > EMA(Input,slowPeriod)[0])
                        {
                            MyEMAGreen[0] = EMA(Input, fastPeriod)[0];
                            MyEMAGreen[1] = EMA(Input, fastPeriod)[1];
                        }
                        else
                        {
                            MyEMARed[0] = EMA(Input, fastPeriod)[0];
                            MyEMARed[1] = EMA(Input, fastPeriod)[1];
                        }​

                        Comment


                          #13
                          Hello Jesse,

                          I tried to compile as you said but I have some compiling error CS1525...

                          Click image for larger version

Name:	image.png
Views:	608
Size:	48.0 KB
ID:	1272787


                          Here all the code, could you please check it to see if more errors appear? Could you please help me to repair this?

                          Code:
                          ​#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;
                          #endregion
                          
                          //This namespace holds Indicators in this folder and is required. Do not change it.
                          namespace NinjaTrader.NinjaScript.Indicators
                          {
                          public class EMA20DIRECCION : Indicator
                          {
                          protected override void OnStateChange()
                          {
                          if (State == State.SetDefaults)
                          {
                          Description = @"Enter the description for your new custom Indicator here.";
                          Name = "EMA20DIRECCION";
                          Calculate = Calculate.OnBarClose;
                          IsOverlay = false;
                          DisplayInDataBox = true;
                          DrawOnPricePanel = true;
                          DrawHorizontalGridLines = true;
                          DrawVerticalGridLines = true;
                          PaintPriceMarkers = true;
                          ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
                          //Disable this property if your indicator requires custom values that cumulate with each new market data event.
                          //See Help Guide for additional information.
                          IsSuspendedWhileInactive = true;
                          AddPlot(Brushes.Green, "MyEMAGreen");
                          AddPlot(Brushes.Red, "MyEMARed");
                          
                          
                          }
                          else if (State == State.Configure)
                          {
                          }
                          }
                          
                          [HASHTAG="t3322"]region[/HASHTAG] Variables
                          // Wizard generated variables
                          private int slowPeriod = 8; // Default setting for SlowPeriod
                          private int fastPeriod = 20; // Default setting for FastPeriod
                          // User defined variables (add any user defined variables below)
                          #endregion
                          
                          
                          protected override void OnBarUpdate()
                          {
                          //Add your custom indicator logic here.
                          if (CurrentBar == 0) return
                          
                          if (EMA(Input, fastPeriod)[0] < EMA(Input,slowPeriod)[0])
                          {
                          MyEMAGreen[0] = EMA(Input, fastPeriod)[0];
                          MyEMAGreen[1] = EMA(Input, fastPeriod)[1];
                          }
                          else
                          {
                          MyEMARed[0] = EMA(Input, fastPeriod)[0];
                          MyEMARed[1] = EMA(Input, fastPeriod)[1];
                          }​
                          }
                          }
                          }
                          
                          [HASHTAG="t3322"]region[/HASHTAG] NinjaScript generated code. Neither change nor remove.
                          
                          namespace NinjaTrader.NinjaScript.Indicators
                          {
                          public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
                          {
                          private EMA20DIRECCION[] cacheEMA20DIRECCION;
                          public EMA20DIRECCION EMA20DIRECCION()
                          {
                          return EMA20DIRECCION(Input);
                          }
                          
                          public EMA20DIRECCION EMA20DIRECCION(ISeries<double> input)
                          {
                          if (cacheEMA20DIRECCION != null)
                          for (int idx = 0; idx < cacheEMA20DIRECCION.Length; idx++)
                          if (cacheEMA20DIRECCION[idx] != null && cacheEMA20DIRECCION[idx].EqualsInput(input))
                          return cacheEMA20DIRECCION[idx];
                          return CacheIndicator<EMA20DIRECCION>(new EMA20DIRECCION(), input, ref cacheEMA20DIRECCION);
                          }
                          }
                          }
                          
                          namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
                          {
                          public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
                          {
                          public Indicators.EMA20DIRECCION EMA20DIRECCION()
                          {
                          return indicator.EMA20DIRECCION(Input);
                          }
                          
                          public Indicators.EMA20DIRECCION EMA20DIRECCION(ISeries<double> input )
                          {
                          return indicator.EMA20DIRECCION(input);
                          }
                          }
                          }
                          
                          namespace NinjaTrader.NinjaScript.Strategies
                          {
                          public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
                          {
                          public Indicators.EMA20DIRECCION EMA20DIRECCION()
                          {
                          return indicator.EMA20DIRECCION(Input);
                          }
                          
                          public Indicators.EMA20DIRECCION EMA20DIRECCION(ISeries<double> input )
                          {
                          return indicator.EMA20DIRECCION(input);
                          }
                          }
                          }
                          
                          #endregion



                          Thanks!!!

                          Comment


                            #14
                            Hello tradingnasdaqprueba

                            You are missing a semi colon after the return statement, you do need semi colons after code just not for if condition statements.

                            This

                            Code:
                            if (CurrentBar == 0) return


                            Should be:

                            Code:
                            if (CurrentBar == 0) return;
                            An if statement is formatted like the following:

                            if( some condition) your code here ;

                            or

                            if( some condition)
                            {
                            your code here ;
                            }

                            Comment


                              #15
                              Okey Thanks! Next error CS0103

                              Click image for larger version

Name:	image.png
Views:	584
Size:	54.0 KB
ID:	1272793
                              Thanks Again!

                              Comment

                              Latest Posts

                              Collapse

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