Skip to content
This repository has been archived by the owner on Sep 19, 2023. It is now read-only.

Commit

Permalink
cryptocurrency info endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelmota committed Oct 14, 2018
1 parent f9c5c7f commit 7faf3e3
Show file tree
Hide file tree
Showing 12 changed files with 388 additions and 420 deletions.
107 changes: 103 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
[![License](http://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/miguelmota/go-coinmarketcap/master/LICENSE.md) [![Build Status](https://travis-ci.org/miguelmota/go-coinmarketcap.svg?branch=master)](https://travis-ci.org/miguelmota/go-coinmarketcap) [![Go Report Card](https://goreportcard.com/badge/github.com/miguelmota/go-coinmarketcap?)](https://goreportcard.com/report/github.com/miguelmota/go-coinmarketcap) [![GoDoc](https://godoc.org/github.com/miguelmota/go-coinmarketcap?status.svg)](https://godoc.org/github.com/miguelmota/go-coinmarketcap)

Supports the CoinMarketCap Version [V2](https://coinmarketcap.com/api) and V1 Public API
Supports the CoinMarketCap API Pro Version, [V2](https://coinmarketcap.com/api) and V1 Public API

## Documentation

Expand All @@ -25,7 +25,67 @@ Supports the CoinMarketCap Version [V2](https://coinmarketcap.com/api) and V1 Pu
go get -u github.com/miguelmota/go-coinmarketcap
```

## Getting started
## Pro V1 (latest)

| Type | Endpoint | Implemented? |
|----------------|----------------------------------------|--------------|
| Cryptocurrency | /v1/cryptocurrency/info | Yes |
| Cryptocurrency | /v1/cryptocurrency/map | Not yet |
| Cryptocurrency | /v1/cryptocurrency/listings/latest | Yes |
| Cryptocurrency | /v1/cryptocurrency/market-pairs/latest | Not yet |
| Cryptocurrency | /v1/cryptocurrency/ohlcv/historical | Not yet |
| Cryptocurrency | /v1/cryptocurrency/quotes/latest | Not yet |
| Cryptocurrency | /v1/cryptocurrency/quotes/historical | Not yet |
| Exchange | /v1/exchange/info | Not yet |
| Exchange | /v1/exchange/map | Not yet |
| Exchange | /v1/exchange/listings/latest | Not yet |
| Exchange | /v1/exchange/market-pairs/latest | Not yet |
| Exchange | /v1/exchange/quotes/latest | Not yet |
| Exchange | /v1/exchange/quotes/historical | Not yet |
| Global Metrics | /v1/global-metrics/quotes/latest | Not yet |
| Global Metrics | /v1/global-metrics/quotes/historical | Not yet |
| Tools | /v1/tools/price-conversion | Not yet |

### Getting started

```go
package main

import (
"fmt"
"log"

cmc "github.com/miguelmota/go-coinmarketcap/pro/v1"
)

func main() {
client := cmc.NewClient(&Config{
ProAPIKey: "01585d6d-123-456-789-3146576cbc70",
})

listings, err := client.CryptocurrencyListingsLatests(&cmc.CryptocurrencyListingsLatestsOptions{
Limit: 1,
})
if err != nil {
log.Fatal(err)
}

fmt.Println(listings[0].Name)
fmt.Println(listings[0].Quote["USD"].Price)
}
```

### Examples

For more examples, check out the [`./pro/v1/example`](./pro/v1/example) directory and [documentation](https://godoc.org/github.com/miguelmota/go-coinmarketcap/pro/v1)

---

## V2

Note: will be deprecated December 2018

### Getting started

```go
package main
Expand All @@ -51,12 +111,51 @@ func main() {
fmt.Println(ticker.Symbol, ticker.Quotes["USD"].Price)
}
}
```

### Examples

For more examples, check out the [`./v2/example`](./v2/example) directory and [documentation](https://godoc.org/github.com/miguelmota/go-coinmarketcap/v2)

---

## V1

Note: will be deprecated November 2018

### Getting started

```go
package main

import (
"fmt"
"log"

cmc "github.com/miguelmota/go-coinmarketcap"
)

func main() {
tickers, err := cmc.Tickers(&cmc.TickersOptions{
Start: 0,
Limit: 100,
Convert: "USD",
})
if err != nil {
log.Fatal(err)
}

for _, ticker := range tickers {
fmt.Println(ticker.Symbol, ticker.Quotes["USD"].Price)
}
}
```

## Examples
### Examples

For more examples, check out the [`./v1/example`](./v1/example) directory and [documentation](https://godoc.org/github.com/miguelmota/go-coinmarketcap/v1)

Check out the [`./example`](./example) directory and documentation.
---

## License

Expand Down
242 changes: 242 additions & 0 deletions pro/v1/coinmarketcap.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,123 @@
// Package coinmarketcap Coin Market Cap API client for Go
package coinmarketcap

import (
"encoding/json"
"errors"
"fmt"
"log"
"os"
"strings"
)

// Interface interface
type Interface interface {
CryptocurrencyInfo(options *CryptocurrencyInfoOptions) (map[string]*CryptocurrencyInfo, error)
CryptocurrencyListingsLatests(options *CryptocurrencyListingsLatestsOptions) ([]*Listing, error)
}

// Status is the status structure
type Status struct {
Timestamp string `json:"timestamp"`
ErrorCode int `json:"error_code"`
ErrorMessage *string `json:"error_message"`
Elapsed int `json:"elapsed"`
CreditCount int `json:"credit_count"`
}

// Response is the response structure
type Response struct {
Status Status `json:"status"`
Data interface{} `json:"data"`
}

// Listing is the listing structure
type Listing struct {
ID float64 `json:"id"`
Name string `json:"name"`
Symbol string `json:"symbol"`
Slug string `json:"slug"`
CirculatingSupply float64 `json:"circulating_supply"`
TotalSupply float64 `json:"total_supply"`
MaxSupply float64 `json:"max_supply"`
DateAdded string `json:"date_added"`
NumMarketPairs float64 `json:"num_market_pairs"`
CMCRank float64 `json:"cmc_rank"`
LastUpdated string `json:"last_updated"`
Quote map[string]*Quote `json:"quote"`
}

// Quote is the quote structure
type Quote struct {
Price float64 `json:"price"`
Volume24H float64 `json:"volume_24h"`
PercentChange1H float64 `json:"percent_change_1h"`
PercentChange24H float64 `json:"percent_change_24h"`
PercentChange7D float64 `json:"percent_change_7d"`
MarketCap float64 `json:"market_cap"`
LastUpdated string `json:"last_updated"`
}

// CryptocurrencyInfo options
type CryptocurrencyInfo struct {
ID float64 `json:"id"`
Name string `json:"name"`
Symbol string `json:"symbol"`
Category string `json:"category"`
Slug string `json:"slug"`
Logo string `json:"logo"`
Tags []string `json:"tags"`
Urls map[string]interface{} `json:"urls"`
}

// CryptocurrencyInfoOptions options
type CryptocurrencyInfoOptions struct {
ID string
Symbol string
}

// CryptocurrencyListingsLatestsOptions options
type CryptocurrencyListingsLatestsOptions struct {
Start int
Limit int
Convert string
Sort string
}

// SortOptions sort options
var SortOptions sortOptions

type sortOptions struct {
Name string
Symbol string
DateAdded string
MarketCap string
Price string
CirculatingSupply string
TotalSupply string
MaxSupply string
NumMarketPairs string
Volume24H string
PercentChange1H string
PercentChange24H string
PercentChange7D string
}

// Client the CoinMarketCap client
type Client struct {
proAPIKey string
}

// Config the client config structure
type Config struct {
ProAPIKey string
}

var (
// ErrCouldNotCast could not cast error
ErrCouldNotCast = errors.New("could not cast")
)

var (
siteURL = "https://coinmarketcap.com"
baseURL = "https://pro-api.coinmarketcap.com/v1"
Expand All @@ -11,7 +128,132 @@ var (

// NewClient initializes a new client
func NewClient(cfg *Config) *Client {
if cfg == nil {
cfg = new(Config)
}

if cfg.ProAPIKey == "" {
cfg.ProAPIKey = os.Getenv("CMC_PRO_API_KEY")
}

if cfg.ProAPIKey == "" {
log.Fatal("Pro API Key is required")
}

return &Client{
proAPIKey: cfg.ProAPIKey,
}
}

// CryptocurrencyInfo returns all static metadata for one or more cryptocurrencies including name, symbol, logo, and its various registered URLs.
func (s *Client) CryptocurrencyInfo(options *CryptocurrencyInfoOptions) (map[string]*CryptocurrencyInfo, error) {
var params []string
if options == nil {
options = new(CryptocurrencyInfoOptions)
}
if options.ID != "" {
params = append(params, fmt.Sprintf("id=%s", options.ID))
}
if options.Symbol != "" {
params = append(params, fmt.Sprintf("symbol=%s", options.Symbol))
}

url := fmt.Sprintf("%s/cryptocurrency/info?%s", baseURL, strings.Join(params, "&"))

body, err := s.makeReq(url)
resp := new(Response)
err = json.Unmarshal(body, &resp)
if err != nil {
return nil, err
}

var result = make(map[string]*CryptocurrencyInfo)
ifcs, ok := resp.Data.(map[string]interface{})
if !ok {
return nil, ErrCouldNotCast
}

for k, v := range ifcs {
info := new(CryptocurrencyInfo)
b, err := json.Marshal(v)
if err != nil {
return nil, err
}
err = json.Unmarshal(b, info)
if err != nil {
return nil, err
}
result[k] = info
}

return result, nil
}

// CryptocurrencyListingsLatests gets a paginated list of all cryptocurrencies with latest market data. You can configure this call to sort by market cap or another market ranking field. Use the "convert" option to return market values in multiple fiat and cryptocurrency conversions in the same call.
func (s *Client) CryptocurrencyListingsLatests(options *CryptocurrencyListingsLatestsOptions) ([]*Listing, error) {
var params []string
if options == nil {
options = new(CryptocurrencyListingsLatestsOptions)
}
if options.Start != 0 {
params = append(params, fmt.Sprintf("start=%v", options.Start))
}
if options.Limit != 0 {
params = append(params, fmt.Sprintf("limit=%v", options.Limit))
}
if options.Convert != "" {
params = append(params, fmt.Sprintf("convert=%s", options.Convert))
}
if options.Sort != "" {
params = append(params, fmt.Sprintf("sort=%s", options.Sort))
}

url := fmt.Sprintf("%s/cryptocurrency/listings/latest?%s", baseURL, strings.Join(params, "&"))

body, err := s.makeReq(url)
resp := new(Response)
err = json.Unmarshal(body, &resp)
if err != nil {
return nil, err
}

var listings []*Listing
ifcs, ok := resp.Data.([]interface{})
if !ok {
return nil, ErrCouldNotCast
}

for i := range ifcs {
ifc := ifcs[i]
listing := new(Listing)
b, err := json.Marshal(ifc)
if err != nil {
return nil, err
}
err = json.Unmarshal(b, listing)
if err != nil {
return nil, err
}
listings = append(listings, listing)
}

return listings, nil
}

func init() {
SortOptions = sortOptions{
Name: "name",
Symbol: "symbol",
DateAdded: "date_added",
MarketCap: "market_cap",
Price: "price",
CirculatingSupply: "circulating_supply",
TotalSupply: "total_supply",
MaxSupply: "max_supply",
NumMarketPairs: "num_market_pairs",
Volume24H: "volume_24h",
PercentChange1H: "percent_change_1h",
PercentChange24H: "percent_change_24h",
PercentChange7D: "percent_change_7d",
}
}
Loading

0 comments on commit 7faf3e3

Please sign in to comment.