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

Testing market position

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

    Testing market position

    I am trying to gather a value for if I am in a position. Super simple. Compiler hates me...

    Logic:
    If market position = long
    do this
    if market position = short
    do that.

    I have the syntax:
    if (MarketPosition == MarketPosition.Long)
    [...rest of code...]

    For whatever reason, the compiler hates this. Nothing I've done has made this function. It always says it doesn't exist in the current context.

    What is the syntax for determining whether your position is long or short? I may be using old/outdated code...

    #2
    Try this,
    if (Position.MarketPosition == MarketPosition.Long)

    See here,

    Comment


      #3
      Hello alphatango,

      Thank you for your post.

      You must access the market position from the Position object, i.e. Position.MarketPosition. This may then be compared with either MarketPosition.Flat, MarketPosition.Long, or MarketPosition.Short. For the syntax and an example of the use of MarketPosition, see the help guide page here:


      Instead of your syntax:
      Code:
      if (MarketPosition == MarketPosition.Long)
      You must use the following:
      Code:
      if (Position.MarketPosition == MarketPosition.Long)
      Please let us know if we may be of further assistance.
      Emily C.NinjaTrader Customer Service

      Comment


        #4
        Thanks for the replies folks. It still gives me a compiler error "Doesn't exist in the current context" for the latter half.

        If (Position.MarketPosition ==
        This part is good.

        the
        [==] "Marketposition.Long" is what it griefs about.

        Comment


          #5
          Originally posted by alphatango View Post
          Thanks for the replies folks. It still gives me a compiler error "Doesn't exist in the current context" for the latter half.

          If (Position.MarketPosition ==
          This part is good.

          the
          [==] "Marketposition.Long" is what it griefs about.
          This likely has to do with the casing of "Marketposition" vs. MarketPosition. Capitalization matters and you will need to be sure to capitalize the 'P' in MarketPosition.

          Please feel free to reach out with any additional questions or concerns.
          Emily C.NinjaTrader Customer Service

          Comment


            #6
            This is my code.

            Code:
                    
            private void CloseAllPositions()
                    {
                        foreach (var position in Positions)
                        {
                            if (Position.MarketPosition == [Compiler Error here]MarketPosition.Long)
                            {
                                ExitLong(position);
                            }
                            else if (Position.MarketPosition == [Compiler Error here]MarketPosition.Short)
                            {
                                ExitShort(position);
                            }
                        }  
                    }​
            The compiler states "The name 'MarketPosition' does not exist in the current context". Points to the 2nd half...

            Comment


              #7
              Hello alphatango,

              Thank you for your reply.

              If you are using the var position while looping through the Positions collection, then you would want to use position.MarketPosition to get the existing market position for that "position" in the Positions collection. Looping is a general C# concept and we only offer the following basic information on looping in the help guide:


              Otherwise, you may use external resources to get more details on loops and how they work.

              Thank you for your time and patience.
              Emily C.NinjaTrader Customer Service

              Comment


                #8
                As Ive been understanding, I could simplify this code with a call to the "fromEntrySignal".
                Code:
                If "entryshort"
                ...
                If "entrylong"
                ...
                . I could even save it as a bool value. I'm not certain how to store what was my last entry signal as a variable. I don't necessarily mind the loop. If I don't have to use them, it means less system resources and (I feel like) more accuracy in position open/close.

                Comment


                  #9
                  Originally posted by alphatango View Post
                  As Ive been understanding, I could simplify this code with a call to the "fromEntrySignal".
                  Code:
                  If "entryshort"
                  ...
                  If "entrylong"
                  ...
                  . I could even save it as a bool value. I'm not certain how to store what was my last entry signal as a variable. I don't necessarily mind the loop. If I don't have to use them, it means less system resources and (I feel like) more accuracy in position open/close.
                  Using the entry signals and a bool does not seem necessary. I suggest starting with print statements to understand the values as the position updates. If you are working with multiple positions for an account and want to get position information, you could use details such as the Print statement in the example on this page:

                  Code:
                            foreach (Position position in Positions)
                             {
                                 Print(String.Format("Position: {0} at {1}", position.MarketPosition, position.AveragePrice));
                             }​
                  The use of position with the lowercase p is arbitrary. Even basing this on the example you provided, you could do the following with a single letter if you desired to:
                  Code:
                   foreach (Position x in Positions)
                  {
                  if (x.MarketPosition == MarketPosition.Long)
                  {
                  // exit the position here
                  }
                  else if (x.MarketPosition == MarketPosition.Short)
                  {
                  // exit the position here
                  }
                  }​
                  Also, if you are working with multiple positions on different instruments, I suggest reviewing the following page about multi time frame and multi instrument scripts:


                  Otherwise, if you are not working with multiple positions and instead are working with only one instrument and account, you could simplify the logic to the following:
                  Code:
                  if (Position.MarketPosition == MarketPosition.Long)
                  {
                  Print("Market position is long.  Position.MarketPosition: " + Position.MarketPosition);
                  ExitLong();
                  }
                  
                  if (Position.MarketPosition == MarketPosition.Short)
                  {
                  Print("Market position is short.  Position.MarketPosition: " + Position.MarketPosition);
                  ExitShort();
                  }​
                  ​​​​​​​Thank you for your patience.
                  Emily C.NinjaTrader Customer Service

                  Comment


                    #10
                    This is the snip I'm working with. I simply would like it not to enter another trade until my position has been stopped out or Profit target is hit.
                    Keeping it simple: I'm working on 1 instrument. I don't want more than 1 position at this point in time. The issue I'm having right now is the update for VolumeGood happens in real time and generates many entries at once on volatile candles. I want it to be a little more patient. lol.

                    Code:
                        if (VolumeGood && IsitTime)
                                {
                                    if (UpDown)
                                    {
                                        EnterLong("VolumeSpike-LE");
                                        SetProfitTarget("VolumeSpike-LE", CalculationMode.Ticks, ProfitTarget);
                    
                                        double stopLossPrice = Position.AveragePrice - (stopLossInTicks * TickSize);
                                        SetStopLoss("VolumeSpike-LE", CalculationMode.Ticks, stopLossInTicks, true);
                                    }
                                    else
                                    {
                                        EnterShort("VolumeSpike-SE");
                    
                                        SetProfitTarget("VolumeSpike-SE", CalculationMode.Ticks, ProfitTarget);
                    
                                        double stopLossPrice = Position.AveragePrice - (stopLossInTicks * TickSize);
                                        SetStopLoss("VolumeSpike-SE", CalculationMode.Ticks, stopLossInTicks, true);
                                    }
                                }      ​
                    I would love to add the "&& Position.MarketPosition == MarketPosition.Flat)" to the if statement, but it refuses to compile. It simply is invalid syntax per my desktop. It will not compile or let things work. I am game for figuring something out. I know I'm probably missing some Class/Object/or otherwise to allow that to be used in the context you are using. I just don't know how to get rid of the error. ChatGPT thinks that syntax is correct, and so does this forum. I'm 90% sure the issue is with my code. Everyone keeps giving me the same syntax and compiler keeps complaining that "The name 'MarketPosition' does not exist in the current method." (Alluding to the "MarketPosition.Flat" portion of the code). MarketPosition.Flat/Short/Long is bad syntax or is missing something to allow it to function. I'm relatively new at C# so it likely is something easy that I'm missing.



                    Comment


                      #11
                      Click image for larger version

Name:	image.png
Views:	113
Size:	28.7 KB
ID:	1273956

                      For Reference. Usually NSEditor will give me prompts for methods and such. After the "==", the "MarketPosition" method does not exist or is not valid by any other words.
                      I'm sure it's something easy I'm missing.

                      Comment


                        #12
                        Hello alphatango,

                        Thank you for your reply.

                        In what method are you trying to add this logic? Is it the "private void CloseAllPositions()" that you mentioned in your snippet earlier? Do you get the same errors when adding similar conditions in another method, such as OnBarUpdate, that result in a Print() statement for debugging?

                        This may have to do with the access level of the method if you are using "private void CloseAllPositions()" - what are the results if you use public override CloseAllPositions() instead to change the access level of the method? I suspect the underlying cause of the errors has to do with using a custom method rather than one of the native NinjaScript methods. You may use custom methods in your scripts, though declaring methods and their access levels/modifiers is a general C# concept and is not specific to NinjaScript. More information may be found via third-party resources, such as the following publicly available link:
                        A method in C# is a code block that contains a series of statements. A program runs the statements by calling the method and specifying arguments.


                        Please let me know if I may be of further assistance.
                        Emily C.NinjaTrader Customer Service

                        Comment


                          #13
                          Good questions! I checked on this and made sure I understood what you were asking.

                          I'm using

                          Code:
                          protected override void OnBarUpdate()
                          
                          {
                          if (VolumeGood && IsitTime && Position.MarketPosition = MarketPosition.Flat)
                                      {
                                          if (UpDown)
                                          {
                                              EnterLong("VolumeSpike-LE");
                                              SetProfitTarget("VolumeSpike-LE", CalculationMode.Ticks, ProfitTarget);
                          
                                              double stopLossPrice = Position.AveragePrice - (stopLossInTicks * TickSize);
                                              SetStopLoss("VolumeSpike-LE", CalculationMode.Ticks, stopLossInTicks, true);
                                          }
                                          else
                                          {
                                              EnterShort("VolumeSpike-SE");
                          
                                              SetProfitTarget("VolumeSpike-SE", CalculationMode.Ticks, ProfitTarget);
                          
                                              double stopLossPrice = Position.AveragePrice - (stopLossInTicks * TickSize);
                                              SetStopLoss("VolumeSpike-SE", CalculationMode.Ticks, stopLossInTicks, true);
                                          }
                                      }      ​
                          }​
                          With regards to a print statement "Print("Market Position: " + Position.MarketPosition)" returns accurately. This has never been the issue though. It's the boolean test of if the Market Position is Long. I cannot compile a program that checks if my position is long, short, or flat.

                          The issue is with the "== MarketPosition.Long)" MarketPosition appears to be unable to be checked against.

                          Comment


                            #14
                            Hello alphatango,

                            Thank you for your reply.

                            There is an issue with the comparison operator in your condition:
                            if (VolumeGood && IsitTime && Position.MarketPosition MarketPosition.Flat)

                            You want to check if Position.MarketPosition equals MarketPosition.Flat, so you must use a double equals sign to compare the two:
                            if (VolumeGood && IsitTime && Position.MarketPosition == MarketPosition.Flat)

                            A single equals sign is an assignment operator which would set the value to an object. Comparison operators are a general C# concept and more information may be found via external resources, such as the following publicly available link:
                            W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.


                            You could also test out certain conditions by configuring them in the Strategy Builder's user interface, then click the "View Code" button to see how the code would appear when scripting in the NinjaScript Editor. This is a helpful way to get more familiar with some of the syntax used for certain conditions and actions in NinjaScript. I suggest testing out configuring some of the common conditions and actions from the following examples, then click "View Code" to see how they are set up in the NinjaScript Editor:Please let us know if we may be of further assistance.
                            Emily C.NinjaTrader Customer Service

                            Comment


                              #15
                              As an update. I was wondering if this was the case. I went through the NS Strategy Builder wizard and added in a bunch of the logic that I want. Once I get that in there, I can shift it around where I need it as it's easier for me just to code a complex If/then or boolean by hand.

                              It added in a big list of Using Declarations. I snipped the updated Using Declarations from the Generated Output, and updated that list in my current code. The error of MarketPosition not existing in the current context cleared.

                              I still don't know what declaration that falls under, but that appears to be the issue.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Nicholewatkinsi, Today, 10:53 PM
                              0 responses
                              4 views
                              0 likes
                              Last Post Nicholewatkinsi  
                              Started by dward123, 01-02-2024, 09:59 PM
                              4 responses
                              175 views
                              0 likes
                              Last Post Lancer
                              by Lancer
                               
                              Started by ETFVoyageur, Today, 04:00 PM
                              2 responses
                              19 views
                              0 likes
                              Last Post ETFVoyageur  
                              Started by AaronKTradingForum, Today, 03:44 PM
                              1 response
                              14 views
                              0 likes
                              Last Post AaronKTradingForum  
                              Started by Felix Reichert, 04-26-2024, 02:12 PM
                              11 responses
                              80 views
                              0 likes
                              Last Post Felix Reichert  
                              Working...
                              X