Add more tests + Log pnl for each backtest

This commit is contained in:
2025-11-14 13:12:04 +07:00
parent 2548e9b757
commit d341ee05c9
11 changed files with 4163 additions and 97 deletions

View File

@@ -188,27 +188,10 @@ public class AgentGrain : Grain, IAgentGrain
var positions = (await _tradingService.GetPositionByUserIdAsync((int)this.GetPrimaryKeyLong()))
.Where(p => p.IsValidForMetrics()).ToList();
// Calculate aggregated statistics from position data
var totalPnL = positions.Sum(p => p.ProfitAndLoss?.Realized ?? 0);
var totalVolume = TradingBox.GetTotalVolumeTraded(positions);
var collateral = positions.Sum(p => p.Open.Price * p.Open.Quantity);
var totalFees = positions.Sum(p => p.CalculateTotalFees());
var metrics = TradingBox.CalculateAgentSummaryMetrics(positions);
// Store total fees in grain state for caching
_state.State.TotalFees = totalFees;
// Calculate wins/losses from position PnL
var totalWins = positions.Count(p => (p.ProfitAndLoss?.Net ?? 0) > 0);
var totalLosses = positions.Count(p => (p.ProfitAndLoss?.Net ?? 0) <= 0);
// Calculate ROI based on PnL minus fees
var netPnL = totalPnL - totalFees;
var totalROI = collateral switch
{
> 0 => (netPnL / collateral) * 100,
>= 0 => 0,
_ => 0
};
_state.State.TotalFees = metrics.TotalFees;
// Calculate total balance (USDC wallet + USDC in open positions value)
decimal totalBalance = 0;
@@ -274,16 +257,16 @@ public class AgentGrain : Grain, IAgentGrain
{
UserId = (int)this.GetPrimaryKeyLong(),
AgentName = _state.State.AgentName,
TotalPnL = totalPnL, // Gross PnL before fees
NetPnL = netPnL, // Net PnL after fees
Wins = totalWins,
Losses = totalLosses,
TotalROI = totalROI,
TotalPnL = metrics.TotalPnL, // Gross PnL before fees
NetPnL = metrics.NetPnL, // Net PnL after fees
Wins = metrics.Wins,
Losses = metrics.Losses,
TotalROI = metrics.TotalROI,
Runtime = runtime,
ActiveStrategiesCount = activeStrategies.Count(),
TotalVolume = totalVolume,
TotalVolume = metrics.TotalVolume,
TotalBalance = totalBalance,
TotalFees = totalFees,
TotalFees = metrics.TotalFees,
};
// Save summary to database
@@ -294,12 +277,13 @@ public class AgentGrain : Grain, IAgentGrain
await _state.WriteStateAsync();
// Insert balance tracking data
InsertBalanceTrackingData(totalBalance, botsAllocationUsdValue, netPnL, usdcWalletValue,
InsertBalanceTrackingData(totalBalance, botsAllocationUsdValue, metrics.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}",
this.GetPrimaryKeyLong(), netPnL, totalPnL, totalFees, totalVolume, totalWins, totalLosses);
this.GetPrimaryKeyLong(), metrics.NetPnL, metrics.TotalPnL, metrics.TotalFees, metrics.TotalVolume,
metrics.Wins, metrics.Losses);
}
catch (Exception ex)
{