forked from ellipti-labs/terra-oracle
/
binance.go
68 lines (55 loc) · 1.35 KB
/
binance.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
package binance
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/everett-protocol/terra-oracle/types"
"io/ioutil"
"net/http"
"regexp"
"time"
)
type BinanceSource struct {
btcToUsd types.Pair
interval time.Duration
}
var _ types.Source = &BinanceSource{}
func SourceProvider() (string, string, types.SourceProvider) {
return types.PairStr(types.BTC, types.USD), "binance", NewBinanceSource
}
func NewBinanceSource(interval time.Duration) types.Source {
return &BinanceSource{
btcToUsd: types.NewPair(types.BTC, types.USD),
interval: interval,
}
}
func (source BinanceSource) Market() string {
return "binance"
}
func (source BinanceSource) Pair() types.Pair {
return source.btcToUsd
}
func (source *BinanceSource) Fetch() error {
resp, err := http.Get("https://www.binance.com/api/v1/aggTrades?limit=1&symbol=BTCUSDT")
if err != nil {
return err
}
defer func() {
resp.Body.Close()
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
re, _ := regexp.Compile("\"p\":\"[0-9.]+\"")
str := re.FindString(string(body))
re, _ = regexp.Compile("[0-9.]+")
price := re.FindString(str)
decAmount, err := sdk.NewDecFromStr(price)
if err != nil {
return err
}
source.btcToUsd = source.btcToUsd.SetPrice(decAmount)
return nil
}
func (source BinanceSource) Interval() time.Duration {
return source.interval
}