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

restart ninjatrader daily

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

    restart ninjatrader daily

    after 2 days, i keep running our of resources. so i want to restart ninjatrader and my laptop daily. the signals are managed by my indicator and they seem to be ok. what precautions and methods should i follow so my strategy continines where i left off.
    1. the state of the order objects
    2. partial executions between restarts

    #2
    Hello junkone,

    Thank you for your reply.

    If you're running out of PC resources, does the script use a large number of drawing objects? Reducing the number of drawing objects used or using SharpDX for rendering objects to the chart may help alleviate this.

    That being said, it's not a bad plan to restart once a day. Keep in mind that after a restart, in the historical data the conditions in the script will be run as a backtest and have historical results before real-time data processing and real-time order submissions begin.

    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.

    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


      #3
      wow. thats a lot of info for me to digest. thanks anyways for putting it together. I am sure i will have more questions as i chug along on this.

      Comment


        #4
        i get this strategy with sync failed daily. i cannot see any errors and need some input on determining why the sync failed.
        Click image for larger version

Name:	pahdNR5.png
Views:	514
Size:	17.5 KB
ID:	1165726

        Comment


          #5
          Hello junkone,

          Thanks for your post.

          The sync column on the strategies tab of the NinjaTrader control center is advising that the strategy position, which is flat, does not match the account position, which shows as 2 short (assuming you have not rearranged the tabs columns).

          From the help guide, Sync column: "Compares the strategy position to the current real-world account position relative to the configured instrument. A value of true indicates the strategy position is currently in sync with the account position" Please see: https://ninjatrader.com/support/help...eStrategiesTab.

          Try closing the two short orders then apply the strategy.
          Paul H.NinjaTrader Customer Service

          Comment


            #6
            Hello junkone,

            This is Jim responding on behalf of Kate who is out of the office at this time.

            Generally the left column will represent the strategy position while the right column represents the account position.

            The strategy position is calculated when the strategy is enabled and processes historical data. In this case, it looks like that strategy calculated it would not be in a position, while the account position was 2 short. I'm including some general information on start behaviors and strategy/account position at the end of my message.

            After reviewing this detail, could you elaborate on what failed with the synchronization? What were you expecting to take place that did not take place? What Start Behavior were you using?

            Understanding Start Bheaviors/Syncing account positions with strategy positions

            When a strategy is enabled, it processes historical data to determine trades that the strategy would have made on the data that is already on the PC/chart and to determine what position the strategy is in. (Strategy positions are separate from actual Account positions.)

            Wait Until Flat will wait until this virtual/historical position is closed before live orders can be submitted. It ensures that the strategy starts trading live from a flat position. If you enable the strategy when the account is flat, the strategy will waiting until this position calculated from historical data is closed so it is logically making trades starting from an entry signal.

            Immediately Submit automatically submits working orders from when the strategy processed historical data, and assumes the strategy position and account position are where you want it when you enable the strategy. This is typically used to have a strategy resume a position after disabling/enabling. If the strategy already had live orders running, the orders will resume with the new enablement of the strategy if they match the historically calculated orders. If the orders calculated from historical data do not match the live working orders, the live working orders will be cancelled and replaced by those calculated from historical data.

            Sync Account Positions is an additional option that has NinjaTrader submit an order to the account to sync the account position to the position calculated by the strategy. (Not the other way around.)

            Adopt Account Position would be used if you want the strategy to inherit the Account Position on enablement. This requires additional programming.

            If you do not want the strategy to calculate a position from processing historical data. Simply add if (State == State.Historical) return; to the top of your strategy logic so historical processing is skipped. The strategy will then always start from a flat position because it has not calculated any orders.

            Strategy vs. Account Position — https://ninjatrader.com/support/help..._account_p.htm

            Start Behaviors — https://ninjatrader.com/support/help..._positions.htm

            We look forward to hearing from you.
            JimNinjaTrader Customer Service

            Comment


              #7
              i cannot figure out how to sync the orders with daily shutdown and startup. Is there a single article with full sample code on how to achieve it using GetRealtimeOrder ?
              In my experiment, i dont see how the Order Object != null on restart of ninjatrader.

              I am using this link as reference.



              Code:
              #region Using declarations
              using System;
              using System.Collections.Generic;
              using System.ComponentModel;
              using System.ComponentModel.DataAnnotations;
              using System.Linq;
              using System.Text;
              using System.Threading.Tasks;
              using System.Windows;
              using System.Windows.Input;
              using System.Windows.Media;
              using System.Xml.Serialization;
              using NinjaTrader.Cbi;
              using NinjaTrader.Gui;
              using NinjaTrader.Gui.Chart;
              using NinjaTrader.Gui.SuperDom;
              using NinjaTrader.Gui.Tools;
              using NinjaTrader.Data;
              using NinjaTrader.NinjaScript;
              using NinjaTrader.Core.FloatingPoint;
              using NinjaTrader.NinjaScript.Indicators;
              using NinjaTrader.NinjaScript.DrawingTools;
              
              #endregion
              using Newtonsoft.Json;
              
              using RestSharp;
              using System.IO;
              using System.Threading;
              
              
              //This namespace holds Strategies in this folder and is required. Do not change it.
              namespace NinjaTrader.NinjaScript.Strategies
              {
              public class testNTissues : Strategy
              {
              private Order TestOrderEntry,TestOrderExit;
              private double rsize;
              private string folderlocation =@"c:\temp\";
              
              
              protected override void OnStateChange()
              {
              try{
              
              if (State == State.SetDefaults)
              {
              Description = @"Enter the description for your new custom Strategy here.";
              Name = "testNTissues";
              Calculate = Calculate.OnEachTick;
              EntriesPerDirection = 1;
              EntryHandling = EntryHandling.AllEntries;
              
              IsExitOnSessionCloseStrategy = false;
              ExitOnSessionCloseSeconds = 30;
              IsFillLimitOnTouch = false;
              MaximumBarsLookBack = MaximumBarsLookBack.Infinite;
              OrderFillResolution = OrderFillResolution.Standard;
              Slippage = 0;
              StartBehavior = StartBehavior.AdoptAccountPosition;
              IsAdoptAccountPositionAware = true;
              TimeInForce = TimeInForce.Gtc;
              TraceOrders = true;
              RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
              StopTargetHandling = StopTargetHandling.PerEntryExecution;
              IsUnmanaged = false;
              // to be customized.
              BarsRequiredToTrade = 100;// THIS NEEDS TO BE CUSTOMIZED.
              // Disable this property for performance gains in Strategy Analyzer optimizations
              // See the Help Guide for additional information
              IsInstantiatedOnEachOptimizationIteration = true;
              PrintTo = PrintTo.OutputTab1;
              //AddPlot(Brushes.Orange, "LongStop");
              // AddPlot(Brushes.Tomato, "ShortStop");
              }
              
              
              
              else if (State == State.Realtime)
              {
              
              if (TestOrderEntry != null){
              Print("before TestOrderEntry" + TestOrderEntry.ToString());
              TestOrderEntry = GetRealtimeOrder(TestOrderEntry);
              }
              if (TestOrderEntry != null){
              Print("after TestOrderEntry" + TestOrderExit.ToString());
              }
              
              if (TestOrderExit != null){
              Print("before TestOrderEntry" + TestOrderEntry.ToString());
              
              TestOrderExit = GetRealtimeOrder(TestOrderExit);
              }
              if (TestOrderExit != null){
              Print("after TestOrderExit" + TestOrderExit.ToString());
              }
              
              
              }
              
              }
              catch (Exception e)
              {
              Print("current state is " + State.ToString());
              Print(DateTime.Now + e.Message + e.StackTrace);
              
              }
              }
              
              
              
              protected override void OnBarUpdate()
              {
              try
              {
              
              
              if (State != State.Realtime)
              return;
              
              
              
              
              //Add your custom strategy logic here.
              switch (Position.MarketPosition)
              {
              case MarketPosition.Flat:
              if(TestOrderEntry ==null && Close[0]>Low[1]){
              TestOrderEntry= EnterLongLimit(0,true,1, Low[1],"TestOrderEntry");
              
              }
              break;
              case MarketPosition.Long:
              
              if(IsFirstTickOfBar && BarsSinceEntryExecution(0,"TestOrderEntry",0) >1)
              {
              TestOrderExit= ExitLongLimit(0,true,1, High[1],"TestOrderExit",TestOrderEntry.FromEntrySignal );
              }
              break;
              }
              
              }
              catch (Exception e)
              {
              Print(DateTime.Now + "onbarupdate" + e.Message + e.StackTrace);
              
              }
              
              }
              protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice,
              int quantity, int filled, double averageFillPrice,
              Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
              {
              try
              {
              
              // Assign entryOrder in OnOrderUpdate() to ensure the assignment occurs when expected.
              // This is more reliable than assigning Order objects in OnBarUpdate, as the assignment is not gauranteed to be complete if it is referenced immediately after submitting
              Print(State.ToString() + order.ToString());
              switch (order.Name)
              {
              case "TestOrderEntry":
              TestOrderEntry= order;
              
              
              
              
              break;
              
              case "TestOrderExit":
              TestOrderExit = order;
              
              
              break;
              
              
              
              
              }
              if (order.OrderState == OrderState.Rejected)
              {
              Print(order.OrderState);
              }
              
              }
              catch (Exception e)
              {
              Print("OnOrderUpdate" +order.ToString() + e.StackTrace);
              
              }
              
              }
              
              
              
              private void WriteException(Exception e)
              {
              Print(e.StackTrace);
              }
              private void WriteMessage(string message)
              {
              
              Print(message);
              
              }
              
              public DateTime currTime()
              {
              DateTime dt = DateTime.Now;
              try
              {
              
              // return Cbi.Connection.PlaybackConnection.Status.ToString( )=="Connected"?Cbi.Connection.PlaybackConnection.N ow:Time[0]
              dt = Cbi.Connection.PlaybackConnection != null ? Cbi.Connection.PlaybackConnection.Now : DateTime.Now;
              
              }
              catch (Exception e)
              {
              Print(e.StackTrace);
              WriteException(e);
              }
              return dt;
              
              }
              
              }
              
              
              
              
              }

              Comment


                #8
                Hello junkone,

                Thank you for your reply.

                You're only submitting orders if the strategy is running in real time:

                if (State != State.Realtime) return;

                There wouldn't be any historical orders calculated prior to real time, so I would expect that checking for an order object would return as null.

                I'm attaching a strategy my colleague Alan created that demonstrates adopting an account position below.

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

                Comment


                  #9
                  here is the condition that i need a sample code that i am still searching for.

                  if i have a open trade with a target order on friday EOD. i would like to restart my ninjatrader nightly. and when i open my ninjatrader on monday and want to modify the open order.

                  I have a sample that gets the access to the order object before state goes realtime but it gets cancelled immeidately after the state goes realtime. how do i stop ninjatrader to cancel live orders issued by the strategy before the restart.

                  The documentation states "If you have existing historical order references which have transitioned to real-time, you MUST update the order object reference to the newly submitted real-time order; otherwise errors may occur as you attempt to cancel the order. You may use the GetRealtimeOrder() helper method to assist in this transition." https://ninjatrader.com/support/help..._positions.htm
                  Pl show a full example code for this demonstrating a open order before the restart and how the order got transitioned from historical to realtime.
                  Attached Files
                  Last edited by junkone; 10-17-2021, 09:40 PM.

                  Comment


                    #10
                    Hello junkone,

                    Thank you for your reply.

                    Your strategy isn't calculating any historical orders as I mentioned above. Since the strategy doesn't calculate historically, any working orders would not match a calculated strategy order. So if you turn this off with your working order, when you restart, any working orders on the account would not match an order calculated by the strategy previously and the order would be cancelled due to this rule:

                    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.

                    Since there is no historical position calculated, GetRealTimeOrder won't do anything - there's no historical order that's been calculated there. I would suggest not using IsAdoptAccountPositionAware here and instead using either Immediately Submit, Synchronize Account as well as allowing the strategy to calculate over historical data by removing these two lines in OnBarUpdate:

                    if (State == State.Historical) return;

                    if (State != State.Realtime)
                    return;

                    Those two lines both keep anything from getting calculated on historical data and are keeping your strategy from recognizing prior positions/orders. Adding intrabar granularity by adding a 1 tick series to your script and submitting orders to that series along with using Tick Replay on the chart for calculating indicators can help the system recognize prior positions. The advantage of using Immediately Submit, Synchronize Account would be that if it doesn't recognize the orders it would cancel and submit new ones according to the positions it has calculated historically.

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

                    Comment


                      #11
                      what should the code do when state is in Historical?
                      is there a sample that does this correctly?

                      i have spent a week and researched every forum thread using GetRealtimeOrder as keyword and could not find out how Ninjatrader will be able retain the order without cancelling it after restart.
                      here is the vanilla version using the examples shared in documetation and ninjatrader continues to cancel the order after restart . Prove me an example or i think this feature of ninjatrader simply does not work.
                      Attached Files
                      Last edited by junkone; 10-19-2021, 11:11 AM.

                      Comment


                        #12
                        Hello junkone,

                        Thank you for your reply.

                        In the above script you are still only submitting orders in real time as we've repeatedly discussed previously. You are not processing over historical data, so it will not be able to match any orders to ones calculated historically nor will anything be transitioned because there are no historical orders for the existing order to be mapped to.

                        //Add your custom strategy logic here.
                        if(State==State.Realtime){
                        if (entryOrder == null && Close[0] > Open[0] )
                        entryOrder = EnterLongLimit(0,true,1,Low[0],"myEntryOrder");
                        else
                        Print("OnBarUpdate()" + entryOrder.ToString());
                        }

                        You would need to remove this for the strategy to process on historical data and be able to match orders instead of cancelling the existing order.

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

                        Comment


                          #13
                          ok. i removed the filtering to State==State.Realtime
                          it still cancels the order after starting up.
                          just to clarify what i did.

                          1. open chart eurchf @ 1 minute
                          2. attach strategy.
                          3. start strategy
                          4. it opens new order with limit price 1
                          5. i stop and start the strategy.

                          My expection is that the limit order @ 1 remains as it is.
                          NT cancels the limit order @ 1
                          and it reissues a new limit order @ 1 after a while.

                          Why is my open order getting cancelled?
                          Attached Files

                          Comment


                            #14
                            Hello junkone,

                            Thank you for your reply.

                            I've revised your test script to remove the try/catch bits and also so it will assign the order to entryOrder in OnOrderUpdate as we suggest assigning this there instead of OnBarUpdate and I am seeing the order be picked back up when the strategy is restarted - I'm not seeing it cancel the order. Do you see the same on your end?

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

                            Comment


                              #15
                              Kate, thank you for helping me out here. However, here is my feedback.
                              This method of restarting Ninjatrader and retaining the order is not documented properly. There are 1000 pieces of the jigsaw puzzle with 12 references to getRealtimeorder(). None of these references portray the full picture of strategy life cycle from startup.

                              what i need to see if how the entire strategy starts and the different phases it goes through. if there is a good detailed document, it will be helpful.

                              I attempted to peek into it by printing sequence number and find it interesting that the entire life cycle is like a replay of what my strategy instance went though for the last 20 days.
                              I will need to review this again especially when i set it up against my broker vs against sim a/c
                              Attached Files
                              Last edited by NinjaTrader_Kate; 10-25-2021, 03:14 PM.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Pattontje, Yesterday, 02:10 PM
                              2 responses
                              14 views
                              0 likes
                              Last Post Pattontje  
                              Started by flybuzz, 04-21-2024, 04:07 PM
                              17 responses
                              229 views
                              0 likes
                              Last Post TradingLoss  
                              Started by agclub, 04-21-2024, 08:57 PM
                              3 responses
                              17 views
                              0 likes
                              Last Post TradingLoss  
                              Started by TradingLoss, 04-21-2024, 04:32 PM
                              4 responses
                              44 views
                              2 likes
                              Last Post TradingLoss  
                              Started by cre8able, 04-17-2024, 04:16 PM
                              6 responses
                              56 views
                              0 likes
                              Last Post cre8able  
                              Working...
                              X