Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

ATM Strategy Inside Bar

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

    #16
    Hello algospoke,

    The log and trace can contain sensitive information. Do not post these on the forums.
    Instead email these to support [at] ninjatrader.com.

    "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?"

    if (State == State.Historical || IsFirstTickOfBar == false)
    return;
    Chelsea B.NinjaTrader Customer Service

    Comment


      #17
      Chelsea,

      When I enabled my strategy today around 9:20am EST on a ES chart on RTH, it immediately wanted to enter a short position. See below pic:
      Click image for larger version

Name:	image.png
Views:	108
Size:	8.0 KB
ID:	1311251

      It didn't take the trade until market open at 9:30am EST. It immediatley entered and exited. It did it twice right at 9:30am (Entered-> exited then Entered->exited). Below is a snip of my code. What am I doing wrong?

      ​​Click image for larger version

Name:	image.png
Views:	103
Size:	27.2 KB
ID:	1311252

      Comment


        #18
        Hello algospoke,

        Add debugging prints and enable TraceOrders to understand behavior.


        It doesn't look like this is the code that sent an entry order. Add print within the condition. Is the print appearing in the output window?
        Add a print to the code you haven't provided that submits an entry order. Is the print appearing?
        Chelsea B.NinjaTrader Customer Service

        Comment


          #19
          Chelsea,

          When I enter a long position, below is the code I am using within OnBarUpdate:
          HTML Code:
          if(Close[0] > High[1] && LongSignal == true && Low[0] > Low[1])
                              {
                                  EnterLong(NumContracts,"LongEntry");
                                  Print(Time[0].ToString() + "| Enter Long");
                              }​
          Once in a long position, I have have the below code within OnExecutionUpdate that helps creates an active profit target and stop loss order:
          HTML Code:
          if(execution.Name == "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);
                                          }
                                      }
                                      if(MaxPT == true)//Check if setting is enabled for setting the max profit target
                                      {
                                          NumOfTicks = (Bull122TargetPrice - EntryPrice)/TickSize;//compare entry price to the current target
                                          if(NumOfTicks >= MaxPTTicks)
                                          {
                                              Bull122TargetPrice = EntryPrice + (MaxPTTicks * TickSize);
                                          }
                                      }
                                      if(MaxSL == true)//Check if setting is enabled for setting the max stop loss
                                      {
                                          NumOfTicks = (EntryPrice - BullStopPrice)/TickSize;
                                          if(NumOfTicks >= MaxSLTicks)
                                          {
                                              BullStopPrice = EntryPrice - (MaxSLTicks * TickSize);
                                          }
                                      }
                                      
                                      ExitLongLimit(0,true,NumContracts,Bull122TargetPrice,"Profit Target","LongEntry");
                                      ExitLongStopMarket(0,true,NumContracts,BullStopPrice,"Stop Loss","LongEntry");
                                      Print(Time[0].ToString() + "Entry Price: " + EntryPrice + "| PT & SL Orders are set" + "| Profit Target Price: " + Bull122TargetPrice + "| Stop Loss Price: " + BullStopPrice);
                                  }
                                  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);
                                          }
                                      }
                                      if(MaxPT == true)//Check if setting is enabled for setting the max profit target
                                      {
                                          NumOfTicks = (BullTargetPrice - EntryPrice)/TickSize;//compare entry price to the current target
                                          if(NumOfTicks >= MaxPTTicks)
                                          {
                                              BullTargetPrice = EntryPrice + (MaxPTTicks * TickSize);
                                          }
                                      }
                                      if(MaxSL == true)//Check if setting is enabled for setting the max stop loss
                                      {
                                          NumOfTicks = (EntryPrice - BullStopPrice)/TickSize;
                                          if(NumOfTicks >= MaxSLTicks)
                                          {
                                              BullStopPrice = EntryPrice - (MaxSLTicks * TickSize);
                                          }
                                      }
                                      
                                      ExitLongLimit(0,true,NumContracts,BullTargetPrice,"Profit Target","LongEntry");
                                      ExitLongStopMarket(0,true,NumContracts,BullStopPrice,"Stop Loss","LongEntry");
                                      Print(Time[0].ToString() + "Entry Price: " + EntryPrice + "| PT & SL Orders are set" + "| Profit Target Price: " + BullTargetPrice + "| Stop Loss Price: " + BullStopPrice);
                                  }
                      }​
          However, there may be a situation in which I want to get out of my long position immediately and switch to a short position because conditions have changed and I haven't reached my profit target or stop loss yet. For those cases, I put the below code:
          HTML Code:
          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();
                                  Print(Time[0].ToString() + "| Exit current Long to Flip to Short");
                                  FlipToShort = false;
                                  #region Grab Profit Target & Stop Prices
                                 
                                  BullTargetPrice = High[2];
                                  BullStopPrice = Low[1];
                                
                                  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];
                                 
                                  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
                              }​
          If the conditions change and my ExitLong() gets executed, the profit target and stop loss orders are still active. My question is, how do I cancel all active orders? For example, after the ExitLong() line I want to put a line of code that says cancel all active orders.

          Comment


            #20
            Hello algospoke,

            You would need to use Exit methods (or unmanaged approach) and assign the orders to variables in OnOrderUpdate(). (Set methods cannot be cancelled)
            Then when you want to cancel, check the <order>.OrderState is OrderState.Working or OrderState.Accepted and supply the order variable to CancelOrder().

            The ProfitCasestopTrailExitOrdersExample linked below has sample code of assigning orders to variables and supplying the order variable to CancelOrder().
            Chelsea B.NinjaTrader Customer Service

            Comment


              #21
              Chelsea,

              I have added the session iterator as you suggested for preventing an orders after exit on session close however, when I enable the strategy right now in the middle of the trading day, the exitOnCloseWait stays true. I ran a print and you can see on the historical prints that it works fine with switching from false during the normal trading hours and then switches to true once we get to session close. Not sure why its not working once I enable in mid trading day as it just stays true. Below is my code. Any ideas what is wrong?

              Click image for larger version

Name:	image.png
Views:	119
Size:	52.3 KB
ID:	1312574

              Also, another issue I am having is that the strategy will immediately enter a trade when I enable it. I thought i fixed it with the if(IsFirstTickOfBar == false) return (seen above under historical). It works fine on playback but not when I enable strategy mid trading hours. Any ideas?

              Thanks

              Comment


                #22
                Hello algospoke,

                Try setting exitOnCloseWait to false in State.DataLoaded.

                As this is a demonstration script, the position is exited on the last historical bar on lines 140 to 149 so that the strategy will immediately place a real-time order to demonstrate the behavior with real-time orders.

                This strategy places a new entry any time the order variables are null.
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #23
                  Chelsea,

                  I tried setting exitOnCloseWait == false in State.DataLoaded but same thing is happening where it immediately goes to true when I enable strategy. See below print:
                  Click image for larger version

Name:	image.png
Views:	100
Size:	17.3 KB
ID:	1312649
                  See below snip of code where I have it set to false in both the State.SetDefaults and Dataloaded. What else am I missing?

                  Click image for larger version

Name:	image.png
Views:	97
Size:	54.1 KB
ID:	1312650

                  Comment


                    #24
                    Hello algospoke,

                    This would imply a condition has set the value to true.

                    Find each line that sets exitOnCloseWait to true, and for the condition this is in print the values in the condition and comparision operators to understand why the condition is evaluating as true.

                    It might be due to the interval of the chart being a bar that is closing during the end of the session time.
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #25
                      Chelsea,

                      I did a "Quick Find" to see where exitOnCloseWait is called and there is no other locations where it is set to true. I just tried adding an else statement that seems to have allow it to work. See below circled in red. However when I look at the output window it flips between true and false constantly. Why is this happening? I am only printing it once in the code as you can see in the below code but it is showing up at the current time and at 4pm (session close). FYI, for reference, I am using ES 5 min chart and have 365 days RTH of historical data loaded and the strategy calculates on each tick.

                      Click image for larger version

Name:	image.png
Views:	107
Size:	31.4 KB
ID:	1312671
                      Click image for larger version

Name:	image.png
Views:	94
Size:	11.8 KB
ID:	1312672

                      Comment


                        #26
                        Hello algospoke,

                        Possibly because it's set to true because the bar time is between the end of session time and then set back to false because the bar is the first bar of the session.

                        The output from the requested prints should tell us more.

                        I look forward to receiving these.
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #27
                          Chelsea,

                          I fixed the issue. Thanks for your help. However, I am still having an issue where if I enable the strategy in the middle of the trading day, sometimes the strategy will enter immediately when I enable it. See below for the code circled in red that I have under (State == State.Historical). I thought this would fix it but its not working. What am I doing wrong?

                          Click image for larger version

Name:	image.png
Views:	88
Size:	28.4 KB
ID:	1313699

                          Comment


                            #28
                            Hello algospoke,

                            This condition and action are in OnStateChange() and are not in OnBarUpdate(). This isn't going to prevent OnBarUpdate() from running. It's just going to return out of the OnStateChange() method.

                            Put the code in OnBarUpdate() if you want this to return out of OnBarUpdate().
                            Chelsea B.NinjaTrader Customer Service

                            Comment


                              #29
                              Chelsea,

                              I am confused. I can't put if(IsFirstTickOfBar == false) return under OnBarUpdate because my code has a bunch of calculations that occur on IsFirstTickOfBar. When I enable the strategy in the middle of the current bar I want to wait til the bar is closed before my code under OnBarUpdate occurs. See your previous post above on 07-17-2024, 05:12 AM where you suggest putting it under Historical but that doesn't seem to work either.

                              Thanks

                              Comment


                                #30
                                Hello algospoke,

                                IsFirstTickOfBar is true on the first tick of a bar updating OnBarUpdate(). This property has no use outside of OnBarUpdate().

                                Returning in OnStateChange() will not prevent OnBarUpdate() from running.

                                "See your previous post above on 07-17-2024, 05:12 AM where you suggest putting it under Historical but that doesn't seem to work either."

                                I'm not sure what you are referring to. Post # 28 does not say to put this code in OnStateChange().

                                "When I enable the strategy in the middle of the current bar I want to wait til the bar is closed before my code under OnBarUpdate occurs."

                                This would only be possible by putting the code in OnBarUpdate().
                                Chelsea B.NinjaTrader Customer Service

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by NullPointStrategies, Today, 05:17 AM
                                0 responses
                                50 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
                                69 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