Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

How to optimize a time period from XY to XY - what is the best entry and exit time?

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

    How to optimize a time period from XY to XY - what is the best entry and exit time?

    Hi guys,

    how can I optimize a time period?

    I know how to optimize Stop and Take Profit sizes in the Strategy Analyzer Optimization (Variables), but I want to have the time period (it doesn't matter which Data Series or symbol I use) which is the most profitable with entry time and exit time.

    Example:

    I want to make an entry at the period between 16:00 o'clock at 18:55 o'clock, how can I optimize this time period?
    The Analyzer could say after the optimization: "The best entry is at 17:24 o'clock and the best exit is at 18:40 o'clock.

    Thank you,
    Andreas

    #2
    Hello Andreas,

    The idea to optimize time is to use int inputs (public integer variables using the NinjaScriptProperty attribute) and use ToTime(Time[0]) to check the bar is between the optimized hour and minute values.

    Below are links to forum posts with sample code.
    https://ninjatrader.com/support/foru...ation-for-time
    https://ninjatrader.com/support/foru...me#post1067014
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Hello Chelsea,
      thank you, so I cannot do this with the Strategy Builder?
      Thank you,
      Andreas

      Comment


        #4
        Hello Andreas,

        In the Strategy Builder, this would require making groups of preset time filters (condition sets). If integer is 1, then set 1 is used with the time filter pre-setup in it.

        Whereas in an unlocked script the integer can be directly compared to the <DateTime>.Hour or <DateTime>.Minute, or some math or creating a new timespan, can be used to join the hour and minute integers so this can be compared with a ToTime(Time[0]) value.
        Last edited by NinjaTrader_ChelseaB; 04-27-2021, 09:07 AM.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Hello Chelsea,
          sorry for the late response, this is interesting, I will have a try at this.
          Thank you!
          Andreas

          Comment


            #6
            Hello Chelsea,
            sorry, again I need you help.

            I build some code with different entries and exits with the goal to compare them at the strategy analyzer.

            But I always get the error: "Error on calling "OnBarUpdate" method on bar 1: Index was outside the bounds of the array.

            Here is some sample code:

            Code:
            //This namespace holds Strategies in this folder and is required. Do not change it.
            namespace NinjaTrader.NinjaScript.Strategies
            {
            public class TIMOPT : Strategy
            {
            protected override void OnStateChange()
            {
            if (State == State.SetDefaults)
            {
            Description = @"Geben Sie hier die Beschreibung für die neue benutzerdefinierte Strategie.";
            Name = "TIMOPT";
            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 = true;
            Entry_Montag = false;
            Entry_Dienstag = false;
            Entry_Mitwoch = false;
            Entry_Donnerstag = false;
            Entry_Freitag = false;
            Exit_Montag = false;
            Exit_Dienstag = false;
            Exit_Mittwoch = false;
            Exit_Donnerstag = false;
            Exit_Freitag = false;
            Entry = DateTime.Parse("00:00", System.Globalization.CultureInfo.InvariantCulture) ;
            Exit = DateTime.Parse("00:00", System.Globalization.CultureInfo.InvariantCulture) ;
            Entry_2015 = false;
            Entry_2030 = false;
            xxxxxxx
            Exit_2245 = false;
            }
            else if (State == State.Configure)
            {
            }
            }
            
            protected override void OnBarUpdate()
            {
            if (BarsInProgress != 0)
            return;
            
            if (CurrentBars[0] < 1)
            return;
            
            // Set 1
            if ((Entry_2015 == true)
            && (Entry.TimeOfDay == Times[20][15].TimeOfDay)
            && (DayOfWeek.Friday == Times[20][15].DayOfWeek))
            {
            EnterLong(Convert.ToInt32(DefaultQuantity), @"Entry_2015");
            }
            
            // Set 2
            if ((Exit.TimeOfDay == Times[21][00].TimeOfDay)
            && (MarketPosition.Long == Position.MarketPosition)
            && (DayOfWeek.Friday == Times[21][00].DayOfWeek)
            && (Exit_2100 == true))
            {
            ExitLong(Convert.ToInt32(DefaultQuantity), @"Exit_2100", "");
            }
            
            
            
            xx
            xxxxx
            
            xxxxxxxx
            
            xx

            Comment


              #7
              Hello andi5385,

              Below is a link to a forum post on indexing errors.
              https://ninjatrader.com/support/foru...13#post1048513

              You are using Times[20].

              May I confirm you have added 20 data series with AddDataSeries?
              https://ninjatrader.com/support/help...dataseries.htm
              https://ninjatrader.com/support/help...ries_times.htm
              Chelsea B.NinjaTrader Customer Service

              Comment


                #8
                Hello Chelsea,
                thank you, you brought me to a general problem in my code, so I built the different sets and conditions, after the optimization he always finishes with strange results.

                Here is the code snippet (Entry_2015 means an entry at 20:15 o'clock):

                Code:
                protected override void OnBarUpdate()
                {
                if (BarsInProgress != 0)
                return;
                
                if (CurrentBars[0] < 1)
                return;
                
                // Set 1
                if ((Entry_2015 == true)
                && (Times[0][0].TimeOfDay == new TimeSpan(20, 15, 0))
                && (DayOfWeek.Monday == Times[0][0].DayOfWeek))
                {
                EnterLong(Convert.ToInt32(DefaultQuantity), @"Entry_2015");
                }
                ###xxx###
                ###xxx###
                ###xxx###
                ###xxx###
                ###xxx###
                
                // Set 9
                if ((Entry_2245 == true)
                && (Times[0][0].TimeOfDay == new TimeSpan(22, 45, 0))
                && (DayOfWeek.Monday == Times[0][0].DayOfWeek))
                {
                EnterLong(Convert.ToInt32(DefaultQuantity), @"Entry_2245");
                }
                
                // Set 10
                if ((Exit_2100 == true)
                && (Times[0][0].TimeOfDay == new TimeSpan(21, 00, 0))
                && (DayOfWeek.Monday == Times[0][0].DayOfWeek))
                {
                ExitLong(Convert.ToInt32(DefaultQuantity), @"Exit_2100", "");
                }
                Attached, you see the confusing results with always the same profit, percent profitable etc. but always another True/False combinations, for example the one in the attachment.
                There is no entry after an exit...?
                By the way, I tried it with an integer datatype, too, another confusing results.

                Thank you very much,
                Andreas
                Attached Files

                Comment


                  #9
                  Hello Andreas,

                  Just to confirm, this is not being created with the Strategy Builder correct?

                  If this is an unlocked script, you no longer have to have separate condition sets to optimize over the time. Instead in an unlocked script the integer can be directly compared to the <DateTime>.Hour or <DateTime>.Minute, or some math or creating a new timespan, can be used to join the hour and minute integers so this can be compared with a ToTime(Time[0]) value, as mentioned in post #4.

                  Are you attempting to manually edit, using an editor outside of NinjaTrader, a script that is still locked for editing in the Strategy Builder?

                  The Times[20], should absolutely not be possible using the Strategy Builder without adding 20 series with AddDataSeries. Previously you have stated you are using the Strategy Builder, and the code you are providing is the workaround for the Strategy Builder since it has limitations to using extremely simple tools and lacks the ability to straight forwardly use ints.


                  To understand why the script is behaving as it is, such as placing orders or not placing orders (or drawing objects or other actions) when expected, it is necessary to add prints to the script that print the values used for the logic of the script to understand how the script is evaluating.

                  In the strategy add prints (outside of any conditions) that print the values of every variable used in every condition that places an order along with the time of that bar.

                  This will print to the output window. Backtest the script and when the output from the output window appears save this by right-clicking the output window and selecting Save As... -> give the output file a name and save -> then attach the output text file to your reply.

                  Output from prints will appear in the NinjaScript Output window.
                  New -> NinjaScript Output

                  The prints should include the time of the bar and should print all values from all variables and all hard coded values in all conditions that must evaluate as true for this action to be triggered. It is very helpful to include labels and operators in the print to understand what is being compared in the condition sets.

                  Below I am providing a link to videos that demonstrate adding prints to a script to get further information about the behavior of the script.
                  NT8 — https://youtu.be/H7aDpWoWUQs?t=2577&...We0Nf&index=14

                  If you are using the Strategy Builder in NinjaTrader 8, you can also build prints in the Actions window under Misc -> Print.
                  NT8 Strategy Builder — https://drive.google.com/open?id=1CC...D4JjJgEIwJKv6L

                  To copy a script and modify the copy (allowing the original to remain in the Strategy Wizard):
                  NT8 — https://www.youtube.com/watch?v=BA0W...utu.be&t=8m15s
                  NT7 — https://www.youtube.com/watch?v=K8v_...utu.be&t=5m33s

                  It is also helpful to enable TraceOrders in State.Configure and print the order object in OnOrderUpdate.
                  TraceOrders - https://ninjatrader.com/support/help...raceorders.htm
                  OnOrderUpdate() - https://ninjatrader.com/support/help...rderupdate.htm

                  I'm also including a link to a forum post with further suggestions on debugging a script.
                  https://ninjatrader.com/support/foru...956#post671956

                  Save the output from the output window to a text file.

                  Let me know if you need assistance creating a print or enabling TraceOrders.
                  Last edited by NinjaTrader_ChelseaB; 04-27-2021, 09:17 AM.
                  Chelsea B.NinjaTrader Customer Service

                  Comment


                    #10
                    Hello Chelsea,

                    thank you for your detailed answer!

                    Yes, I tried it via NinjaScript Editor but I see, this will be to complicated for me, so I will try it via condition builder.

                    Have a nice day,
                    Andreas

                    Comment


                      #11
                      Hello Chelsea,
                      like you said in Post #4, do you have an example script to simply compare entries and exits in a timespan from 20-23 o'clock for optimization?
                      Thank you,
                      Andreas

                      Comment


                        #12
                        Hello andi5385,

                        As a convenience to you I have created an example that uses the concept I have linked in post #2.
                        Attached Files
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          Hello Chelsea,
                          sorry for the last answer.
                          Thank you for your effort, really, really friendly!
                          I will try it!

                          Have a nice day and thumbs up to this your support again, always getting fast and helpful answers, really great.
                          Andreas

                          Comment

                          Latest Posts

                          Collapse

                          Topics Statistics Last Post
                          Started by ct, Today, 01:53 AM
                          0 responses
                          2 views
                          0 likes
                          Last Post ct
                          by ct
                           
                          Started by SmartArtsStudio, Yesterday, 11:24 PM
                          0 responses
                          3 views
                          0 likes
                          Last Post SmartArtsStudio  
                          Started by kenz987, Yesterday, 10:06 PM
                          0 responses
                          4 views
                          0 likes
                          Last Post kenz987
                          by kenz987
                           
                          Started by AaronKoRn, Yesterday, 07:24 PM
                          0 responses
                          8 views
                          0 likes
                          Last Post AaronKoRn  
                          Started by Aquatrade, 05-15-2021, 11:46 AM
                          1 response
                          17 views
                          0 likes
                          Last Post NinjaTrader_ChelseaB  
                          Working...
                          X