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

Request for help with strategy code logic

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

    Request for help with strategy code logic

    In the following “for practice” strategy my intent is to enter long if flat and the previous two daily bars were green and to go for a profit of 10 ticks with a stop of 30 ticks. Variable0 is +1 if long, -1 if short and 0 if flat ... with a mirror image of the logic if previous two daily bars were red.

    It is “almost” working but not quite [e.g.] on Oct18 a position is correctly not taken
    but on Oct19 a position should have been taken but was not taken.

    Any help/suggestions about this issue will be much appreciated.
    The chart and code are as follows:

    Click image for larger version

Name:	NOV9----3.jpg
Views:	1
Size:	359.3 KB
ID:	906479

    Click image for larger version

Name:	NOV9----2.jpg
Views:	1
Size:	284.1 KB
ID:	906480

    #2
    I changed both Variable0 <= 0 in Condition Set1 and Variable0 >= 0 in Condition Set2
    to Variable0 = 0 … but it didn’t change anything.

    Comment


      #3
      The attachment shows the current state of the code.
      It appears on the chart that the position entries have been appearing one day late.

      Does anyone know of a way to correct the issue?

      Click image for larger version

Name:	NOV10.jpg
Views:	1
Size:	468.1 KB
ID:	881079

      Comment


        #4
        Hello JoeMiller,

        Thank you for your note.

        If your strategy is executing 1 day late, or 1 bar, you may want to reduce your Bars ago values by 1. For example, use Close[0]>=Open[0] && Close[1]>=Open[1]. This says if this bar is green, and last bar was green, then on the next bar, enter Long.

        Please let us know if you need further assistance.
        Alan P.NinjaTrader Customer Service

        Comment


          #5
          these are daily bars with calculateonbarclode=false so i have to use bars 1 & 2.
          can't use bars 1 & 0 and get any meaningful results [i think?].

          Comment


            #6
            Hello JoeMiller,

            When making the changes to the code I suggested and applying the strategy to bonds, the strategy entered a position on 10/19 as expected.

            Your conditions require a close of the daily bar to be above the open; this doesn’t become true until the daily bar closes. Thus whether COBC was set to true or false in this case would not have an impact.

            Please let us know if you need further assistance.
            Attached Files
            Alan P.NinjaTrader Customer Service

            Comment


              #7
              my understanding is as follows:

              calculateonbarclose=false so bars [1] & [2] are yesterday and day before yesterday ... both
              bars are history and forever determined and unchanging ... see thread attachment at
              http://ninjatrader.com/support/forum...ad.php?t=91802 which for convenience is reproduced here
              Click image for larger version

Name:	NOV10#2.jpg
Views:	1
Size:	331.4 KB
ID:	881087
              so is it not true that my logic says two green bars occurred on 10/17 &10/18 so enter long on 10/19 and then,in this case, hit goal or stop loss on 10/19 depending on which one was hit first?

              Comment


                #8
                A RELATED QUESTION [i.e.] ''HOW TO DEBUG''

                please advise me on how to debug my strategy [i.e.] please provide links to videos and the help guide, etc. so i can learn how to do some debugging.

                is there a debug method whereby i can halt execution at a break-point?

                many thanks for all your help

                Comment


                  #9
                  Hello JoeMiller,

                  Setting COBC=False does not shift the bars ago value.

                  Your logic will evaluate whether yesterday and the day prior’s bars were green bars, and if so, will submit your orders on the next bar. Thus there will be a bar between the last green bar and where your orders are submitted. You should make the changes I suggested in my previous reply if you’d like your orders to be submitted on the bar immediately prior to the 2nd green bar.

                  I’ve provided a link to Visual Studio Debugging below.


                  I’ve also provided some links which you may find helpful on debugging.
                  Debugging: http://ninjatrader.com/support/forum...ead.php?t=3418
                  TraceOrders: http://ninjatrader.com/support/forum...ead.php?t=3627

                  Please let us know if you need further assistance.
                  Alan P.NinjaTrader Customer Service

                  Comment


                    #10
                    Originally posted by joemiller View Post
                    my understanding is as follows:

                    calculateonbarclose=false so bars [1] & [2] are yesterday and day before yesterday ... both
                    bars are history and forever determined and unchanging ... see thread attachment at
                    http://ninjatrader.com/support/forum...ad.php?t=91802 which for convenience is reproduced here
                    [ATTACH]41166[/ATTACH]
                    so is it not true that my logic says two green bars occurred on 10/17 &10/18 so enter long on 10/19 and then,in this case, hit goal or stop loss on 10/19 depending on which one was hit first?
                    Your understanding is actually correct, but you are being flummoxed from the difference in behavior in the Strategy Analyzer and a realtime chart, due to how the data must unfortunately be processed when you are triggering off a tick that is not involved in the decision, and you are processing with COBC = false in realtime.

                    The way to handle it is to compensate somehow for the difference in display environment. One way is to process Historical data differently from realtime data. The other way is to calculate differently, depending on where the calculation takes place: Strategy Analyzer or realtime chart.

                    Copy and paste your entire code into a post, so that I can make the adjustments for you. I really do not feel like typing out the stuff from your picture.

                    Comment


                      #11
                      Thanks Alan & Koganam.

                      I was just about to reply with a bunch more questions Kogonam. On previous occasions you have pulled me out of the quicksand and I continue to really appreciate it.

                      Here is the requested code...

                      #region Using declarations
                      using System;
                      using System.ComponentModel;
                      using System.Diagnostics;
                      using System.Drawing;
                      using System.Drawing.Drawing2D;
                      using System.Xml.Serialization;
                      using NinjaTrader.Cbi;
                      using NinjaTrader.Data;
                      using NinjaTrader.Indicator;
                      using NinjaTrader.Gui.Chart;
                      using NinjaTrader.Strategy;
                      #endregion

                      // This namespace holds all strategies and is required. Do not change it.
                      namespace NinjaTrader.Strategy
                      {
                      /// <summary>
                      /// variable0 = +1 or -1 for current position = long or short or 0 = flat. Entry signal is red/green bar change confrirmed by a second red/green bar in the same direction.
                      /// </summary>
                      [Description("variable0 = +1 or -1 for current position = long or short or 0 = flat. Entry signal is red/green bar change confrirmed by a second red/green bar in the same direction.")]
                      public class SwingRedBlueBars2 : Strategy
                      {
                      #region Variables
                      // Wizard generated variables
                      private int profitGoal = 16; // Default setting for ProfitGoal
                      private int stopLoss = 16; // Default setting for StopLoss
                      // User defined variables (add any user defined variables below)
                      #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()
                      {
                      SetProfitTarget("L", CalculationMode.Ticks, ProfitGoal);
                      SetStopLoss("L", CalculationMode.Ticks, StopLoss, false);
                      SetProfitTarget("S", CalculationMode.Ticks, ProfitGoal);
                      SetStopLoss("S", CalculationMode.Ticks, StopLoss, false);

                      CalculateOnBarClose = false;
                      }

                      /// <summary>
                      /// Called on each bar update event (incoming tick)
                      /// </summary>
                      protected override void OnBarUpdate()
                      {
                      // Condition set 1
                      if (Close[1] >= Open[1]
                      && Close[2] >= Open[2]
                      && Variable0 == 0)
                      {
                      EnterLong(DefaultQuantity, "L");
                      Variable0 = 1;
                      }

                      // Condition set 2
                      if (Close[1] <= Open[1]
                      && Close[2] <= Open[2]
                      && Variable0 == 0)
                      {
                      EnterShort(DefaultQuantity, "S");
                      Variable0 = -1;
                      }

                      // Condition set 3
                      if (Position.MarketPosition == MarketPosition.Flat)
                      {
                      Variable0 = 0;
                      }
                      }

                      #region Properties
                      [Description("Profit Goal [ticks]")]
                      [GridCategory("Parameters")]
                      public int ProfitGoal
                      {
                      get { return profitGoal; }
                      set { profitGoal = Math.Max(1, value); }
                      }

                      [Description("Stop Loss [ticks]")]
                      [GridCategory("Parameters")]
                      public int StopLoss
                      {
                      get { return stopLoss; }
                      set { stopLoss = Math.Max(1, value); }
                      }
                      #endregion
                      }
                      }

                      Comment


                        #12
                        I know that due to certain ingrates on this forum, I had vowed never to again provide a complete class package to anyone. However, in this case, I am attaching the complete class to this post, simply in response to your telling me that you are happy to have my assistance, unlike the nincompoop who sent me this private mail that I now choose to expose to the public ridicule that I expect it to generate.

                        First I will explain what I did.
                        1. Create an int variable field to use to adjust the bars that we reference, depending on where we are in NT.
                        2. Set the value of the bar where it is most efficient.
                        3. Use that value to adjust the bar references.


                        1. Create a class variable called calcIndex. We initialize it to zero, because that is the value that we want it to be most of the time. Presumably we want to trade live eventually.
                        Code:
                        private int calcIndex = 0; [COLOR=Blue]//we shall use this to adjust our bar references[/COLOR]
                        2. Use OnStartUp() to change this value to 1 if we are in the Strategy Analyzer, so we need to do this only once.
                        Code:
                         protected override void OnStartUp()
                        {
                        if (Account.Name == "Backtest") [COLOR=blue]//this means that we are in the Strategy Analyser[/COLOR]
                        calcIndex = 1;
                        }
                        3. In OBU, we adjust calcIndex based on whether or not we are on a historical bar. This will do 2 things for us. When we load/reload the chart, we shall see the same trades that occurred on the live chart, and also still on the live chart be calculating with the correct bar references. (I noticed in passing that you have no escape for initial bars that are referenced, so I am a bit surprised that you got any output at all.)

                        I inserted this at the top of OBU.
                        Code:
                         if (CurrentBar < 2) return;
                        
                        if (!Historical) calcIndex = 0;
                        else calcIndex = 1;
                        
                        //the rest goes here
                        Here is how we adjust the references:
                        Code:
                         if (Close[1 - calcIndex] >= Open[1 - calcIndex]
                        && Close[2 - calcIndex] >= Open[2 - calcIndex]
                        && Variable0 == 0)
                        So, if we are on historical bars, or in the Strategy Analyser, we use bars 0 and 1, but if we are live, we use bars 1 and 2.

                        I deliberately avoided using more efficient shorthand syntax, just so that the code is more readable to most.

                        If you want to know why I checked for not Historical first, instead of what seems the more intuitive Historical, let me know and I will explain.

                        Notice that the file name is not the same as the class name, as usually happens with NT. If you want to, just change the filename to match the class name.

                        Lest I forget, this PM will not mean that I will not continue to help those who would like my help. Can you believe this?! (See the attached picture, if it is still there) He is actually someone else on this forum, who created a new account just so that he could tell me such nonsense. How can someone who has only 5 posts even begin to know what I have posted, unless he used to use another name that was more active. Yes, I know who it is, and I have told him so.

                        All the best to you Joe.
                        Attached Files
                        Last edited by koganam; 01-27-2020, 09:23 PM.

                        Comment


                          #13
                          Originally posted by koganam View Post

                          Lest I forget, this PM will not mean that I will not continue to help those who would like my help. Can you believe this?! (See the attached picture, if it is still there) He is actually someone else on this forum, who created a new account just so that he could tell me such nonsense. How can someone who has only 5 posts even begin to know what I have posted, unless he used to use another name that was more active. Yes, I know who it is, and I have told him so.
                          I've had a couple of those.

                          Comment


                            #14
                            Koganam,

                            Delivery of complete strategy code will significantly simplify my life. A nice surprise because forums are for presentation of specific snippet questions, not free module coding ... but it is always welcome. Because I am vaguely aware of concepts like 'class variable' and the myriad of other C# structure concepts I am spared the agony of working in the dark.

                            What is 'OBU'?
                            What does 'PM' mean?

                            Can I do this entirely within the Wizard of must I unlock the code?

                            Comment


                              #15
                              What is 'OBU'? - OnBarUpdate().
                              What does 'PM' mean? - Private Message
                              Can I do this entirely within the Wizard of must I unlock the code?
                              The code is already unlocked. There are many ways to use it. Here are 2 different ways to use it.
                              1. Download the file, copy it to your Strategy directory, remove your original file, compile. OR
                              2. Download the file. Open it and copy and paste the entire contents into your original file, replacing all the content in the original file, compile.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by r68cervera, Today, 05:29 AM
                              0 responses
                              2 views
                              0 likes
                              Last Post r68cervera  
                              Started by geddyisodin, Today, 05:20 AM
                              0 responses
                              3 views
                              0 likes
                              Last Post geddyisodin  
                              Started by JonesJoker, 04-22-2024, 12:23 PM
                              6 responses
                              35 views
                              0 likes
                              Last Post JonesJoker  
                              Started by GussJ, 03-04-2020, 03:11 PM
                              12 responses
                              3,239 views
                              0 likes
                              Last Post Leafcutter  
                              Started by AveryFlynn, Today, 04:57 AM
                              0 responses
                              6 views
                              0 likes
                              Last Post AveryFlynn  
                              Working...
                              X