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 Mindset, 04-21-2026, 06:46 AM
    0 responses
    44 views
    0 likes
    Last Post Mindset
    by Mindset
     
    Started by M4ndoo, 04-20-2026, 05:21 PM
    0 responses
    56 views
    0 likes
    Last Post M4ndoo
    by M4ndoo
     
    Started by M4ndoo, 04-19-2026, 05:54 PM
    0 responses
    35 views
    0 likes
    Last Post M4ndoo
    by M4ndoo
     
    Started by cmoran13, 04-16-2026, 01:02 PM
    0 responses
    95 views
    0 likes
    Last Post cmoran13  
    Started by PaulMohn, 04-10-2026, 11:11 AM
    0 responses
    57 views
    0 likes
    Last Post PaulMohn  
    Working...
    X