Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

ATM Strategy Inside Bar

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

    ATM Strategy Inside Bar

    I am making an ATM strategy on entering long on a break above an inside bar. My goal is for the strategy to enter a trade automatically and then be able to control the take profit target and stop loss manually. I followed the SampleATMStrategy but I am not having any luck on being able to compile it. Below is my code. What am I missing? My error says "The name 'atmCallbackErrorCode' does not exist in the current context" and 'atmCallbackId' does not exist in the current context"

    HTML 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 InsideBarATM : Strategy
        {
            private string atmStrategyId;
            private string atmStrategyOrderId;
            private bool    isAtmStrategyCreated    = false;
                
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description                                    = @"Enter the description for your new custom Strategy here.";
                    Name                                        = "InsideBarATM";
                    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                                    = false;
                    RealtimeErrorHandling                        = RealtimeErrorHandling.StopCancelClose;
                    StopTargetHandling                            = StopTargetHandling.PerEntryExecution;
                    BarsRequiredToTrade                            = 20;
                    // Disable this property for performance gains in Strategy Analyzer optimizations
                    // See the Help Guide for additional information
                    IsInstantiatedOnEachOptimizationIteration    = false;
                    Barssinceentry = 5;
                }
                else if (State == State.Configure)
                {
                }
            }
    
            protected override void OnBarUpdate()
            {
                if (CurrentBar < BarsRequiredToTrade)
                    return;
                
                isAtmStrategyCreated = false;
                atmStrategyId = GetAtmStrategyUniqueId();
                  atmStrategyOrderId = GetAtmStrategyUniqueId();
                
                if(High[2]>High[1] && Low[2]<Low[1] && Close[0]>High[1] && Low[0]>Low[1])
                    AtmStrategyCreate(OrderAction.Buy,OrderType.Market,0,0,TimeInForce.Day,atmStrategyOrderId,"Test",atmStrategyId,(atmCallbackErrorCode,atmCallbackId));
                if (atmCallbackErrorCode == ErrorCode.NoError && atmCallBackId == atmStrategyId)
                            isAtmStrategyCreated = true;
                if(BarsSinceEntryExecution()>Barssinceentry)
                    ExitLong();
            }
            
            #region Properties
            [Range(1, int.MaxValue), NinjaScriptProperty]
            [Display(ResourceType = typeof(Custom.Resource), Name = "Bars Since Entry", GroupName = "NinjaScriptStrategyParameters", Order = 0)]
            public int Barssinceentry
            { get; set; }
            #endregion
        }
    }
    
    ​

    #2
    Hello algospoke,

    atmCallbackErrorCode and atmCallbackId only exist within the callback function of AtmStrategyCreate(), and cannot be used outside of it in the conditions you have.

    The help guide provides sample code.


    AtmStrategyCreate(OrderAction.Buy, OrderType.Market, 0, 0, TimeInForce.Day,
    atmStrategyOrderId, "MyTemplate", atmStrategyId, (atmCallbackErrorCode, atmCallbackId) => { // <-- this opening curly brace is the start of the callback function block
    if (atmCallbackId == atmStrategyId)
    {
    if (atmCallbackErrorCode == Cbi.ErrorCode.NoError)
    {
    isAtmStrategyCreated = true;
    }
    }
    });​ // <-- this closing curly brace is the end of the callback function block


    Further, AtmStrategy methods will not be seen by the strategy position, order method overrides, or properties.

    From the help guide
    "Executions from ATM Strategies will not have an impact on the hosting NinjaScript strategy position and PnL - the NinjaScript strategy hands off the execution aspects to the ATM, thus no monitoring via the regular NinjaScript strategy methods will take place (also applies to strategy performance tracking)"


    This means that BarsSinceEntryExecution() and ExitLong() will not work on orders created with AtmStrategy methods.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Chelsea,

      Thanks for the reply. I was able to revise my code but it won't enter a trade even though the conditions are true. I added a Print so that I can verify a trade should be executed but it never does. I am using the playback feature. See below for updated code. Also, how do I add a 8 tick profit target and and 20 tick stop loss immediately once a buy is executed? Alternatively, how can I set the profit target and stop loss equivalent to a price (for example setting profit target equal to High[2] and stop loss equal to Low[2]) ?

      HTML 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 InsideBarATM : Strategy
          {
              private string atmStrategyId;
              private string atmStrategyOrderId;
              private bool    isAtmStrategyCreated    = false;
                  
              protected override void OnStateChange()
              {
                  if (State == State.SetDefaults)
                  {
                      Description                                    = @"Enter the description for your new custom Strategy here.";
                      Name                                        = "InsideBarATM";
                      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                                    = false;
                      RealtimeErrorHandling                        = RealtimeErrorHandling.StopCancelClose;
                      StopTargetHandling                            = StopTargetHandling.PerEntryExecution;
                      BarsRequiredToTrade                            = 20;
                      // Disable this property for performance gains in Strategy Analyzer optimizations
                      // See the Help Guide for additional information
                      IsInstantiatedOnEachOptimizationIteration    = false;
                  }
                  else if (State == State.Configure)
                  {
                  }
              }
      
              protected override void OnBarUpdate()
              {
                  if (CurrentBar < BarsRequiredToTrade)
                      return;
                  if (State < State.Realtime)
                        return;
                  
                  isAtmStrategyCreated = false;
                  atmStrategyId = GetAtmStrategyUniqueId();
                    atmStrategyOrderId = GetAtmStrategyUniqueId();
                  
                  if(High[2]>High[1] && Low[2]<Low[1] && Close[0]>High[1] && Low[0]>Low[1])
                  {
                      Print(Time[0].ToString() + "| Long  ");
                      AtmStrategyCreate(OrderAction.Buy,OrderType.Market,0,0,TimeInForce.Day,atmStrategyOrderId,"Test",atmStrategyId,(atmCallbackErrorCode,atmCallbackId)=>{
                  if(atmCallbackId == atmStrategyId)
                  {
                      if(atmCallbackErrorCode == Cbi.ErrorCode.NoError)
                      {
                          isAtmStrategyCreated = true;
                      }
                  }
                  });
                  }
              #region Properties
              
              #endregion
          }
      }
      }
      
      ​

      Comment


        #4
        Hello algospoke,

        May I confirm that you have saved an Atm template with the name "Test"?

        Please provide a screenshot of this template.

        "Also, how do I add a 8 tick profit target and and 20 tick stop loss immediately once a buy is executed?"

        If you are using AtmStrategy methods, you would need to setup the stop and target in the Atm template.

        If you want to submit the stop and target from code and not use the AtmStrategy, then don't use AtmStrategyCreate() and use SetStopLoss(CalculationMode.Ticks, 20); and SetProfitTarget(CalculationMode.Ticks, 8); and submit the order with EnterLong() instead.

        "Alternatively, how can I set the profit target and stop loss equivalent to a price (for example setting profit target equal to High[2] and stop loss equal to Low[2])"

        Don't use AtmStrategy methods. Use EnterLong() to enter the position.
        In OnExecutionUpdate() submit the stop and limit order at a specific price.

        if (execution.Name == "LongEntryOrderName")
        {
        if (High[2] > GetCurrentAsk())
        ExitLongLimit(1, true, 1, High[2], "profit target", "LongEntryOrderName");
        if (Low[2] < GetCurrentBid())
        ExitLongStopMarket(1, true, 1, Low[2] , "stop loss", "LongEntryOrderName");
        }
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Chelsea,

          Ok I added a ATM template called "Test" and that worked which is perfect for setting profit target and stop losses based on ticks. Thanks for the clarification on that.

          However, if I want to set profit target and stop losses based on a specific price, how do I do that with ATM? I understand your suggestion on using EnterLong(), ExitLongLimit() and ExitLongStopMarket() however, I want to have the ability to manually change the profit target and stop loss within the chart after the trade has been executed by the code. Whenever I use those commands, the profit targets and stop losses don't pop up on the chart like an ATM does. I want it to look like the attached pic so i can drag around the profit target and stop loss manually within the chart. My goal is to be able to set the profit target to the High[2] and the stop loss to be set to Low[2] however if I see some other conditions developing on the chart then I want to be able to drag the profit target/stop loss to a new price.

          Click image for larger version

Name:	NinjaATM.png
Views:	350
Size:	22.6 KB
ID:	1303936

          Thanks

          Comment


            #6
            Hello algospoke,

            This is Gaby following up for Chelsea who is out of office.

            It’s possible to manually modify stops and targets submitted by a NinjaScript Strategy by using exit methods, such as ExitLongStopMarket(), with isLiveUntilCancelled set to true.

            Make sure you have the ChartTrader open in order to view the trade markers to manually modify the stops and targets.

            ExitLongStopMarket(int barsInProgressIndex, bool isLiveUntilCancelled, int quantity, double stopPrice, string signalName, string fromEntrySignal)

            Help Guide: NinjaScript > Language Reference > Strategy > Order Methods > Managed Approach > ExitLongStopMarket()

            Using isLiveUntilCancelled set to true allows the orders to be submitted once without being updated again from the script. This will allow you to manually modify the orders without them moving back to the original price from the strategy. We suggest submitting the orders from OnExecutionUpdate() when the entry order fills.

            ManuallyModifiableStopTargetExample_NT8 demonstrates placing an exit stop and limit order which can be manually modified.

            Please let us know if you have any further questions.​
            Attached Files

            Comment


              #7
              Gaby,

              I am working on a new different strategy using the information you previously provided. Only in the past week or so, the strategy is no longer working correctly. I have NOT changed the code at all. Whenever I activate the strategy now in Playback or in a Live Simulated account, the first executed trade always ends up being 2 contracts instead of 1 and the profit target and stop losses aren't being activated. See below pic.​

              Click image for larger version

Name:	image.png
Views:	317
Size:	208.2 KB
ID:	1307571

              ​For my strategy, below is my code for my Entry:
              HTML Code:
              #region Entries Signals
                                  //Buy if current bar breaks above previous bar high
                                  if(Close[0] > High[1] && LongSignal == true)
                                  {
                                      EnterLong(NumContracts,"LongEntry");
                                      EntryPrice = Position.AveragePrice;//Get entry price to compare against the targets
                                      if(Trigger122BullTargets == true)
                                      {
                                          if(ChangeTarget == true)//Check if setting for changing target is enabled
                                          {
                                              NumOfTicks = (Bull122TargetPrice - EntryPrice)/TickSize;//compare entry price to the current target
                                              if(NumOfTicks <= TickRange)//change the profit target if current target is within the range set by the user
                                              {
                                                  Bull122TargetPrice = EntryPrice + (NewTickTarget * TickSize);
                                              }
                                          }
                                          ExitLongLimit(0,true,NumContracts,Bull122TargetPrice,"Profit Target","LongEntry");
                                          ExitLongStopMarket(0,true,NumContracts,BullStopPrice,"Stop Loss","LongEntry");
                                      }
                                      else
                                      {
                                          if(ChangeTarget == true)//Check if setting for changing target is enabled
                                          {
                                              NumOfTicks = (BullTargetPrice - EntryPrice)/TickSize;//compare entry price to the current target
                                              if(NumOfTicks <= TickRange)//change the profit target if current target is within the range set by the user
                                              {
                                                  BullTargetPrice = EntryPrice + (NewTickTarget * TickSize);
                                              }
                                          }
                                          ExitLongLimit(0,true,NumContracts,BullTargetPrice,"Profit Target","LongEntry");
                                          ExitLongStopMarket(0,true,NumContracts,BullStopPrice,"Stop Loss","LongEntry");
                                      }
                                      CheckIntraBar = false; //Reset to calculate on start of new bar instead of on each tick
                                      LongSignal = false; //Reset back to false
                                      ShortSignal = false;
                                      
                                  }
                                  //Short if current bar breaks below previous bar low
                                  else if(Close[0] < Low[1] && ShortSignal == true)
                                  {
                                      EnterShort(NumContracts,"ShortEntry");    
                                      EntryPrice = Position.AveragePrice;//Get entry price to compare against the targets
                                      if(Trigger122BearTargets == true)
                                      {
                                          if(ChangeTarget == true)//Check if setting for changing target is enabled
                                          {
                                              NumOfTicks = (EntryPrice - Bear122TargetPrice)/TickSize;//compare entry price to the current target
                                              if(NumOfTicks <= TickRange)//change the profit target if current target is within the range set by the user
                                              {
                                                  Bear122TargetPrice = EntryPrice - (NewTickTarget * TickSize);
                                              }
                                          }
                                          ExitShortLimit(0,true,NumContracts,Bear122TargetPrice,"Profit Target","ShortEntry");
                                          ExitShortStopMarket(0,true,NumContracts,BearStopPrice,"Stop Loss","ShortEntry");
                                      }
                                      else
                                      {
                                          if(ChangeTarget == true)//Check if setting for changing target is enabled
                                          {
                                              NumOfTicks = (EntryPrice - BearTargetPrice)/TickSize;//compare entry price to the current target
                                              if(NumOfTicks <= TickRange)//change the profit target if current target is within the range set by the user
                                              {
                                                  BearTargetPrice = EntryPrice - (NewTickTarget * TickSize);
                                              }
                                          }
                                          ExitShortLimit(0,true,NumContracts,BearTargetPrice,"Profit Target","ShortEntry");
                                          ExitShortStopMarket(0,true,NumContracts,BearStopPrice,"Stop Loss","ShortEntry");
                                      }
                                      CheckIntraBar = false; //Reset to calculate on start of new bar instead of on each tick
                                      LongSignal = false;
                                      ShortSignal = false; //Reset back to false
                                  }
                                  #endregion​
              Below is my code for my exits if the profit target/stop losses aren't hit:
              HTML Code:
              #region Active Position - Exits
                              //Reset Trigger122BullTargets and Trigger122BearTargets back to false after we go from an active position to a flat position
                              if(Position.MarketPosition == MarketPosition.Flat && (previousMarketPosition == MarketPosition.Long || previousMarketPosition == MarketPosition.Short))
                              {
                                  Trigger122BullTargets = false;
                                  Trigger122BearTargets = false;
                              }
                              
                              //Establish exits for Long Positions when 1-2-2 Bullish is the Strat
                              if(Position.MarketPosition == MarketPosition.Long && Trigger122BullTargets == true)
                              {
                                  if(FlipToShort == false)
                                  {
                                      previousMarketPosition = Position.MarketPosition;
                                      return; //Don't do anymore calculations below this until we exit our current trade
                                  }
                                  
                                  else if(FlipToShort == true)
                                  {
                                      previousMarketPosition = Position.MarketPosition;
                                      ExitLong();
                                      FlipToShort = false;
                                      #region Grab Profit Target & Stop Prices
                                      //For Bullish Strats - Profit Targets are the high price of 2 bars ago & Stop Price is the low of previous bar
                                      BullTargetPrice = High[2];
                                      BullStopPrice = Low[1];
                                      //For Rev Strat 1-2-2 Bullish strat - Profit Target is the high price of 3 bars ago
                                      Bull122TargetPrice = High[3];
                                      
                                      //For Bearish Strats - Profit Targets are the low price of 2 bars ago & Stop Price is the high of previous bar
                                      BearTargetPrice = Low[2];
                                      BearStopPrice = High[1];
                                      //For Rev Strat 1-2-2 strats - Profit Targets is the low price of 3 bars ago
                                      Bear122TargetPrice = Low[3];
                                      
                                      #endregion//Need to grab new targets bc they are normally grabbed on first tick but FlipToShort/Long may have happen within the bar
                                  }
                                  
                              }
                              
                              //Establish exits for Long Positions for all Strats except 1-2-2 Bullish
                              if(Position.MarketPosition == MarketPosition.Long && Trigger122BullTargets == false)
                              {
                                  if(FlipToShort == false)
                                  {
                                      previousMarketPosition = Position.MarketPosition;
                                      return;//Don't do anymore calculations below this until we exit our current trade
                                  }
                                  
                                  else if(FlipToShort == true)
                                  {
                                      previousMarketPosition = Position.MarketPosition;
                                      ExitLong();
                                      FlipToShort = false;
                                      #region Grab Profit Target & Stop Prices
                                      //For Bullish Strats - Profit Targets are the high price of 2 bars ago & Stop Price is the low of previous bar
                                      BullTargetPrice = High[2];
                                      BullStopPrice = Low[1];
                                      //For Rev Strat 1-2-2 Bullish strat - Profit Target is the high price of 3 bars ago
                                      Bull122TargetPrice = High[3];
                                      
                                      //For Bearish Strats - Profit Targets are the low price of 2 bars ago & Stop Price is the high of previous bar
                                      BearTargetPrice = Low[2];
                                      BearStopPrice = High[1];
                                      //For Rev Strat 1-2-2 strats - Profit Targets is the low price of 3 bars ago
                                      Bear122TargetPrice = Low[3];
                                      
                                      #endregion//Need to grab new targets bc they are normally grabbed on first tick but FlipToShort/Long may have happen within the bar
                                  }
                                  
                              }
                              
                              //Establish exits for Short Positions when 1-2-2 Bearish is the Strat
                              if(Position.MarketPosition == MarketPosition.Short && Trigger122BearTargets == true)
                              {
                                  if(FlipToLong == false)
                                  {
                                      previousMarketPosition = Position.MarketPosition;
                                      return;//Don't do anymore calculations below this until we exit our current trade
                                  }
                                  
                                  else if(FlipToLong == true)
                                  {
                                      previousMarketPosition = Position.MarketPosition;
                                      ExitShort();
                                      FlipToLong = false;
                                      #region Grab Profit Target & Stop Prices
                                      //For Bullish Strats - Profit Targets are the high price of 2 bars ago & Stop Price is the low of previous bar
                                      BullTargetPrice = High[2];
                                      BullStopPrice = Low[1];
                                      //For Rev Strat 1-2-2 Bullish strat - Profit Target is the high price of 3 bars ago
                                      Bull122TargetPrice = High[3];
                                      
                                      //For Bearish Strats - Profit Targets are the low price of 2 bars ago & Stop Price is the high of previous bar
                                      BearTargetPrice = Low[2];
                                      BearStopPrice = High[1];
                                      //For Rev Strat 1-2-2 strats - Profit Targets is the low price of 3 bars ago
                                      Bear122TargetPrice = Low[3];
                                      
                                      #endregion//Need to grab new targets bc they are normally grabbed on first tick but FlipToShort/Long may have happen within the bar
                                  }
                                  
                              }
                              
                              //Establish exits for Short Positions for all Strats except 1-2-2 Bearish
                              if(Position.MarketPosition == MarketPosition.Short && Trigger122BearTargets == false)
                              {
                                  if(FlipToLong == false)
                                  {
                                      previousMarketPosition = Position.MarketPosition;
                                      return;//Don't do anymore calculations below this until we exit our current trade
                                  }
                                  
                                  else if(FlipToLong == true)
                                  {
                                      previousMarketPosition = Position.MarketPosition;
                                      ExitShort();
                                      FlipToLong = false;
                                      #region Grab Profit Target & Stop Prices
                                      //For Bullish Strats - Profit Targets are the high price of 2 bars ago & Stop Price is the low of previous bar
                                      BullTargetPrice = High[2];
                                      BullStopPrice = Low[1];
                                      //For Rev Strat 1-2-2 Bullish strat - Profit Target is the high price of 3 bars ago
                                      Bull122TargetPrice = High[3];
                                      
                                      //For Bearish Strats - Profit Targets are the low price of 2 bars ago & Stop Price is the high of previous bar
                                      BearTargetPrice = Low[2];
                                      BearStopPrice = High[1];
                                      //For Rev Strat 1-2-2 strats - Profit Targets is the low price of 3 bars ago
                                      Bear122TargetPrice = Low[3];
                                      
                                      #endregion//Need to grab new targets bc they are normally grabbed on first tick but FlipToShort/Long may have happen within the bar
                                  }
                                  
                              }
                              #endregion​
              I have the variable "NumContracts" equal to 1 at all times so I am not sure why the first entry is always 2 contracts and the profit target/stop losses aren't working. Can you explain why this is happening? Like I said, this strategy has worked fine in the past but the last couple weeks it is doing this weird 2 contract entry when I activate it and the first entry is triggered. I am curious if something in Ninjascript changed recently?

              Attached Files

              Comment


                #8
                Hello algospoke,

                The ExitLongLimit() and ExitLongStopMarket() should be submitted from OnExecutionUpdate() after the entry order fills.

                See lines 46 through 55 in the ManuallyModifiableStopTargetExample_NT8 gaby has provided.

                Enable TraceOrders.

                Print the time of the bar and the value of NumContracts one line above the call to EnterLong() and EnterShort.

                Print the order.ToString() at the top of OnOrderUpdate().

                Save the output from the output window by right-clicking and selecting Save as.

                Attach the output text file to your next post, and we will be happy to assist with understanding the behavior.
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Chelsea - thanks for your response. I was able to fix some things but have some follow up questions:

                  1) How do i enable TraceOrders? Where in the code do i enable it?

                  2) I am running the same strategy on multiple instruments with different inputs. How do I assign an output window to each one of these strategies that are running?

                  3) I reran the strategy that was buying 2 contracts (even though it is always set to 1) in playback on the same day with the same inputs and it never bought 2 contracts. Why would playback be different than live?

                  4) All the strategies are applied to a chart with Trading Hours set to US Equities RTH. I went to enable all of them around 9:20am EST and a couple of them immediately entered a trade. Why would the strategy enter a trade when the data series is set to US Equities RTH?

                  Comment


                    #10
                    Hello algospoke,

                    "How do i enable TraceOrders? Where in the code do i enable it?"

                    In OnStateChange():

                    else if (State == State.Configure)
                    {
                    TraceOrders = true;
                    }

                    Below is a link to the help guide.


                    "I reran the strategy that was buying 2 contracts (even though it is always set to 1) in playback on the same day with the same inputs and it never bought 2 contracts. Why would playback be different than live?"

                    Either multiple orders are being submitted or the quantity parameter supplied was 2.

                    The output from prints and TraceOrders would provide that information.

                    "All the strategies are applied to a chart with Trading Hours set to US Equities RTH. I went to enable all of them around 9:20am EST and a couple of them immediately entered a trade. Why would the strategy enter a trade when the data series is set to US Equities RTH?"

                    If the order was a real-time order, it could be a synchronization order if using Immediately Submit Start behavior. Or possibly the chart is not using the US Equities RTH template or possibly the Trading Hours template was modified.
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      Chelsea,

                      I have multiple strategies running at the same time on different time frames and instruments. See below snip of the strategies window where I have them enabled.

                      Click image for larger version

Name:	image.png
Views:	292
Size:	9.2 KB
ID:	1309813
                      I even have them on separate chart tabs. See below pic
                      Click image for larger version

Name:	image.png
Views:	289
Size:	3.4 KB
ID:	1309814
                      How do I apply a separate output window to each of the strategies that I have running? I want separate outputs for each strategy that is active.

                      Comment


                        #12
                        Hello algospoke,

                        Unfortunately, only one output window can be opened and this only has two tabs.

                        But you could write the information to separate text files with a C# StreamWriter.
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          Chelsea,

                          I ran the same strategy on 7/12 and again it is trading more than 1 contract even tho NumContracts is always set to 1. I am trying to upload excel files of the Orders, Log, and Executions for the day but I am unable to. What is the best way to show you those if i can't upload excel files? Will that assist in determining what is going wrong with my strategy?

                          Also, I have the "Exit on Session close" enabled for the strategy however, it reentered right after it actually exited on session close. See below pic of the orders log. Why would it reenter?

                          Click image for larger version

Name:	image.png
Views:	287
Size:	40.7 KB
ID:	1310811

                          Comment


                            #14
                            Hello algospoke,

                            I'm not seeing any entry orders with a quantity of more than 1.

                            Are you asking about multiple entries?

                            Below is a link to an example that demonstrates preventing new entries after the Exit on session close.
                            Chelsea B.NinjaTrader Customer Service

                            Comment


                              #15
                              Chelsea,

                              I am trying to upload excel files of the Orders, Log, and Executions for the day to show you the multiple entries but I am unable to. What is the best way to show you those if i can't upload excel files?

                              Also, when I enable a strategy in the middle of the RTH, sometimes it will enter a trade immediately after I enable a strategy. Is there a way to code the strategy so that when I enable it, it won't enter a trade until the next new bar?

                              Thanks

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by NullPointStrategies, Today, 05:17 AM
                              0 responses
                              44 views
                              0 likes
                              Last Post NullPointStrategies  
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              126 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              65 views
                              0 likes
                              Last Post NabilKhattabi  
                              Started by Deep42, 03-06-2026, 12:28 AM
                              0 responses
                              42 views
                              0 likes
                              Last Post Deep42
                              by Deep42
                               
                              Started by TheRealMorford, 03-05-2026, 06:15 PM
                              0 responses
                              46 views
                              0 likes
                              Last Post TheRealMorford  
                              Working...
                              X