Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Get Position Time and Strategy

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

    Get Position Time and Strategy

    Hi all,

    I would need to check the exact bar when a position was opened. I know that would be easy to use BarsSinceEntryExecution() but when the strategy restart or any disconnection appears the value is reset.

    Do we have any parameter I could use to get the bar open position or the time when the position was opened? For now I am checking the executions account to get the last execution.time but I don't know if there is a faster way.

    Moreover, I would like to know if there is a way to identify which strategy does a specific account position belong to. I mean which strategy opened that specific position? Is it possible?

    Thank you for your support.

    Regards.


    #2
    Hello Peppo,

    The Position object itself would not have that information..

    You could save the time of the last execution to a variable when the entry execution fills in OnExecutionUpdate(). This would be the last entry time that contributed to a position.

    A NinjaScript Strategy would only have a Position(s) opened by that instance of a strategy.

    From the Addon approach looking at orders of the account, there would be nothing documented for this, and I am unsure if this would be possible.
    However, if it were, it would likely be the GetOwnerId returned from the entry order.
    Some undocumented code that may give you some ideas can be found here.
    NinjaTrader.NinjaScript.AtmStrategy.StartAtmStrategy("S10_P10", entryOrder); This does not return a strategyID, which is needed for any following action, like closing the strategy. How can I get it? Thanks.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Hi Chelsea,

      Thanks for your reply but I think I didn't explain the problem properly.

      I am taking about the fact that the strategy is restarted for any reason. In this case, whatever variable I set at restart is gone and I lose the information. This is why I am using the executions array of account.

      My question is how can I get the position execution time without referring to the account executions?

      For the strategy id I will test it.

      Thank you.

      Regards.

      Comment


        #4
        Hello Peppo,

        If the strategy is disabled and re-enabled with the Immediately Submit start behavior, any orders that are matched in historical will be resumed.

        Below is a link to a forum post on resuming a strategy.


        Any variable, would be set again as the script processes the historical data.

        The position execution time is just the order execution time.

        If the order was not submitted by the strategy instance, you will have to get the order from the Account.Executions.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Hi Chelsea,

          I agree but in my strategy I use IsFirstTickOfBar to place an order and I am not able to simulate the historical trades to be compliant with Immediately Submit start behavior.

          For now what I am doing is looking at Account.Executions to find the last execution.Time correspoding to the instrument I am using.

          Thank you.

          Regards.

          Comment


            #6
            Hello Peppo,

            IsFirstTickOfBar implies Calculate OnEachTick or OnPriceChange, which historically requires TickReplay.
            This is detailed in the forum post I have linked.

            Is TickReplay enabled? Is this a bar type that supports TickReplay?

            Are you implementing 1-tick intra-bar granularity to increase order fill accuracy so the orders may be resumed?

            Regardless, the strategy position has a quantity, and averageprice, but does not have a time. The entry execution has the time the position was last updated (as multiple entries can affect the position quantity and average price).
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Hi Chelsea,

              I don't have TickReplay enabled.

              Anyway, I will try to get 1-tick intra-bar granularity for the most recent bars and implement the solution you have suggested with Immediately Submit to resume the historical orders.

              Thank you.

              Regards.

              Comment


                #8
                Hi Chelsea,

                I did some tests with Immediately Submit start behavior and unfortunately this is not what I want to achieve.

                After the restart, I would like to check only if there is an open position and resume the corresponding stop and target orders. I thougth IsAdoptAccountPositionAware is what I need and I found this example AdoptAccountPositionTestManaged here:

                Hello, What can I do if my strategy is recalculated due to a network disconnection or if I compile the code and the previous Take Profit, Stop Loss or pending orders are lost? Can I detect pending orders in the chart under the account class? (they are still there, but lost contact with my strategy). Or is there any other way


                and I have seen that the strategy does not start if all the working orders present in the chart are not cancelled. To make it working I put Account.CancelAllOrders(Instrument) in the State.Configure and apply new ones in State.Realtime.

                Now, I don't want to cancel the orders every time and then apply new ones. Is there any way I can read the pre-existing orders and keep them in the strategy?

                With IsAdoptAccountPositionAware is possible to understand in which bar the position was opened?

                Thank you.

                Regards.



                Comment


                  #9
                  Hello Peppo,

                  "After the restart, I would like to check only if there is an open position and resume the corresponding stop and target orders."

                  For resuming a strategy, it would be required to use the Immediately Submit start behavior. This start behavior will use the historically calculated position, which if 1-tick intra-bar granularity has been implemented, should be the position the strategy left when disabled. Any stops and targets that are matched would be resumed and not cancelled. The strategy would continue and resume from where the strategy was last disabled, resuming the position and any working orders such as the stop and target.

                  With Adopt account, this will modify the strategy position to match the account position, and then will cancel the existing working orders and send new working orders.

                  To confirm, you are not wanting to resuming a previous position and stop and target, and you are instead wanting to manually create an account position and have the strategy adopt that position and place new stop and targets, is this correct?

                  Where you have mentioned:
                  "Now, I don't want to cancel the orders every time and then apply new ones. Is there any way I can read the pre-existing orders and keep them in the strategy?"
                  This would require resuming the position and previous orders with Immediately submit and 1-tick intra-bar granularity.

                  "With IsAdoptAccountPositionAware is possible to understand in which bar the position was opened?"
                  This is not used to resume a position. This is used for the strategy to actively adopt the account position, whatever it may be. There would not be a way of knowing when the account position was opened, as this would not be opened with code.
                  Last edited by NinjaTrader_ChelseaB; 08-02-2022, 03:21 PM.
                  Chelsea B.NinjaTrader Customer Service

                  Comment


                    #10
                    Hi Chelsea,

                    thank you for your explanation.

                    When the strategy is restarted, I want to resume the position and all the stop/target orders if there was an open position. Otherwise, if there is no open position, I want that the strategy does nothing but wait for the next entry. In principle, I want to resume the last context.

                    Now, just for my understanding, if we use Immediately Submit the account position and strategy position are assumed to be in sync. From the help guide I see:

                    "Any remaining active strategy orders that cannot be successfully paired will be submitted live and the strategy will begin managing your Strategy Position assuming your Account Position is in sync with it."

                    Now, the historical orders generated by the strategy are the result of the algorithm present in the strategy itself. This means that they could not match what happened in the real world. What I want to say is that, if an order to open a certain position was not executed by the broker for any reason, when the strategy is restarted will assume that, based on the computed algorithm, a position was opened even if that never happened in the past. So, with Immediately Submit the strategy will start to place stop/target orders even if the position was never there. Is my understanding correct?

                    I see the same thing also with Immediately Submit Synchronize account because as stated in the help guide:

                    "If the Account Position does not match your Strategy Position, NinjaTrader will submit a market order(s) to reconcile the Account Position to match your Strategy Position. The strategy will then begin managing your Strategy Position immediately."

                    This means that, even if there was no open position in the past (because of broker or any other reason), NinjaTrader will force to open a new position with a market order.

                    Now, let's assume that in the strategy I use Limit order to open a position. This means that I will get a completely different results from what I expect since the strategy will use market orders at restart. Is it correct?

                    Thank you.

                    Regards.

                    Comment


                      #11
                      Hello Peppo,

                      That would be correct. For the strategy to resume the account position, the account position would have to be left open and the strategy would resume it.
                      The orders would be left working and the strategy would resume them.

                      Where you have mentioned:
                      "Now, the historical orders generated by the strategy are the result of the algorithm present in the strategy itself. This means that they could not match what happened in the real world. "

                      This should be the same logic that submitted the orders in real-time if the orders are going to be resumed. The 1-tick intra-bar granularity to ensure that the order fills and prices match the real-time trades as closely as possible so that the position and orders can be resumed. This is what is discussed in the forum post I linked you.

                      "What I want to say is that, if an order to open a certain position was not executed by the broker for any reason, when the strategy is restarted will assume that, based on the computed algorithm, a position was opened even if that never happened in the past."

                      It is possible that the historical performance does not calculate exactly the same, however with the intra-bar granularity this would be as close as possible and generally enough for the strategy to resume. That said, this is the only way to resume a position and orders.

                      "This means that, even if there was no open position in the past (because of broker or any other reason), NinjaTrader will force to open a new position with a market order."
                      If the strategy position does not match the account position, then the position is not being resumed. But you can absolutely, change the account position to match the strategy position with Synchronize account option.

                      "Now, let's assume that in the strategy I use Limit order to open a position. This means that I will get a completely different results from what I expect since the strategy will use market orders at restart. Is it correct?"
                      I'm not quite understanding this. If the position is being resumed, that was the same limit order in historical data that opened the same position. Why would the results be different?
                      If you are asking about the synchronize, then its not resuming the position.
                      Chelsea B.NinjaTrader Customer Service

                      Comment


                        #12
                        Hi Chelsea,

                        it is clear that we can use the 1-tick intra-bar granularity to match order fills and prices with real-time trades but, as far as I understood, it can happen a discrepancy between historical computation and reality. Let's say I place a buy order of 100 contracts through the strategy but during real-time only 50 contracts are filled by the broker. Now, at restart the strategy will calculate that 100 contracts have been filled and not 50. Do you confirm?

                        Regarding the second point, I meant that the strategy with Immediately Submit Synchronize account will submit market order to reconcile Account Position and Strategy Position regardless from what is implemented in the strategy itself (in case the positions do not match). I mean the account position is not open but it is expected a strategy position. Correct?

                        If this is confirmed, I don't think I am going to use Immediately Submit neither Immediately Submit Synchronize account.

                        I think IsAdoptAccountPositionAware is the one closest to my objective. Maybe I can write to a file the bar where the order has been filled (by the way I want the order to be filled only in such a specific bar).

                        Thank you.

                        Regards.

                        Comment


                          #13
                          Hello Peppo,

                          If something very unusual, like an order part filling and not fully filling ever in real-time, would not happen in backtest correct. If the order fills at a different price, this could cause the stop and target to be submitted at a different price, which could cause the orders to not be matched and would be cancelled and resubmitted at the new price.

                          That said, Immediately submit with 1 tick granularity is the closest to real-time results and the only way to get a strategy to resume a previously made position and working orders.

                          However, feel free to use whatever suits you.

                          Where you have stated:
                          "Regarding the second point, I meant that the strategy with Immediately Submit Synchronize account will submit market order to reconcile Account Position and Strategy Position regardless from what is implemented in the strategy itself (in case the positions do not match). I mean the account position is not open but it is expected a strategy position. Correct?"

                          If the account position was not left open there is no position to resume. The position of the account should not be changed when the strategy is disabled for it to be resumed. When strategy is re-enabled, that same unmodified position is what would be resumed.
                          Chelsea B.NinjaTrader Customer Service

                          Comment


                            #14
                            Hi Chelsea,

                            sorry to come back on this topic but I found an error in my strategy while cancelling all the orders for a specific instrument.

                            I decided to use the IsAdoptAccountPositionAware and as expected all the orders have to be cancelled as stated in the following error message I receive:

                            "Default 'Strategy' could not be enabled because the ‘Start behavior’ parameter 'Adopt account position' requires that there are no working orders on this strategy's instrument(s) in 'Sim101'. Please cancel any working orders on the same account-instrument combo(s) first to be able to enable your strategy".

                            This is what I have implemented in the strategy:

                            ...
                            else if (State == State.Configure)
                            {
                            Account.CancelAllOrders(Instrument);
                            }
                            else if (State == State.Realtime)
                            {
                            SetStopLoss(CalculationMode.Percent, StopPerc);
                            }
                            ...

                            but it does not work as I expect all the time and I get the previous message.

                            How can I make sure that all the orders on a specific instrument are cancelled before the strategy starts working?

                            Thank you.

                            Regards.

                            Comment


                              #15
                              Hello Peppo,

                              I'm not sure of a workaround for this. The strategy is going to check there are no working orders before it attempts to enable. I'm not certain this will work.

                              You will likely need to manually cancel all orders before enabling the strategy.

                              Your strategy can of course cancel any working orders it has submitted when disabled.


                              Chelsea B.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by NullPointStrategies, Yesterday, 05:17 AM
                              0 responses
                              81 views
                              0 likes
                              Last Post NullPointStrategies  
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              149 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              79 views
                              0 likes
                              Last Post NabilKhattabi  
                              Started by Deep42, 03-06-2026, 12:28 AM
                              0 responses
                              52 views
                              0 likes
                              Last Post Deep42
                              by Deep42
                               
                              Started by TheRealMorford, 03-05-2026, 06:15 PM
                              0 responses
                              59 views
                              0 likes
                              Last Post TheRealMorford  
                              Working...
                              X