-
Notifications
You must be signed in to change notification settings - Fork 3
/
global_quote.go
58 lines (52 loc) · 1.86 KB
/
global_quote.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package alphavantage
import (
"encoding/json"
"fmt"
"strconv"
"strings"
)
// GlobalQuoteResponse - encapsulates global quote repsonse
type GlobalQuoteResponse struct {
GlobalQuote GlobalQuote `json:"Global Quote"`
}
// GlobalQuote - encapsulates global quote
type GlobalQuote struct {
Symbol string `json:"01. symbol"`
Open float64 `json:"02. open,string"`
High float64 `json:"03. high,string"`
Low float64 `json:"04. low,string"`
Price float64 `json:"05. price,string"`
Volume int `json:"06. volume,string"`
LatestTradingDay string `json:"07. latest trading day"`
PreviousClose float64 `json:"08. previous close,string"`
Change float64 `json:"09. change,string"`
ChangePercentStr string `json:"10. change percent"`
ChangePercent float64
}
func toGlobalQuote(buf []byte) (*GlobalQuote, error) {
globalQuoteResponse := &GlobalQuoteResponse{}
if err := json.Unmarshal(buf, globalQuoteResponse); err != nil {
return nil, err
}
return &globalQuoteResponse.GlobalQuote, nil
}
// GlobalQuote fetches data from the Global Quote endpoint for the given symbol
func (c *Client) GlobalQuote(symbol string) (*GlobalQuote, error) {
const functionName = "GLOBAL_QUOTE"
url := fmt.Sprintf("%s/query?function=%s&symbol=%s&apikey=%s",
baseURL, functionName, symbol, c.apiKey)
body, err := c.makeHTTPRequest(url)
if err != nil {
return nil, err
}
globalQuote, err := toGlobalQuote(body)
if err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
globalQuote.ChangePercentStr = strings.ReplaceAll(globalQuote.ChangePercentStr, "%", "")
globalQuote.ChangePercent, err = strconv.ParseFloat(globalQuote.ChangePercentStr, 64)
if err != nil {
return nil, fmt.Errorf("cannot parse field ChangePercent(%q): %v", globalQuote.ChangePercentStr, err)
}
return globalQuote, nil
}