arnaucube
arnaucube/balance-checkerPublic Self-hosted repository
balance-checker/main.go
main.goRaw
  1package main
  2
  3import (
  4	"encoding/json"
  5	"flag"
  6	"fmt"
  7	"io/ioutil"
  8	"net/http"
  9	"os"
 10	"strconv"
 11	"strings"
 12)
 13
 14type Currency struct {
 15	Id     int    `json:"id"`
 16	Name   string `json:"name"`
 17	Symbol string `json:"symbol"`
 18	Quote  struct {
 19		USD struct {
 20			Price float64 `json:"price"`
 21		}
 22	}
 23}
 24type Content struct {
 25	Data []Currency
 26}
 27
 28type Result struct {
 29	Symbol  string
 30	Balance float64
 31	USD     float64
 32}
 33
 34func main() {
 35	var configPath string
 36	flag.StringVar(&configPath, "config", "config.yaml", "Path to config.toml")
 37	flag.Parse()
 38
 39	if err := MustRead(configPath); err != nil {
 40		fmt.Println(err)
 41		os.Exit(1)
 42	}
 43
 44	currencies := getCurrencies()
 45
 46	results, total := calculateResults(currencies, C.Currencies)
 47	printResults(results, total)
 48}
 49
 50func printResults(results []Result, total float64) {
 51	fmt.Println("Curr	Balance		USD")
 52	for _, r := range results {
 53		fmt.Println(r.Symbol + "	" +
 54			strconv.FormatFloat(r.Balance, 'f', 6, 64) + "	" +
 55			strconv.FormatFloat(r.USD, 'f', 6, 64))
 56	}
 57
 58	fmt.Println("\ntotal USD:", total)
 59}
 60
 61func calculateResults(currencies []Currency, configCurrencies map[string]float64) ([]Result, float64) {
 62	var results []Result
 63	var total float64
 64	total = 0
 65	for _, c := range currencies {
 66		if configCurrencies[strings.ToLower(c.Symbol)] != 0 {
 67			balance := configCurrencies[strings.ToLower(c.Symbol)]
 68			price := c.Quote.USD.Price
 69			result := Result{
 70				Symbol:  c.Symbol,
 71				Balance: balance,
 72				USD:     balance * price,
 73			}
 74			results = append(results, result)
 75			total = total + result.USD
 76		}
 77	}
 78	return results, total
 79}
 80
 81func getCurrencies() []Currency {
 82	url := "https://web-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?limit=35&start=1"
 83	response, err := http.Get(url)
 84	if err != nil {
 85		fmt.Println(err)
 86		os.Exit(1)
 87	}
 88	defer response.Body.Close()
 89	contents, err := ioutil.ReadAll(response.Body)
 90	if err != nil {
 91		fmt.Println(err)
 92		os.Exit(1)
 93	}
 94
 95	var content Content
 96	err = json.Unmarshal(contents, &content)
 97	if err != nil {
 98		fmt.Println(err)
 99		os.Exit(1)
100	}
101	return content.Data
102}