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

Help with resources for first indicator

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

    Help with resources for first indicator

    I am a lifelong programmer and trader but just bought ninjatrader. I feel confident enough now to start my hand at scripting and have some free time so thought I'd give it a go. I would love some pointers to getting started!

    I thought I'd start with one I do as my first for most platforms (my hello world if you will), a basic rubber band reversion to the mean trade.
    I have developed this for ThinkorSwim and Worden TC2000 so I feel confident I can accomplish this, platform allowing:

    Black is English of what I want, blue is the Thinkorswim code I would use. I already use bar color changes for things, but do not use arrows on any bars - so that seems perfect for my indicator

    Bearish Signal
    The 50 SMA is less than the 50 SMA one bar ago (downtrend according to my methods)
    SMA(50) < SMA(5)[1]
    Bar closes with real body above the 50 SMA.
    Close > 50 SMA
    Stochastic(k 5, d 3, smooth 2) %K > 80
    Stochastick(5,3,2).FullK > 80
    Stochastic(k 5, d 3, smooth 2) %D > 55
    Stochastick(5,3,2).FullD > 55


    Bullish Signal
    The 50 SMA from one bar ago is greater than the 50 SMA on the current bar (uptrend according to my methods)
    SMA(50) < SMA(5)[1]
    The current bar closes with real body below the 50 SMA.
    Close > 50 SMA
    Stochastic(k 5, d 3, smooth 2) %K < 20
    Stochastick(5,3,2).FullK < 20
    Stochastic(k 5, d 3, smooth 2) %D < 45
    Stochastick(5,3,2).FullD < 45

    (off my head, not cut and pasted, so could have mistake)

    That sounds like enough to tackle now. Again not looking for anyone to make this for me or a pre-made one. Just to help me get going myself.

    Thanks so much!
    Attached Files
    Last edited by UncleRyan; 05-06-2020, 02:26 PM. Reason: pic

    #2
    you may need the basic knowledge of c# , then the educational introduction of Ninjatrader 8 basic programming of indicators and strategy and the use of the wizard.


    Comment


      #3
      Hello UncleRyan,

      Thanks for your post.

      As a suggestion, it may be easier for you to get started with the Strategy Builder. The strategy builder uses a non programming interface to help you create strategies. The advantage for you is that it generates the actual Ninjascript code so you would be able to see how this will be created in Ninjascript which is based on C# and that will help your understanding of Ninjascript.

      The algorithm you are showing can easily translate in the Strategy Builder. The strategy does not have to place trades. It can be used to place drawing objects on the chart when the signal are true which would allow you to visually see that the code is working as expected, or not.

      After you have developed your code through the strategy builder, you can recreate as an indicator using the indicator wizard to create the structure and then copy the code from the strategy builder using view code. (It is not quite that simple but that is the general idea).

      Here are the educational resource available on the strategy builder:
      Free live webinar every other Thursday at 4:00 PM EST, through this link to all webinars: https://ninjatrader.com/PlatformTraining
      Previous recording of the Strategy Builder 301 webinar: https://youtu.be/HCyt90GAs9k?list=PL...auWXkWe0Nf&t=2
      Help guide for the strategy builder: https://ninjatrader.com/support/help...gy_builder.htm

      The help guide for the strategy builder contains a page for the "conditions builder" which shows many examples of constructing conditions similar to what you are wanting to do.

      I think you have the right idea to start with a simple exercise and build from there. I think you will find that the strategy builder is a great way to generate the code needed.


      Paul H.NinjaTrader Customer Service

      Comment


        #4
        Thanks a lot, those look like good resources. I will let you know how it goes

        Comment


          #5
          Okay - So i decided to make this a watchlist column rather than indicator on my charts. It will report a 1 for possible long, -1 for possible short, 0 for neither (not a complete trade setup).

          I used the strategy builder as suggested to build the strategy listed above, then added the code elements where appropriate to an Indicator. I am error-free at this point, have the column loaded but its just doing the ellipsis (...) thinking. I'd imagine its a structural issue from bad cutting and pasting. If someone more experienced could eye an error, I'd appreciate it. Thanks for the help so far.

          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 MyStatusColumn : Indicator
              {
                  private SMA SMA1;
                  private SMA SMA2;
                  private Stochastics Stochastics1;
          
                  protected override void OnStateChange()
                  {
                      if (State == State.SetDefaults)
                      {
                          Description                                    = @"MyStatusColumn";
                          Name                                        = "MyStatusColumn";
                          Calculate                                    = Calculate.OnBarClose;
                          IsOverlay                                    = false;
                          DisplayInDataBox                            = false;
                          DrawOnPricePanel                            = false;
                          DrawHorizontalGridLines                        = false;
                          DrawVerticalGridLines                        = false;
                          PaintPriceMarkers                            = false;
                          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;
                      }
                  }
          
                  protected override void OnBarUpdate()
                  {
          
                      Value[0] = 0;
                      SMA1                = SMA(Close, 50);
                      SMA2                = SMA(Close, 50);
                      Stochastics1        = Stochastics(Close, 3, 5, 2);
          
                       // Set 1
                      if ((SMA1[0] > SMA2[1])
                           && (High[0] <= SMA1[0])
                           && (Low[0] <= SMA2[0])
                           && (Stochastics1.K[0] <= 20)
                           && (Stochastics1.D[0] <= 45))
                      {    
                          Value[0] = 1;
          
                      }
                      if ((SMA1[0] < SMA2[1])
                           && (High[0] >= SMA1[0])
                           && (Low[0] >= SMA2[0])
                           && (Stochastics1.K[0] >= 80)
                           && (Stochastics1.D[0] >= 55))
                      {    
                          Value[0] = -1;
          
                      }
          
                  }
              }
          }
          
          #region NinjaScript generated code. Neither change nor remove.
          
          namespace NinjaTrader.NinjaScript.Indicators
          {
              public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
              {
                  private MyStatusColumn[] cacheMyStatusColumn;
                  public MyStatusColumn MyStatusColumn()
                  {
                      return MyStatusColumn(Input);
                  }
          
                  public MyStatusColumn MyStatusColumn(ISeries<double> input)
                  {
                      if (cacheMyStatusColumn != null)
                          for (int idx = 0; idx < cacheMyStatusColumn.Length; idx++)
                              if (cacheMyStatusColumn[idx] != null &&  cacheMyStatusColumn[idx].EqualsInput(input))
                                  return cacheMyStatusColumn[idx];
                      return CacheIndicator<MyStatusColumn>(new MyStatusColumn(), input, ref cacheMyStatusColumn);
                  }
              }
          }
          
          namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
          {
              public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
              {
                  public Indicators.MyStatusColumn MyStatusColumn()
                  {
                      return indicator.MyStatusColumn(Input);
                  }
          
                  public Indicators.MyStatusColumn MyStatusColumn(ISeries<double> input )
                  {
                      return indicator.MyStatusColumn(input);
                  }
              }
          }
          
          namespace NinjaTrader.NinjaScript.Strategies
          {
              public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
              {
                  public Indicators.MyStatusColumn MyStatusColumn()
                  {
                      return indicator.MyStatusColumn(Input);
                  }
          
                  public Indicators.MyStatusColumn MyStatusColumn(ISeries<double> input )
                  {
                      return indicator.MyStatusColumn(input);
                  }
              }
          }
          
          #endregion
          Last edited by UncleRyan; 05-09-2020, 01:36 PM.

          Comment


            #6
            Hello UncleRyan,

            Thanks for your reply.

            What I recommend is that you create as an indicator, not a market analyzer column.

            In an indicator you will want to use AddPlot() to create a plot output that can be read by the market analyzer. The market analyzer has an 'indicator Column" that you can add any indicator to that has a plot.

            Probably the easiest way for you to get there would be to use the Indicator wizard in the Ninjascript editor. This is accessed by the "+" tab in the lower left and you would select new Indicator. You would need to provide any inputs and when you get to plost, add a transparent plot and you might name it Signal.

            You can then copy your OnBarUpdate() code over.

            I would change Values[0] to Signal[0] as it is the name of the plot and is more descriptive when reading it.

            I recommend moving these lines to State.DataLoaded which you would need to add (or replace state.Configure if nothing to configure):

            SMA1 = SMA(Close, 50);
            SMA2 = SMA(Close, 50);
            Stochastics1 = Stochastics(Close, 3, 5, 2);

            The reason for that is you really only need to do that once so you don't need to call it on each OnBarUpdate()

            By creating in the indicator wizard, the wizard will add the public output for the plot which will be found in region properties.
            Paul H.NinjaTrader Customer Service

            Comment


              #7
              If you recall I was making a Market Analyzer column to show when price is below an uptrending MA or above a downtrending, and in overbought oversold to then watch for a divergence using an unusual stochastic. It's working about twice as accurately as it has on any other platform so I'm really pleased, However I'm concerned I'm computing too much too often because it's slowing my NT a bit(I run a lot of scanners, have a great system/connection, but need them to be streamlined). I'm not sure if I can move some of the computations to a different section. Can you just advise me as you have before on figuring out what to move and where. You mentioned moving things to DataLoaded but after watching some videos and reading I could use some clarity. Any other criticism is welcomed.

              Question: I asked on another post but confused the person who was trying to help me. Since you know what i'm trying to do: If it returns a 1 in the Column for Market Analyzer, it's reading the most recent bars in post market, not the last session bar (market close). Is that correct? Is this determined by the "Instrument Default or Default 24x7 .. x5" settings?

              And thank you so much for your help so far. You've saved me a lot of time get going on NT so quickly and I really appreciate it.

              This was made as an indicator, and then loaded in the market analyzer column as Indicator - as you advised.

              Code:
                  public class MyStatusColumn : Indicator
                  {
                      protected override void OnStateChange()
                      {
                          if (State == State.SetDefaults)
                          {
                              Description                                    = @"Enter the description for your new custom Indicator here.";
                              Name                                        = "MyStatusColumn";
                              Calculate                                    = Calculate.OnBarClose;
                              IsOverlay                                    = false;
                              DisplayInDataBox                            = true;
                              DrawOnPricePanel                            = true;
                              DrawHorizontalGridLines                        = true;
                              DrawVerticalGridLines                        = true;
                              PaintPriceMarkers                            = true;
                              ScaleJustification                            = NinjaTrader.Gui.Chart.ScaleJustification.Right;
                              IsSuspendedWhileInactive                    = true;
                              AddPlot(Brushes.RoyalBlue, "Signal");
              
                          }
                          else if (State == State.DataLoaded){
              
                          }
                      }
                      protected override void OnBarUpdate()
                      {
              
                          if(CurrentBar < 1) return;
              
              
                          if (
                              IsRising(SMA(50)) && 
                              High[0] <= SMA(50)[0] &&
                              Low[0] <= SMA(50)[0]  &&
                              Stochastics(3,5,2).K[0] <= 20 && 
                              Stochastics(3,5,2).D[0] <= 45
                              ){
                              Value[0] = 1;
                          }
                          if (
                              IsFalling(SMA(50)) && 
                              High[0] >= SMA(50)[0] &&
                              Low[0] >= SMA(50)[0]  &&
                              Stochastics(3,5,2).K[0] >= 80 && 
                              Stochastics(3,5,2).D[0] >= 55
              
                              ){
                              Value[0] = -1;
                          }
                          else{
                              Value[0] = 0;
                          }
                      }
              
                      #region Properties
              
                      [Browsable(false)]
                      [XmlIgnore]
                      public Series<double> Signal
                      {
                          get { return Values[0]; }
                      }
                      #endregion
              
                  }

              Comment


                #8
                Hello UncleRyan,

                Thanks for your reply.

                You will want to create private instances of the indicators (SMA and Stochastics) used in OnBarUpdate(). For the resource use, please see "Referencing indicator methods" in the section " Performance practices" on this page: https://ninjatrader.com/support/help..._practices.htm If you create a condition (with an indicator) in the strategy builder and then do a view code you will see that it generates code according to the best practice.

                The Market analyzer is a real time display so yes it will be processing the current data according to the Calculate setting used. (Display is based on just closed bar in your case of Calculate.OnBarClose). Note: Since you have added a colored plot, you can always add it to a chart and observe the signal (Make sure you are using the same data series settings (bars, time frame data loaded, trading hours, etc) in both analyzer and chart).

                Now that you have created an indicator that provides the +/- 1 or 0 signal, you can also create "cell conditions" in the market analyzer based on the value of the signal and this will allow you to use cell colors and text when the signal =1 or =1 or zero. https://ninjatrader.com/support/help...lter_condi.htm

                Paul H.NinjaTrader Customer Service

                Comment


                  #9
                  Thanks a lot, Paul. That all makes sense and I will work on your suggestions.

                  That also clears up the closing bar/session question I had.

                  For Alerts - I did what you said previously, so it shows a nice color and text to tell me rather than a -1 +1 etc. But for Alerts, can I still say "if it says -1 do this" even though I've made it colored and other text, its still reading the value regardless of .. how pretty I make it?


                  Comment


                    #10
                    Hello UncleRyan,

                    Thanks for your reply.

                    Yes, the Market analyzer Alert will be reading the same signal so you would need the alert to check for a numeric value of 1 or -1 as needed. I've attached an example screenshot of an indicator called MAcrossbuilder that outputs the typical +/-1 and 0 and configured a market analyzer alert based on that.

                    Click image for larger version

Name:	Ur-1.PNG
Views:	388
Size:	104.4 KB
ID:	1099557
                    Paul H.NinjaTrader Customer Service

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by sdauteuil, 09-23-2021, 10:16 AM
                    4 responses
                    1,208 views
                    0 likes
                    Last Post jacobpescaia44  
                    Started by agclub, 04-21-2024, 08:57 PM
                    5 responses
                    34 views
                    0 likes
                    Last Post agclub
                    by agclub
                     
                    Started by ESHunter, Today, 08:06 PM
                    2 responses
                    18 views
                    0 likes
                    Last Post ESHunter  
                    Started by ETFVoyageur, 05-07-2024, 07:05 PM
                    19 responses
                    150 views
                    0 likes
                    Last Post ETFVoyageur  
                    Started by ETFVoyageur, Yesterday, 10:13 PM
                    3 responses
                    26 views
                    0 likes
                    Last Post ETFVoyageur  
                    Working...
                    X