-
Notifications
You must be signed in to change notification settings - Fork 0
/
coin_gecko.exs
107 lines (87 loc) · 2.67 KB
/
coin_gecko.exs
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
Mix.install([
{:tesla, "~> 1.4"},
{:hackney, "~> 1.18"},
{:jason, "~> 1.4"}
])
defmodule CoinGecko do
@moduledoc """
Provides helper functions to interact with CoinGecko API
"""
require Logger
@api_host "https://api.coingecko.com/api/v3"
@recv_timeout 30_000
@currency "usd"
@days_ago 14
@data_interval "daily"
@doc """
Searches for coins, categories and markets listed on CoinGecko ordered by largest Market Cap first
"""
@spec search(query :: String.t()) :: {:ok, map()} | {:error, any()}
def search(query) when is_binary(query) do
client = client()
case Tesla.get(client, "/search", query: [query: query]) do
{:ok, response} ->
{:ok, response.body}
{:error, reason} = error ->
Logger.error(fn -> "coins search by name: " <> inspect(reason) end)
error
end
end
def search(_), do: {:error, "invalid search text."}
@doc """
Get current data (name, price, market, ... including exchange tickers) for a coin
"""
@spec get_by_id(id :: String.t()) :: {:ok, map()} | {:error, any()}
def get_by_id(id) when is_binary(id) do
client = client()
path = "/coins/#{id}"
case Tesla.get(client, path) do
{:ok, response} ->
{:ok, response.body}
{:error, reason} = error ->
Logger.error(fn -> "get coin by id: " <> inspect(reason) end)
error
end
end
def get_by_id(_), do: {:error, "invalid coin id."}
@doc """
Get historical market data include price, market cap, and 24h volume (granularity auto) for a coin
"""
@spec get_market_chart(
id :: String.t(),
currency :: String.t(),
days :: non_neg_integer(),
interval :: String.t()
) :: {:ok, map()} | {:error, any()}
def get_market_chart(id, currency \\ @currency, days \\ @days_ago, interval \\ @data_interval)
def get_market_chart(id, currency, days, interval) when is_binary(id) do
client = client()
path = "/coins/#{id}/market_chart"
case Tesla.get(client, path,
query: [
vs_currency: currency,
days: days,
interval: interval
]
) do
{:ok, response} ->
{:ok, response.body}
{:error, reason} = error ->
Logger.error(fn -> "coin historical market data: " <> inspect(reason) end)
error
end
end
def get_market_chart(_, _, _, _), do: {:error, "invalid coin id."}
defp client() do
Tesla.client(
[
{Tesla.Middleware.BaseUrl, @api_host},
{Tesla.Middleware.JSON, engine: Jason}
],
{
Tesla.Adapter.Hackney,
ssl_options: [verify: :verify_none], recv_timeout: @recv_timeout
}
)
end
end