refactor: 优化YahooMarketService,复用实例并改进异常类型

This commit is contained in:
OpenClaw Agent 2026-03-17 04:22:00 +00:00
parent 2a6512ff48
commit aa4f63455b

View File

@ -34,7 +34,10 @@ public class YahooMarketService : IYahooMarketService
public YahooMarketService(ILogger<YahooMarketService> logger) public YahooMarketService(ILogger<YahooMarketService> logger)
{ {
_logger = logger; _logger = logger;
_yahooQuotes = new YahooQuotesBuilder().Build(); // 默认获取最近60天的历史数据
_yahooQuotes = new YahooQuotesBuilder()
.WithHistoryStartDate(Instant.FromDateTimeUtc(DateTime.UtcNow.AddDays(-60)))
.Build();
} }
public async Task<MarketPriceResponse> GetStockPriceAsync(string symbol) public async Task<MarketPriceResponse> GetStockPriceAsync(string symbol)
@ -43,11 +46,11 @@ public class YahooMarketService : IYahooMarketService
Snapshot? snapshot = await _yahooQuotes.GetSnapshotAsync(symbol); Snapshot? snapshot = await _yahooQuotes.GetSnapshotAsync(symbol);
if (snapshot is null) if (snapshot is null)
throw new Exception($"Yahoo未知标的: {symbol}"); throw new InvalidOperationException($"Yahoo未知标的: {symbol}");
decimal price = snapshot.RegularMarketPrice; decimal price = snapshot.RegularMarketPrice;
if (price <= 0) if (price <= 0)
throw new Exception($"Yahoo获取价格失败标的: {symbol}"); throw new InvalidOperationException($"Yahoo获取价格失败标的: {symbol}");
decimal previousClose = snapshot.RegularMarketPreviousClose; decimal previousClose = snapshot.RegularMarketPreviousClose;
if (previousClose <= 0) if (previousClose <= 0)
@ -70,16 +73,9 @@ public class YahooMarketService : IYahooMarketService
{ {
_logger.LogInformation("Yahoo获取历史数据: {Symbol}, {Timeframe}, {Limit}", symbol, timeframe, limit); _logger.LogInformation("Yahoo获取历史数据: {Symbol}, {Timeframe}, {Limit}", symbol, timeframe, limit);
// 计算历史数据的开始时间 Result<History> result = await _yahooQuotes.GetHistoryAsync(symbol);
Instant startDate = Instant.FromDateTimeUtc(DateTime.UtcNow.AddDays(-limit * 2));
YahooQuotes yahooQuotes = new YahooQuotesBuilder()
.WithHistoryStartDate(startDate)
.Build();
Result<History> result = await yahooQuotes.GetHistoryAsync(symbol);
if (result.Value == null) if (result.Value == null)
throw new Exception($"Yahoo获取历史数据失败标的: {symbol}"); throw new InvalidOperationException($"Yahoo获取历史数据失败标的: {symbol}");
History history = result.Value; History history = result.Value;
var ticks = history.Ticks; var ticks = history.Ticks;