bit4sat/btc/price.go
2019-04-03 20:18:51 +02:00

78 lines
1.4 KiB
Go

package btc
import (
"encoding/json"
"errors"
"fmt"
"log"
"math"
"net/http"
"net/url"
"git.sp4ke.com/sp4ke/bit4sat/config"
)
const (
BitcoinAverageAPI = "https://apiv2.bitcoinaverage.com"
BTCMsatRatio = float64(100000000000)
)
var FixedRates = map[string]float64{
"BTC": 1,
}
func ToMsat(currency string, amount float64) (int64, error) {
rate, err := getRate(currency)
if err != nil {
return -1, err
}
return int64(math.Round((amount / rate) * BTCMsatRatio)), nil
}
func getRate(currency string) (float64, error) {
pairName := "BTC" + currency
reqParams := url.Values{}
reqParams.Set("crypto", "BTC")
reqParams.Set("fiat", currency)
reqUri := fmt.Sprintf("%s/indices/global/ticker/short?%s",
BitcoinAverageAPI, reqParams.Encode())
// TODO: remove on prod and use normal client
// Used for connectivity problems
proxyUrl, err := url.Parse(config.HttpProxy)
if err != nil {
log.Fatal(err)
}
client := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyUrl),
},
}
resp, err := client.Get(reqUri)
if err != nil {
return -1, err
}
var data map[string]interface{}
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&data)
if err != nil {
log.Fatal(err)
}
pair := data[pairName]
price, ok := pair.(map[string]interface{})["last"].(float64)
if !ok {
return -1, errors.New("bitcoinaverage parsing result")
}
return price, nil
}