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

Position.MarketPosition is always Flat even when I enter a Long position

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

    Position.MarketPosition is always Flat even when I enter a Long position

    I am learning about the OnBarUpdate, OnOrderUpdate, and OnExecutionUpdate methods as well as the idea of intrabar granularity. In a broad sense, I want to enter a Long position in my OnBarUpdate method, and then exit the position in the OnExecutionUpdate method. However, I still want to "watch the price" in the OnBarUpdate method to adjust my stop loss and profit targets. But what is interesting is that the Market Position is always flat in the OnBarUpdate method even when I have entered a Long position. This is pretty confusing. In the attached simple example, I am simply entering a long position when the time is between 11AM and 12 PM. I have also added a secondary data series at the 1 minute level (my primary data series is at 30 min level). In my OnBarUpdate method, I added a Print statement to print out the position. When I enter a Long position, I should be able to see that the Market Position is Long in my Print statement but I am seeing the position as Flat. Why is this the case? I have logic in the OnBarUpdate update method that only triggers when the Market Position is Long. Also, for some strange reason, when I print out Times[0][0] when BarsInProgress = 1, it does not print the time out in the minute level even though my secondary data series is at the minute level. For your reference, I was using the Strategy Analyzer with ES-3-21, on 1/4/21 with Profit Ticks set to 10 and StopLossTicks set to 20.
    Attached Files
    Last edited by lewisquake; 02-23-2021, 08:08 PM.

    #2
    Looking at your OnBarUpdate code, I would say that what you are seeing is expected behavior.

    The Position is object is not updated until (at the very least) a partial fill happens.

    Neither OnOrderUpdate nor OnExecutionUpdate will be called while your OnBarUpdate is
    currently being processed.

    This is where you must say 10 times "NinjaTrader is an event driven system", and then
    realize Position won't change until the event actually happens -- and when it happens you'll
    see it via your callbacks.

    Comment


      #3
      Hi bltdavid. Thanks for your reply. So what would be the process to adjust my stop loss/profit target if the Position is never updated. Does that mean I have to manage all my stop loss/profit target within the OnBarUpdate method and just forget about using the other methods? The reason I am using those other methods because I believed it was considered best practice and I want to use the actual Fill Price instead of AveragePrice. Here is a simple scenario I tried to implement in the attached code from my previous post but failed:
      1. Between 11AM and 12PM enter a Long on the Primary Bar
      2. Look at the secondary data series(1 minute bar) and if Position is Long
        1. If Close[0] > (Average Fill Price + ProfitTicks/2 * TickSize) set Stop Loss to Average Fill Price (Break Even)
        2. Otherwise exit at Original Stop Loss
      Any ideas if this could be implemented using the combination of those three methods or would I have to lump everything in the OnBarUpdate?
      Last edited by lewisquake; 02-23-2021, 11:25 PM.

      Comment


        #4
        Originally posted by lewisquake View Post
        So what would be the process to adjust my stop loss/profit target if the Position is never updated. Does that mean I have to manage all my stop loss/profit target within the OnBarUpdate method and just forget about using the other methods? The reason I am using those other methods because I believed it was considered best practice and I want to use the actual Fill Price instead of AveragePrice. Here is a simple scenario I tried to implement in the attached code from my previous post but failed:
        1. Between 11AM and 12PM enter a Long on the Primary Bar
        2. Look at the secondary data series(1 minute bar) and if Position is Long
          1. If Close[0] > (Average Fill Price + ProfitTicks/2 * TickSize) set Stop Loss to Average Fill Price (Break Even)
          2. Otherwise exit at Original Stop Loss
        Any ideas if this could be implemented using the combination of those three methods or would I have to lump everything in the OnBarUpdate?
        What? Who said 'Position' is never updated? Not me.

        As my last answer implied, it is not updated just because you call EnterLong() -- it's updated
        when the fill (or partial fill) event happens. Why the "never" comment? It is certainly being updated,
        though definitely not inside the same OBU as when EnterLong executes. Experiment again and
        convince yourself this is true.

        What stop management do you mean?
        You mean your 'Breakeven plus Half' idea I highlighted in red?
        (I didn't see any code for this in your original post)

        I see you enter the stop and target orders from OEU, which is good.
        You can certainly do that and then update the stop loss to BE+Half in OBU later
        during BIP == 1 processing. Is this what you tried to implement?

        Yes, all 3 methods, OBU, OOU, and OEU, can work together to do exactly what you're
        describing. The main issue seems to me your OBU is not done yet.

        Ok, you tried to implement some new changes and they failed.
        How did they fail?
        Last edited by bltdavid; 02-24-2021, 12:11 AM.

        Comment


          #5
          Hi bltdavid,

          I appreciate your suggestions. I have attached updated code where I have implemented my stop management logic. I also printed out the Market Position in OBU, and it was always Flat as was expected. I created a global entryprice variable that is defined as entryprice = execution.Order.AverageFillPrice. In my OBU method I added this:

          Code:
          if(BarsInProgress == 1)
          {
          if(Close[0] > entryprice + ProfitTicks/2*TickSize /*and we are in Long Position*/ )
          {
          StopLossTicks = 0;
          
          }
          
          }
          My questions is, in that code I need to also add a condition if I am in a Long position (as I may add some Short Position logic later). I could add the condition in the if statement, && entryOrder !=null, but I want to distinguish whether the entryorder is a Long order or a Short Order. It also looks that a Stop order is never executed whenever I test the strategy through the Strategy Anaylzer.
          Attached Files
          Last edited by lewisquake; 02-24-2021, 01:15 AM.

          Comment


            #6
            Hello lewisquake,

            Thank you for post.

            Who is your broker? There is a known issue with Rithmic based connections (and to a considerably lesser extent, Interactive Brokers) where the order in which Order/Execution/Position updates occur, and Position updates may not occur at all.

            If this is the case, the workaround would be to use the Unmanaged approach which allows you to calculate the strategy position internally and not be dependent on Position updates from the connection. I'm attaching a sample strategy that demonstrates this.

            If you're not using a Rithmic based connection, we'd want to test a reduced script that reproduces the position not changing. Any user inputs should be hardcoded instead, and it should be simplified as much as possible.

            Thanks in advance; I look forward to assisting you further.



            Attached Files
            Kate W.NinjaTrader Customer Service

            Comment


              #7
              Hi Kate,

              I am using Continuum for my connection. I updated the code to hardcode the stop loss and profit target. As mentioned in my previous post, the high level pseudocode is as follows:
              1. Between 11AM and 12PM enter a Long on the Primary Bar
              2. Look at the secondary data series(1 minute bar) and if Position is Long
                1. If Close[0] > (Average Fill Price +10/2 * TickSize) set Stop Loss to Average Fill Price (Break Even)
                2. Otherwise exit at Original Stop Loss
              I am not seeing any stop orders being executed, only take profit. I am following the advice from bltdavid where I updated my Stop loss on the OnBarUpdate method in Post #4 with BIP =1.
              Attached Files
              Last edited by lewisquake; 02-24-2021, 10:21 AM.

              Comment


                #8
                Hello lewisquake,

                Thank you for your reply.

                You didn't quite hardcode all the values right so I restored them to using the inputs in the attached revised script - generally we don't make changes but it's easier to show you what the issue is as it's a little confusing to just read it. If I'm understanding right, the issue is that the original version does not move the stop to break even. The reason this never occurred is because in order for your script to update the stop, it needs to get called again with the same Signal names. Because you're originally submitting the stop loss in OnExecutionUpdate which is only called when an order execution is received, the StopLossTicks get updated to 0 when the price is more than 10 ticks above the fill price and never gets reset to the original value, any order placed after this occurs would place the stop loss at the average entry price, most likely resulting in a near immediate fill of further stops.

                You'd want to call the stop loss again within OnBarUpdate instead. Also, instead of resetting StopLossTicks to 0, simply set Position.AveragePrice as the price of the updated stop. You'll notice I also check to make sure that a stop currently is active, and also check that a bool I added (IsBreakEven) is false before trying to move the order so it only gets updated once instead of every time OnBarUpdate runs and the Close is still greater than 10 ticks above the entry. I then would reset that bool once either the stop or target fills and the stopOrder and targetOrder variables are set back to null.

                I've renamed this version to testAPIModified so you can import this and compare to your original code to understand the differences.

                Please let us know if we may be of further assistance to you.
                Attached Files
                Kate W.NinjaTrader Customer Service

                Comment


                  #9
                  Question for support.
                  (Please refer to attached screenshot)
                  (Please consider your answer be more designed to help our young OP with his learning
                  than to address me directly. Let's make this a teachable moment)

                  Is it OK to use different BarsInProgress arguments when creating the stop/target orders
                  when OrderState.PartFilled vs creating the stop/target orders when OrderState.Filled?

                  If the orders are created via PartFilled on BIP=1, and then "updated" on Filled using BIP=0,
                  will this have any impact on the script? I mean, the change in BIP will still find the correct
                  existing orders and update the order quantities, as OP intends, if a partial fill happens first?

                  In other words, is the 1 vs 0 change in BIP necessary, or benign, or a bug?
                  Attached Files

                  Comment


                    #10
                    Hello bltdavid,

                    Thank you for your reply.

                    That's an interesting question, and honestly I'll need to do some testing on that - I didn't test with anything but a single quantity, so I'm not entirely sure what the result would be. That's a good catch, as I didn't notice that in the code since I didn't really make adjustments there.

                    I'll let you know my findings when I have those!

                    Thanks in advance; I look forward to assisting you further.
                    Kate W.NinjaTrader Customer Service

                    Comment


                      #11
                      Hi Kate,

                      Do you have any updates on the issue regarding different BIP arguments?

                      Comment


                        #12
                        Hello lewisquake,

                        Thank you for your reply.

                        So, in my testing, it seems to not really matter in this particular case - the order changes still get made. However, in speaking with my colleagues, we'd imagine there could certainly be scenarios in which this could become problematic. We would recommend submitting all order changes to the same data series, and would generally recommend submitting orders to the most granular series.

                        Please let us know if we may be of further assistance to you.
                        Kate W.NinjaTrader Customer Service

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by Brevo, Today, 01:45 AM
                        0 responses
                        3 views
                        0 likes
                        Last Post Brevo
                        by Brevo
                         
                        Started by aussugardefender, Today, 01:07 AM
                        0 responses
                        3 views
                        0 likes
                        Last Post aussugardefender  
                        Started by pvincent, 06-23-2022, 12:53 PM
                        14 responses
                        239 views
                        0 likes
                        Last Post Nyman
                        by Nyman
                         
                        Started by TraderG23, 12-08-2023, 07:56 AM
                        9 responses
                        384 views
                        1 like
                        Last Post Gavini
                        by Gavini
                         
                        Started by oviejo, Today, 12:28 AM
                        0 responses
                        6 views
                        0 likes
                        Last Post oviejo
                        by oviejo
                         
                        Working...
                        X