Add agentbalance

This commit is contained in:
2025-08-15 19:35:01 +07:00
parent f58d1cea3b
commit cd93dede4e
11 changed files with 100 additions and 18 deletions

View File

@@ -14,6 +14,10 @@ public class AgentGrain : Grain, IAgentGrain, IRemindable
private readonly ILogger<AgentGrain> _logger;
private readonly IBotService _botService;
private readonly IAgentService _agentService;
private readonly IExchangeService _exchangeService;
private readonly IUserService _userService;
private readonly IAccountService _accountService;
private readonly ITradingService _tradingService;
private const string _updateSummaryReminderName = "UpdateAgentSummary";
public AgentGrain(
@@ -21,12 +25,20 @@ public class AgentGrain : Grain, IAgentGrain, IRemindable
IPersistentState<AgentGrainState> state,
ILogger<AgentGrain> logger,
IBotService botService,
IAgentService agentService)
IAgentService agentService,
IExchangeService exchangeService,
IUserService userService,
IAccountService accountService,
ITradingService tradingService)
{
_state = state;
_logger = logger;
_botService = botService;
_agentService = agentService;
_exchangeService = exchangeService;
_userService = userService;
_accountService = accountService;
_tradingService = tradingService;
}
public override Task OnActivateAsync(CancellationToken cancellationToken)
@@ -122,6 +134,43 @@ public class AgentGrain : Grain, IAgentGrain, IRemindable
runtime = bots.Max(b => b.StartupTime);
}
// Calculate total balance (USDC + open positions value)
decimal totalBalance = 0;
try
{
var userId = (int)this.GetPrimaryKeyLong();
var user = await _userService.GetUserByIdAsync(userId);
if (user != null)
{
var userAccounts = await _accountService.GetAccountsByUserAsync(user, hideSecrets: true, true);
foreach (var account in userAccounts)
{
// Get USDC balance
var usdcBalances = await _exchangeService.GetBalances(account);
var usdcBalance = usdcBalances.FirstOrDefault(b => b.TokenName?.ToUpper() == "USDC")?.Amount ??
0;
totalBalance += usdcBalance;
}
// Get positions for all bots using their GUIDs as InitiatorIdentifier
var botPositions =
await _tradingService.GetPositionsByInitiatorIdentifiersAsync(_state.State.BotIds);
foreach (var position in botPositions.Where(p => !p.IsFinished()))
{
totalBalance += position.Open.Price * position.Open.Quantity;
totalBalance += position.ProfitAndLoss?.Realized ?? 0;
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error calculating total balance for agent {UserId}", this.GetPrimaryKeyLong());
totalBalance = 0; // Set to 0 if calculation fails
}
var summary = new AgentSummary
{
UserId = (int)this.GetPrimaryKeyLong(),
@@ -133,6 +182,7 @@ public class AgentGrain : Grain, IAgentGrain, IRemindable
Runtime = runtime,
ActiveStrategiesCount = bots.Count(b => b.Status == BotStatus.Running),
TotalVolume = totalVolume,
TotalBalance = totalBalance,
};
// Save summary to database