forked from OpenBazaar/go-ethwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exchange_rates.go
356 lines (323 loc) · 9.14 KB
/
exchange_rates.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package wallet
import (
"encoding/json"
"errors"
"net"
"net/http"
"reflect"
"strconv"
"strings"
"sync"
"time"
exchange "github.com/OpenBazaar/spvwallet/exchangerates"
"golang.org/x/net/proxy"
)
// ExchangeRateProvider - used for looking up exchange rates for ETH
type ExchangeRateProvider struct {
fetchURL string
cache map[string]float64
client *http.Client
decoder ExchangeRateDecoder
bitcoinProvider *exchange.BitcoinPriceFetcher
}
// ExchangeRateDecoder - used for serializing/deserializing provider struct
type ExchangeRateDecoder interface {
decode(dat interface{}, cache map[string]float64, bp *exchange.BitcoinPriceFetcher) (err error)
}
// OpenBazaarDecoder - decoder to be used by OB
type OpenBazaarDecoder struct{}
// KrakenDecoder - decoder with Kraken exchange as provider
type KrakenDecoder struct{}
// PoloniexDecoder - decoder with Poloniex exchange as provider
type PoloniexDecoder struct{}
// BitfinexDecoder - decoder with Bitfinex exchange as provider
type BitfinexDecoder struct{}
// BittrexDecoder - decoder with Bittrex exchange as provider
type BittrexDecoder struct{}
// EthereumPriceFetcher - get ETH prices from the providers (exchanges)
type EthereumPriceFetcher struct {
sync.Mutex
cache map[string]float64
providers []*ExchangeRateProvider
}
// NewEthereumPriceFetcher - instantiate a eth price fetcher
func NewEthereumPriceFetcher(dialer proxy.Dialer) *EthereumPriceFetcher {
bp := exchange.NewBitcoinPriceFetcher(dialer)
z := EthereumPriceFetcher{
cache: make(map[string]float64),
}
dial := net.Dial
if dialer != nil {
dial = dialer.Dial
}
tbTransport := &http.Transport{Dial: dial}
client := &http.Client{Transport: tbTransport, Timeout: time.Minute}
z.providers = []*ExchangeRateProvider{
{"https://api.kraken.com/0/public/Ticker?pair=ETHXBT", z.cache, client, KrakenDecoder{}, bp},
}
go z.run()
return &z
}
// GetExchangeRate - fetch the exchange rate for the specified currency
func (z *EthereumPriceFetcher) GetExchangeRate(currencyCode string) (float64, error) {
currencyCode = NormalizeCurrencyCode(currencyCode)
z.Lock()
defer z.Unlock()
price, ok := z.cache[currencyCode]
if !ok {
return 0, errors.New("currency not tracked")
}
return price, nil
}
// GetLatestRate - refresh the cache and return the latest exchange rate for the specified currency
func (z *EthereumPriceFetcher) GetLatestRate(currencyCode string) (float64, error) {
currencyCode = NormalizeCurrencyCode(currencyCode)
z.fetchCurrentRates()
z.Lock()
defer z.Unlock()
price, ok := z.cache[currencyCode]
if !ok {
return 0, errors.New("currency not tracked")
}
return price, nil
}
// GetAllRates - refresh the cache
func (z *EthereumPriceFetcher) GetAllRates(cacheOK bool) (map[string]float64, error) {
if !cacheOK {
err := z.fetchCurrentRates()
if err != nil {
return nil, err
}
}
z.Lock()
defer z.Unlock()
copy := make(map[string]float64, len(z.cache))
for k, v := range z.cache {
copy[k] = v
}
return copy, nil
}
// UnitsPerCoin - return weis in 1 ETH
func (z *EthereumPriceFetcher) UnitsPerCoin() int64 {
return 1000000000000000000
}
func (z *EthereumPriceFetcher) fetchCurrentRates() error {
z.Lock()
defer z.Unlock()
for _, provider := range z.providers {
err := provider.fetch()
if err == nil {
return nil
}
}
return errors.New("all exchange rate API queries failed")
}
func (z *EthereumPriceFetcher) run() {
z.fetchCurrentRates()
ticker := time.NewTicker(time.Minute * 15)
defer ticker.Stop()
for range ticker.C {
z.fetchCurrentRates()
}
}
func (provider *ExchangeRateProvider) fetch() (err error) {
if len(provider.fetchURL) == 0 {
err = errors.New("provider has no fetchUrl")
return err
}
resp, err := provider.client.Get(provider.fetchURL)
if err != nil {
return err
}
decoder := json.NewDecoder(resp.Body)
var dataMap interface{}
err = decoder.Decode(&dataMap)
if err != nil {
return err
}
return provider.decoder.decode(dataMap, provider.cache, provider.bitcoinProvider)
}
func (b OpenBazaarDecoder) decode(dat interface{}, cache map[string]float64, bp *exchange.BitcoinPriceFetcher) (err error) {
//data := dat.(map[string]interface{})
data, ok := dat.(map[string]interface{})
if !ok {
return errors.New(reflect.TypeOf(b).Name() + ".decode: type assertion failed invalid json")
}
eth, ok := data["ETH"]
if !ok {
return errors.New(reflect.TypeOf(b).Name() + ".decode: type assertion failed, missing 'ETH' field")
}
val, ok := eth.(map[string]interface{})
if !ok {
return errors.New(reflect.TypeOf(b).Name() + ".decode: type assertion failed")
}
ethRate, ok := val["last"].(float64)
if !ok {
return errors.New(reflect.TypeOf(b).Name() + ".decode: type assertion failed, missing 'last' (float) field")
}
for k, v := range data {
if k != "timestamp" {
val, ok := v.(map[string]interface{})
if !ok {
return errors.New(reflect.TypeOf(b).Name() + ".decode: type assertion failed")
}
price, ok := val["last"].(float64)
if !ok {
return errors.New(reflect.TypeOf(b).Name() + ".decode: type assertion failed, missing 'last' (float) field")
}
cache[k] = price * (1 / ethRate)
}
}
return nil
}
func (b KrakenDecoder) decode(dat interface{}, cache map[string]float64, bp *exchange.BitcoinPriceFetcher) (err error) {
rates, err := bp.GetAllRates(false)
if err != nil {
return err
}
obj, ok := dat.(map[string]interface{})
if !ok {
return errors.New("krakenDecoder type assertion failure")
}
result, ok := obj["result"]
if !ok {
return errors.New("krakenDecoder: field `result` not found")
}
resultMap, ok := result.(map[string]interface{})
if !ok {
return errors.New("KrakenDecoder type assertion failure")
}
pair, ok := resultMap["XETHXXBT"]
if !ok {
return errors.New("krakenDecoder: field `ETHXBT` not found")
}
pairMap, ok := pair.(map[string]interface{})
if !ok {
return errors.New("krakenDecoder type assertion failure")
}
c, ok := pairMap["c"]
if !ok {
return errors.New("krakenDecoder: field `c` not found")
}
cList, ok := c.([]interface{})
if !ok {
return errors.New("krakenDecoder type assertion failure")
}
rateStr, ok := cList[0].(string)
if !ok {
return errors.New("krakenDecoder type assertion failure")
}
price, err := strconv.ParseFloat(rateStr, 64)
if err != nil {
return err
}
rate := price
if rate == 0 {
return errors.New("bitcoin-ethereum price data not available")
}
for k, v := range rates {
cache[k] = v * rate
}
return nil
}
func (b BitfinexDecoder) decode(dat interface{}, cache map[string]float64, bp *exchange.BitcoinPriceFetcher) (err error) {
rates, err := bp.GetAllRates(false)
if err != nil {
return err
}
obj, ok := dat.(map[string]interface{})
if !ok {
return errors.New("bitfinexDecoder: type assertion failure")
}
r, ok := obj["last_price"]
if !ok {
return errors.New("bitfinexDecoder: field `last_price` not found")
}
rateStr, ok := r.(string)
if !ok {
return errors.New("bitfinexDecoder: type assertion failure")
}
price, err := strconv.ParseFloat(rateStr, 64)
if err != nil {
return err
}
rate := price
if rate == 0 {
return errors.New("bitcoin-ethereum price data not available")
}
for k, v := range rates {
cache[k] = v * rate
}
return nil
}
func (b BittrexDecoder) decode(dat interface{}, cache map[string]float64, bp *exchange.BitcoinPriceFetcher) (err error) {
rates, err := bp.GetAllRates(false)
if err != nil {
return err
}
obj, ok := dat.(map[string]interface{})
if !ok {
return errors.New("bittrexDecoder: type assertion failure")
}
result, ok := obj["result"]
if !ok {
return errors.New("bittrexDecoder: field `result` not found")
}
resultMap, ok := result.(map[string]interface{})
if !ok {
return errors.New("bittrexDecoder: type assertion failure")
}
exRate, ok := resultMap["Last"]
if !ok {
return errors.New("bittrexDecoder: field `Last` not found")
}
rate, ok := exRate.(float64)
if !ok {
return errors.New("bittrexDecoder type assertion failure")
}
if rate == 0 {
return errors.New("bitcoin-ethereum price data not available")
}
for k, v := range rates {
cache[k] = v * rate
}
return nil
}
func (b PoloniexDecoder) decode(dat interface{}, cache map[string]float64, bp *exchange.BitcoinPriceFetcher) (err error) {
rates, err := bp.GetAllRates(false)
if err != nil {
return err
}
data, ok := dat.(map[string]interface{})
if !ok {
return errors.New(reflect.TypeOf(b).Name() + ".decode: type assertion failed")
}
var rate float64
v := data["BTC_ETH"]
//data := dat.(map[string]interface{})
//var rate float64
val, ok := v.(map[string]interface{})
if !ok {
return errors.New(reflect.TypeOf(b).Name() + ".decode: type assertion failed")
}
s, ok := val["last"].(string)
if !ok {
return errors.New(reflect.TypeOf(b).Name() + ".decode: type assertion failed, missing 'last' (string) field")
}
price, err := strconv.ParseFloat(s, 64)
if err != nil {
return err
}
rate = price
if rate == 0 {
return errors.New("bitcoin-ethereum price data not available")
}
for k, v := range rates {
cache[k] = v * rate
}
return nil
}
// NormalizeCurrencyCode standardizes the format for the given currency code
func NormalizeCurrencyCode(currencyCode string) string {
return strings.ToUpper(currencyCode)
}