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

Data Series Subtract Previous Price from Current

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

    Data Series Subtract Previous Price from Current

    In the future i am looking to build a complex indicator but would like to first start with being able to store and use values within a data series. The problem is, the documentation links confuse me quite a bit when going through them as i am not quite sure how to implement them in the standard start script given.





    I don't understand how to apply this within the code.



    Ultimately, what i would like to do is take the current candles close price and subtract it from the Open price of 4 candles ago, store the answer, then apply it as the profit target. As for working code examples i made a simply entry code below for examples to be displayed with. Again i would greatly appreciate your help if possible.





    namespace NinjaTrader.Strategy
    {
    /// <summary>
    /// Enter the description of your strategy here
    /// </summary>
    [Description("Enter the description of your strategy here")]
    public class DataHelp : Strategy
    {
    #region Variables
    // Wizard generated variables
    private int myInput0 = 1; // Default setting for MyInput0
    // User defined variables (add any user defined variables below)
    private int ProfitTarget = 5; // Define Profit Target
    private DataSeries myCalculation; // Define a DataSeries variable

    #endregion

    /// <summary>
    /// This method is used to configure the strategy and is called once before any strategy method is called.
    /// </summary>
    protected override void Initialize()
    {
    CalculateOnBarClose = true;
    myCalculation = new DataSeries(this, MaximumBarsLookBack.Infinite);

    }

    /// <summary>
    /// Called on each bar update event (incoming tick)
    /// </summary>
    protected override void OnBarUpdate()
    {


    if( CrossAbove(DM(14).DiMinus, DM(14).DiPlus, 1))
    {
    myCalculation.Set(Open[4] - Close[0])= ProfitTarget; // Not sure how to place this

    EnterShort(DefaultQuantity, "");
    SetProfitTarget("", CalculationMode.Ticks, ProfitTarget);
    }
    }

    #region Properties
    [Description("")]
    [GridCategory("Parameters")]
    public int MyInput0
    {
    get { return myInput0; }
    set { myInput0 = Math.Max(1, value); }
    }

    public int ProfitTarget
    {
    get { return ProfitTarget; }
    set { ProfitTarget = Math.Max(1, value); }
    }
    #endregion
    }
    }

    #2
    Hello NewCode,

    Thanks for your post.

    As presented your code would likely generate an error of trying to access an index before the bar is available. When you load an indicator, the code of the indicator will load the very first bar of data available (historically, so if the chart has 5 days of data loaded, the first bar would be from 5 days ago).

    On that first bar loaded when you code hits this line: myCalculation.Set(Open[4] - Close[0])= ProfitTarget; it would error out because the bars ago reference of [4] does not exist at that time. To work around this, you add a check of the CurrentBar property which holds the bar number of the bar being processed. Typically you would perform this check at the top of the OnBarUpdate() method, here is an example:

    if (CurrentBar < 4) return; // you would adjust the value (4 in the example) depending on the bars ago reference. Other considerations may be for any moving averages to have their period of bars before accessing them (mainly for accuracy considerations).
    Reference: https://ninjatrader.com/support/help...currentbar.htm

    On this line: myCalculation.Set(Open[4] - Close[0])= ProfitTarget; I'm not entire certain what you want to do. The Open[4] - Close[0] will set the value of the data series with the difference in price. The assignment of ProfitTarget would not work.

    I suspect you would want to check to see if the price difference is greater than or equal to the profit target? If, as I suspect the profit target is in Ticks, you would need to convert the price difference to ticks by dividing by the tick size of the instrument, for example myCalculation.Set((Open[4] - Close[0]) / TickSize ); Here is the helpguide link to the "TickSize" property: https://ninjatrader.com/support/help.../?ticksize.htm

    Here is an example of the logical statement to ask if the ticks are >= profit target:
    if (myCalculation[0] >= ProfitTarget)
    {
    SetProfitTarget("", CalculationMode.Ticks, ProfitTarget);
    EnterShort(DefaultQuantity, "");
    }


    Note that the index of [0] would represent the calculation just performed above. Note that I moved the setting of the profit target prior to the EnterShort, this is the recommended practice when setting the profit target dynamically. (You are using the same profit target of 5 ticks so this coding really is not needed in the example but if you decide to change the profit target value while running, then for sure this is the correct order of setting the target before placing the order because the Set methods will retain and apply the last set value immediately upon entry order filling).

    While I understand you are working through the learning process just for clarification in the example you are showing a data series that is not needed as you can store the calculation results in a double variable, for example, double myCalc = (Open[4] - Close[0]) / TickSize;
    Paul H.NinjaTrader Customer Service

    Comment


      #3
      i am still confused as where to position a few things. I am getting 2 errors

      Error: } expected
      Error: already contains a definition for ProfitTarget



      protected override void OnBarUpdate()
      {
      if (CurrentBar < 4)

      return;



      myCalculation.Set((Open[4] - Close[0]) / TickSize ); // Not sure how to place this


      if( CrossAbove(DM(14).DiMinus, DM(14).DiPlus, 1) && myCalculation[0] >= ProfitTarget)

      {

      SetProfitTarget("", CalculationMode.Ticks, ProfitTarget);
      EnterShort(DefaultQuantity, "");
      }
      }



      looks like the area 2 is coming from here


      public int ProfitTarget
      {
      get { return ProfitTarget; }
      set { ProfitTarget = Math.Max(1, value); }
      }

      Comment


        #4
        Hello NewCode,

        Thanks for your reply.

        In the case of the error "already contains a definition for ProfitTarget", going back to your first post you have this line that creates the error: private int ProfitTarget = 5; // Define Profit Target
        Please remove or comment out that line.

        Regarding the error, "Error: } expected" It is hard to see based on what you have posted. Each "{" must have a closing "}". The "braces" are used to encapsulate the code section that relates. In C#/Ninjascript, you can have many layers of embedded {}.

        If you are unable to determine where the braces should be, please repost your entire source code or attach the .CS file to your post.
        Paul H.NinjaTrader Customer Service

        Comment


          #5
          namespace NinjaTrader.Strategy
          {
          /// <summary>
          /// Enter the description of your strategy here
          /// </summary>
          [Description("Enter the description of your strategy here")]
          public class DataHelp : Strategy
          {
          #region Variables
          // Wizard generated variables
          private int myInput0 = 1; // Default setting for MyInput0
          // User defined variables (add any user defined variables below)
          private int ProfitTarget = 5; // Define Profit Target
          private DataSeries myCalculation; // Define a DataSeries variable
          // private double myCalculation;

          #endregion

          /// <summary>
          /// This method is used to configure the strategy and is called once before any strategy method is called.
          /// </summary>
          protected override void Initialize()
          {
          CalculateOnBarClose = true;
          //SetProfitTarget("", CalculationMode.Ticks, ProfitTarget);
          myCalculation = new DataSeries(this, MaximumBarsLookBack.Infinite);

          }

          /// <summary>
          /// Called on each bar update event (incoming tick)
          /// </summary>
          protected override void OnBarUpdate()
          {

          if (CurrentBar < 4)

          return;

          myCalculation.Set((Open[4] - Close[0]) / TickSize );// Not sure how to place this


          if( CrossAbove(DM(14).DiMinus, DM(14).DiPlus, 1) )

          {
          //myCalculation.Set((Open[4] - Close[0]) / TickSize );// Not sure how to place this

          if(myCalculation[0] >= ProfitTarget)
          {
          SetProfitTarget("", CalculationMode.Ticks, ProfitTarget);
          EnterShort(DefaultQuantity, "");

          }
          }
          }

          #region Properties
          [Description("")]
          [GridCategory("Parameters")]
          public int MyInput0
          {
          get { return myInput0; }
          set { myInput0 = Math.Max(1, value); }
          }


          #endregion
          }
          }

          Comment


            #6
            Hello NewCode,

            Thanks for your reply.

            I do not see any issues with the braces {}. Please compile your code again and look carefully at the left column of the error message. The left column is "Ninjascript File", it may be that the error is actually in another file which would also need to be corrected before you can successfully compile. NinjaTrader will compile every source code file at once to provide you with the fastest execution possible however an error in any file will prevent a successful compilation.
            Paul H.NinjaTrader Customer Service

            Comment


              #7
              All other strategies are good now but i am still getting the same error. It is almost as if i have calculation.set in the wrong place but i an not entirely sure. How do i download the .cs file to send to you?

              Comment


                #8
                Hello NewCode,

                Thanks for your reply.

                You can send the source code file to PlatformSupport[at]NinjaTrader[dot]Com (replace the [at] with @ and [dot] with . ) Mark the e-mail subject as Atten:Paul and please include a link to this forum for reference in the e-mail.

                The file would be found in Documents>NinjaTrader8>bin>Custom>Strategies> it will have the name of your strategy with .CS extension
                Paul H.NinjaTrader Customer Service

                Comment


                  #9
                  Source Code

                  Did you get the source code?

                  Comment


                    #10
                    Hello NewCode,

                    Thanks for your reply.

                    Yes, we received your first e-mail on June 19th and I replied on June 19th. Please check your junk or spam e-mail as you would have gotten an immediate automated e-mail advising we received your e-mail and then my response was sent a short time later, perhaps they are both in your junk/spam.

                    I also have the e-mail you just sent, I will reply to that with the same answer as was previously sent.
                    Paul H.NinjaTrader Customer Service

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by Sparkyboy, Today, 10:57 AM
                    0 responses
                    3 views
                    0 likes
                    Last Post Sparkyboy  
                    Started by TheMarlin801, 10-13-2020, 01:40 AM
                    21 responses
                    3,917 views
                    0 likes
                    Last Post Bidder
                    by Bidder
                     
                    Started by timmbbo, 07-05-2023, 10:21 PM
                    3 responses
                    153 views
                    0 likes
                    Last Post grayfrog  
                    Started by Lumbeezl, 01-11-2022, 06:50 PM
                    30 responses
                    812 views
                    1 like
                    Last Post grayfrog  
                    Started by xiinteractive, 04-09-2024, 08:08 AM
                    3 responses
                    11 views
                    0 likes
                    Last Post NinjaTrader_Erick  
                    Working...
                    X