Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Best way to do something at a specific time

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

    Best way to do something at a specific time

    Hi. Assume I want to draw an object at exactly 09:30 each day. What is the best way to do it? I mean exactly this time, not between 09:30 and 09:35, exactly 09:30:000

    if (Time[0].TimeOfDay == MyDateTime.TimeOfDay) {
    // Do something
    }

    This doesn't work. I guess because if the chart is OnBarClose, a particular bar might not close at exactly MyDateTime.

    So is the best way to do it like this?

    if ((Time[0].TimeOfDay >= MyDateTime.TimeOfDay) && (MyVar = false)) {
    // Do something
    myVar = true;
    // Then later reset the myVar back to false.
    }​

    Or something similar ?

    #2
    Hello lucyb,

    If the primary series is a 1 minute, 2 minute, 5 minute, 10 minute, 15 minute, or 30 minute series there will be bar closes at 9:30 as long as this is in the Trading hours template.

    if (ToTime(Time[0]) == 93000)
    {
    // trigger action
    }

    If the primary series is not a minute series and has arbitrary bar close times, add a 30 minute series with AddDataSeries() so that you can trigger events when a bar closes at 9:30.

    AddDataSeries(null, BarsPeriodType.Minute, 30);

    if (BarsInProgress == 1 && ToTime(Times[1][0]) == 93000)
    {
    // trigger action
    }
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Hi. Yes I'm using tick charts. Good tip adding a 30 minute series, thanks for that!.

      Comment


        #4
        Could you help me with something related please. Your code works. But I don't understand why this doesn't.

        AddDataSeries(null, BarsPeriodType.Minute, 30); // state cfig
        StartTime = 18:30 //TimeDate Var

        If ((BarsinProgress == 1) && (Times[1][0].TimeOfDay == StartTime)) {

        // Do something

        }

        I get bars out of range error. Do you know why? If I use your code and print these outputs Times[1][0].TimeOfDay && StartTime, they are identical. Both 18:30

        Comment


          #5
          Hello lucyb,

          What is the full exact error message?

          You are certain this branching command is causing the error? If you comment the branching command out the error goes away?

          The isse is not with logic with the branching command?

          Is StartTime declared as a TimeSpan object?
          Chelsea B.NinjaTrader Customer Service

          Comment


            #6
            This is the error:

            Indicator 'OvernightHLV2': Error on calling 'OnBarUpdate' method on bar 0: You are accessing an index with a value that is invalid since it is out-of-range. I.E. accessing a series [barsAgo] with a value of 5 when there are only 4 bars on the chart.

            I have:

            private DateTime StartTime
            StartTime = 18:30

            Comment


              #7
              Hello lucyb,

              <DateTime>.TimeOfDay returns a TimeSpan and not a DateTime.

              See the Microsoft documentation:


              This means your code is wrong and cannot compile.
              Also there are capitalization errors in your post. This convinces me that is not the code in your script, as the code you have suggested cannot compile and if the script isn't compiled it isn't running that code.

              Testing with StartTime as a TimeSpan and correct syntax I am not getting any run-time errors.
              LucybTest_NT8.zip

              The code you provided you provided is not the code you are testing.
              Chelsea B.NinjaTrader Customer Service

              Comment


                #8
                This is not working for me either using a 5min data series on a 500 tick chart. When using:
                if (BarsInProgress == 0 && (Times[2][0].TimeOfDay) == StartTime) {
                I get it to work for every other day.

                When using:
                if (BarsInProgress == 1 && (Times[2][0].TimeOfDay) == StartTime) {
                it does not work at all.

                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.LynnsStrategies
                {
                    public class TimeTEST : Strategy
                    {
                        
                        private TimeSpan StartTime;
                        private TimeSpan EndTime;
                
                 
                        protected override void OnStateChange()
                        {
                            if (State == State.SetDefaults)
                            {
                                Description                                    = @"This is a template for Unmanaged strategies that can be used as reference for developing your own Unmanaged strategy.";
                                Name                                        = "TimeTEST NT8";
                                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                                    = true;
                                RealtimeErrorHandling                        = RealtimeErrorHandling.StopCancelClose;
                                StopTargetHandling                            = StopTargetHandling.PerEntryExecution;
                                BarsRequiredToTrade                            = 20;
                                IsUnmanaged                                 = true;
                                IsAdoptAccountPositionAware                 = true;
                                // Disable this property for performance gains in Strategy Analyzer optimizations
                                // See the Help Guide for additional information
                                IsInstantiatedOnEachOptimizationIteration    = true;
                                
                                
                            }
                            else if (State == State.Configure)
                            {
                                 AddDataSeries(BarsPeriodType.Tick, 1);  // [1]
                                 AddDataSeries(BarsPeriodType.Minute, 5);  // [2]
                                 AddDataSeries(BarsPeriodType.Minute, 15);  // [3]
                                 AddDataSeries(BarsPeriodType.Minute, 60);  // [4]
                                 //AddDataSeries(BarsPeriodType.Dat, 1);  // [5]
                
                            }
                            else if (State == State.DataLoaded)
                            {
                                
                                StartTime = new TimeSpan(5, 30, 0);
                                EndTime = new TimeSpan(14, 00, 0);
                            }
                            else if (State == State.Realtime)
                            {
                                var aStrategyPosition = this.Position;
                                var aRealAccount = PositionAccount;
                                // convert any old historical order object references
                                // to the new live order submitted to the real-time account
                            }
                        }
                
                        protected override void OnBarUpdate() {
                            //if (State == State.Historical)
                                //return;
                            if (CurrentBars[0] < 1 || CurrentBars[1] < 1 || CurrentBars[2] < 5 || CurrentBars[3] < 1  || CurrentBars[4] < 1)// || CurrentBars[7] < BarsRequiredToPlot)
                                return;
                            
                            if (BarsInProgress != 0)
                                return;
                            
                            if (BarsInProgress == 0 && (Times[2][0].TimeOfDay) == StartTime) {
                                Print(Times[0][0] + " -------------- Beginning of session CurrentBars[0]: " + CurrentBars[2]);
                            }
                               
                            Print(Times[0][0] + " -------------- CurrentBars[2]: " + CurrentBars[2]);
                                    
                            if (IsFirstTickOfBar) {  }
                
                        }
                
                    }
                }​

                Comment


                  #9
                  Hello nelslynn,

                  To understand why the script is behaving as it is, such as placing orders or not placing orders or drawing objects 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 date time of the bar and all values compared in every condition that triggers the action.
                  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 important to include a text label for each value and for each comparison operator in the print to understand what is being compared in the condition sets.
                  The debugging print output should clearly show what the condition is, what time the conditions are being compared, all values being compared, and how they are being compared.

                  Prints will appear in the NinjaScript Output window (New > NinjaScript Output window).

                  Further, enable TraceOrders which will let us know if any orders are being ignored and not being submitted when the condition to place the orders is evaluating as true.
                  After enabling TraceOrders remove the instance of the strategy from the Configured list in the Strategies window and add a new instance of the strategy from the Available list.
                  Last, print the order.ToString() at the top of the OnOrderUpdate() override, as this will show us when orders become working and are being filled, and print the GetCurrentAsk() and GetCurrentBid() in OnOrderUpdate() as well so we can see what the market price is at the time of a fill.

                  I am happy to assist you with analyzing the output from the output window.

                  Run or 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.

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


                  Let me know the date and time the behavior occurred or when you are expecting the behavior to occur.​
                  Chelsea B.NinjaTrader Customer Service

                  Comment


                    #10
                    Did you look at my script? I have a print statement and I still don't understand. I wouldn't have posted if I hadn't already spent an hour on this. I'm simply trying to get the time issue to work, why would I add OnOrderUpdate when I can't get this simple example to work?

                    Comment


                      #11
                      Hello nelslynn,

                      To confirm, the print statement is printing all values used in the branching command one line above the branching command and includes labels for each value and comparison operator?

                      I looked at the suggested code in post # 8, but I am not seeing this in the code. The print is to tell you why the condition is evaluating as true or false.

                      In the code you suggested I see a print within some logic blocks, but no print above the branching command printing all values compared in the branching command.

                      You can also contact a professional NinjaScript Consultant who would be eager to create or modify this script at your request or assist you with your script. The NinjaTrader Ecosystem has affiliate contacts who provide educational as well as consulting services. Please let me know if you would like a list of affiliate consultants who would be happy to create this script or any others at your request or provide one on one educational services.
                      Chelsea B.NinjaTrader Customer Service

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                      0 responses
                      571 views
                      0 likes
                      Last Post Geovanny Suaza  
                      Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                      0 responses
                      330 views
                      1 like
                      Last Post Geovanny Suaza  
                      Started by Mindset, 02-09-2026, 11:44 AM
                      0 responses
                      101 views
                      0 likes
                      Last Post Mindset
                      by Mindset
                       
                      Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                      0 responses
                      548 views
                      1 like
                      Last Post Geovanny Suaza  
                      Started by RFrosty, 01-28-2026, 06:49 PM
                      0 responses
                      549 views
                      1 like
                      Last Post RFrosty
                      by RFrosty
                       
                      Working...
                      X