diff --git a/src/Managing.Application/Bots/Grains/LiveTradingBotGrain.cs b/src/Managing.Application/Bots/Grains/LiveTradingBotGrain.cs index a49a0e54..46cd3b82 100644 --- a/src/Managing.Application/Bots/Grains/LiveTradingBotGrain.cs +++ b/src/Managing.Application/Bots/Grains/LiveTradingBotGrain.cs @@ -165,8 +165,40 @@ public class LiveTradingBotGrain : Grain, ILiveTradingBotGrain, IRemindable try { + // Handle fallback for empty AccountName before creating the trading bot instance + var config = _state.State.Config; + if (string.IsNullOrEmpty(config.AccountName)) + { + // Fallback: Get the first account for the user + if (_state.State.User == null) + { + throw new InvalidOperationException($"Bot '{config.Name}' (ID: {_state.State.Identifier}) has no user information. Cannot determine fallback account."); + } + + var firstAccount = await ServiceScopeHelpers.WithScopedService( + _scopeFactory, + async accountService => + { + var userAccounts = await accountService.GetAccountsByUserAsync(_state.State.User, true, true); + var account = userAccounts.FirstOrDefault(); + if (account == null) + { + throw new InvalidOperationException($"User '{_state.State.User.Name}' has no accounts configured."); + } + return account; + }); + + // Update the configuration with the fallback account name + config.AccountName = firstAccount.Name; + _state.State.Config = config; + await _state.WriteStateAsync(); + + _logger.LogInformation("Bot '{BotName}' (ID: {BotId}) using fallback account '{AccountName}' for user '{UserName}'", + config.Name, _state.State.Identifier, firstAccount.Name, _state.State.User.Name); + } + // Create and initialize trading bot instance - _tradingBot = CreateTradingBotInstance(_state.State.Config); + _tradingBot = CreateTradingBotInstance(config); await _tradingBot.Start(previousStatus); // Set startup time only once (first successful start) diff --git a/src/Managing.Application/ManageBot/BotService.cs b/src/Managing.Application/ManageBot/BotService.cs index 5778b3f3..a78094df 100644 --- a/src/Managing.Application/ManageBot/BotService.cs +++ b/src/Managing.Application/ManageBot/BotService.cs @@ -129,6 +129,7 @@ namespace Managing.Application.ManageBot return firstAccount; }); + botConfig.AccountName = account.Name; _tradingBotLogger.LogInformation("Bot '{BotName}' (ID: {BotId}) using fallback account '{AccountName}' for user '{UserName}'", botConfig.Name, identifier, account.Name, user.Name); } @@ -159,6 +160,7 @@ namespace Managing.Application.ManageBot } } + await UpdateBotConfiguration(identifier, botConfig); var grainState = await botGrain.GetBotDataAsync(); if (previousStatus == BotStatus.Saved)