From 4d4e5b6d25bef71e1d3d2a4e1a796936ccda87a5 Mon Sep 17 00:00:00 2001 From: cryptooda Date: Thu, 20 Nov 2025 20:34:12 +0700 Subject: [PATCH] Update position value calculations in AgentGrain and BotService - Changed the calculation of USDC value in AgentGrain to use net profit and loss instead of realized profit. - Added similar position value calculations in BotService, including error handling for position retrieval failures. --- .../Bots/Grains/AgentGrain.cs | 4 ++-- .../ManageBot/BotService.cs | 20 +++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/Managing.Application/Bots/Grains/AgentGrain.cs b/src/Managing.Application/Bots/Grains/AgentGrain.cs index 7d68f787..ed8529a7 100644 --- a/src/Managing.Application/Bots/Grains/AgentGrain.cs +++ b/src/Managing.Application/Bots/Grains/AgentGrain.cs @@ -214,8 +214,8 @@ public class AgentGrain : Grain, IAgentGrain foreach (var position in positions.Where(p => p.IsOpen())) { var positionUsd = position.Open.Price * position.Open.Quantity; - var realized = position.ProfitAndLoss?.Realized ?? 0; - usdcInPositionsValue += positionUsd + realized; + var net = position.ProfitAndLoss?.Net ?? 0; + usdcInPositionsValue += positionUsd + net; } totalBalance = usdcWalletValue + usdcInPositionsValue; diff --git a/src/Managing.Application/ManageBot/BotService.cs b/src/Managing.Application/ManageBot/BotService.cs index 2593dfe2..9e352ea7 100644 --- a/src/Managing.Application/ManageBot/BotService.cs +++ b/src/Managing.Application/ManageBot/BotService.cs @@ -416,6 +416,26 @@ namespace Managing.Application.ManageBot } var usdcValue = usdcBalance?.Amount ?? 0m; + + // Get positions for the user and add their USDC value (similar to AgentGrain.UpdateSummary) + try + { + var positions = (await _tradingService.GetPositionByUserIdAsync(account.User.Id)) + .Where(p => p.IsValidForMetrics()).ToList(); + + foreach (var position in positions.Where(p => p.IsOpen())) + { + var positionUsd = position.Open.Price * position.Open.Quantity; + var net = position.ProfitAndLoss?.Net ?? 0; + usdcValue += positionUsd + net; + } + } + catch (Exception ex) + { + _tradingBotLogger.LogError(ex, "Error calculating position values for available allocation for user {UserId}", account.User.Id); + // Continue with calculation even if position retrieval fails + } + var available = usdcValue - totalAllocatedForAccount; return available < 0m ? 0m : available; });