Latest fix

This commit is contained in:
Eden Kirin
2025-12-25 20:02:47 +01:00
parent f077893c39
commit af9bf84d0a
4 changed files with 989 additions and 27 deletions

View File

@ -67,42 +67,68 @@ func fetchExchangeRate() (float64, error) {
func fetchStockPrice(ticker string) (float64, error) {
client := &http.Client{Timeout: 10 * time.Second}
// Try Yahoo Finance API
url := fmt.Sprintf("https://query1.finance.yahoo.com/v8/finance/chart/%s?interval=1d&range=1d", ticker)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return 0, err
// Try different ticker formats for European stocks
tickersToTry := []string{ticker}
// If ticker doesn't have exchange suffix, try adding common ones
if !strings.Contains(ticker, ".") {
tickersToTry = append(tickersToTry,
ticker+".L", // London Stock Exchange
ticker+".AS", // Amsterdam
ticker+".PA", // Paris
ticker+".DE", // XETRA (Germany)
ticker+".MI", // Milan
)
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
var lastErr error
for _, tryTicker := range tickersToTry {
// Try Yahoo Finance API
url := fmt.Sprintf("https://query1.finance.yahoo.com/v8/finance/chart/%s?interval=1d&range=1d", tryTicker)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
lastErr = err
continue
}
resp, err := client.Do(req)
if err != nil {
return 0, fmt.Errorf("failed to fetch from Yahoo: %w", err)
}
defer resp.Body.Close()
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
body, err := io.ReadAll(resp.Body)
if err != nil {
return 0, fmt.Errorf("failed to read response: %w", err)
}
resp, err := client.Do(req)
if err != nil {
lastErr = fmt.Errorf("failed to fetch from Yahoo: %w", err)
continue
}
defer resp.Body.Close()
var chartData YahooChartResponse
if err := json.Unmarshal(body, &chartData); err != nil {
return 0, fmt.Errorf("failed to decode Yahoo response: %w", err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
lastErr = fmt.Errorf("failed to read response: %w", err)
continue
}
if chartData.Chart.Error != nil {
return 0, fmt.Errorf("Yahoo API error: %s", chartData.Chart.Error.Description)
}
var chartData YahooChartResponse
if err := json.Unmarshal(body, &chartData); err != nil {
lastErr = fmt.Errorf("failed to decode Yahoo response: %w", err)
continue
}
if len(chartData.Chart.Result) > 0 {
price := chartData.Chart.Result[0].Meta.RegularMarketPrice
if price > 0 {
return price, nil
if chartData.Chart.Error != nil {
lastErr = fmt.Errorf("Yahoo API error: %s", chartData.Chart.Error.Description)
continue
}
if len(chartData.Chart.Result) > 0 {
price := chartData.Chart.Result[0].Meta.RegularMarketPrice
if price > 0 {
log.Printf("Successfully fetched price for %s (tried as %s): $%.2f", ticker, tryTicker, price)
return price, nil
}
}
}
if lastErr != nil {
return 0, fmt.Errorf("price not found after trying all formats: %w", lastErr)
}
return 0, fmt.Errorf("price not found in response")
}