how to deal with ninjatrader cancelling open orders

Discussion in 'Automated Trading' started by junkone, Nov 12, 2021.

  1. junkone

    junkone

    whenever i restart ninjatrader and restart my strategy, it cancels my oopen orders. i have a long thread with them on thier forum and still cannot figure out how to prevent NT from cancelling my existing orders.
    does anyone have a clear methodlogy. I am sure there must be a way to deal with this but i dont have a good understanding of the strategy startup and how to prevent this situation.
     
  2. RedDuke

    RedDuke

    We added logic in a strategy to resubmit them. The code is quote simple:

    if(myOrder.OrderState == OrderState.Cancelled ||
    myOrder.OrderState == OrderState.Rejected){

    add logic here to resubmit stop loss and take profit orders
    }
     
  3. xandman

    xandman

    So, there is no global setting to cancel all orders on shutdown?
     
  4. RedDuke

    RedDuke

    there is, but I do not think canceling stops is a good idea :sneaky:
     
    xandman likes this.
  5. junkone

    junkone

    i think we are getting side tracked.
    Here is the situation.
    • my strategy place a entry order either for enttry or exit depending on strategy state
    • i restart ninjatrader as part of daily mainteance.
    • the open orders gets cancelled out by ninjatrader as its internal logic reviews to see if the open orders cannot be found in its internal collection.
    • for the life of me, i cannot get NT to not cancel my open orders on starting the strategy.


    • 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
      
      //This namespace holds Strategies in this folder and is required. Do not change it.
      namespace NinjaTrader.NinjaScript.Strategies
      {
          public class restartdailyexampleRevised2 : Strategy
          {
              private Order entryOrder = null, exitOrder = null;
              private bool placeexit=false;
              private double targetPrice;
              protected override void OnStateChange()
              {
                  try{
                  if (State == State.SetDefaults)
                  {
                      Description = @"Enter the description for your new custom Strategy here.";
                      Name = "restartdailyexampleRevised2";
                      Calculate = Calculate.OnBarClose;
                      EntriesPerDirection = 1;
                      EntryHandling = EntryHandling.AllEntries;
                      IsExitOnSessionCloseStrategy = true;
                      ExitOnSessionCloseSeconds = 30;
                      IsFillLimitOnTouch = false;
                      MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
                      OrderFillResolution = OrderFillResolution.Standard;
                      Slippage = 0;
                      //StartBehavior = StartBehavior.ImmediatelySubmitSynchronizeAccount;
                        StartBehavior = StartBehavior.WaitUntilFlat;
                      TimeInForce = TimeInForce.Gtc;
                      TraceOrders = true;
                      RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
                      StopTargetHandling = StopTargetHandling.PerEntryExecution;
                      BarsRequiredToTrade = 20;
                       IsAdoptAccountPositionAware = true;
                      // Disable this property for performance gains in Strategy Analyzer optimizations
                      // See the Help Guide for additional information
                      IsInstantiatedOnEachOptimizationIteration = true;
                  }
                  else if (State == State.Configure)
                  {
                       AddDataSeries(BarsPeriodType.Tick, 1);
                  }
                  // one time only, as we transition from historical to real-time
                  else if (State == State.Realtime)
                  {
                      // convert any old historical order object references
                      // to the new live order submitted to the real-time account
                      if (entryOrder != null)
                      {
                          Print("found historical entry order " + entryOrder.ToString());
                          entryOrder = GetRealtimeOrder(entryOrder);
                      }
                      if (exitOrder != null)
                      {
                          Print("found historical exit order " + exitOrder.ToString());
                          exitOrder = GetRealtimeOrder(exitOrder);
                      }
      
                  }
                  }
                  catch(Exception w){
                      Print(w.StackTrace);
                  }
              }
      
              protected override void OnBarUpdate()
              {
      if(BarsInProgress==0 &&  CurrentBar>14){
          targetPrice=High[0]+ATR(14)[1];
                  if (entryOrder == null && Close[0] > Open[0] && Close[0]>Low[0] )
                      EnterLongLimit(1, true, 1, Low[0], "myEntryOrder");
                 
      }
      
      
              }
              protected override void OnExecutionUpdate(Cbi.Execution execution, string executionId, double price, int quantity,
                       Cbi.MarketPosition marketPosition, string orderId, DateTime time)
      
              {
      
      
          exitOrder = ExitLongLimit(1, true, 1, targetPrice, "myExitOrder", entryOrder.FromEntrySignal);       
      
                  Print(string.Format(" OnExecutionUpdate() Instrument: {0} Quantity: {1} Price: {2} time:{3} execution object {4}",
      
                          execution.Instrument.FullName, quantity, price, time, execution));
                 
      
      
              }
      
              protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
              {
      
                  // the code below is added to illustrate how an order ID may change through out the lifetime of the order.
                  // It is critical you update your order references in these scenarios.
                  Print("OnOrderUpdate( State " + State.ToString());
                  if (order.Name == "myEntryOrder")
                  {
      
                      entryOrder = order;
      
                      // Reset the entryOrder object to null if order was cancelled without any fill
                      if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
                      {
                          entryOrder = null;
      
                      }
                      if (State == State.Historical)
                      {
                          Print(order.OrderId);// e.g., NT-0001
                          Print(order.ToString());// e.g., NT-0001
                      }
      
                      else if (State == State.Realtime)
                      {
                          Print(order.OrderId); // e.g., 3259392555
                          Print(order.ToString());
                      }
                  }
                  if (order.Name == "myExitOrder")
                  {
      
                      exitOrder = order;
      
                      // Reset the entryOrder object to null if order was cancelled without any fill
                      if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
                      {
                          exitOrder = null;
      
                      }
                      if (State == State.Historical)
                      {
                          Print(order.OrderId);// e.g., NT-0001
                          Print(order.ToString());// e.g., NT-0001
                      }
      
                      else if (State == State.Realtime)
                      {
                          Print(order.OrderId); // e.g., 3259392555
                          Print(order.ToString());
                      }
                  }
              }
      
          }
      }
     
  6. junkone

    junkone

    this i will try.
     
  7. RedDuke

    RedDuke

    We do it all the time. Just make sure to create order object first, and then resubmit exists in relation it it. Order object will be null after restart.
     
  8. Move your account to a better brokerage house. You get what you pay for bro. Ninjatrader is a pos
     
  9. Overnight

    Overnight

    Is it doing this on your live account, or the sim account?
     
  10. RedDuke

    RedDuke

    wrong. Ninja is fantastic software that is dirt cheap. We running fully automated algos without a single glitch. Plus full power of c# at one’s disposal.
     
    #10     Nov 13, 2021
    SimpleMeLike and virtusa like this.