Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Get bar index from date time.

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

    Get bar index from date time.

    I'm trying to look back the current week and the previous week. I can get datetime from the beginning of the week, but I need to translate that into a bars ago index. Is there a built in function to do this or does brute force and ignorance rule the day?

    Thanks

    #2
    Hello Herrwolf1,

    Thank you for your note.

    To do that, you'd need to use DateTime.AddDays() to get the appropriate date to check. Here's a publicly accessible link from Microsoft's documentation to more information:

    https://docs.microsoft.com/en-us/dot...tframework-4.5

    So, for example, to get the date we want to look at a week ago, you'd need to calculate that date.

    If we're looking at today's date, and we want to know what the date was a week ago, we could do something like this:

    Code:
    DateTime TodaysDate = DateTime.Now;
    DateTime OneWeekAgo = TodaysDate.AddDays(-7);
    If you're looking for bars at a specific time, you'd want to use the DateTime.AddDays() to get the correct date from which to retrieve the close price and then you can use Bars.GetBar() to get a price from a specified time:

    https://ninjatrader.com/support/helpGuides/nt8/getbar.htm

    Expanding on our example above:

    Code:
    DateTime TodaysDate = DateTime.Now;
    DateTime OneWeekAgo = TodaysDate.AddDays(-7);
    
    // Calculate the bars ago value for the 9:30 AM bar for 7 days ago
    int barsAgo = CurrentBar - Bars.GetBar(new DateTime(OneWeekAgo.Year, OneWeekAgo.Month, OneWeekAgo.Day, 9, 30,0));
    
    // Print out the 9:30 AM bar closing price from last week
    Print("The close price on the 9:30 AM bar was: " + Close[barsAgo].ToString());
    Please let us know if we may be of further assistance to you.

    Comment

    Latest Posts

    Collapse

    Topics Statistics Last Post
    Started by CarlTrading, 03-31-2026, 09:41 PM
    1 response
    81 views
    1 like
    Last Post NinjaTrader_ChelseaB  
    Started by CarlTrading, 04-01-2026, 02:41 AM
    0 responses
    42 views
    0 likes
    Last Post CarlTrading  
    Started by CaptainJack, 03-31-2026, 11:44 PM
    0 responses
    64 views
    2 likes
    Last Post CaptainJack  
    Started by CarlTrading, 03-30-2026, 11:51 AM
    0 responses
    68 views
    0 likes
    Last Post CarlTrading  
    Started by CarlTrading, 03-30-2026, 11:48 AM
    0 responses
    55 views
    0 likes
    Last Post CarlTrading  
    Working...
    X