diff --git a/AssetManager.Services/PortfolioService.cs b/AssetManager.Services/PortfolioService.cs index 50383e1..95f553f 100644 --- a/AssetManager.Services/PortfolioService.cs +++ b/AssetManager.Services/PortfolioService.cs @@ -222,11 +222,23 @@ public class PortfolioService : IPortfolioService continue; } - // 获取实时价格(自动路由数据源) - var priceResponse = await _marketDataService.GetPriceAsync(pos.StockCode, pos.AssetType ?? "Stock"); + // 获取实时价格(自动路由数据源),失败则降级使用成本价 + decimal currentPrice = pos.AvgPrice; + decimal previousClose = pos.AvgPrice; + try + { + var priceResponse = await _marketDataService.GetPriceAsync(pos.StockCode, pos.AssetType ?? "Stock"); + if (priceResponse.Price > 0) + { + currentPrice = priceResponse.Price; + previousClose = priceResponse.PreviousClose > 0 ? priceResponse.PreviousClose : currentPrice; + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, "获取标的 {StockCode} 实时价格失败,使用成本价作为当前价", pos.StockCode); + } - decimal currentPrice = priceResponse.Price; - decimal previousClose = priceResponse.PreviousClose; decimal currentPositionValue = pos.Shares * currentPrice; decimal costPositionValue = pos.Shares * pos.AvgPrice; decimal todayProfit = previousClose > 0 ? pos.Shares * (currentPrice - previousClose) : 0; @@ -289,11 +301,23 @@ public class PortfolioService : IPortfolioService continue; } - // 获取实时价格(自动路由数据源) - var priceResponse = await _marketDataService.GetPriceAsync(pos.StockCode, pos.AssetType ?? "Stock"); + // 获取实时价格(自动路由数据源),失败则降级使用成本价 + decimal currentPrice = pos.AvgPrice; + decimal previousClose = pos.AvgPrice; + try + { + var priceResponse = await _marketDataService.GetPriceAsync(pos.StockCode, pos.AssetType ?? "Stock"); + if (priceResponse.Price > 0) + { + currentPrice = priceResponse.Price; + previousClose = priceResponse.PreviousClose > 0 ? priceResponse.PreviousClose : currentPrice; + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, "获取标的 {StockCode} 实时价格失败,使用成本价作为当前价", pos.StockCode); + } - decimal currentPrice = priceResponse.Price; - decimal previousClose = priceResponse.PreviousClose; decimal positionValue = pos.Shares * currentPrice; decimal cost = pos.Shares * pos.AvgPrice; decimal profit = positionValue - cost; @@ -551,10 +575,21 @@ public class PortfolioService : IPortfolioService continue; } - // 获取实时价格(自动路由数据源) - var priceResponse = _marketDataService.GetPriceAsync(pos.StockCode, pos.AssetType ?? "Stock").GetAwaiter().GetResult(); + // 获取实时价格(自动路由数据源),失败则降级使用成本价 + decimal currentPrice = pos.AvgPrice; + try + { + var priceResponse = _marketDataService.GetPriceAsync(pos.StockCode, pos.AssetType ?? "Stock").GetAwaiter().GetResult(); + if (priceResponse.Price > 0) + { + currentPrice = priceResponse.Price; + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, "获取标的 {StockCode} 实时价格失败,使用成本价计算组合总价值", pos.StockCode); + } - decimal currentPrice = priceResponse.Price; totalPortfolioValue += pos.Shares * currentPrice; }