Use bot allocation on running strategies only

This commit is contained in:
2025-10-04 13:54:14 +07:00
parent f72bfc4ab8
commit 3635fb4c29

View File

@@ -169,7 +169,7 @@ public class AgentGrain : Grain, IAgentGrain
try try
{ {
// Get all positions for this agent's bots as initiator // 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 // Calculate aggregated statistics from position data
var totalPnL = positions.Sum(p => p.ProfitAndLoss?.Realized ?? 0); var totalPnL = positions.Sum(p => p.ProfitAndLoss?.Realized ?? 0);
@@ -201,9 +201,6 @@ public class AgentGrain : Grain, IAgentGrain
{ {
var userId = (int)this.GetPrimaryKeyLong(); var userId = (int)this.GetPrimaryKeyLong();
var user = await _userService.GetUserByIdAsync(userId); var user = await _userService.GetUserByIdAsync(userId);
if (user != null)
{
var userAccounts = await _accountService.GetAccountsByUserAsync(user, hideSecrets: true, true); var userAccounts = await _accountService.GetAccountsByUserAsync(user, hideSecrets: true, true);
foreach (var account in userAccounts) foreach (var account in userAccounts)
@@ -223,7 +220,6 @@ public class AgentGrain : Grain, IAgentGrain
totalBalance = usdcWalletValue + usdcInPositionsValue; totalBalance = usdcWalletValue + usdcInPositionsValue;
} }
}
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Error calculating total balance for agent {UserId}", this.GetPrimaryKeyLong()); _logger.LogError(ex, "Error calculating total balance for agent {UserId}", this.GetPrimaryKeyLong());
@@ -232,23 +228,24 @@ public class AgentGrain : Grain, IAgentGrain
usdcInPositionsValue = 0; usdcInPositionsValue = 0;
} }
var bots = await ServiceScopeHelpers.WithScopedService<IBotService, IEnumerable<Bot>>(_scopeFactory, var activeStrategies = await ServiceScopeHelpers.WithScopedService<IBotService, List<Bot>>(_scopeFactory,
async (botService) => { return await botService.GetBotsByUser((int)this.GetPrimaryKeyLong()); }); async (botService) =>
{
return (await botService.GetBotsByUser((int)this.GetPrimaryKeyLong()))
.Where(b => b.Status == BotStatus.Running)
.ToList();
});
// Calculate Runtime based on the earliest position date // Calculate Runtime based on the earliest position date
DateTime? runtime = null; DateTime? runtime = null;
if (positions.Any()) var botsAllocationUsdValue = 0m;
{
runtime = bots.Min(p => p.StartupTime);
}
var activeStrategiesCount = bots.Count(b => b.Status == BotStatus.Running); if (activeStrategies.Any())
{
runtime = activeStrategies.Min(p => p.StartupTime);
// Calculate bots allocation USD value from bot configurations // Calculate bots allocation USD value from bot configurations
var botsAllocationUsdValue = 0m; var botIds = activeStrategies.Select(b => b.Identifier);
if (bots.Any())
{
var botIds = bots.Select(b => b.Identifier);
var botConfigs = var botConfigs =
await ServiceScopeHelpers.WithScopedService<IBotService, IEnumerable<TradingBotConfig>>( await ServiceScopeHelpers.WithScopedService<IBotService, IEnumerable<TradingBotConfig>>(
_scopeFactory, _scopeFactory,
@@ -266,7 +263,7 @@ public class AgentGrain : Grain, IAgentGrain
Losses = totalLosses, Losses = totalLosses,
TotalROI = totalROI, TotalROI = totalROI,
Runtime = runtime, Runtime = runtime,
ActiveStrategiesCount = activeStrategiesCount, ActiveStrategiesCount = activeStrategies.Count(),
TotalVolume = totalVolume, TotalVolume = totalVolume,
TotalBalance = totalBalance, TotalBalance = totalBalance,
TotalFees = totalFees, TotalFees = totalFees,
@@ -276,7 +273,8 @@ public class AgentGrain : Grain, IAgentGrain
await _agentService.SaveOrUpdateAgentSummary(summary); await _agentService.SaveOrUpdateAgentSummary(summary);
// Insert balance tracking data // Insert balance tracking data
InsertBalanceTrackingData(totalBalance, botsAllocationUsdValue, netPnL, usdcWalletValue, usdcInPositionsValue); InsertBalanceTrackingData(totalBalance, botsAllocationUsdValue, netPnL, usdcWalletValue,
usdcInPositionsValue);
_logger.LogDebug( _logger.LogDebug(
"Updated agent summary from position data for user {UserId}: NetPnL={NetPnL}, TotalPnL={TotalPnL}, Fees={Fees}, Volume={Volume}, Wins={Wins}, Losses={Losses}", "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
/// <summary> /// <summary>
/// Inserts balance tracking data into the AgentBalanceRepository /// Inserts balance tracking data into the AgentBalanceRepository
/// </summary> /// </summary>
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 try
{ {
@@ -657,7 +656,8 @@ public class AgentGrain : Grain, IAgentGrain
} }
catch (Exception ex) 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());
} }
} }
} }