Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Exit on session close backwards when Tick Replay

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

    Exit on session close backwards when Tick Replay

    Hi,

    All I am trying to do is simply buy on same day of candle that opens greater than the day before, but I do not want to buy the next day that is why I had to use Calculate.OnPriceChange or something like that. I have my code below. When I take Tick Replay off it won't be able to work as intended (it will buy the next day but I won't have the Exit on session error). Exit on session close should always be the last candle which is May 3 in my example.

    IN OTHER WORDS:

    Like lets say we have daily candlesticks from today and 4 days before. now tomorrow the open will have a price. I want to trade on the open tomorrow based on if the open is > the close we had today.




    What is going on?

    Sry for the confusion, but my followingCandle is really reffering to the day before the current day candle so like the previous

    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


    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class CandlestickStrategy : Strategy
    {
    [NinjaScriptProperty]
    public int OrderQuantity { get; set; } = 1;

    [NinjaScriptProperty]
    public double StopLossPercentage { get; set; } = 0.2;

    [NinjaScriptProperty]
    public System.TimeSpan TradeTime { get; set; } = new System.TimeSpan(16, 5, 0);

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "CandlestickStrategy";
    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 = 5;
    IsInstantiatedOnEachOptimizationIteration = true;
    }
    else if (State == State.Configure)
    {

    Calculate = Calculate.OnPriceChange;

    // Add a 1-tick series for intra-bar granularity
    AddDataSeries(BarsPeriodType.Tick, 1);

    // Set a percentage-based stop loss
    SetStopLoss(CalculationMode.Percent, StopLossPercentage);
    }
    }

    protected override void OnBarUpdate()
    {
    // Only process on the primary bar series and ensure enough bars are loaded
    if (BarsInProgress != 0 || CurrentBar < 5)
    return;

    // Check if the current bar is a new bar
    if (IsFirstTickOfBar)
    {
    // Get the bar index for the current trading day
    int currentDayBarIndex = Bars.GetBar(Time[0].Date);
    Print("Current Day Bar Index: " + currentDayBarIndex);



    // Get the open price of the current trading day
    double currentDayOpen = Open[currentDayBarIndex];
    Print("Current Day Open: " + currentDayOpen);

    // Define necessary variables
    double followingCandleOpen = Open[0];

    // Conditions for buying
    if (followingCandleOpen > currentDayOpen)
    {
    EnterLong(OrderQuantity, "Buy4"); // Enter a long position with the "Buy4" label
    }
    }
    }







    }
    }

    Thank you,

    MatHatter​
    Attached Files
    Last edited by MatHatter; 08-14-2024, 07:40 PM.

    #2
    Don t backtest on Day backtest on 1min

    Comment


      #3
      ChatGPT pushed me in the right direction after posting this post in it...​ I was trying to brute force the code to work with [0] for the previous day, but not with OnPriceChange I can probably just use [0] for current day and [1] for day before. sry just the trade the next day logic has messed up this logic that seemingly makes no sense but it does. I don't expect Exit on session close at the gravestone doji 17735.5 so it still seems a wrong. code: region Using declarations
      using System;
      using NinjaTrader.NinjaScript.Strategies;
      using NinjaTrader.Data;

      #endregion

      namespace NinjaTrader.NinjaScript.Strategies
      {
      public class ReversalCandlestickStrategy : Strategy
      {
      [NinjaScriptProperty]
      public int OrderQuantity { get; set; } = 1;

      [NinjaScriptProperty]
      public double StopLossPercentage { get; set; } = 0.2;

      [NinjaScriptProperty]
      public System.TimeSpan TradeTime { get; set; } = new System.TimeSpan(16, 5, 0);

      protected override void OnStateChange()
      {
      if (State == State.SetDefaults)
      {
      Description = @"Enter the description for your new custom Strategy here.";
      Name = "ReversalCandlestickStrategy";
      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 = 5;
      IsInstantiatedOnEachOptimizationIteration = true;
      }
      else if (State == State.Configure)
      {
      Calculate = Calculate.OnEachTick;

      // Add a 1-tick series for intra-bar granularity
      AddDataSeries(BarsPeriodType.Tick, 1);

      // Set a percentage-based stop loss
      SetStopLoss(CalculationMode.Percent, StopLossPercentage);
      }
      }

      protected override void OnBarUpdate()
      {
      // Only process on the primary bar series and ensure enough bars are loaded
      if (BarsInProgress != 0 || CurrentBar < 5)
      return;

      // Get the open price of the previous day
      double previousDayOpen = Open[1];

      // Get the open price of the current trading day
      double currentDayOpen = Open[0];
      Print("Previous Day Open: " + previousDayOpen);
      Print("Current Day Open: " + currentDayOpen);

      // Conditions for buying
      if (currentDayOpen > previousDayOpen)
      {
      EnterLong(OrderQuantity, "Buy4"); // Enter a long position with the "Buy4" label
      }
      }
      }
      }
      Click image for larger version

Name:	image.png
Views:	115
Size:	57.7 KB
ID:	1314177

      Comment


        #4
        I am running a daily strategy ajgauss13

        Comment


          #5
          ​this is not the actual strategy, I am just trying to make sure it works. anyways, this is what I believe the code should look like when working.. like the buys should be there if > day before close and then just exit when last data candle in series which would be at ExitClick image for larger version

Name:	image.png
Views:	84
Size:	63.3 KB
ID:	1314181

          Comment


            #6
            Hello MattHatter,

            Thank you for your post.

            If your strategy is running Calculate.OnPriceChange, you'll need to implement 1-tick intrabar granularity in additional to enabling Tick Replay for accuracy in backtest. Have you implemented intrabar granularity?

            I'm seeing you added the 1-tick series but aren't actually submitting the orders to the more granular series.

            Intra-bar granularity adds a second data series such as a 1 tick series using AddDataSeries() so that the strategy or indicator has the individual ticks in the historical data in between the High and Low of the primary series.
            Last edited by NinjaTrader_Gaby; 08-15-2024, 07:08 AM.

            Comment


              #7
              Hi Gaby,

              I see now that the buys should only occur at the last to green bars at May 2 and 3 (because the strategy requires at least 5 bars to calculate / implement). I added the 1 to the EntryLong before the OrderQuantity. It seemed to help a lot. However, I am still having Exit on session close errors. Like that should only happen on May 3. (in the video Chelsea was talking about if adding daily the add data series code is 2, but I am really lost there, I just kept as 1).

              I believe it is working as far as where the orders are applied, but now the Exit on session close is still posing an issue. It almost seems like it is running backwards... Besides, I see why Buy4 comes up twice in that May2 candle, it is because it dipped below the open of the day before and went above it during the day. How can if Exit on session a day before on May1 it doesn't make any sense. I provided the code so you can try yourself. I am using NQ 09-24 and Last Day 1 Tick Replay Start 4/25/2024 End 5/3/2024 Break EOD Bars min 5.

              I've tried setting exit on session to false just to see if I got any different results, but same.

              Please help.

              Thank you for your help insofar!

              Best regards,

              MatHatter

              Click image for larger version

Name:	image.png
Views:	142
Size:	68.3 KB
ID:	1314239
              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


              namespace NinjaTrader.NinjaScript.Strategies
              {
              public class ReversalCandlestickStrategy : Strategy
              {
              [NinjaScriptProperty]
              public int OrderQuantity { get; set; } = 1;

              [NinjaScriptProperty]
              public double StopLossPercentage { get; set; } = 0.2;

              [NinjaScriptProperty]
              public System.TimeSpan TradeTime { get; set; } = new System.TimeSpan(16, 5, 0);

              protected override void OnStateChange()
              {
              if (State == State.SetDefaults)
              {
              Description = @"Enter the description for your new custom Strategy here.";
              Name = "ReversalCandlestickStrategy";
              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 = 5;
              IsInstantiatedOnEachOptimizationIteration = true;
              }
              else if (State == State.Configure)
              {
              Calculate = Calculate.OnPriceChange;

              // Add a 1-tick series for intra-bar granularity
              AddDataSeries(BarsPeriodType.Tick, 1);

              // Set a percentage-based stop loss
              SetStopLoss(CalculationMode.Percent, StopLossPercentage);
              }
              }

              protected override void OnBarUpdate()
              {
              // Only process on the primary bar series and ensure enough bars are loaded
              if (BarsInProgress != 0 || CurrentBar < 5)
              return;

              // Get the open price of the previous day
              double previousDayOpen = Open[1];

              // Get the open price of the current trading day
              double currentDayOpen = Open[0];
              Print("Previous Day Open: " + previousDayOpen);
              Print("Current Day Open: " + currentDayOpen);

              // Conditions for buying
              if (currentDayOpen > previousDayOpen)
              {
              EnterLong(1, OrderQuantity, "Buy4"); // Enter a long position with the "Buy4" label
              }
              }
              }
              }​

              Comment


                #8
                Hello,

                Are you testing on daily bars? This property is designed to be only used on intraday strategies. It's not intended to be used on daily bars.

                This is noted in the Help Guide.

                Comment


                  #9
                  Hello,

                  So you are saying Exit on session close doesn't work for Daily candlesticks at all? It seemed to work before when not using Tick Replay BarsInProgress stuff. What is the proper way to go about closing out all trades at the last candle in the series for Daily strategies? I've tried setting IsExitOnSessionCloseStrategy = false; but doesn't seem to do anything.

                  Thank you

                  Comment


                    #10
                    What are you referring to as the last candle in the series? There is no "last daily bar", bars are going to keep coming as the days progress.

                    If there is a specific criteria you want to use to identify what the last bar you want to exit all trades on, you'll need to add logic in your script to identify on exactly which bar you want to exit.

                    Comment


                      #11
                      Hi Gaby,

                      Ok, with the code below, how do I get Exit on session close to be removed? It keeps coming up on the chart/executions even after setting IsExitOnSessionCloseStrategy = false;

                      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


                      namespace NinjaTrader.NinjaScript.Strategies
                      {
                      public class ReversalCandlestickStrategy : Strategy
                      {
                      [NinjaScriptProperty]
                      public int OrderQuantity { get; set; } = 1;

                      [NinjaScriptProperty]
                      public double StopLossPercentage { get; set; } = 0.2;

                      [NinjaScriptProperty]
                      public System.TimeSpan TradeTime { get; set; } = new System.TimeSpan(16, 5, 0);

                      [NinjaScriptProperty]
                      [Display(Name = "End Date", Order = 4, GroupName = "Parameters")]
                      public DateTime EndDate { get; set; } = DateTime.Now;

                      protected override void OnStateChange()
                      {
                      if (State == State.SetDefaults)
                      {
                      Description = @"Enter the description for your new custom Strategy here.";
                      Name = "ReversalCandlestickStrategy";
                      EntriesPerDirection = 1;
                      EntryHandling = EntryHandling.AllEntries;
                      IsExitOnSessionCloseStrategy = false; // Ensure this is set to false
                      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 = 5;
                      IsInstantiatedOnEachOptimizationIteration = true;
                      }
                      else if (State == State.Configure)
                      {
                      Calculate = Calculate.OnPriceChange;

                      // Add a 1-tick series for intra-bar granularity
                      AddDataSeries(BarsPeriodType.Tick, 1);

                      // Set a percentage-based stop loss
                      SetStopLoss(CalculationMode.Percent, StopLossPercentage);
                      }
                      }

                      protected override void OnBarUpdate()
                      {
                      // Only process on the primary bar series and ensure enough bars are loaded
                      if (BarsInProgress != 0 || CurrentBar < 5)
                      return;

                      // Get the open price of the previous day
                      double previousDayOpen = Open[1];

                      // Get the open price of the current trading day
                      double currentDayOpen = Open[0];
                      Print("Previous Day Open: " + previousDayOpen);
                      Print("Current Day Open: " + currentDayOpen);

                      // Conditions for buying
                      if (currentDayOpen > previousDayOpen)
                      {
                      EnterLong(1, OrderQuantity, "Buy4"); // Enter a long position with the "Buy4" label
                      }

                      // Exit all trades at the end of the specified date
                      if (Time[0].Date == EndDate.Date)
                      {
                      ExitLong("Exit at end of date");
                      }
                      }
                      }
                      }



                      Thanks

                      Comment


                        #12
                        I am afraid you are going to say I can't buy the open price based on logic for that current day based on Ninja Trader, but that is only for intraday. Like is it possible to buy at open on the new day for that day and not the next with the open price integrated into some logic?

                        Comment


                          #13
                          Hello,

                          After setting IsExitOnSessionCloseStrategy = false within State.SetDefaults, you'll need to remove the old strategy instance and add a new instance to any chart or from the Strategies tab to pull the new defaults.

                          Like is it possible to buy at open on the new day for that day and not the next with the open price integrated into some logic?
                          Yes, it is possible implement your own custom logic to buy at the open of a daily bar and not the next bar.

                          Comment


                            #14
                            holy cow, I think I got it to work!!! I put IsExitOnSessionCloseStrategy = false; inside else if (State == State.Configure) as well and it worked

                            Comment


                              #15
                              I think maybe I should have a buy at May 3 as well based on the logic because that candle is > the day befores close. I am content for now though because I see a lot better results. Maybe it has something to do with the End Date.

                              Click image for larger version

Name:	image.png
Views:	75
Size:	62.3 KB
ID:	1314276

                              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