Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Coingecko #1

Merged
merged 5 commits into from Oct 9, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 19 additions & 0 deletions .travis.yml
@@ -0,0 +1,19 @@
language: go

go:
- 1.11.x

install:
- export GOMETALINTER_VERSION=2.0.11
- ./.travis/gometalinter-install.sh
- export PATH=$PATH:${TRAVIS_HOME}/gometalinter/gometalinter-${GOMETALINTER_VERSION}-linux-amd64
- export GO111MODULE=on

cache:
directories:
- ${TRAVIS_HOME}/gometalinter/gometalinter-${GOMETALINTER_VERSION}-linux-amd64

script:
- gometalinter --config=gometalinter.json ./...
- go build -v -mod=vendor ./...
- go test -v -mod=vendor ./...
18 changes: 18 additions & 0 deletions .travis/gometalinter-install.sh
@@ -0,0 +1,18 @@
#!/bin/bash

set -euo pipefail

readonly version="$GOMETALINTER_VERSION"
readonly archive_url="https://github.com/alecthomas/gometalinter/releases/download/v$version/gometalinter-$version-linux-amd64.tar.gz"
readonly gometalinter_dir="${TRAVIS_HOME}/gometalinter"

if [[ -f "$gometalinter_dir/gometalinter-$version-linux-amd64/gometalinter" ]]; then
echo "gometalinter is already installed, skipping..."
exit 0
fi

pushd "$gometalinter_dir"
curl -fsSLO "$archive_url"
tar xvf "gometalinter-$version-linux-amd64.tar.gz"
rm "gometalinter-$version-linux-amd64.tar.gz"
popd
81 changes: 81 additions & 0 deletions coingecko/coingecko.go
@@ -0,0 +1,81 @@
package coingecko

import (
"encoding/json"
"fmt"
"net/http"
"time"
)

// CoinGecko is the CoinGecko implementation of Provider. The
// precision of CoinGecko provider is up to day.
type CoinGecko struct {
client *http.Client
baseURL string
}

// New creates a new CoinGecko instance.
func New() *CoinGecko {
const (
defaultTimeout = time.Second * 10
baseURL = "https://api.coingecko.com/api/v3"
)
client := &http.Client{
Timeout: defaultTimeout,
}
return &CoinGecko{
client: client,
baseURL: baseURL,
}
}

type historyResponse struct {
MarketData marketData `json:"market_data"`
}

type marketData struct {
CurrentPrice map[string]float64 `json:"current_price"`
}

// Rate returns the rate of given token in real world currency at given timestamp.
func (cg *CoinGecko) Rate(token, currency string, timestamp time.Time) (float64, error) {
const timeLayout = "02-01-2006"

url := fmt.Sprintf("%s/coins/%s/history", cg.baseURL, token)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return 0, err
}
req.Header.Add("Accept", "application/json")
q := req.URL.Query()
q.Add("date", timestamp.UTC().Format(timeLayout))
req.URL.RawQuery = q.Encode()
rsp, err := cg.client.Do(req)
if err != nil {
return 0, err
}
defer rsp.Body.Close()

if rsp.StatusCode != http.StatusOK {
return 0, fmt.Errorf("unexpected status code: %s", rsp.Status)
}

var history = &historyResponse{}
if err = json.NewDecoder(rsp.Body).Decode(history); err != nil {
return 0, err
}
rate, ok := history.MarketData.CurrentPrice[currency]
if !ok {
return 0, fmt.Errorf("currency %q not found in market data", currency)
}
return rate, nil
}

// USDRate returns the historical price of ETH.
func (cg *CoinGecko) USDRate(timestamp time.Time) (float64, error) {
const (
ethereumID = "ethereum"
usdID = "usd"
)
return cg.Rate(ethereumID, usdID, timestamp)
}
21 changes: 21 additions & 0 deletions coingecko/coingecko_test.go
@@ -0,0 +1,21 @@
package coingecko

import (
"testing"
"time"
)

func TestCoinGecko(t *testing.T) {
cg := New()
rate, err := cg.Rate("bitcoin", "usd", time.Now())
if err != nil {
t.Fatal(err)
}
t.Logf("current Bitcoin/SGD price: %f", rate)

rate, err = cg.USDRate(time.Now())
if err != nil {
t.Fatal(err)
}
t.Logf("current ETH/USD rate: %f", rate)
}
3 changes: 3 additions & 0 deletions doc.go
@@ -0,0 +1,3 @@
// Package tokenrate supports query historical rates of tokens. There
// are multiple implementations using different API providers.
package tokenrate
10 changes: 10 additions & 0 deletions gometalinter.json
@@ -0,0 +1,10 @@
{
"Vendor": true,
"DisableAll": true,
"Enable": [
"gofmt",
"golint",
"vet"
],
"Deadline": "5m"
}
17 changes: 17 additions & 0 deletions interface.go
@@ -0,0 +1,17 @@
package tokenrate

import "time"

// Provider is the common interface to query historical rates of any
// token to real worldp currencies.
// **Experimental**: the token, each provider intepretered currency,
// parameters differently.
type Provider interface {
Rate(token, currency string, timestamp time.Time) (float64, error)
}

// ETHUSDRateProvider is the common interface to query historical
// rates of ETH to USD.
type ETHUSDRateProvider interface {
USDRate(time.Time) (float64, error)
}