-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprice.go
101 lines (84 loc) · 2.13 KB
/
price.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
)
const (
solAddr = "So11111111111111111111111111111111111111112"
jarvAddr = "CmpuL8k9KY3NrpfDRoJrVmuwd1zRMFRUxX55avyGpump"
fartAddr = "9BB6NFEcjBCtnNLFko2FqVQBq8HHM13kCyYcdQbgpump"
wormAddr = "DwDtUqBZJtbRpdjsFw3N7YKB5epocSru25BGcVhfcYtg"
// Jupiter API
host = "https://api.jup.ag"
priceEndpoint = "/price/v2"
priceFetchInterval = 5 * time.Second
)
type priceFetcher struct {
client *http.Client
ticker *time.Ticker
coinAddr string
coinName string
priceChan chan price
}
func newPriceFetcher(name, addr string) *priceFetcher {
return &priceFetcher{
client: &http.Client{},
ticker: time.NewTicker(priceFetchInterval),
coinAddr: addr,
coinName: name,
priceChan: make(chan price),
}
}
func (pf *priceFetcher) fetchPrice() error {
url := fmt.Sprintf("%s%s?ids=%s,%s", host, priceEndpoint, pf.coinAddr, solAddr)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return fmt.Errorf("error creating request: %w", err)
}
// fetch the endpoint on every tick
for range pf.ticker.C {
resp, err := pf.client.Do(req)
if err != nil {
return fmt.Errorf("error fetching price: %w", err)
}
defer resp.Body.Close()
type respObj struct {
Data map[string]struct {
Price string `json:"price"`
} `json:"data"`
TimeTake float64 `json:"timeTaken"`
}
var data respObj
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return fmt.Errorf("error decoding response: %w", err)
}
coinP := newPrice(pf.coinName, pf.coinAddr, data.Data[pf.coinAddr].Price)
pf.priceChan <- coinP
}
return nil
}
func newPrice(name, mint, priceUSD string) price {
p, err := strconv.ParseFloat(priceUSD, 64)
if err != nil {
fmt.Println("Error converting price to float64:", err)
return price{}
}
return price{
name: name,
mint: mint,
priceUSD: p,
ts: time.Now(),
}
}
type price struct {
name string
mint string
priceUSD float64
ts time.Time
}
func (p price) String() string {
return fmt.Sprintf("%s @ %s - $%.5f", p.name, p.ts.Format(time.Stamp), p.priceUSD)
}