Reduce API call when fetching new candles

This commit is contained in:
2025-09-17 17:45:41 +07:00
parent 900405b3de
commit 841bb20800
3 changed files with 85 additions and 12 deletions

View File

@@ -107,17 +107,33 @@ public static class CandleHelpers
public static TimeSpan GetDueTimeForTimeframe(Timeframe timeframe, DateTime now)
{
var intervalMinutes = GetBaseIntervalInSeconds(timeframe) / 60;
// Calculate the next candle boundary
var nextBoundary = GetNextCandleBoundary(now, intervalMinutes);
// Add 1 second to ensure we're after the candle closes
var targetTime = nextBoundary.AddSeconds(1);
// Return the time difference
return targetTime - now;
}
/// <summary>
/// Gets the next expected candle time for the given timeframe.
/// This is useful to determine if a new candle should be available yet.
/// </summary>
/// <param name="timeframe">The timeframe to calculate for</param>
/// <param name="now">The current time (defaults to DateTime.UtcNow)</param>
/// <returns>The next expected candle time</returns>
public static DateTime GetNextExpectedCandleTime(Timeframe timeframe, DateTime? now = null)
{
var currentTime = now ?? DateTime.UtcNow;
var intervalMinutes = GetBaseIntervalInSeconds(timeframe) / 60;
// Calculate the next candle boundary
return GetNextCandleBoundary(currentTime, intervalMinutes).AddSeconds(-1);
}
private static DateTime GetNextCandleBoundary(DateTime now, double intervalMinutes)
{
// For different timeframes, we need to align to different boundaries
@@ -159,7 +175,7 @@ public static class CandleHelpers
var boundary = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
return boundary.AddDays(1);
}
// Fallback to 5-minute intervals
var fallbackMinute = (now.Minute / 5) * 5;
var fallbackBoundary = new DateTime(now.Year, now.Month, now.Day, now.Hour, fallbackMinute, 0);