You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.0 KiB

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