Remove expected candle and fix update candles
This commit is contained in:
@@ -126,6 +126,13 @@ public class CandleStoreGrain : Grain, ICandleStoreGrain, IAsyncObserver<Candle>
|
||||
_state.State.Candles = new List<Candle>();
|
||||
}
|
||||
|
||||
// Check for gaps in the candle data
|
||||
if (HasGapInCandleData(candle))
|
||||
{
|
||||
await LoadInitialCandlesAsync(candle.Exchange, candle.Ticker, candle.Timeframe);
|
||||
return;
|
||||
}
|
||||
|
||||
// Add the new candle
|
||||
_state.State.Candles.Add(candle);
|
||||
|
||||
@@ -163,6 +170,58 @@ public class CandleStoreGrain : Grain, ICandleStoreGrain, IAsyncObserver<Candle>
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if there's a gap in the candle data by comparing the time interval
|
||||
/// between the new candle and the last candle in the store.
|
||||
/// </summary>
|
||||
/// <param name="newCandle">The new candle received from the stream</param>
|
||||
/// <returns>True if a gap is detected, false otherwise</returns>
|
||||
private bool HasGapInCandleData(Candle newCandle)
|
||||
{
|
||||
try
|
||||
{
|
||||
// If no candles exist, no gap to check
|
||||
if (_state.State.Candles == null || _state.State.Candles.Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Get the last candle from the store
|
||||
var lastCandle = _state.State.Candles
|
||||
.OrderBy(c => c.Date)
|
||||
.LastOrDefault();
|
||||
|
||||
if (lastCandle == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Calculate the expected time interval for this timeframe
|
||||
var expectedInterval = TimeSpan.FromSeconds(CandleHelpers.GetBaseIntervalInSeconds(newCandle.Timeframe));
|
||||
|
||||
// Calculate the actual time difference between the new candle and the last candle
|
||||
var actualInterval = newCandle.Date - lastCandle.Date;
|
||||
|
||||
// Check if the actual interval matches the expected interval (with a small tolerance)
|
||||
var tolerance = TimeSpan.FromSeconds(1); // 1 second tolerance for minor timing differences
|
||||
var isGap = Math.Abs((actualInterval - expectedInterval).TotalSeconds) > tolerance.TotalSeconds;
|
||||
|
||||
if (isGap)
|
||||
{
|
||||
_logger.LogWarning("Gap detected: Expected interval {ExpectedInterval}, actual interval {ActualInterval} for {GrainKey}",
|
||||
expectedInterval, actualInterval, this.GetPrimaryKeyString());
|
||||
}
|
||||
|
||||
return isGap;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error checking for gaps in candle data for grain {GrainKey}", this.GetPrimaryKeyString());
|
||||
// In case of error, assume no gap to avoid unnecessary refreshes
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task LoadInitialCandlesAsync(TradingExchanges exchange, Ticker ticker, Timeframe timeframe)
|
||||
{
|
||||
try
|
||||
|
||||
Reference in New Issue
Block a user