107 lines
2.5 KiB
Go
107 lines
2.5 KiB
Go
package finnhub
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
const baseURL = "https://finnhub.io/api/v1"
|
|
|
|
type Client struct {
|
|
apiKey string
|
|
http *http.Client
|
|
}
|
|
|
|
type NewsItem struct {
|
|
ID int `json:"id"`
|
|
Category string `json:"category"`
|
|
Datetime int64 `json:"datetime"`
|
|
Headline string `json:"headline"`
|
|
Related string `json:"related"`
|
|
Source string `json:"source"`
|
|
URL string `json:"url"`
|
|
Summary string `json:"summary"`
|
|
}
|
|
|
|
func New(apiKey string) *Client {
|
|
return &Client{
|
|
apiKey: apiKey,
|
|
http: &http.Client{Timeout: 10 * time.Second},
|
|
}
|
|
}
|
|
|
|
func (c *Client) CompanyNews(symbol, from, to string) ([]NewsItem, error) {
|
|
url := fmt.Sprintf("%s/company-news?symbol=%s&from=%s&to=%s&token=%s",
|
|
baseURL, symbol, from, to, c.apiKey)
|
|
return c.fetchNews(url)
|
|
}
|
|
|
|
func (c *Client) MarketNews() ([]NewsItem, error) {
|
|
url := fmt.Sprintf("%s/news?category=general&token=%s", baseURL, c.apiKey)
|
|
return c.fetchNews(url)
|
|
}
|
|
|
|
// NextEarningsDate retourne la prochaine date d'annonce des résultats (90 jours max).
|
|
func (c *Client) NextEarningsDate(symbol string) (string, error) {
|
|
from := time.Now().Format("2006-01-02")
|
|
to := time.Now().AddDate(0, 3, 0).Format("2006-01-02")
|
|
url := fmt.Sprintf("%s/calendar/earnings?from=%s&to=%s&symbol=%s&token=%s",
|
|
baseURL, from, to, symbol, c.apiKey)
|
|
|
|
resp, err := c.http.Get(url)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != 200 {
|
|
return "", fmt.Errorf("finnhub earnings: HTTP %d", resp.StatusCode)
|
|
}
|
|
|
|
var result struct {
|
|
EarningsCalendar []struct {
|
|
Date string `json:"date"`
|
|
Symbol string `json:"symbol"`
|
|
} `json:"earningsCalendar"`
|
|
}
|
|
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
|
return "", err
|
|
}
|
|
if len(result.EarningsCalendar) == 0 {
|
|
return "", nil
|
|
}
|
|
return result.EarningsCalendar[0].Date, nil
|
|
}
|
|
|
|
func (c *Client) Ping() error {
|
|
url := fmt.Sprintf("%s/news?category=general&minId=999999999&token=%s", baseURL, c.apiKey)
|
|
resp, err := c.http.Get(url)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode == 401 || resp.StatusCode == 403 {
|
|
return fmt.Errorf("invalid API key (HTTP %d)", resp.StatusCode)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (c *Client) fetchNews(url string) ([]NewsItem, error) {
|
|
resp, err := c.http.Get(url)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != 200 {
|
|
return nil, fmt.Errorf("finnhub: HTTP %d", resp.StatusCode)
|
|
}
|
|
|
|
var items []NewsItem
|
|
if err := json.NewDecoder(resp.Body).Decode(&items); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|