Profile picture

Co-founder @ RMOTR

Cryptocompare API Examples

Last updated: December 7th, 20182018-12-07Project preview

Cryptocompare (https://min-api.cryptocompare.com) offers a FREE API to access crypto data. The free tier offers 100,000 monthly API calls. There are multiple endpoints exposed (prices, exchanges, OHLC, etc).

Let's get started.

In [1]:
import os
import requests
import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline

API Authentication

Before we begin, you MUST get a free API key from Cryptocompare: https://min-api.cryptocompare.com/. After getting the API Key, you can set it as an environment variable (in the project edit page) or just replace it where it says 'YOUR-API-KEY'.

In [2]:
CRYPTOCOMPARE_KEY = os.environ.get('CRYPTOCOMPARE_KEY', 'YOUR-API-KEY')
In [3]:
assert CRYPTOCOMPARE_KEY != 'YOUR-API-KEY'

We'll create a headers dictionary containing the API Key for any request we make in the future. If your API Key is not correctly set, your requests will fail.

In [4]:
headers = {
    'authorization': f'Apikey {CRYPTOCOMPARE_KEY}'
}

Endpoints

There are multiple endpoints exposed, we'll go over the most important ones, one by one:

/data/price: Get price data at a given moment

This endpoint returns price information for a given asset (provided by the param fsym and optionally different exchanges. The simplest example is probably:

In [10]:
resp = requests.get(
    'https://min-api.cryptocompare.com/data/price', headers=headers,
    params={'fsym': 'BTC', 'tsyms': 'USD,EUR'})
In [11]:
resp
Out[11]:
<Response [200]>

Bitcoin price expressed in US Dollars and Euros:

In [12]:
resp.json()
Out[12]:
{'USD': 3905.76, 'EUR': 3426.14}

It optionally accepts an exchange, with the e param. For example:

Bitstamp

In [13]:
resp = requests.get(
    'https://min-api.cryptocompare.com/data/price', headers=headers,
    params={'fsym': 'BTC', 'tsyms': 'USD,EUR', 'e': 'Bitstamp'})
In [14]:
resp
Out[14]:
<Response [200]>
In [15]:
resp.json()
Out[15]:
{'USD': 3858.82, 'EUR': 3402.74}

Coinbase

In [16]:
resp = requests.get(
    'https://min-api.cryptocompare.com/data/price', headers=headers,
    params={'fsym': 'BTC', 'tsyms': 'USD,EUR', 'e': 'Coinbase'})
In [17]:
resp
Out[17]:
<Response [200]>
In [18]:
resp.json()
Out[18]:
{'USD': 3861.01, 'EUR': 3411.02}

/data/pricemulti: Get prices for multiple symbols

This endpoint returns price information for a multiple assets (provided by the param fsyms and optionally different exchanges.

In [21]:
resp = requests.get(
    'https://min-api.cryptocompare.com/data/pricemulti', headers=headers,
    params={'fsyms': 'BTC,ETH,LTC', 'tsyms': 'USD,EUR'})
In [22]:
resp
Out[22]:
<Response [200]>
In [23]:
resp.json()
Out[23]:
{'BTC': {'USD': 3904.34, 'EUR': 3424.93},
 'ETH': {'USD': 108.35, 'EUR': 95.05},
 'LTC': {'USD': 30.61, 'EUR': 26.87}}
In [24]:
pd.DataFrame(resp.json()).T
Out[24]:
EUR USD
BTC 3424.93 3904.34
ETH 95.05 108.35
LTC 26.87 30.61

Providing an exchange with the e param:

In [25]:
resp = requests.get(
    'https://min-api.cryptocompare.com/data/pricemulti', headers=headers,
    params={'fsyms': 'BTC,ETH,LTC', 'tsyms': 'USD,EUR', 'e': 'Bitstamp'})
In [26]:
resp
Out[26]:
<Response [200]>
In [27]:
resp.json()
Out[27]:
{'BTC': {'USD': 3853.63, 'EUR': 3408.09},
 'ETH': {'USD': 107.22, 'EUR': 94.7},
 'LTC': {'USD': 30.39, 'EUR': 26.85}}
In [28]:
pd.DataFrame(resp.json()).T
Out[28]:
EUR USD
BTC 3408.09 3853.63
ETH 94.70 107.22
LTC 26.85 30.39

/data/all/exchanges: Get info about exchanges

This endpoint returns info about exchanges and the available symbols for each one of them. This endpoint doesn't require authentication:

In [29]:
resp = requests.get('https://min-api.cryptocompare.com/data/all/exchanges')
In [30]:
resp
Out[30]:
<Response [200]>
In [31]:
doc = resp.json()

A list of all the exchanges:

In [36]:
for exchange in list(doc.keys())[:10]:
    print(exchange)
print("\nList truncated for conciseness...")
ABCC
ACX
Abucoins
AidosMarket
BCEX
BTC38
BTCAlpha
BTCBOX
BTCChina
BTCE

List truncated for conciseness...

Sybols supported by different exchanges:

In [78]:
doc['Coinbase']
Out[78]:
{'BCH': ['USD', 'BTC', 'GBP', 'EUR'],
 'ETH': ['USD', 'BTC', 'USDC', 'EUR', 'GBP'],
 'LTC': ['GBP', 'EUR', 'BTC', 'USD'],
 'BTC': ['GBP', 'CAD', 'USD', 'EUR', 'USDC'],
 'BCHABC': ['EUR', 'USD', 'GBP', 'BTC'],
 'BAT': ['USDC'],
 'ETC': ['BTC', 'EUR', 'GBP', 'USD'],
 'ZRX': ['USD', 'BTC', 'EUR']}
In [79]:
doc['Bitstamp']
Out[79]:
{'XRP': ['EUR', 'BTC', 'USD'],
 'BTC': ['USD', 'EUR'],
 'ETH': ['BTC', 'EUR', 'USD'],
 'BCH': ['BTC', 'USD', 'EUR'],
 'BCHABC': ['USD', 'BTC', 'EUR'],
 'LTC': ['EUR', 'USD', 'BTC'],
 'EUR': ['USD']}
In [81]:
doc['OKCoin']
Out[81]:
{'BCH': ['CNY', 'USD'],
 'LTLTC': ['CNY'],
 'BTC': ['USD', 'CNY', 'LTC'],
 'LTC': ['USD', 'CNY'],
 'BTLTC': ['CNY'],
 'ETC': ['USD', 'CNY'],
 'ETH': ['USD', 'CNY']}

OHLC Data

This is probably the most useful endpoint, where you can get historic price information by exchange and assets. There are multiple periods to consult:

  • Daily data: /data/histoday
  • Hourly data: /data/histohour
  • Minute data: /data/histominute

For these queries, I'll be using Bitstamp as the exchange:

/data/histoday: Daily OHLC

In [37]:
resp = requests.get(
    'https://min-api.cryptocompare.com/data/histoday', headers=headers,
    params={'fsym': 'BTC', 'tsym': 'USD', 'limit': 1000, 'e': 'Bitstamp'})
In [38]:
resp
Out[38]:
<Response [200]>
In [39]:
doc = resp.json()
In [40]:
doc.keys()
Out[40]:
dict_keys(['Response', 'Type', 'Aggregated', 'Data', 'TimeTo', 'TimeFrom', 'FirstValueInArray', 'ConversionType', 'RateLimit', 'HasWarning'])
In [46]:
print(f"Response was: {doc['Response']}")
Response was: Success

Example of data returned:

In [47]:
doc['Data'][:2]
Out[47]:
[{'time': 1457568000,
  'close': 416.5,
  'high': 416.9,
  'low': 409.31,
  'open': 412.99,
  'volumefrom': 5105.04,
  'volumeto': 2110300.04},
 {'time': 1457654400,
  'close': 418.1,
  'high': 421.91,
  'low': 415.11,
  'open': 416,
  'volumefrom': 5905.9,
  'volumeto': 2476673.27}]

The values include the timestamp (the day, in this case) + OHLC (open, high, low, close), plus volume information. This is probably better visualized with a Pandas DataFrame:

In [50]:
df = pd.DataFrame(doc['Data'])
df['time'] = pd.to_datetime(df['time'], unit='s')
df.set_index('time', inplace=True)
df.tail()
Out[50]:
close high low open volumefrom volumeto
time
2018-12-01 4140.39 4264.47 3904.34 3971.06 6412.23 26273733.31
2018-12-02 4102.05 4265.00 4030.00 4140.39 7019.16 28949962.29
2018-12-03 3834.34 4115.15 3747.00 4102.05 10726.68 41858808.87
2018-12-04 3903.52 4033.98 3730.00 3834.34 12249.94 47819573.30
2018-12-05 3861.70 3913.62 3774.73 3903.52 5409.33 20764338.15

Using pandas we can now plot close prices:

In [51]:
df['close'].plot(figsize=(14, 7))
Out[51]:
<matplotlib.axes._subplots.AxesSubplot at 0x7fc74225eac8>

/data/histominute: Minute OHLC

This endpoint provides minute data with a limit of 2000 records per request. It can also be used for historical records.

In [28]:
resp = requests.get(
    'https://min-api.cryptocompare.com/data/histominute', headers=headers,
    params={'fsym': 'BTC', 'tsym': 'USD', 'e': 'Bitstamp', 'limit': 2000})
In [29]:
resp
Out[29]:
<Response [200]>
In [30]:
doc = resp.json()
In [31]:
doc.keys()
Out[31]:
dict_keys(['Response', 'Type', 'Aggregated', 'Data', 'TimeTo', 'TimeFrom', 'FirstValueInArray', 'ConversionType', 'RateLimit', 'HasWarning'])
In [32]:
print(f"Response was: {doc['Response']}")
Response was: Success
In [33]:
df = pd.DataFrame(doc['Data'])
df['time'] = pd.to_datetime(df['time'], unit='s')
df.set_index('time', inplace=True)
df.tail()
Out[33]:
close high low open volumefrom volumeto
time
2018-12-06 17:11:00 3577.00 3577.00 3559.97 3559.97 11.31 40350.45
2018-12-06 17:12:00 3576.99 3580.00 3564.33 3577.00 90.22 322784.93
2018-12-06 17:13:00 3573.48 3576.99 3566.00 3576.99 23.34 83374.10
2018-12-06 17:14:00 3569.96 3574.86 3568.00 3573.48 27.10 96812.51
2018-12-06 17:15:00 3569.38 3569.96 3569.38 3569.96 0.00 0.00
In [34]:
df['close'].plot(figsize=(14, 7))
Out[34]:
<matplotlib.axes._subplots.AxesSubplot at 0x7ff820b66390>

In this case, we've gotten 2000 records from:

In [35]:
df.index.min()
Out[35]:
Timestamp('2018-12-05 07:55:00')

up to:

In [36]:
df.index.max()
Out[36]:
Timestamp('2018-12-06 17:15:00')

To request previous periods you can use the toTs parameter, with a unix timestamp:

In [37]:
df.index.min().timestamp()
Out[37]:
1543996500.0
In [38]:
resp = requests.get(
    'https://min-api.cryptocompare.com/data/histominute', headers=headers,
    params={
        'fsym': 'BTC',
        'tsym': 'USD',
        'e': 'Bitstamp',
        'limit': 2000,
        'toTs': int(df.index.min().timestamp())
    }
)
In [39]:
resp
Out[39]:
<Response [200]>
In [40]:
doc = resp.json()
In [41]:
print(f"Response was: {doc['Response']}")
Response was: Success
In [43]:
df = pd.DataFrame(doc['Data'])
df['time'] = pd.to_datetime(df['time'], unit='s')
df.set_index('time', inplace=True)
df.tail()
Out[43]:
close high low open volumefrom volumeto
time
2018-12-05 07:51:00 3798.46 3803.07 3796.95 3803.07 9.73 36975.17
2018-12-05 07:52:00 3795.13 3798.46 3792.76 3798.46 11.06 41947.39
2018-12-05 07:53:00 3799.19 3801.14 3794.02 3795.13 16.63 63121.53
2018-12-05 07:54:00 3797.45 3800.00 3793.74 3799.19 4.38 16629.83
2018-12-05 07:55:00 3792.42 3797.95 3788.24 3797.45 23.46 88916.60
In [46]:
df['close'].plot(figsize=(14, 7))
Out[46]:
<matplotlib.axes._subplots.AxesSubplot at 0x7ff820996668>
In [44]:
df.index.min()
Out[44]:
Timestamp('2018-12-03 22:35:00')
In [45]:
df.index.max()
Out[45]:
Timestamp('2018-12-05 07:55:00')
In [ ]:
 
In [ ]:
 
In [47]:
context = {
    book:
    author:
}
if request.POST:
    if valid:
        return redirect()
    else:
        eroor
        roror
        context[errorr] = errors
        ....

return render()
  File "<ipython-input-47-30cf64725723>", line 1
    if request.POST:
                    ^
SyntaxError: unexpected EOF while parsing
In [ ]:
 
Notebooks AI
Notebooks AI Profile20060