This repository has been archived by the owner on Feb 24, 2023. It is now read-only.
/
alphavantagestock.go
102 lines (88 loc) · 2.29 KB
/
alphavantagestock.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package driver
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
"github.com/bandprotocol/band/go/dt"
"github.com/ethereum/go-ethereum/common"
"github.com/spf13/viper"
"github.com/tidwall/gjson"
)
var alphaVantageStockApikey = os.Getenv("AlphaVantageStockApikey")
var alphaVantageStockCaches = make(map[string]ValueWithLastUpdated)
type AlphaVantageStock struct{}
func queryStockValue(from string) error {
client := http.Client{}
req, err := http.NewRequest("GET", "https://www.alphavantage.co/query", nil)
if err != nil {
return err
}
q := req.URL.Query()
q.Add("function", "GLOBAL_QUOTE")
q.Add("symbol", from)
q.Add("apikey", alphaVantageStockApikey)
req.URL.RawQuery = q.Encode()
req.Header.Add("Accept", "application/json")
res, err := client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
value := gjson.GetBytes(body, "Global Quote.05\\. price")
if !value.Exists() {
return fmt.Errorf("Key doesn't existed")
}
var temp ValueWithLastUpdated
temp.value = value.Float()
temp.lastUpdated = time.Now().Unix()
alphaVantageStockCaches[from] = temp
return nil
}
func (*AlphaVantageStock) Configure(config *viper.Viper) {
alphaVantageStockApikey = config.GetString("apikey")
}
func (*AlphaVantageStock) QuerySpotPrice(symbol string) (float64, error) {
pairs := strings.Split(symbol, "-")
if len(pairs) != 1 {
return 0, fmt.Errorf("spotpx: symbol %s is not valid", symbol)
}
var err error
if _, ok := alphaVantageStockCaches[symbol]; ok {
if lastUpdated == 0 || time.Now().Unix()-alphaVantageStockCaches[symbol].lastUpdated > 1200 {
err = queryStockValue(symbol)
}
} else {
err = queryStockValue(symbol)
}
if err != nil {
return 0, err
}
if _, ok := alphaVantageStockCaches[symbol]; ok {
return alphaVantageStockCaches[symbol].value, nil
}
return 0, fmt.Errorf("Invalid key")
}
func (a *AlphaVantageStock) Query(key []byte) dt.Answer {
keys := strings.Split(string(key), "/")
if len(keys) != 2 {
return dt.NotFoundAnswer
}
if keys[0] == "SPOTPX" {
value, err := a.QuerySpotPrice(keys[1])
if err != nil {
return dt.NotFoundAnswer
}
return dt.Answer{
Option: dt.Answered,
Value: common.BigToHash(PriceToBigInt(value)),
}
}
return dt.NotFoundAnswer
}