Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

NinjaScript Indicator Behavior

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

    NinjaScript Indicator Behavior

    Hello,

    I created an indicator that draws a green horizontal line if the RSI and the current candlestick is bullish and that draws a deep pink horizontal line if the RSI and the current candlestick is bearish. Other criteria include the EMA's, and the Parabolic SAR.

    But in the case where I am bullish and there is a green horizontal line, but then the current candlestick turns into a red bearish candle, I would like for the green horizontal line that was drawn on the chart to disappear or to become transparent; instead it usually remains.

    The same is true if the RSI drops below 55, or if the EMA setup that triggered the signal has reversed, or if the price goes below the Parabolic SAR. I would like for the green horizontal line that was drawn on the chart to disappear or to become transparent; instead it usually remains.

    And the inverse is true for a deep pink horizontal line that has been drawn on the chart and then the current candlestick turns into a green bullish candle, or the RSI, Parabolic SAR, or EMA that triggered the short signal has reversed.

    For that behavior, would I add an else if statement to cause the horizontal line to be removed or to become transparent, in those situations?

    If so, what code could I use? I'm still new to NinjaScript and to C#.


    Screenshot attached regarding the section where I assume I would add an if statement or other code.
    Attached Files

    #2
    Hello i2w8am9ii2,
    Thanks for your post.

    Each line is removed when the other is drawn on my chart. I would expect this because the tag is the same.

    If you pass in the same "tag" value each time you draw an object, the same draw object is modified. If unique tags are used each time, a new draw object will be created on the chart. Are you saying that both lines are being drawn on the chart at the same time and are not changing colors?
    Josh G.NinjaTrader Customer Service

    Comment


      #3
      Hi Josh,

      Thanks for your reply.

      No, I'm not saying that both lines are being drawn on the chart at the same time and are not changing colors. Only one line is being drawn at a time, and the current line will change colors, when all four criteria for a trade in the opposite direction are met.

      But in the meanwhile, if one or more of the original criteria that triggered the signal for the horizontal line to be drawn no longer exist, I would like for the horizontal line to take on a transparent color, or to be removed, until either all four criteria for a trade in the opposite direction exist, or until all four criteria for a trade in the same direction exist.

      And the four criteria for a long trade (LimeGreen horizontal line) are: * RSI >= 55 * 5 EMA > 15 EMA * High of current price bar > Parabolic SAR * High of current price bar > Opening price

      The four criteria for a short trade (DeepPink horizontal line) are: * RSI <= 45 * 5 EMA < 15 EMA * Low of current price bar < Parabolic SAR * Low of current price bar < Opening price

      In other words, with the colored horizontal line becoming transparent or being removed, I am wanting an earlier indication that the price might be reversing, losing strength, or going beginning to consolidate

      Comment


        #4
        I added a couple of else if statements. Screenshot attached.

        The horizontal line does become transparent at times, and then later changes to LimeGreen or to DeepPink, but the behavior seems to be far too delayed.

        Is there anything you can see that I did wrong?
        Attached Files

        Comment


          #5
          You will need to create a condition that either removes that draw object with RemoveDrawObject() or set the brush to transparent with the same condition.

          Help Guide - RemoveDrawObject()

          EDIT : I replied right when you posted again. I do not see anything that sticks out as "wrong" in your code. This is going to come down to the logic you have chosen for your lines.
          Josh G.NinjaTrader Customer Service

          Comment


            #6
            Hi Josh,

            Thanks for your reply and for the link.

            I will try the RemoveDrawObject() later on.

            In the meanwhile, for the existing else if statement code that I added, do you think it will make a difference in regards to the delayed behavior that I'm experiencing, if I change the order around, to be if > else if > else if > else if - instead of what I have now, which is:

            if > if > else if > else if


            And is keeping the tag names all the same, what I should be doing, for the result I'm wanting?

            Comment


              #7
              Originally posted by i2w8am9ii2 View Post
              I will try the RemoveDrawObject() later on.
              Recommend you try that now.

              Originally posted by i2w8am9ii2 View Post
              In the meanwhile, for the existing else if statement code that I added, do you think it will make a difference in regards to the delayed behavior that I'm experiencing, if I change the order around, to be if > else if > else if > else if - instead of what I have now, which is:

              if > if > else if > else if
              Yes. Because you've changed the order of the logic, it may very well change what happens.

              And you allude to a strange kind of question, "does your code changes make a difference?".

              Well, yes, of course, changes to the logic will result in different results -- that's exactly the point of the changes, and completely expected, isn't it?

              Now whether that difference is what you wanted -- well, that's up to you.

              [You've asked the kind of question that seems rather obvious: similar to "If I press the gas pedal down further, will that change the speed of the car"? Also, your question is way too specific and your code sample way too general to guess what the difference in results will actually be. Always attach a complete working sample of code, so people have something specific to play with, when you need a truly spot-on specific answer. ]

              Originally posted by i2w8am9ii2 View Post
              And is keeping the tag names all the same, what I should be doing, for the result I'm wanting?
              Try this:
              Go back to your first attached screenshot image.

              1. Make 'Set 2' be an 'else if' statement.

              3. Add an 'else' statement after 'Set 2' that removes the draw object, like this,

              Code:
              else
              {
                  RemoveDrawObject("soTag002");
              }
              Does that achieve the effect you're looking for?
              Last edited by bltdavid; 09-05-2018, 09:57 PM.

              Comment


                #8
                Hi bltdavid,

                Thanks for your reply.

                Attached is a screenshot of the new order of my if > else if statements that I just recently tried out, before I read your reply. Again, the updated NinjaScript was slow to update the changes in the indicator behavior that I wanted.

                I will try your suggestion of using RemoveDrawObject("soTag002"); now.

                Below is the current version of my code:

                Keep in mind that I could not add the end code, because the forum said it was too long.

                // Copyright (C) 2018, 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>
                /// The RSI (Relative Strength Index) is a price-following oscillator that ranges between 0 and 100.
                /// </summary>
                public class soRSI1EMA1ParSAR1Price1 : Indicator
                {
                private Series<double> avgDown;
                private Series<double> avgUp;
                private double constant1;
                private double constant2;
                private double constant3;
                private Series<double> down;
                private SMA smaDown;
                private SMA smaUp;
                private Series<double> up;

                // Code that I added ************************************************** *******************************
                // Code that I added ************************************************** *******************************

                private RSI RSI1;
                private EMA EMA1;
                private EMA EMA2;
                private ParabolicSAR ParabolicSAR1;

                // End - code that I added ************************************************** *******************************
                // End - code that I added ************************************************** *******************************

                protected override void OnStateChange()
                {
                if (State == State.SetDefaults)
                {
                Description = NinjaTrader.Custom.Resource.NinjaScriptIndicatorDe scriptionRSI;
                Name = "soRSI1EMA1ParSAR1Price1";
                IsSuspendedWhileInactive = true;
                BarsRequiredToPlot = 20;
                Period = 14;
                Smooth = 3;

                AddPlot(Brushes.DodgerBlue, NinjaTrader.Custom.Resource.NinjaScriptIndicatorNa meRSI);
                AddPlot(Brushes.Goldenrod, NinjaTrader.Custom.Resource.NinjaScriptIndicatorAv g);

                AddLine(Brushes.DarkCyan, 30, NinjaTrader.Custom.Resource.NinjaScriptIndicatorLo wer);
                AddLine(Brushes.DarkCyan, 70, NinjaTrader.Custom.Resource.NinjaScriptIndicatorUp per);
                }
                else if (State == State.Configure)
                {
                constant1 = 2.0 / (1 + Smooth);
                constant2 = (1 - (2.0 / (1 + Smooth)));
                constant3 = (Period - 1);
                }
                else if (State == State.DataLoaded)
                {
                avgUp = new Series<double>(this);
                avgDown = new Series<double>(this);
                down = new Series<double>(this);
                up = new Series<double>(this);
                smaDown = SMA(down, Period);
                smaUp = SMA(up, Period);

                // Code that I added ************************************************** *******************************
                // Code that I added ************************************************** *******************************

                RSI1 = RSI(Close, 14, 3);
                EMA1 = EMA(Close, 5);
                EMA2 = EMA(Close, 15);
                ParabolicSAR1 = ParabolicSAR(Close, 0.02, 0.2, 0.02); // = ParabolicSAR(Close, 0.02, 0.2, 0.02);

                // End - code that I added ************************************************** *******************************
                // End - code that I added ************************************************** *******************************
                }
                }

                protected override void OnBarUpdate()
                {
                if (CurrentBar == 0)
                {
                down[0] = 0;
                up[0] = 0;

                if (Period < 3)
                Avg[0] = 50;

                return;
                }

                double input0 = Input[0];
                double input1 = Input[1];
                down[0] = Math.Max(input1 - input0, 0);
                up[0] = Math.Max(input0 - input1, 0);

                if (CurrentBar + 1 < Period)
                {
                if (CurrentBar + 1 == Period - 1)
                Avg[0] = 50;
                return;
                }

                if ((CurrentBar + 1) == Period)
                {
                // First averages
                avgDown[0] = smaDown[0];
                avgUp[0] = smaUp[0];
                }
                else
                {
                // Rest of averages are smoothed
                avgDown[0] = (avgDown[1] * constant3 + down[0]) / Period;
                avgUp[0] = (avgUp[1] * constant3 + up[0]) / Period;
                }

                double avgDown0 = avgDown[0];
                double value0 = avgDown0 == 0 ? 100 : 100 - 100 / (1 + avgUp[0] / avgDown0);
                Default[0] = value0;
                Avg[0] = constant1 * value0 + constant2 * Avg[1];

                // OnBarUpdate() Code that I added ************************************************** *********************
                // OnBarUpdate() Code that I added ************************************************** *********************

                if (CurrentBars[0] < 1)
                return;

                // Set 1
                if ((RSI1.Avg[0] >= 55)
                && (EMA1[0] > EMA2[0])
                && (High[0] > ParabolicSAR1[0])
                && (High[0] > Open[0]))
                {
                // Draw.HorizontalLine(this, @"RSI1EMA1ParSAR1Price1 Horizontal Line_1", false, 0, Brushes.LimeGreen, DashStyleHelper.Solid, 3);

                Draw.HorizontalLine(this, "soTag002", Close[0] - 4 * TickSize, Brushes.LimeGreen, DashStyleHelper.Solid, 5);
                }

                // New else if statement that I added ************************************************** *******************
                // New else if statement that I added ************************************************** *******************

                else if ((RSI1.Avg[0] < 55)
                || (EMA1[0] < EMA2[0])
                || (Low[0] < ParabolicSAR1[0])
                || (Low[0] < Open[0]))
                {
                // Draw.HorizontalLine(this, @"RSI1EMA1ParSAR1Price1 Horizontal Line_1", false, 0, Brushes.LimeGreen, DashStyleHelper.Solid, 3);

                Draw.HorizontalLine(this, "soTag002", Close[0] - 4 * TickSize, Brushes.Transparent, DashStyleHelper.Solid, 5);
                }

                // Set 2
                else if ((RSI1.Avg[0] <= 45)
                && (EMA1[0] < EMA2[0])
                && (Low[0] < ParabolicSAR1[0])
                && (Low[0] < Open[0]))
                {
                // Draw.HorizontalLine(this, @"RSI1EMA1ParSAR1Price1 Horizontal Line_1", false, 0, Brushes.DeepPink, DashStyleHelper.Solid, 3);

                Draw.HorizontalLine(this, "soTag002", Close[0] + 4 * TickSize, Brushes.DeepPink, DashStyleHelper.Solid, 5);
                }

                // New else if statement that I added ************************************************** *******************
                // New else if statement that I added ************************************************** *******************

                else if ((RSI1.Avg[0] > 45)
                || (EMA1[0] > EMA2[0])
                || (High[0] > ParabolicSAR1[0])
                || (High[0] > Open[0]))
                {
                // Draw.HorizontalLine(this, @"RSI1EMA1ParSAR1Price1 Horizontal Line_1", false, 0, Brushes.DeepPink, DashStyleHelper.Solid, 3);

                Draw.HorizontalLine(this, "soTag002", Close[0] + 4 * TickSize, Brushes.Transparent, DashStyleHelper.Solid, 5);
                }

                // End - code that I added ************************************************** *******************************
                // End - code that I added ************************************************** *******************************
                }

                #region Properties
                [Browsable(false)]
                [XmlIgnore()]
                public Series<double> Avg
                {
                get { return Values[1]; }
                }

                [Browsable(false)]
                [XmlIgnore()]
                public Series<double> Default
                {
                get { return Values[0]; }
                }

                [Range(1, int.MaxValue), NinjaScriptProperty]
                [Display(ResourceType = typeof(Custom.Resource), Name = "Period", GroupName = "NinjaScriptParameters", Order = 0)]
                public int Period
                { get; set; }

                [Range(1, int.MaxValue), NinjaScriptProperty]
                [Display(ResourceType = typeof(Custom.Resource), Name = "Smooth", GroupName = "NinjaScriptParameters", Order = 1)]
                public int Smooth
                { get; set; }
                #endregion
                }
                }

                #region NinjaScript generated code. Neither change nor remove.
                Attached Files

                Comment


                  #9
                  Originally posted by i2w8am9ii2 View Post
                  Thanks for your reply.
                  You're welcome. But you're not making it easy to help you.

                  I requested you attach complete working sample code.



                  "Attaching a file" and "copying & pasting your working sample code into the message" are not equivalent.

                  You previously attached a screenshot file ... it was easy, right?

                  So, why not attach your NinjaScript code file?

                  [Think how much faster the reader would be if all they had to do was download your attached file and start right away compiling and inspecting your code ... ]

                  Comment


                    #10
                    Hi bltdavid,

                    I am new to NinjaScript and to creating indicators, so please bear with my lack of experience.

                    Attached is the .cs file for the indicator. I assume that is what you are wanting when you say that you are wanting me to "attach complete working sample code". Please let me know if instead you are wanting something else.

                    Attached also is a screenshot of my latest attempt to make this indicator work in the way that I am wanting. I added "and/or" code (&& II). You might want to explore that further.

                    I also thought that the issue might be with the Properties: Price type: Close/ High/ Low/ Median/ Open/ Typical/ Weighted settings.

                    At this time it is set to 'Close' in the State.DataLoaded section.

                    But again, these troubleshooting theories are coming from someone new to NinjaScript and C# and with almost zero indicator development experience. But it is somewhere to start looking in my opinion.
                    Attached Files

                    Comment


                      #11
                      Originally posted by i2w8am9ii2 View Post
                      I am new to NinjaScript and to creating indicators, so please bear with my lack of experience.
                      No problem, I totally get where you are coming from.

                      There's a learning curve to everything that is worthwhile in life, and NinjaTrader is no exception.

                      Even using this forum in the best possible way has a learning curve, too!

                      Thank you very much for uploading your NinjaScript code file. Yes, that is exactly what I meant. Always attach a working sample that illustrates your problem -- if you can't do that (because you need to protect your intellectual property, which only the pro's and business types are really concerned about here) you'll suffer longer than necessary trying to fix your issue.

                      Helping diagnose issues is soooooooo much easier when people attach their code.

                      It's like complaining about car trouble to your favorite mechanic, and the first thing he asks is to see your car -- well, we need to see your code -- trying to help fix your code starts with the same diagnostic mentality as your car mechanic, we need to see it not working so we can see & advise you of a fix.

                      Originally posted by i2w8am9ii2 View Post
                      But again, these troubleshooting theories are coming from someone new to NinjaScript and C# and with almost zero indicator development experience. But it is somewhere to start looking in my opinion.
                      Again, no problem. Hang in there, you have lots to learn, but it should be a fun ride.

                      Ok, let me look at your code ... compiles ok ... hmm, good good ... yes, yes ...



                      I added it to a 5-Min CL chart, but I don't see your line being drawn.

                      Am I missing something?
                      What kind of chart should I add your indicator to?
                      Which instrument and bar type?

                      Also, please restate your current problem -- I see you've updated the code logic, so what is the issue we're trying to resolve again?

                      What's not working right?
                      Last edited by bltdavid; 09-05-2018, 11:45 PM.

                      Comment


                        #12
                        Hi bltdavid,

                        Thanks for your reply and for understanding my situation and explaining how things work when it comes to indicator development troubleshooting more clearly.

                        I use this indicator on Tick charts, such as a 75 Tick chart and a 150 Tick chart and it is also can be used on a 1 minute chart. I haven't really been testing it on longer time-frame charts like a 5 minute or larger.

                        The four criteria for a long trade (LimeGreen horizontal line to be drawn) are: * RSI equal to or greater than 55 * 5 EMA above 15 EMA * High of current price bar above Parabolic SAR * High of current price bar above Opening price

                        The four criteria for a short trade (DeepPink horizontal line to be drawn) are: * RSI equal to or less than 45 * 5 EMA below 15 EMA * Low of current price bar below Parabolic SAR * Low of current price bar below Opening price.


                        All that worked fine on my first working version of this indicator. But the problem was that after the initial conditions that existed to cause the horizontal line to be drawn were in place, if any of them changed, the horizontal line would remain, until the opposite signal criteria were all met.

                        And often, by that time, a complete trend reversal had taken place. So I am wanting an earlier warning of a possible change in the price action. And if the LimeGreen horizontal line disappears after it was drawn, or if the DeepPink horizontal line disappears after it was drawn, that could warn me of a possible change in the price action and to tighten my stop-loss or take partial profits, etc.

                        Attached is a text file of the code for the indicator when it was working to draw the horizontal lines each and every time, before I started editing the code looking for earlier price action warning signs.

                        You can just copy and paste that code into a NinjaScript file and test it out, and see if you see what I am referring to.

                        Attached also is a screenshot of a chart when the DeepPink horizontal line should have been drawn, but was not. In the screenshot, the purple Moving Average is the 5 EMA and the black Moving Average is the 15 EMA. The gray dots are of course the Parabolic SAR. And the blue line is the RSI. The purple horizontal line is just the current price.

                        Before I took that screenshot, a LimeGreen horizontal line was drawn. But it would not draw a DeepPink horizontal line when the price action reversed. You might want to start looking there (at the short trade entry signal).
                        Attached Files
                        Last edited by i2w8am9ii2; 09-06-2018, 12:13 AM.

                        Comment


                          #13
                          Hi i2w8am9ii2,

                          Excuse me if I chime in here uninvited and bltdavid already helping you along. I am not a programmer and work my way with the trial and error method. Drawing lines and making them disappear was something I dealt with.

                          Your horizontal lines are two distinctly different drawing objects so you need to give them different tag names. Please see my notes to your specific code attached hereto. Perhaps it helps.

                          sandman
                          Attached Files

                          Comment


                            #14
                            Hi sandman,

                            Thanks for your reply.

                            Originally I did have both drawing objects with different tag names. But then both the LimeGreen and DeepPink horizontal lines would appear simultaneously, which is not what I am wanting.

                            I do not want a bullish and bearish signal appearing at the same time. I know it makes sense, but since we are both new to NinjaScript programming, I think we will sometimes discover that what seems obvious will not be what works.

                            Edit/Update: I did just look at your PDF and will try what you suggest. Maybe you are right. I do not know enough NinjaScript or C# to be able to know.
                            Last edited by i2w8am9ii2; 09-06-2018, 06:39 AM.

                            Comment


                              #15
                              Hi sandman,

                              I just tried out the changes you suggested in your PDF. It seems to work great.

                              Thanks so much. It seems you do know quite a bit more NinjaScript and C# than I do. You seem to have figured this out.

                              I am still testing it initially, but so far, it does seem to be working as I intended.

                              Again, I do appreciate your help very much.

                              Update: My initial testing was on long trades, and I jumped to the conclusion that the same was true for short trades. But I am now seeing that the DeepPink horizontal line is not being drawn for short setups. So the indicator behavior is not yet working.
                              Last edited by i2w8am9ii2; 09-06-2018, 07:24 AM.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by pvincent, 06-23-2022, 12:53 PM
                              14 responses
                              237 views
                              0 likes
                              Last Post Nyman
                              by Nyman
                               
                              Started by TraderG23, 12-08-2023, 07:56 AM
                              9 responses
                              382 views
                              1 like
                              Last Post Gavini
                              by Gavini
                               
                              Started by oviejo, Today, 12:28 AM
                              0 responses
                              1 view
                              0 likes
                              Last Post oviejo
                              by oviejo
                               
                              Started by pechtri, 06-22-2023, 02:31 AM
                              10 responses
                              125 views
                              0 likes
                              Last Post Leeroy_Jenkins  
                              Started by judysamnt7, 03-13-2023, 09:11 AM
                              4 responses
                              59 views
                              0 likes
                              Last Post DynamicTest  
                              Working...
                              X