diff --git a/src/Managing.Application/Bots/TradingBotBase.cs b/src/Managing.Application/Bots/TradingBotBase.cs index a2915ee..4f23343 100644 --- a/src/Managing.Application/Bots/TradingBotBase.cs +++ b/src/Managing.Application/Bots/TradingBotBase.cs @@ -1024,17 +1024,35 @@ public class TradingBotBase : ITradingBot if (currentCandle != null) { - List recentCandles = null; - await ServiceScopeHelpers.WithScopedService(_scopeFactory, async exchangeService => - { - recentCandles = Config.IsForBacktest - ? new List() { LastCandle } - : (await exchangeService.GetCandlesInflux(TradingExchanges.Evm, Config.Ticker, - DateTime.UtcNow.AddHours(-4), Config.Timeframe)).ToList(); - }); + List recentCandles = null; + await ServiceScopeHelpers.WithScopedService(_scopeFactory, async exchangeService => + { + recentCandles = Config.IsForBacktest + ? (LastCandle != null ? new List() { LastCandle } : new List()) + : (await exchangeService.GetCandlesInflux(TradingExchanges.Evm, Config.Ticker, + DateTime.UtcNow.AddHours(-4), Config.Timeframe)).ToList(); + }); - var minPriceRecent = recentCandles.Min(c => c.Low); - var maxPriceRecent = recentCandles.Max(c => c.High); + // Check if we have any candles before proceeding + if (recentCandles == null || !recentCandles.Any()) + { + await LogWarning($"No recent candles available for position {position.Identifier}. Using current candle data instead."); + + // Fallback to current candle if available + if (currentCandle != null) + { + recentCandles = new List { currentCandle }; + } + else + { + await LogWarning($"No candle data available for position {position.Identifier}. Cannot determine stop loss/take profit hit."); + Logger.LogError("No candle data available for position {PositionId}. Cannot determine stop loss/take profit hit.", position.Identifier); + return; + } + } + + var minPriceRecent = recentCandles.Min(c => c.Low); + var maxPriceRecent = recentCandles.Max(c => c.High); bool wasStopLossHit = false; bool wasTakeProfitHit = false;