Historical Hourly chart gives only first 25 records

Hello Everyone,

I am trying to pull hourly data using the below code . But I am noticing that it always gives me only first 25 records , thought I am trying to pull last 100 hrs it gives me only for first 25 hours

            startTime = Convert.ToDateTime("7/21/2021 9:00:00 AM");
            endTime = DateTime.UtcNow;
            barRequest = new HistoricalBarsRequest("TSLA", startTime, endTime, BarTimeFrame.Hour);
            bars = await alpacaDataClient.ListHistoricalBarsAsync(barRequest);
            bars1 = bars.Items;

I am expecting the above code to retrieve hourly bars from 07\21 to current (07\26) . but it gives me the result only for first 25 hours .

Not sure, if i am missing anything . Any help or insight on this is much appreciated .

Thanks,
Suren

This is expected (partially) behavior. See the Paging section of the documentation.

The SDK returns only first page of data and you have to re-request the rest using the NextPageToken property of response and original request parameters. You can do it manually in the 'whileloop or useGetHistoricalBarsAsAsyncEnumerableorGetHistoricalBarsPagesAsAsyncEnumerable` extension methods from the Alpaca.Markets.Extensions package.

I strongly recommend you the second approach but if you prefer to understand what happened under the hood of these methods see the next snippet:

var startTime = new DateTime(2021, 7, 21, 0, 0, 0, DateTimeKind.Utc);
var endTime = DateTime.UtcNow;

var bars = new List<IBar>();
var request = new HistoricalBarsRequest(
    "AAPL", startTime, endTime, BarTimeFrame.Hour);
do
{
    var page = await client.ListHistoricalBarsAsync(request);

    bars.AddRange(page.Items);
    Console.WriteLine(page.Items.Count);

    request.WithPageToken(page.NextPageToken);
} while (request.Pagination.Token is not null);

Console.WriteLine();
Console.WriteLine(bars.Count);
1 Like

Thank you oleg .

That worked like a charm :slight_smile:

@oleg.rakhmatulin @admins I am getting the same issue with the latest C# SDK 7.0.6 and my NextPageToken is also null so I dont get more data at all. I am capped at 62 bars. According to my calculations based on below values I should get 120 bars. I have an unlimited data paid account.

My start datetime is 1/1/2024 6:15:00 PM
end datetime is 1/3/2024 12:15:00 AM
Timeframe is new BarTimeFrame(15, BarTimeFrameUnit.Minute)

@Uttam Alpaca API never returns “empty” bars. If there are no trades during the time sampling interval you’ll just not get anything for this time point. In your case, 62 bars mean you have 15 and a half hours of good trading for the target asset and it sounds fair because you have one full trading day and just half of another one. I assume that you provide time in the EST timezone in your question.

Got it. I realized that Jan 1st was a holiday and 2 other days prior as well so no data. I increased the timeframe and it worked. Thanks Oleg.