Arpit Gupta
Arpit Gupta

Reputation: 1277

Create 75-Mins timeblock for multiple DateTimes of a day

I am working on a stock market software. Where I am having a candle every 5 minutes. So whenever a time-frame of say 30 minutes is selected, what we do is -

long val = (long)(D * 24 * 60) / 30; //D is datetime of candle converted in OA date in double.
//The above code never create problem as (24*60)%30 == 0.

The above line returns same value for every half an hour chunk i. e. candle of 10:35, 10:40.....11:00. With that we can easily find out chunks of half an hour, whenever val is changed.

Now, We have a challange to implement the chunk of 75-Mins in the same way. Our market start from 9:15 and ends at 3:30. Suppose date for which 75-Mins needs to be calculated is 22-9-2018. For that I will need to have exactly 5 candle of below time -

  1. 22-9-2018 10:30 (9:15 to 10:30 = 75 mins)
  2. 22-9-2018 11:45
  3. 22-9-2018 1:00
  4. 22-9-2018 2:15
  5. 22-9-2018 3:30

I need to have same kind of code as metioned above which will calculate same value for these five chunks.

Problem I found is, If we start 75 from 12:00, then the chunk in market time will be at 8:45 to 10:00 while we require from 9:15 to 10:30 first chunk.

Also, (24*60)%75 = 15, So 15 Mins difference everyday disturbs the next day calculation too.

UPDATE -

To clear the question, For a chunk from 10:35 to 11:45, I will have candles like 10:35, 10:40, 10:45..... 11:45. For all these datetimes, I need a same numeric return value. As soon as the candle of 11:50 comes, the returned numeric value will get changed and my new 75 Min chunk will start. It will give same value till 1:00.

Upvotes: 1

Views: 95

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

You can use a loop or a linq query like this:

var startTime = new DateTime(2018, 09, 22, 9, 15, 0);
var times = Enumerable.Range(1, 5).Select(x => startTime.AddMinutes(x * 75)).ToList();

Example

Here is also another example about how to split a date range. In the following example, i included the start time also as part of the result:

IEnumerable<DateTime> Split(DateTime start, DateTime end, int minutes)
{
    if (minutes <= 0)
        throw new ArgumentException(
            $"'{nameof(minutes)}' should be greater than 0.",
            nameof(minutes));
    var result = start;
    while (result <= end)
    {
        yield return result;
        result = result.AddMinutes(minutes);
    }
}

And here is the usage:

var startTime = new DateTime(2018, 09, 22, 9, 15, 0);
var endTime = startTime.AddHours(7);
var times = Split(startTime, endTime, 75).ToList(); 

Upvotes: 2

Related Questions