Update balance tracking

This commit is contained in:
2025-10-03 16:43:20 +07:00
parent 6928770da7
commit f72bfc4ab8
11 changed files with 136 additions and 34 deletions

View File

@@ -25,8 +25,10 @@ public class AgentBalanceRepository : IAgentBalanceRepository
{
var balanceDto = new AgentBalanceDto
{
AgentName = balance.AgentName,
UserId = balance.UserId,
TotalBalanceValue = balance.TotalBalanceValue,
UsdcWalletValue = balance.UsdcWalletValue,
UsdcInPositionsValue = balance.UsdcInPositionsValue,
BotsAllocationUsdValue = balance.BotsAllocationUsdValue,
PnL = balance.PnL,
Time = balance.Time
@@ -40,7 +42,7 @@ public class AgentBalanceRepository : IAgentBalanceRepository
});
}
public async Task<IList<AgentBalance>> GetAgentBalances(string agentName, DateTime start, DateTime? end = null)
public async Task<IList<AgentBalance>> GetAgentBalancesByUserId(int userId, DateTime start, DateTime? end = null)
{
var results = await _influxDbRepository.QueryAsync(async query =>
{
@@ -48,15 +50,17 @@ public class AgentBalanceRepository : IAgentBalanceRepository
$"|> range(start: {start:s}Z" +
(end.HasValue ? $", stop: {end.Value:s}Z" : "") +
$") " +
$"|> filter(fn: (r) => r[\"agent_name\"] == \"{agentName}\") " +
$"|> filter(fn: (r) => r[\"user_id\"] == \"{userId}\") " +
$"|> pivot(rowKey: [\"_time\"], columnKey: [\"_field\"], valueColumn: \"_value\")";
var result = await query.QueryAsync<AgentBalanceDto>(flux, _influxDbRepository.Organization);
return result.Select(balance => new AgentBalance
{
AgentName = balance.AgentName,
UserId = balance.UserId,
TotalBalanceValue = balance.TotalBalanceValue,
UsdcWalletValue = balance.UsdcWalletValue,
UsdcInPositionsValue = balance.UsdcInPositionsValue,
BotsAllocationUsdValue = balance.BotsAllocationUsdValue,
PnL = balance.PnL,
Time = balance.Time
@@ -81,20 +85,31 @@ public class AgentBalanceRepository : IAgentBalanceRepository
var balances = await query.QueryAsync<AgentBalanceDto>(flux, _influxDbRepository.Organization);
// Group balances by agent name
// Group balances by user ID
var agentGroups = balances
.GroupBy(b => b.AgentName)
.Select(g => new AgentBalanceHistory
.GroupBy(b => b.UserId)
.Select(g =>
{
AgentName = g.Key,
AgentBalances = g.Select(b => new AgentBalance
var userBalances = g.Select(b => new AgentBalance
{
AgentName = b.AgentName,
UserId = b.UserId,
TotalBalanceValue = b.TotalBalanceValue,
UsdcWalletValue = b.UsdcWalletValue,
UsdcInPositionsValue = b.UsdcInPositionsValue,
BotsAllocationUsdValue = b.BotsAllocationUsdValue,
PnL = b.PnL,
Time = b.Time
}).OrderBy(b => b.Time).ToList()
}).OrderBy(b => b.Time).ToList();
// Use a default agent name since we don't store it in AgentBalance anymore
var mostRecentAgentName = $"User_{g.Key}";
return new AgentBalanceHistory
{
UserId = g.Key,
AgentName = mostRecentAgentName,
AgentBalances = userBalances
};
}).ToList();
return (agentGroups, agentGroups.Count);