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

Reset variable to 0 when new position is initiated

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

    Reset variable to 0 when new position is initiated

    Hi,

    I've an indicator which I would like to be 0 when a new position is created in addition to First Bar of Session. I was able to figure out First Bar of Session, but how do I call out new position?

    private double calloutzero;

    if ((IsFirstBarOfSession) || (___________))
    {
    calloutzero = 0;
    }

    #2
    Hello AgriTrdr,

    Thanks for your post.

    To detect if your account is in a current position in a custom indicator, you could use the <Account>.Positions collection or the PositionUpdate event handler.

    See the help guide documentation for more information and sample code.

    Account: https://ninjatrader.com/support/help...ount_class.htm

    <Account>.Positions: https://ninjatrader.com/support/help...ns_account.htm

    PositionUpdate: https://ninjatrader.com/support/help...tionupdate.htm

    Let me know if I may further assist.
    Brandon H.NinjaTrader Customer Service

    Comment


      #3
      Thanks for the reply! I understand both of the methods. What would be the if condition to have this initiated? It’s the red blank line in the first post.

      Comment


        #4
        Hello AgriTrdr,

        Thanks for your note.

        You could consider creating a class-level bool variable (initially set to false), use PositionUpdate to determine if the MarketPosition is Long or Short, and flip the bool to true. Then, you could check if that bool is true in your condition along with IsFirstBarOfSession to set the calloutzero variable to 0 when you are in a Long or Short market position and IsFirstBarOfSession is true. PositionUpdate could be used to determine if you are in a Flat position and the bool could be flipped to false.

        Please let me know if I may assist further.
        Brandon H.NinjaTrader Customer Service

        Comment


          #5
          Did i get this right?

          Code:
          namespace NinjaTrader.NinjaScript.Indicators
          {
          public class Name : Indicator
          {
          private double calloutzero;
          private bool direction = false;
          
          private Account account;
          
          protected override void OnStateChange()
          {
          if (State == State.SetDefaults)
          {
          Description = @"";
          Name = "Name";
          Calculate = Calculate.OnEachTick;
          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.DodgerBlue, "Difference");
          AddLine(Brushes.DarkGray, 0, "ZeroLine");
          lock (Account.All)
          myAccount = Account.All.FirstOrDefault(a => a.Name == "Sim101");
          }
          else if (State == State.Configure)
          {
          AddDataSeries(Data.BarsPeriodType.Tick, 1);
          }
          else if (State == State.DataLoaded)
          {
          lock (myAccount.Positions)
          {
          Print("Positions in State.DataLoaded:");
          
          foreach (Position position in myAccount.Positions)
          {
          Print(String.Format("Position: {0} at {1}", position.MarketPosition, position.AveragePrice));
          }
          }
          }
          }
          
          protected override void OnBarUpdate()
          {
          if (CurrentBars[0] < 12 || CurrentBars[1] < 12)
          return;
          
          if ((Position.MarketPosition == MarketPosition.Long) || (Position.MarketPosition == MarketPosition.Short))
          {
          direction = true;
          }
          
          if ((Bars.IsFirstBarOfSession) || (direction == true))
          {
          calloutzero = 0;
          }
          
          if ((Close[0] > Open[0]) || (Close[0] < Open[0]))
          {
          buys += 1;
          sells += 1;
          }
          
          if (Position.MarketPosition == MarketPosition.Flat)
          {
          direction = false;
          }
          
          Difference[0] = (calloutzero)/2;
          
          
          }

          Comment


            #6
            Hello AgriTrdr,

            Thanks for your note.

            I see that you are checking if Position.MarketPosition == MarketPosition.Long or MarketPosition.Short in OnBarUpdate().

            Using Position.MarketPosition in the OnBarUpdate() method is only available for strategies, not indicators.

            You could use the Account class PositionUpdate event handler to detect the position of an account in an indicator and flip a bool to true or false.

            Then, you could check if myBool is true in your condition in the OnBarUpdate() method and set your calloutzero variable to 0.

            I have attached an example script to this post demonstrating this concept and linked a demonstration video below.

            The way the indicator works is when a Buy or Sell order is submitted the PositionUpdate event handler triggers and sets myBool to true. When the order is sold and you are in a flat position, the PositionUpdate event handler fires and myBool is set to false. In OnBarUpdate() we check if myBool is true and call the Draw.Dot() method to draw a dot above the bar that myBool becomes true on. We also check if myBool is false in OnBarUpdate() and call RemoveDrawObject() to remove the dot from the chart.

            Demo Video: https://brandonh-ninjatrader.tinytak...MV8yMDUwNjY4OQ

            See this help guide page for more information: https://ninjatrader.com/support/help...tionupdate.htm

            Let me know if I may further assist.​
            Attached Files
            Brandon H.NinjaTrader Customer Service

            Comment


              #7
              Oh wow this is great. It worked exactly as I had wanted it. Thank you so much! I really appreciate you taking the time to do the example file.

              Comment


                #8
                One small thing... for the account name in the indicator file instead of typing it in. Could I just say "Default"?

                Comment


                  #9
                  Hello AgriTrdr,

                  Thanks for your note.

                  You would need to specify the exact Account Name as seen in the previously attached sample script or a TypeConverter could be used to create a user-defined Account selector.

                  See the attached sample script demonstrating using a TypeConverter to accomplish this.

                  See this help guide page for more information about TypeConverter: https://ninjatrader.com/support/help...=typeconverter

                  Please let me know if you have further questions.
                  Attached Files
                  Brandon H.NinjaTrader Customer Service

                  Comment


                    #10
                    After testing the indicator, overall it works great, but what I realize is:

                    If I reverse the position from long to short or short to long it doesn't go to 0. Otherwise, it's working great and goes to 0.

                    I tried changing the code to create a separate bool for each condition, but it's still not working. How can I fix this?

                    Code:
                    private void OnPositionUpdate(object sender, PositionEventArgs e)
                            {
                                // Output the new position
                                Print(string.Format("MarketPosition: {0} AveragePrice: {1} Quantity: {2}", e.MarketPosition, e.AveragePrice, e.Quantity));
                    
                                if (e.MarketPosition == MarketPosition.Long)
                                {
                                    S1 = true;
                                    S2 = false;
                                    S3 = false;
                                }
                                else if (e.MarketPosition == MarketPosition.Short)
                                {
                                    S2 = true;
                                    S1 = false;
                                    S3 = false;
                                }
                                else if (e.MarketPosition == MarketPosition.Flat)
                                {
                                    S3 = true;
                                    S1 = false;
                                    S2 = false;
                                }
                            }
                    
                            protected override void OnBarUpdate()
                            {
                                if (CurrentBars[0] < 12 || CurrentBars[1] < 12)
                                    return;
                    
                                if (S1 == true)
                                {
                                    buys += 1;
                                    sells += 1;
                                }
                                else if ((S2 == false) && (S3 == false))
                                {
                                    buys = 0;
                                    sells = 0;
                                }
                    
                                if (S2 == true)
                                {
                                    buys += 1;
                                    sells += 1;
                                }
                                else if ((S1 == false) && (S3 == false))
                                {
                                    buys = 0;
                                    sells = 0;
                                }
                    
                                if (S3 == true)
                                {
                                    buys = 0;
                                    sells = 0;
                                }
                                else if ((S1 == false) && (S2 == false))
                                {
                                    buys = 0;
                                    sells = 0;
                                }
                    
                                Difference[0] = (buys - sells)/2;    
                            }​
                    Last edited by AgriTrdr; 11-14-2022, 09:59 PM.

                    Comment


                      #11
                      Hello AgriTrdr,

                      Thanks for your note.

                      I see in the code you shared that you are setting S1 to true, S2 to false, and S3 to false when in a long position. Then you check if S1 is true and increment buys and sells by 1. You also have an else if condition checking if S2 and S3 are false and set the buys and sells to 0.

                      If S1 is true then S2 and S3 will be false. This means the 'if' condition and the 'else if' condition are both true.

                      Ultimately, to understand how the script is behaving so that you can modify the logic to suit your needs, you must add debugging prints to the script to see how each variable is evaluating.

                      Prints will appear in the NinjaScript Output window (New > NinjaScript Output window).

                      Below is a link to a forum post that demonstrates how to use prints to understand behavior.

                      https://ninjatrader.com/support/foru...121#post791121

                      Let us know if we may assist further.​
                      Brandon H.NinjaTrader Customer Service

                      Comment


                        #12
                        I don't think the issue is with debugging. What I need is a statement to say if it's a long position and I want to go short, what it should do first is go flat and then short. What would that statement be?

                        Comment


                          #13
                          Hello AgriTrdr,

                          Thanks for your note.

                          With any script, it is necessary to debug your logic so that you understand exactly how each variable in your script is evaluating. This allows you to understand where logic is or is not being reached and why.

                          For example, if you print out S1, S2, and S3 in your script then you could see which conditions are becoming true and which logic is being fired. See below what those prints might look like.

                          Code:
                          Print("S1" + S1);
                          Print("(S2 == false) && (S3 == false): " + ((S2 == false) && (S3 == false)));
                          if (S1 == true)
                          {
                              buys += 1;
                              sells += 1;
                              Print("Buys and Sells incremented. " + " Buys: " + buys + " Sells: " + sells );
                          
                          }
                          else if ((S2 == false) && (S3 == false))
                          {
                              buys = 0;
                              sells = 0;
                              Print("Buys and Sells set to 0. " + " Buys: " + buys + " Sells: " + sells );
                          }​
                          By adding these prints, you could see if your first condition becomes true/false and if the second condition is true/false. You are also able to tell which logic is being reached and how those variables are evaluating.

                          For example, if S1 is true, we can see the logic in that condition is fired and that the buys and sells variables are incremented and what those values are. We could also see if the second condition is becoming true, if the logic is being reached, and if the buys and sells are getting set to 0.

                          Since you are using an if/else if condition, then if both conditions are evaluating true, only the first condition will fire. The 'else if' condition will only trigger when the 'if' condition is false.

                          You should add debugging prints to the script so that you can determine how your logic is processing. Then, you could modify the script to suit your needs.

                          "say if it's a long position and I want to go short, what it should do first is go flat and then short. What would that statement be?"

                          You could check if Position.MarketPosition is equal to MarketPosition.Flat before placing your short order.

                          Or, you could consider submitting an entry order in the opposite direction depending on your needs.

                          From the Managed Approach help guide: Entry() methods will reverse the position automatically. For example if you are in a 1 contract long position and now call EnterShort() -> you will see 2 executions, one to close the prior long position and the other to get you into the desired 1 contract short position.

                          Managed Approach: https://ninjatrader.com/support/help...d_approach.htm

                          Let me know if I may assist further.
                          Last edited by NinjaTrader_BrandonH; 11-15-2022, 02:54 PM.
                          Brandon H.NinjaTrader Customer Service

                          Comment

                          Latest Posts

                          Collapse

                          Topics Statistics Last Post
                          Started by athexinehowley, Today, 02:39 AM
                          0 responses
                          4 views
                          0 likes
                          Last Post athexinehowley  
                          Started by dtaylor, Today, 02:24 AM
                          0 responses
                          4 views
                          0 likes
                          Last Post dtaylor
                          by dtaylor
                           
                          Started by RosaRichardow, Today, 12:21 AM
                          1 response
                          4 views
                          0 likes
                          Last Post marcus2300  
                          Started by ETFVoyageur, Today, 12:45 AM
                          1 response
                          8 views
                          0 likes
                          Last Post ETFVoyageur  
                          Started by TradeSaber, Yesterday, 10:33 PM
                          1 response
                          12 views
                          0 likes
                          Last Post TradeSaber  
                          Working...
                          X