-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprice.go
94 lines (82 loc) · 2.2 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
package main
import (
"fmt"
"net/http"
"time"
"github.com/monero-atm/pricefetcher"
"github.com/rs/zerolog/log"
)
type xmrPrice struct {
Amount float64 `json:"amount"`
Short string `json:"short"`
}
type priceUpdate struct {
Currencies []xmrPrice `json:"currencies"`
}
// Only XMR/EUR and XMR/USD pairs are available. When another fiat currency is
// specified, this function will calculate the value based on the daily rate
// provided by European Central Bank. "fiatEurRate" contains this rate.
// It's ignored when "currency" is set to EUR or USD.
func getXmrPrice(currencies []string, fiatRates map[string]float64, fee float64) (priceUpdate, error) {
var pu priceUpdate
cl := &http.Client{Timeout: 5 * time.Second}
fetcher := pricefetcher.New(cl)
// Get EUR rate
eurRate, source, err := fetcher.FetchXMRPrice("EUR")
if err != nil {
return pu, err
} else {
log.Info().Float64("rate", eurRate).Str("source", source).Msg("Got XMR/EUR rate")
}
for _, c := range currencies {
var xp xmrPrice
if c == "USD" {
usdRate, source, err := fetcher.FetchXMRPrice("USD")
if err != nil {
return pu, err
} else {
log.Info().Float64("rate", usdRate).Str("source", source).Msg("Got XMR/USD rate")
}
xp.Amount = usdRate
xp.Short = c
} else if c == "EUR" {
xp.Amount = eurRate
xp.Short = "EUR"
} else {
if val, ok := fiatRates[c]; ok {
xp.Amount = eurRate * val
xp.Short = c
} else {
return pu, fmt.Errorf("ECB doesn't have a rate for this currency")
}
}
xp.Amount *= (1 + fee)
pu.Currencies = append(pu.Currencies, xp)
}
return pu, err
}
func pricePoll(currencies []string, fiatRates map[string]float64, fee float64) {
pause := false
// Fetch the price for the first time without the wait.
prices, err := getXmrPrice(currencies, fiatRates, fee)
if err != nil {
log.Error().Err(err).Msg("Failed to get XMR price")
} else {
priceEvent <- prices
}
for {
select {
case p := <-pricePause:
pause = p
case <-time.After(cfg.PricePollFreq):
if !pause {
prices, err := getXmrPrice(currencies, fiatRates, fee)
if err != nil {
log.Error().Err(err).Msg("Failed to get XMR price")
} else {
priceEvent <- prices
}
}
}
}
}