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

Resume Historical Orders in Unmanaged Approach

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

    #16
    Hello Peppo,

    Thank you for your reply.

    That would probably be the best way to ensure everything's cancelled out. Manual orders wouldn't be recognized by the strategy as having been submitted by it so those would not be cancelled when the strategy is restarted.

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

    Comment


      #17
      Originally posted by NinjaTrader_Kate View Post
      I'd take a look at this version of the UnmanagedOnOrderUpdate that tracks the position for the strategy internally - you could combine this with logic to check the position of the account, track that as your current position, then update that calculated position as you manually enter further trades.
      Kate,

      thank you for the code for UnmanagedOnOrderUpdate. In case the connection is lost for whatever reason, I experience that there are multiple working orders with different OrderIDs that have been submitted with

      SubmitOrderUnmanaged(0, OrderAction.Buy, OrderType.Limit, 1, LongEntryLimit, 0, oco, "Long limit entry");

      When restarting the strategy I would like to pick-up these historical working orders. I noticed that you convert any old historical order object reference to the new live order using GetRealTimeOrder(longEntry). However, when starting the strategy e.g. longEntry should equal null, therefore GetRealTimeOrder(longEntry) will not work I guess, right? Moreover, as longEntry will get initialized with null after a restart of the strategy another order will be fired to the system using SubmitOrderUnmanaged(0, OrderAction.Buy, OrderType.Limit, 1, LongEntryLimit, 0, oco, "Long limit entry"); Then there would be still at least two working orders - GetRealTimeOrder(longEntry) will retrieve only one order and this would be the new order that just has been submitted?

      Do I need to cancel the historical working orders somehow or did I understood your code wrong?

      Kind regards
      Gerik

      Comment


        #18
        Hello Gerik,

        Thank you for your reply.

        Are you creating separate Order variables for each order being placed? If you're submitting more than one entry order that may be active (ie. not yet filled) at the same time, each of these entries should be tracked in their own variable, for example, if I have three long entries, I'd want to track those in three separate variables, so if I'm saving one to longEntry, I might save the order objects for the others in a variable called longEntry2 or longEntry3.

        This way, when re-enabling the strategy you still have the order references for those and can use GetRealTimeOrder for each one that may be necessary.

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

        Comment


          #19
          Hello Kate,

          I submit only one long entry and I use only one variable.

          How can I pick up the order that is still active and not filled when the strategy gets restarted?

          Kind regards
          Gerik

          Comment


            #20
            Hello Gerik,

            Thank you for your clarification.

            Depending on your settings, the script will either not try and match any previous made orders made by the script on a previous run (Wait until flat), or will attempt to resume and try and match previously made orders (Immediately submit) with the orders it calculates in historical data.

            If the settings are setup to resume and have the calculated historical orders match the previously made real-time orders, when orders are matched, these will still show in the real-time strategy performance as real-time (as these orders were made in real-time and by being matched are resumed).

            NinjaTrader can try and resume your strategies when you restart them, however, it's not a guarantee.


            To do this, you will need to enable the following option before starting a new instance of a strategy:
            • Right-click the chart and select Strategies or right-click the Strategies tab of the Control Center and select New Strategy...
            • Select the strategy from the Available list (in the Chart Strategies window click the New button to add an instance of the strategy)
            • In the parameters on the right, set 'Start behavior' to 'Immediately submit, synchronize account' (or 'Immediately submit')
            • After running your strategy, be sure to save your workspace when you shutdown NinjaTrader
            Below is a link to the help guide on Syncing Account Positions. Please see the section 'Immediately submit, synchronize account'
            http://ninjatrader.com/support/helpG...hronizeAccount

            Further, below is a public link to a forum post about startup behavior.
            https://ninjatrader.com/support/foru...776#post528776

            With these options the following will happen when the strategy resumes. (From the help guide on Immediately submit, synchronize account):

            This combination should be used when you want to begin trading your strategy off a flat state with minimal user interaction to sync your Account Position prior to start.
            • When your strategy starts it will check for any active orders previously generated by the strategy on your account. Any active orders on the account previously generated by the strategy that does not match* an active strategy order will be cancelled. Should the strategy be unable to cancel and receive confirmation on the cancellation of these orders within 40 seconds the strategy will not start and an alert will be issued.
            • The matching active orders on the account will then be mapped to the active strategy orders. These orders will be resumed properly.
              After the strategy is successful in cancelling any orders necessary, any remaining active strategy orders that cannot be successfully paired will be submitted live and the strategy will then try to sync your Account Position to your Strategy Position. On multi-instrument strategies it will perform this check for all instruments used by the strategy.

              (It would be recommended to disable the Tools > Options > Strategies > NinjaScript > 'Cancel entry orders / Cancel exit orders when strategy is disabled' so that these remain in a working state so these can be resumed (should they not fill while the strategy is disabled))
            • If the Account Position matches your Strategy Position, no reconciliatory order will be submitted. The strategy will then begin managing your Strategy Position immediately.
            • 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.

              * A previously generated order is considered to match an active strategy order when the order action, order type, quantity, limit price, and stop price are exactly identical.
            As mentioned in the help guide, if the historical orders do not match real-time orders made previously they are cancelled.

            If you want to ensure that your strategy resumes the previously placed orders and positions with the 'Immediately submit' setup, you will need to ensure that the historical trades match the real time trades.

            Adding intra-bar granularity can help with this.

            When in historical data, only the Open, High, Low, an Close will be available and there will be no intra-bar data. Intra-bar granularity adds a second data series such as a 1 tick series so that the strategy has finer granularity in the historical data in between the OHLC of the primary series. This allows for more accurate trades.

            If the strategy was running in real-time with Calculate set to 'On price change' or 'On each tick', it would be recommended to enable TickReplay so that any indicators that may have been updating in real-time and whom's values are used in conditions that trigger orders can also update historically for each tick or price change.

            Below is a link to an official reference sample that demonstrates how to add intra-bar granularity.
            http://www.ninjatrader.com/support/f...ead.php?t=6652

            Also, here is a link to the differences on real-time vs backtest (historical).
            http://ninjatrader.com/support/helpG...ime_vs_bac.htm

            As well as a link to the help guide on the AddDataSeries() method.
            http://ninjatrader.com/support/helpG...dataseries.htm

            A link to the help guide on BarsInProgress.
            http://ninjatrader.com/support/helpG...inprogress.htm

            And a link to the help guide on Multi-Time Frame & Instruments. Please see the section 'How Bar Data is Referenced', and 'Accessing the Price Data in a Multi-Bars NinjaScript'.
            http://ninjatrader.com/support/helpG...nstruments.htm

            And a link to another forum post that describes intra-bar granularity with a 1 tick series, TickReplay, and High Order Fill resolution in more detail.
            https://ninjatrader.com/support/foru...297#post491297

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

            Comment


              #21
              Hello Kate,

              thank you for your message. I am using the unmanaged approach and I do not want NinjaTrader to synchronize or match residual working orders from a previous instance with calculated orders as I want to do it on my own in my strategy code.

              Therefore, I would like to either change/re-use an residual working order based on the name of the order or to cancel the order. However, as there has been a reconnection or a restart of the computer for whatever reason, the order seems not be associated to the strategy anymore.

              Again, how can I fetch, cancel or change the already existing working order based on e.g. the name of the order?

              Kind regards
              Gerik

              Comment


                #22
                Hello Gerik,

                Thank you for your reply.

                The strategy wouldn't be able to recognize the order from a name directly, however, you could theoretically check the Account and cancel any open orders on the instrument when the strategy is started:




                That's not particularly necessary, however, as using Immediately Submit, Synchronize Account would check any open orders on the account, cancel them if they don't match what the strategy has calculated it should have submitted at the given point, and then submit orders to match it's calculated position after your changes.

                Please let us know if we may be of further assistance to you.

                Kate W.NinjaTrader Customer Service

                Comment


                  #23
                  Hello Kate,

                  I tried to run myAccount.CancelAllOrders(Instrument); within State == State.DataLoaded and it seems that nothing has been deleted by the strategy.

                  I is also not possible to cancel the residual working order in the Orders Tab of Account Data by pressing on "x". Nothing happens.

                  Any ideas why it is like this?

                  Kind regards
                  Gerik



                  Comment


                    #24
                    Hello Gerik,

                    Thank you for your reply.

                    The following works for me to cancel an existing active order on the Sim101 account:

                    Code:
                    private Account myAccount;
                    protected override void OnStateChange()
                    {
                    if (State == State.SetDefaults)
                    {
                    Description = @"This is a template for Unmanaged strategies that can be used as reference for developing your own Unmanaged strategy.";
                    Name = "ExampleCancelAllOrdersUnmanaged NT8";
                    Calculate = Calculate.OnBarClose;
                    EntriesPerDirection = 1;
                    EntryHandling = EntryHandling.AllEntries;
                    IsExitOnSessionCloseStrategy = true;
                    ExitOnSessionCloseSeconds = 30;
                    IsFillLimitOnTouch = false;
                    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
                    OrderFillResolution = OrderFillResolution.Standard;
                    Slippage = 0;
                    StartBehavior = StartBehavior.WaitUntilFlat;
                    TimeInForce = TimeInForce.Gtc;
                    TraceOrders = true;
                    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
                    StopTargetHandling = StopTargetHandling.PerEntryExecution;
                    BarsRequiredToTrade = 20;
                    IsUnmanaged = true;
                    IsAdoptAccountPositionAware = true;
                    // Disable this property for performance gains in Strategy Analyzer optimizations
                    // See the Help Guide for additional information
                    IsInstantiatedOnEachOptimizationIteration = true;
                    
                    // Find our Sim101 account
                    lock (Account.All)
                    myAccount = Account.All.FirstOrDefault(a => a.Name == "Sim101");
                    
                    }
                    else if (State == State.DataLoaded)
                    {
                    if (myAccount != null)
                    {
                    myAccount.CancelAllOrders(this.Instrument);
                    }
                    }
                    Can you supply a screenshot of the working orders in the Orders tab that shows the orders that you can't manually cancel?

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

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by elirion, Today, 01:36 AM
                    0 responses
                    3 views
                    0 likes
                    Last Post elirion
                    by elirion
                     
                    Started by gentlebenthebear, Today, 01:30 AM
                    0 responses
                    4 views
                    0 likes
                    Last Post gentlebenthebear  
                    Started by samish18, Yesterday, 08:31 AM
                    2 responses
                    9 views
                    0 likes
                    Last Post elirion
                    by elirion
                     
                    Started by Mestor, 03-10-2023, 01:50 AM
                    16 responses
                    390 views
                    0 likes
                    Last Post z.franck  
                    Started by rtwave, 04-12-2024, 09:30 AM
                    4 responses
                    34 views
                    0 likes
                    Last Post rtwave
                    by rtwave
                     
                    Working...
                    X