Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

Entry at Open and Exit at Close on same bar, either for Daily or Intraday bars

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

    Entry at Open and Exit at Close on same bar, either for Daily or Intraday bars

    Hello

    I’m trying to get the Entry and the Exit of a position in the same bar but I’m always getting the Exit at the Open of the next bar. I started trying with Daily bars and I was thinking this was due the fact to use Daily bars but when I also tried with 60min bars I got the exact same behavior, having the Exit at the Open of the next bar.

    I tried with taking some extra ideas from the next thread:
    https://ninjatrader.com/support/foru...it-on-same-bar

    and I changed from ‘Calculate.OnPriceChange’ to ‘Calculate.OnEachTick’ in order to “To obtain intrabar actions”, but still getting the same result when for example I select daily bars, even when in the Strategy Analyzer are selected the settings “Break at EOD” and “Exit on session close”, and I thought that if using these settings with intrabar information and specifying “Exit on session close” then the result would have to be to get the Exit of the position at the Close, at least for the Daily bars.

    Also, as I read in that thread, I also tried adding ‘IsFirstTickOfBar’ in the Entry and/or in the Exit condition, but in case of being needed in the Exit condition then I wouldn’t fully understand the reason to use ‘IsFirstTickOfBar’ for an event that happens at the end of the bar and not at beginning, because it would be to check the “first tick”, no?

    Below you can see I’m using ‘(BarsSinceEntryExecution(0, @"Long", 0) == 0)’ with the idea that the Exit order can be placed in the same bar that the Entry order was placed too (‘… == 0’ equal to the current bar):


    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 StrategyTest : Strategy
     {
      private RSI RSI1;
    
     protected override void OnStateChange()
     {
     if (State == State.SetDefaults)
     {
     Description = @"Enter the description for your new custom Strategy here.";
     Name = "StrategyTest";
     Calculate = Calculate.OnEachTick;
     EntriesPerDirection = 1;
     EntryHandling = EntryHandling.AllEntries;
     IsExitOnSessionCloseStrategy = true;
     ExitOnSessionCloseSeconds = 30;
     IsFillLimitOnTouch = false;
     MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
     OrderFillResolution = OrderFillResolution.Standard;
     Slippage = 0;
     StartBehavior = StartBehavior.ImmediatelySubmit;
     TimeInForce = TimeInForce.Day;
     TraceOrders = false;
     RealtimeErrorHandling = RealtimeErrorHandling.IgnoreAllErrors;
     StopTargetHandling = StopTargetHandling.PerEntryExecution;
     BarsRequiredToTrade = 1;
     // Disable this property for performance gains in Strategy Analyzer optimizations
     // See the Help Guide for additional information
     IsInstantiatedOnEachOptimizationIteration = true;
     }
     else if (State == State.Configure)
     {
     }
     else if (State == State.DataLoaded)
     {[INDENT]RSI1 = RSI(Close, 14, 1);[/INDENT][INDENT]RSI1.Plots[0].Brush = Brushes.DodgerBlue;[/INDENT][INDENT]RSI1.Plots[1].Brush = Brushes.Goldenrod;[/INDENT][INDENT]AddChartIndicator(RSI1);[/INDENT]
     
    
      }
    }
    
      protected override void OnBarUpdate()
      {[INDENT]if (BarsInProgress != 0)[/INDENT][INDENT]return;[/INDENT][INDENT]if (CurrentBars[0] < 1)[/INDENT][INDENT]return;[/INDENT][INDENT]
    // Set 1
    // if (IsFirstTickOfBar)
    // {[/INDENT][INDENT]    if (RSI1.Default[0] > 70)[/INDENT][INDENT]    {[/INDENT][INDENT=2]EnterLong(Convert.ToInt32(DefaultQuantity), @"Long");[/INDENT][INDENT=2]BackBrushAll = Brushes.Green;[/INDENT][INDENT]    }
    // }[/INDENT][INDENT]
    // Set 2
    // if (IsFirstTickOfBar)
    // {
          if (BarsSinceEntryExecution(0, @"Long", 0) == 0)
          {[/INDENT][INDENT=2]ExitLong(Convert.ToInt32(DefaultQuantity), @"Exit", @"Long");
      BackBrush = Brushes.Yellow;[/INDENT][INDENT]    }
    // }[/INDENT]
     
    
    
      }
     }
    }

    I need help to handle these kind of cases in a simplified way please, either for Daily and for intraday bars.


    Thank you in advance!
    Last edited by futurenow; 05-25-2022, 02:27 PM.

    #2
    Btw, I would like to ask about if there are ways to just paste the code here in this forum site, inside "【CODE】and【/CODE】" and that the code keeps the source format, in order to have the code in an easy-to-read-view and in that way not to have to re-format the code format here putting spaces and "indents" to have a clean and friendly view.

    I tried taking the code from Visual Studio Code but it doesn't keep an exact view as the one seen in the NinjaScript Editor that would be the ideal scenario.

    Thank you!

    Comment


      #3
      Hi futurenow, thanks for your post. Strategy backtests are done OnBarClose by default. We have an example here showing how to set up a strategy to perform intrabar order fills:


      Best regards,
      -ChrisL
      Chris L.NinjaTrader Customer Service

      Comment


        #4
        Originally posted by NinjaTrader_ChrisL View Post
        Strategy backtests are done OnBarClose by default. We have an example here showing how to set up a strategy to perform intrabar order fills:
        Thank you for your answer

        Yes, I’ve been testing the example “SampleIntrabarBacktest_NT8.zip” from the link you provided, and it provides intrabar order fills, however I notice that in exchange to that, the kind of solution used in that script example makes the backtest process much heavier and dilated. For example, before to use this solution, the backtest process for Daily bars with the simple logic shown in the main post above to test its behavior for the last 10 years was taking seconds, but after using the solution inside “SampleIntrabarBacktest_NT8”, now the backtest takes more than 20 minutes, and this would be due the line ‘AddDataSeries(Data.BarsPeriodType.Tick, 1)’ that of course adds 1 tick data that is a more granular data, but, as I comment here, the kind of logic I need to backtest is very simple as you can see above and maybe there would be no need to use a 1 tick data to just work with the Exit at the Close of the bar.

        In the other hand, prior to use this solution I was getting the Exit of the position exactly at the Open of the next bar after the condition was met (i.e. right after the Close), but now instead to get the Exit exactly at the Close of the bar where the condition is met, as you can see in the picture, I’m getting the Exit at any random level that sometimes is near to the Close of the bar, but many other times is not near to the Close of the bar, and please note that in this case, in the code is not specified a Stop Loss or Target, i.e. here we are talking about to just Exit at the Close of the same bar where the position was Entered.


        So, I would like to know, please, what would be the way to get the Exit of the position exactly at the Close of the same bar where the position was Entered? either for Daily and Intraday bars. The idea would simply be that the order Entry be placed at the Open of the bar, and order Exit be placed at the Close of the same bar of the Entry. And, wouldn’t be a simpler way to obtain the Entry at the bar Open and the Exit at the bar Close without adding a 1 tick DataSeries? Because this makes that a simple process becomes much heavier and for this case I don’t see I exactly need intrabar bar data because I see it is more about just the Open and the Close of the bar, nothing else.


        Thank you!


        Click image for larger version

Name:	SampleIntrabarBacktest_NT8.zip logic provides intrabar order fill vs default after-bar-Close-order-fill BUT the Exit is not at bar Close as I need.png
Views:	742
Size:	33.3 KB
ID:	1202911

        Comment


          #5
          Hi futurenow thanks for your reply.

          If the bar is time based you can exit at the end time of the bar. If the bar is a Tick bar you can exit at the last tick of the bar, which is countable because each tick bar has a finite amount of ticks in it.

          Kind regards,
          -ChrisL
          Chris L.NinjaTrader Customer Service

          Comment


            #6
            Hello

            I’m working again with this kind of situations, at this time taking the script “SampleIntrabarBacktest_NT8.zip” as the main base and working the Exits with ‘BarsSinceEntryExecution()’.

            Once again the concept is very very simple, to Entry at bar’s Open, and to Exit at the Close of the same bar, i.e. to get the Entry and the Exit in the same bar.

            But I’m not getting the desired result.

            I’ve spent some time trying with different combinations of things like changing from ‘Calculate.OnBarClose’ to ‘Calculate.OnEachTick’, trying with different ways of ‘BarsSinceEntryExecution()’ specifying and not specifying the “barsInProgressIndex” also trying with something like ‘BarsSinceEntryExecution(0, "signalName", 0) == -1’ as I could see in some example in the NinjaTrader site, trying with different time-frames, leaving the sample strategy as simplified as possible in order to have only the most essential logic to get the desired Entry and Exit Result, etc. etc. but nothing works.


            I attached the modified “SampleIntrabarBacktest” script I’m using, and some of tests I did in the Strategy Analyzer with the ES futures are:
            • Using a secondary DataSeries with time-frame = 1 min, and a time-frame = 60 min in the Strategy Analyzer for the main DataSeries. Here the Strategy Analyzer shows the historical trades placed, but the Exit being placed at the next bar Open.
            • Using a secondary DataSeries with time-frame = 1 min, and a time-frame = 1 Day in the Strategy Analyzer for the main DataSeries. Here the Strategy Analyzer doesn’t show 1 single historical trade placed, 0 trades. Actually, the primary time-frame = 1 Day is the main situation I’m looking to have the Exit at the Daily bar Close, but I also need to cover the same situation for intraday time-frames as 5 min, 60 min, …


            The idea is to have a kind of universal backtester that can work either with a 5 min primary bars, or with a Daily primary bars, and that it gets the Exit at the bar Close in any time-frame (at least with time-based bars), either if we specify it has to Entry and Exit in the same bar (BarsSinceEntryExecution(0, "signalName", 0) == 0) or if we specify it has to Entry and then Exit N bars later (BarsSinceEntryExecution(0, "signalName", 0) == N).

            Thank you​



            Click image for larger version

Name:	SampleIntrabarBacktestBseExitAtTheSameBarClose - Backtest.png
Views:	614
Size:	102.5 KB
ID:	1222933

            Comment


              #7
              Hello futurenow,

              For the exit to be on the same bar, it would have to be submitted before the bar closes.

              In historical data, Tick Replay would be necessary to trigger OnBarUpdate() with Calculate.OnEachTick before the bar closes. This is in addition to placing the orders to a 1 tick series.

              Enable TickReplay.

              (Or submit the order during BarsInProgress 1 instead of BarsInProgress 0)
              Chelsea B.NinjaTrader Customer Service

              Comment


                #8
                Originally posted by NinjaTrader_ChelseaB View Post
                In historical data, Tick Replay would be necessary to trigger OnBarUpdate() with Calculate.OnEachTick before the bar closes. This is in addition to placing the orders to a 1 tick series.

                Enable TickReplay.

                (Or submit the order during BarsInProgress 1 instead of BarsInProgress 0)

                Thank you for your really fast response!

                About to “Enable TickReplay”, yes, it could work in cases where the backtests are for a relatively short (not too long) range of time, but in my case is not an efficient way because at this moment I need to do backtests/optimizations for 3-5-10 years back, and with “TickReplay” the backtest process would take an exaggerated amount of time (if available for 3+ years), and here we are talking about that when using time-frames from 1 min or more with standard order fill resolution, for example working with Daily bars, a backtest can take ~5-30 seconds. So, for this specific case TickReplay would not be the way.


                And about “submit the order during BarsInProgress 1 instead of BarsInProgress 0”, I was trying this, working with BarsInProgress 1, and yes, the sample strategy gets the intrabar Entries and Exits but I can’t get the Exits exactly at the main DataSeries bar’s Close level, in fact I see the Exits are near of the Entry (“away” from the bar Close). Please check the code inside the new attached file in this response, where in the comments parts you can see some of the last things I was trying.

                Oh, the picture if using a primary DataSeries = 60 min. When I try with a primary DataSeries = 1 Day, the Strategy Analyzer keeps in in blank, with 0 trades.


                By the way, I remember to read in other threads about this topic, to where the conditions are met, to place 1 trade per bar (seen from in the main DataSeries chosen in the Strategy Analyzer), with the Entry at the Open of the bar and the Exit at the Close of the bar, and seeing that NinjaTrader 8 seems to not to have a kind of function to activate this mode for the trades in the historical data, could be possible the development team upload a strategy sample that handle these cases?

                Thank you in advance!


                Click image for larger version

Name:	SampleIntrabarBacktestBseExitAtTheSameBarClose - Backtest 2.png
Views:	658
Size:	107.6 KB
ID:	1222963

                Comment


                  #9
                  Hello futurenow,

                  There is no getting around this.

                  If you want to submit an order before the bar closes, then OnBarUpdate has to update before the bar closes. This can be with TickReplay or with an added series.

                  For order fills to be intra-bar, these have to be placed to an added 1 tick (or 1 second series).

                  If you want an order to fill at the close of a bar, that order must be submitted a fraction of a second before the bar closes and there has to be a tick to fill the order during that second.

                  That would mean you need either 1 second or 1 tick granularity.


                  Where you have inquired:
                  to where the conditions are met, to place 1 trade per bar (seen from in the main DataSeries chosen in the Strategy Analyzer), with the Entry at the Open of the bar and the Exit at the Close of the bar, and seeing that NinjaTrader 8 seems to not to have a kind of function to activate this mode for the trades in the historical data
                  I'm trying to understand what this means.

                  Are you asking for an example that adds a 1 second series that places an order on the first tick of a new bar and places an exit order 1 second before the bar closes?
                  Chelsea B.NinjaTrader Customer Service

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by algospoke, 04-17-2024, 06:40 PM
                  6 responses
                  48 views
                  0 likes
                  Last Post algospoke  
                  Started by arvidvanstaey, Today, 02:19 PM
                  4 responses
                  11 views
                  0 likes
                  Last Post arvidvanstaey  
                  Started by samish18, 04-17-2024, 08:57 AM
                  16 responses
                  61 views
                  0 likes
                  Last Post samish18  
                  Started by jordanq2, Today, 03:10 PM
                  2 responses
                  9 views
                  0 likes
                  Last Post jordanq2  
                  Started by traderqz, Today, 12:06 AM
                  10 responses
                  18 views
                  0 likes
                  Last Post traderqz  
                  Working...
                  X