Update balance tracking
This commit is contained in:
@@ -31,9 +31,40 @@ public class AgentService : IAgentService
|
||||
|
||||
public async Task<AgentBalanceHistory> GetAgentBalances(string agentName, DateTime start,
|
||||
DateTime? end = null)
|
||||
{
|
||||
// Get userId from agentName by looking up the user
|
||||
var userId = await ServiceScopeHelpers.WithScopedService<IUserService, int?>(_serviceScopeFactory,
|
||||
async (userService) =>
|
||||
{
|
||||
var user = await userService.GetUserByAgentName(agentName);
|
||||
return user?.Id;
|
||||
});
|
||||
|
||||
if (!userId.HasValue)
|
||||
{
|
||||
// Return empty result if user not found
|
||||
return new AgentBalanceHistory
|
||||
{
|
||||
UserId = 0,
|
||||
AgentName = agentName,
|
||||
AgentBalances = new List<AgentBalance>()
|
||||
};
|
||||
}
|
||||
|
||||
// Use the UserId-based method internally
|
||||
var result = await GetAgentBalancesByUserId(userId.Value, start, end);
|
||||
|
||||
// Override the AgentName to use the requested agentName instead of the default
|
||||
result.AgentName = agentName;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<AgentBalanceHistory> GetAgentBalancesByUserId(int userId, DateTime start,
|
||||
DateTime? end = null)
|
||||
{
|
||||
var effectiveEnd = end ?? DateTime.UtcNow;
|
||||
string cacheKey = $"AgentBalances_{agentName}_{start:yyyyMMdd}_{effectiveEnd:yyyyMMdd}";
|
||||
string cacheKey = $"AgentBalancesByUserId_{userId}_{start:yyyyMMdd}_{effectiveEnd:yyyyMMdd}";
|
||||
|
||||
// Check if the balances are already cached
|
||||
var cachedBalances = _cacheService.GetValue<AgentBalanceHistory>(cacheKey);
|
||||
@@ -43,12 +74,13 @@ public class AgentService : IAgentService
|
||||
return cachedBalances;
|
||||
}
|
||||
|
||||
var balances = await _agentBalanceRepository.GetAgentBalances(agentName, start, end);
|
||||
var balances = await _agentBalanceRepository.GetAgentBalancesByUserId(userId, start, end);
|
||||
|
||||
// Create a single AgentBalanceHistory with all balances
|
||||
var result = new AgentBalanceHistory
|
||||
{
|
||||
AgentName = agentName,
|
||||
UserId = userId,
|
||||
AgentName = $"User_{userId}",
|
||||
AgentBalances = balances.OrderBy(b => b.Time).ToList()
|
||||
};
|
||||
|
||||
|
||||
@@ -193,8 +193,10 @@ public class AgentGrain : Grain, IAgentGrain
|
||||
_ => 0
|
||||
};
|
||||
|
||||
// Calculate total balance (USDC + open positions value)
|
||||
// Calculate total balance (USDC wallet + USDC in open positions value)
|
||||
decimal totalBalance = 0;
|
||||
decimal usdcWalletValue = 0;
|
||||
decimal usdcInPositionsValue = 0;
|
||||
try
|
||||
{
|
||||
var userId = (int)this.GetPrimaryKeyLong();
|
||||
@@ -209,20 +211,25 @@ public class AgentGrain : Grain, IAgentGrain
|
||||
// Get USDC balance
|
||||
var usdcBalances = await GetOrRefreshBalanceDataAsync(account.Name);
|
||||
var usdcBalance = usdcBalances?.UsdcValue ?? 0;
|
||||
totalBalance += usdcBalance;
|
||||
usdcWalletValue += usdcBalance;
|
||||
}
|
||||
|
||||
foreach (var position in positions.Where(p => !p.IsFinished()))
|
||||
{
|
||||
totalBalance += position.Open.Price * position.Open.Quantity;
|
||||
totalBalance += position.ProfitAndLoss?.Realized ?? 0;
|
||||
var positionUsd = position.Open.Price * position.Open.Quantity;
|
||||
var realized = position.ProfitAndLoss?.Realized ?? 0;
|
||||
usdcInPositionsValue += positionUsd + realized;
|
||||
}
|
||||
|
||||
totalBalance = usdcWalletValue + usdcInPositionsValue;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error calculating total balance for agent {UserId}", this.GetPrimaryKeyLong());
|
||||
totalBalance = 0; // Set to 0 if calculation fails
|
||||
usdcWalletValue = 0;
|
||||
usdcInPositionsValue = 0;
|
||||
}
|
||||
|
||||
var bots = await ServiceScopeHelpers.WithScopedService<IBotService, IEnumerable<Bot>>(_scopeFactory,
|
||||
@@ -269,7 +276,7 @@ public class AgentGrain : Grain, IAgentGrain
|
||||
await _agentService.SaveOrUpdateAgentSummary(summary);
|
||||
|
||||
// Insert balance tracking data
|
||||
InsertBalanceTrackingData(totalBalance, botsAllocationUsdValue, netPnL);
|
||||
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}",
|
||||
@@ -626,14 +633,16 @@ public class AgentGrain : Grain, IAgentGrain
|
||||
/// <summary>
|
||||
/// Inserts balance tracking data into the AgentBalanceRepository
|
||||
/// </summary>
|
||||
private void InsertBalanceTrackingData(decimal totalAccountUsdValue, decimal botsAllocationUsdValue, decimal pnl)
|
||||
private void InsertBalanceTrackingData(decimal totalAccountUsdValue, decimal botsAllocationUsdValue, decimal pnl, decimal usdcWalletValue, decimal usdcInPositionsValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
var agentBalance = new AgentBalance
|
||||
{
|
||||
AgentName = _state.State.AgentName,
|
||||
UserId = (int)this.GetPrimaryKeyLong(),
|
||||
TotalBalanceValue = totalAccountUsdValue,
|
||||
UsdcWalletValue = usdcWalletValue,
|
||||
UsdcInPositionsValue = usdcInPositionsValue,
|
||||
BotsAllocationUsdValue = botsAllocationUsdValue,
|
||||
PnL = pnl,
|
||||
Time = DateTime.UtcNow
|
||||
@@ -642,13 +651,13 @@ public class AgentGrain : Grain, IAgentGrain
|
||||
_agentBalanceRepository.InsertAgentBalance(agentBalance);
|
||||
|
||||
_logger.LogDebug(
|
||||
"Inserted balance tracking data for agent {AgentName}: TotalBalanceValue={TotalBalanceValue}, BotsAllocationUsdValue={BotsAllocationUsdValue}, PnL={PnL}",
|
||||
agentBalance.AgentName, agentBalance.TotalBalanceValue, agentBalance.BotsAllocationUsdValue,
|
||||
"Inserted balance tracking data for user {UserId}: TotalBalanceValue={TotalBalanceValue}, BotsAllocationUsdValue={BotsAllocationUsdValue}, PnL={PnL}",
|
||||
agentBalance.UserId, agentBalance.TotalBalanceValue, agentBalance.BotsAllocationUsdValue,
|
||||
agentBalance.PnL);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error inserting balance tracking data for agent {AgentName}", _state.State.AgentName);
|
||||
_logger.LogError(ex, "Error inserting balance tracking data for user {UserId}", (int)this.GetPrimaryKeyLong());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user