-
Notifications
You must be signed in to change notification settings - Fork 21
/
coinmarketcap.go
378 lines (338 loc) · 9.36 KB
/
coinmarketcap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
// Package coinmarketcap Coin Market Cap API client for Go
package coinmarketcap
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"sort"
"github.com/anaskhan96/soup"
"github.com/coincircle/go-coinmarketcap/types"
)
var (
siteURL = "https://coinmarketcap.com"
baseURL = "https://api.coinmarketcap.com/v2"
coinGraphURL = "https://graphs2.coinmarketcap.com/currencies"
globalMarketGraphURL = "https://graphs2.coinmarketcap.com/global/marketcap-total"
altcoinMarketGraphURL = "https://graphs2.coinmarketcap.com/global/marketcap-altcoin"
)
// Interface interface
type Interface interface {
Listings() ([]*types.Listing, error)
Tickers(options *TickersOptions) ([]*types.Ticker, error)
Ticker(options *TickerOptions) (*types.Ticker, error)
TickerGraph(options *TickerGraphOptions) (*types.TickerGraph, error)
GlobalMarket(options *GlobalMarketOptions) (*types.GlobalMarket, error)
GlobalMarketGraph(options *GlobalMarketGraphOptions) (*types.MarketGraph, error)
GlobalAltcoinMarketGraph(options *GlobalAltcoinMarketGraphOptions) (*types.MarketGraph, error)
Markets(options *MarketsOptions) ([]*types.Market, error)
Price(options *PriceOptions) (float64, error)
CoinID(symbol string) (int, error)
CoinSlug(symbol string) (string, error)
}
// listingsMedia listings response media
type listingsMedia struct {
Data []*types.Listing `json:"data"`
}
// Listings gets all coin listings
func Listings() ([]*types.Listing, error) {
url := fmt.Sprintf("%s/listings", baseURL)
resp, err := makeReq(url)
var body listingsMedia
err = json.Unmarshal(resp, &body)
if err != nil {
return nil, err
}
return body.Data, nil
}
// TickersOptions options for tickers method
type TickersOptions struct {
Start int
Limit int
Convert string
}
// tickerMedia tickers response media
type tickersMedia struct {
Data map[string]*types.Ticker `json:"data,omitempty"`
Metadata struct {
Timestamp int64
NumCryptoCurrencies int `json:"num_cryptocurrencies,omitempty"`
Error string `json:",omitempty"`
}
}
// Tickers gets ticker information on coins
func Tickers(options *TickersOptions) ([]*types.Ticker, error) {
var params []string
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=%v", options.Convert))
}
url := fmt.Sprintf("%s/ticker?%s", baseURL, strings.Join(params, "&"))
resp, err := makeReq(url)
var body tickersMedia
err = json.Unmarshal(resp, &body)
if err != nil {
return nil, err
}
data := body.Data
var tickers []*types.Ticker
for _, v := range data {
tickers = append(tickers, v)
}
if body.Metadata.Error != "" {
return nil, errors.New(body.Metadata.Error)
}
sort.Slice(tickers, func(i, j int) bool {
return tickers[i].Rank < tickers[j].Rank
})
return tickers, nil
}
// TickerOptions options for ticker method
type TickerOptions struct {
Symbol string
Convert string
}
type tickerMedia struct {
Data *types.Ticker `json:"data"`
}
// Ticker gets ticker information about a cryptocurrency
func Ticker(options *TickerOptions) (*types.Ticker, error) {
var params []string
if options.Convert != "" {
params = append(params, fmt.Sprintf("convert=%v", options.Convert))
}
id, err := CoinID(options.Symbol)
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s/ticker/%v?%s", baseURL, id, strings.Join(params, "&"))
resp, err := makeReq(url)
if err != nil {
return nil, err
}
var body tickerMedia
err = json.Unmarshal(resp, &body)
if err != nil {
return nil, err
}
return body.Data, nil
}
// TickerGraphOptions options for ticker graph
type TickerGraphOptions struct {
Symbol string
Start int64
End int64
}
// TickerGraph gets graph data points for a cryptocurrency
func TickerGraph(options *TickerGraphOptions) (*types.TickerGraph, error) {
slug, err := CoinSlug(options.Symbol)
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s/%s/%d/%d", coinGraphURL, slug, options.Start*1000, options.End*1000)
resp, err := makeReq(url)
if err != nil {
return nil, err
}
var data *types.TickerGraph
err = json.Unmarshal(resp, &data)
if err != nil {
return nil, err
}
return data, nil
}
// GlobalMarketOptions options for global data method
type GlobalMarketOptions struct {
Convert string
}
// globalMedia global data response media
type globalMarketMedia struct {
Data *types.GlobalMarket `json:"data"`
}
// GlobalMarket gets information about the global market of the cryptocurrencies
func GlobalMarket(options *GlobalMarketOptions) (*types.GlobalMarket, error) {
var params []string
if options.Convert != "" {
params = append(params, fmt.Sprintf("convert=%v", options.Convert))
}
url := fmt.Sprintf("%s/global?%s", baseURL, strings.Join(params, "&"))
resp, err := makeReq(url)
var body globalMarketMedia
err = json.Unmarshal(resp, &body)
if err != nil {
return nil, err
}
return body.Data, nil
}
// GlobalMarketGraphOptions options for global market graph method
type GlobalMarketGraphOptions struct {
Start int64
End int64
}
// GlobalMarketGraph get graph data points of global market
func GlobalMarketGraph(options *GlobalMarketGraphOptions) (*types.MarketGraph, error) {
url := fmt.Sprintf("%s/%d/%d", globalMarketGraphURL, options.Start*1000, options.End*1000)
resp, err := makeReq(url)
if err != nil {
return nil, err
}
var data *types.MarketGraph
err = json.Unmarshal(resp, &data)
if err != nil {
return nil, err
}
return data, nil
}
// GlobalAltcoinMarketGraphOptions options for global altcoin market graph method
type GlobalAltcoinMarketGraphOptions struct {
Start int64
End int64
}
// GlobalAltcoinMarketGraph gets graph data points of altcoin market
func GlobalAltcoinMarketGraph(options *GlobalAltcoinMarketGraphOptions) (*types.MarketGraph, error) {
url := fmt.Sprintf("%s/%d/%d", altcoinMarketGraphURL, options.Start*1000, options.End*1000)
resp, err := makeReq(url)
if err != nil {
return nil, err
}
var data *types.MarketGraph
err = json.Unmarshal(resp, &data)
if err != nil {
return nil, err
}
return data, nil
}
// MarketsOptions options for markets method
type MarketsOptions struct {
Symbol string
}
// Markets get market data for a cryptocurrency
func Markets(options *MarketsOptions) ([]*types.Market, error) {
slug, err := CoinSlug(options.Symbol)
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s/currencies/%s/#markets", siteURL, slug)
var markets []*types.Market
response, err := soup.Get(url)
if err != nil {
return nil, err
}
rows := soup.HTMLParse(response).Find("table", "id", "markets-table").Find("tbody").FindAll("tr")
for _, row := range rows {
var data []string
for _, column := range row.FindAll("td") {
attrs := column.Attrs()
if attrs["data-sort"] != "" {
data = append(data, attrs["data-sort"])
} else {
data = append(data, column.Text())
}
}
markets = append(markets, &types.Market{
Rank: toInt(data[0]),
Exchange: data[1],
Pair: data[2],
VolumeUSD: toFloat(data[3]),
Price: toFloat(data[4]),
VolumePercent: toFloat(data[5]),
Updated: data[6],
})
}
return markets, nil
}
// PriceOptions options for price method
type PriceOptions struct {
Symbol string
Convert string
}
// Price gets price of a cryptocurrency
func Price(options *PriceOptions) (float64, error) {
coin, err := Ticker(&TickerOptions{
Convert: options.Convert,
Symbol: options.Symbol,
})
if err != nil {
return 0, err
}
if coin == nil {
return 0, errors.New("coin not found")
}
return coin.Quotes[options.Convert].Price, nil
}
// CoinID gets the ID for the cryptocurrency
func CoinID(symbol string) (int, error) {
symbol = strings.ToUpper(strings.TrimSpace(symbol))
listings, err := Listings()
if err != nil {
return 0, err
}
for _, l := range listings {
if l.Symbol == symbol {
return l.ID, nil
}
}
//returns error as default
return 0, errors.New("coin not found")
}
// CoinSlug gets the slug for the cryptocurrency
func CoinSlug(symbol string) (string, error) {
symbol = strings.ToUpper(strings.TrimSpace(symbol))
coin, err := Ticker(&TickerOptions{
Symbol: symbol,
})
if err != nil {
return "", err
}
if coin == nil {
return "", errors.New("coin not found")
}
return coin.Slug, nil
}
// toInt helper for parsing strings to int
func toInt(rawInt string) int {
parsed, _ := strconv.Atoi(strings.Replace(strings.Replace(rawInt, "$", "", -1), ",", "", -1))
return parsed
}
// toFloat helper for parsing strings to float
func toFloat(rawFloat string) float64 {
parsed, _ := strconv.ParseFloat(strings.Replace(strings.Replace(strings.Replace(rawFloat, "$", "", -1), ",", "", -1), "%", "", -1), 64)
return parsed
}
// doReq HTTP client
func doReq(req *http.Request) ([]byte, error) {
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if 200 != resp.StatusCode {
return nil, fmt.Errorf("%s", body)
}
return body, nil
}
// makeReq HTTP request helper
func makeReq(url string) ([]byte, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
resp, err := doReq(req)
if err != nil {
return nil, err
}
return resp, err
}