Fix restart with no accountName

This commit is contained in:
2025-10-12 16:28:53 +07:00
parent 30fccc3644
commit 49b0f7b696
2 changed files with 35 additions and 1 deletions

View File

@@ -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<IAccountService, Account>(
_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)