diff --git a/src/Managing.Application/Bots/Grains/AgentGrain.cs b/src/Managing.Application/Bots/Grains/AgentGrain.cs index 6789c63f..6af3ec85 100644 --- a/src/Managing.Application/Bots/Grains/AgentGrain.cs +++ b/src/Managing.Application/Bots/Grains/AgentGrain.cs @@ -169,7 +169,7 @@ public class AgentGrain : Grain, IAgentGrain try { // Get all positions for this agent's bots as initiator - var positions = await _tradingService.GetPositionByUserIdAsync((int)this.GetPrimaryKeyLong()); + var positions = (await _tradingService.GetPositionByUserIdAsync((int)this.GetPrimaryKeyLong())).ToList(); // Calculate aggregated statistics from position data var totalPnL = positions.Sum(p => p.ProfitAndLoss?.Realized ?? 0); @@ -201,28 +201,24 @@ public class AgentGrain : Grain, IAgentGrain { var userId = (int)this.GetPrimaryKeyLong(); var user = await _userService.GetUserByIdAsync(userId); + var userAccounts = await _accountService.GetAccountsByUserAsync(user, hideSecrets: true, true); - if (user != null) + foreach (var account in userAccounts) { - var userAccounts = await _accountService.GetAccountsByUserAsync(user, hideSecrets: true, true); - - foreach (var account in userAccounts) - { - // Get USDC balance - var usdcBalances = await GetOrRefreshBalanceDataAsync(account.Name); - var usdcBalance = usdcBalances?.UsdcValue ?? 0; - usdcWalletValue += usdcBalance; - } - - foreach (var position in positions.Where(p => !p.IsFinished())) - { - var positionUsd = position.Open.Price * position.Open.Quantity; - var realized = position.ProfitAndLoss?.Realized ?? 0; - usdcInPositionsValue += positionUsd + realized; - } - - totalBalance = usdcWalletValue + usdcInPositionsValue; + // Get USDC balance + var usdcBalances = await GetOrRefreshBalanceDataAsync(account.Name); + var usdcBalance = usdcBalances?.UsdcValue ?? 0; + usdcWalletValue += usdcBalance; } + + foreach (var position in positions.Where(p => !p.IsFinished())) + { + var positionUsd = position.Open.Price * position.Open.Quantity; + var realized = position.ProfitAndLoss?.Realized ?? 0; + usdcInPositionsValue += positionUsd + realized; + } + + totalBalance = usdcWalletValue + usdcInPositionsValue; } catch (Exception ex) { @@ -232,23 +228,24 @@ public class AgentGrain : Grain, IAgentGrain usdcInPositionsValue = 0; } - var bots = await ServiceScopeHelpers.WithScopedService>(_scopeFactory, - async (botService) => { return await botService.GetBotsByUser((int)this.GetPrimaryKeyLong()); }); + var activeStrategies = await ServiceScopeHelpers.WithScopedService>(_scopeFactory, + async (botService) => + { + return (await botService.GetBotsByUser((int)this.GetPrimaryKeyLong())) + .Where(b => b.Status == BotStatus.Running) + .ToList(); + }); // Calculate Runtime based on the earliest position date DateTime? runtime = null; - if (positions.Any()) - { - runtime = bots.Min(p => p.StartupTime); - } - - var activeStrategiesCount = bots.Count(b => b.Status == BotStatus.Running); - - // Calculate bots allocation USD value from bot configurations var botsAllocationUsdValue = 0m; - if (bots.Any()) + + if (activeStrategies.Any()) { - var botIds = bots.Select(b => b.Identifier); + runtime = activeStrategies.Min(p => p.StartupTime); + + // Calculate bots allocation USD value from bot configurations + var botIds = activeStrategies.Select(b => b.Identifier); var botConfigs = await ServiceScopeHelpers.WithScopedService>( _scopeFactory, @@ -266,7 +263,7 @@ public class AgentGrain : Grain, IAgentGrain Losses = totalLosses, TotalROI = totalROI, Runtime = runtime, - ActiveStrategiesCount = activeStrategiesCount, + ActiveStrategiesCount = activeStrategies.Count(), TotalVolume = totalVolume, TotalBalance = totalBalance, TotalFees = totalFees, @@ -276,7 +273,8 @@ public class AgentGrain : Grain, IAgentGrain await _agentService.SaveOrUpdateAgentSummary(summary); // Insert balance tracking data - InsertBalanceTrackingData(totalBalance, botsAllocationUsdValue, netPnL, usdcWalletValue, usdcInPositionsValue); + InsertBalanceTrackingData(totalBalance, botsAllocationUsdValue, netPnL, usdcWalletValue, + usdcInPositionsValue); _logger.LogDebug( "Updated agent summary from position data for user {UserId}: NetPnL={NetPnL}, TotalPnL={TotalPnL}, Fees={Fees}, Volume={Volume}, Wins={Wins}, Losses={Losses}", @@ -633,7 +631,8 @@ public class AgentGrain : Grain, IAgentGrain /// /// Inserts balance tracking data into the AgentBalanceRepository /// - private void InsertBalanceTrackingData(decimal totalAccountUsdValue, decimal botsAllocationUsdValue, decimal pnl, decimal usdcWalletValue, decimal usdcInPositionsValue) + private void InsertBalanceTrackingData(decimal totalAccountUsdValue, decimal botsAllocationUsdValue, decimal pnl, + decimal usdcWalletValue, decimal usdcInPositionsValue) { try { @@ -657,7 +656,8 @@ public class AgentGrain : Grain, IAgentGrain } catch (Exception ex) { - _logger.LogError(ex, "Error inserting balance tracking data for user {UserId}", (int)this.GetPrimaryKeyLong()); + _logger.LogError(ex, "Error inserting balance tracking data for user {UserId}", + (int)this.GetPrimaryKeyLong()); } } } \ No newline at end of file