Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Automatically flatten the account at the end of the session

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

    Automatically flatten the account at the end of the session

    Hello,

    My current simple MA crossover strategy sometimes opens a position in the very last second of the market close, and I need to prevent that. I was thinking to use Flatten() as follows,

    Code:
    Account.Flatten(new[]{Instrument.GetInstrument("MES DEC23")});​

    but I have two issues with this: First, I'm unsure how to set a specific time for this (end of NY session i.e. 4pm ET). Second, I'm worried that even after flattening all positions, the strategy might still open new ones. If there's a more effective way to ensure that the strategy not only refrains from opening new positions but also closes all existing ones by the market's end, I would greatly appreciate your assistance. Thank you very much!
    Last edited by rezamerik; 11-05-2023, 09:51 PM.

    #2
    Hello rezamerik,

    Thank you for your post.

    Please see these example scripts from the forum post linked below, which demonstrate how to prevent a new entry after the exit on session close by using a SessionIterator.

    SessionIterator - https://ninjatrader.com/support/help...oniterator.htm

    https://forum.ninjatrader.com/forum/...ose#post100666

    If you have any questions, please let me know.

    Comment


      #3
      Hi NinjaTrader_Gaby! Thank you for your response. I appreciated the idea of skipping the last bar of the session in post Uncategorized Groups of the thread you shared. However, I'm having trouble implementing it. While I can compile the strategy without errors, my backtests still show the strategy opens trades on the last bar! As mentioned before, I'm using a simple crossover strategy, and here is the code I've written:

      Code:
      protected override void OnBarUpdate()
      {
      
          if (CurrentBar < BarsRequiredToTrade)
              return;
      
          if (Bars.IsLastBarOfSession)
              return;
      
          if (CrossAbove(smaFast, smaSlow, 1))
              EnterLong();
          else if (CrossBelow(smaFast, smaSlow, 1))
              EnterShort();
      
      }​

      The logic seems correct, but it's puzzling that the strategy is still opening positions on the last bar. Can you please help me identify what I might be missing? Thank you.

      Comment


        #4
        Hello,

        First, what bar period are you using? From the Help Guide:

        "This property will always return false on non-intraday bar periods (e.g., Day, Month, etc.)"

        https://ninjatrader.com/support/help...rofsession.htm


        In order to better understand how the code is working, it will be necessary to use Print to see how the conditions are evaluating and enable TraceOrders to see if orders are being submitted, ignored, rejected, or cancelled.

        Below is a link to a forum post that demonstrates using prints to understand behavior and includes a link to a video recorded using the Strategy Builder to add prints.

        https://ninjatrader.com/support/foru...121#post791121

        Enable TraceOrders, print the time of the bar and all values used in the conditions that submit entry orders. Include labels for all values and comparison operators.

        Let me know if you need any assistance creating a print or enabling TraceOrders.

        Save the output from the output window to a text file and provide this with your reply.

        I'll be happy to assist with analyzing the output.

        Comment


          #5
          Thanks so much for the info Gaby! I've rewritten my code as shown below, and it compiles without any errors. However, the output window remains empty. Do you have any insights into what might be causing this issue? I'd be more than willing to share the entire strategy code if that would assist you. Thank you once again.

          Code:
          protected override void OnBarUpdate()
          {
          
          if (CurrentBar < BarsRequiredToTrade)
          return;
          
          if (Bars.IsLastBarOfSession)
          return;
          
          // Print the time of the bar
          Print("Bar Time: " + Time[0]);
          
          // Define the conditions for entering a long or short position
          bool conditionLong = CrossAbove(smaFast, smaSlow, 1);
          bool conditionShort = CrossBelow(smaFast, smaSlow, 1);
          
          // Print the values and comparison operators used
          Print("smaFast: " + smaFast[0]);
          Print("smaSlow: " + smaSlow[0]);
          Print("Condition Long: " + conditionLong);
          Print("Condition Short: " + conditionShort);
          
          // Submit entry orders based on the conditions
          if (conditionLong)
          {
          Print("Entering Long");
          EnterLong();
          }
          else if (conditionShort)
          {
          Print("Entering Short");
          EnterShort();
          }
          
          {
          TraceOrders = true;
          }
          
          }​

          Comment


            #6
            Hello,

            Depending on the bar type used, the Bars.IsLastBarOfSession may not have a value of false. Print this to the output window one line above the condition to confirm.

            Code:
            Print(Time[0] + " | Bars.IsLastBarOfSession: " + Bars.IsLastBarOfSession.ToString());
            
            if (Bars.IsLastBarOfSession)
            
            return;
            Also, can we confirm the script has been enabled?

            Are there errors appearing on the Log tab of the Control Center when the script is enabled?

            Comment


              #7
              Hi Gaby - my bad, it turned out I had made a mistake in the code, but it's all fixed now. I've attached the output file below. Since I'm using eight-minute bars, the Bars.IsLastBarOfSession condition is working fine.

              There's one specific trade that shouldn't open in the last bar, but it does, and I'm getting some strange prints. The strategy closes this position on the first bar of the next session, and that also generates prints that I don't quite understand. I'd love to hear your insights on this. Pleae let me know if you need anything else and thank you!

              P.S. here's the relevant output:


              Code:
              Bar Time: 6/20/2023 12:54:00 PM
              smaFast: 15461.6666666667
              smaSlow: 15458.6539473684
              Condition Long: True
              Condition Short: False
              Entering Long
              6/20/2023 12:54:00 PM Strategy 'MACrossover/-1': Entered internal SubmitOrderManaged() method at 6/20/2023 12:54:00 PM: BarsInProgress=0 Action=Buy OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal=''
              Bar Time: 6/21/2023 6:38:00 AM
              smaFast: 15436.75
              smaSlow: 15459.4578947368
              Condition Long: False
              Condition Short: True
              Entering Short
              6/21/2023 6:38:00 AM Strategy 'MACrossover/-1': Entered internal SubmitOrderManaged() method at 6/21/2023 6:38:00 AM: BarsInProgress=0 Action=SellShort OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal=''​
              Attached Files

              Comment


                #8
                Hello,

                Thank you for your response.

                Are you using the Print statement to check if your isLastBarOfSession return statement is working? This should be preventing your script from entering a trade on the last bar. I am not seeing in the output. We need this print statement to see if and when it is evaluating as true or false.

                Code:
                Print(Time[0] + " | Bars.IsLastBarOfSession: " + Bars.IsLastBarOfSession.ToString());
                if (Bars.IsLastBarOfSession)
                return;
                ​

                Comment


                  #9
                  Hey Gaby! I managed to figure it out. There was a problem with the open on bar close that I finally resolved, and now everything seems to be working as it should. Thanks again for all your support and for introducing me to 'Print' and 'TradeOrder' – they are incredibly helpful for debugging. Have a fantastic day!



                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by NullPointStrategies, Today, 05:17 AM
                  0 responses
                  20 views
                  0 likes
                  Last Post NullPointStrategies  
                  Started by argusthome, 03-08-2026, 10:06 AM
                  0 responses
                  119 views
                  0 likes
                  Last Post argusthome  
                  Started by NabilKhattabi, 03-06-2026, 11:18 AM
                  0 responses
                  63 views
                  0 likes
                  Last Post NabilKhattabi  
                  Started by Deep42, 03-06-2026, 12:28 AM
                  0 responses
                  41 views
                  0 likes
                  Last Post Deep42
                  by Deep42
                   
                  Started by TheRealMorford, 03-05-2026, 06:15 PM
                  0 responses
                  45 views
                  0 likes
                  Last Post TheRealMorford  
                  Working...
                  X