desarrollo,  python

Python CoinMarketCap API – Consultando Criptodivisas con Python

Python nos permite prácticamente cualquier cosa de forma sencilla, en esta ocasión vamos a ver como obtener información del mercado de las Cryptodivisas con apenas unas lineas de código.

Hace unos días vimos cómo hacer consultas desde el Shell con Coinmon. En esta ocasión utilizaremos la API CoinMarketCap, la misma que utiliza Coinmon. Esta API permite utilizar los servicios de CoinMarketCap. De momento no vamos a mostrar gráficas, pero todo se andará.

Para ello en esta primera entrega de Criptodivisas y Python vamos a utilizar un recubrimiento de dicha API, la CoinMarketCAP. Más adelante veremos que es posible acceder directamente mediante requests.

Instalación

pip3 install coinmarketcap

Después de unos segundos bajando e instalando packetes…

Collecting coinmarketcap
  Downloading https://files.pythonhosted.org/packages/a8/da/c64662a91905017f237f5ff2778b68638946b0d6268513efadd4d1363669/coinmarketcap-5.0.3.tar.gz
Collecting requests>=2.18.4 (from coinmarketcap)
  Downloading https://files.pythonhosted.org/packages/65/47/7e02164a2a3db50ed6d8a6ab1d6d60b69c4c3fdf57a284257925dfc12bda/requests-2.19.1-py2.py3-none-any.whl (91kB)
    100% |████████████████████████████████| 92kB 197kB/s 
Collecting requests_cache>=0.4.13 (from coinmarketcap)
  Downloading https://files.pythonhosted.org/packages/00/62/9e45a38988cb48c474805a1626439f4d9a486a042bd077af888fa8b17a64/requests_cache-0.4.13-py2.py3-none-any.whl
Collecting idna<2.8,>=2.5 (from requests>=2.18.4->coinmarketcap)
  Downloading https://files.pythonhosted.org/packages/4b/2a/0276479a4b3caeb8a8c1af2f8e4355746a97fab05a372e4a2c6a6b876165/idna-2.7-py2.py3-none-any.whl (58kB)
    100% |████████████████████████████████| 61kB 209kB/s 
Collecting urllib3<1.24,>=1.21.1 (from requests>=2.18.4->coinmarketcap)
  Downloading https://files.pythonhosted.org/packages/bd/c9/6fdd990019071a4a32a5e7cb78a1d92c53851ef4f56f62a3486e6a7d8ffb/urllib3-1.23-py2.py3-none-any.whl (133kB)
    100% |████████████████████████████████| 143kB 240kB/s 
Collecting chardet<3.1.0,>=3.0.2 (from requests>=2.18.4->coinmarketcap)
  Using cached https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl
Collecting certifi>=2017.4.17 (from requests>=2.18.4->coinmarketcap)
  Downloading https://files.pythonhosted.org/packages/df/f7/04fee6ac349e915b82171f8e23cee63644d83663b34c539f7a09aed18f9e/certifi-2018.8.24-py2.py3-none-any.whl (147kB)
    100% |████████████████████████████████| 153kB 197kB/s 
Building wheels for collected packages: coinmarketcap
  Running setup.py bdist_wheel for coinmarketcap ... done
  Stored in directory: /home/nuse/.cache/pip/wheels/5c/73/ec/47f4d3160b8d215cc223937a3886eccfc690cd3dbb5152ab42
Successfully built coinmarketcap
Installing collected packages: idna, urllib3, chardet, certifi, requests, requests-cache, coinmarketcap
Successfully installed certifi-2018.8.24 chardet-3.0.4 coinmarketcap-5.0.3 idna-2.7 requests-2.19.1 requests-cache-0.4.13 urllib3-1.23

Listo, ya lo tenemos todo preparado para comenzar. Vamos a Python!

Uso/Codigo

Este primer ejemplo solicita estadísticas al sistema, por parámetros le indicamos que lo muestre en euros.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct  9 13:07:47 2018
@author: altaruru
https://pypi.org/project/coinmarketcap/
"""
from coinmarketcap import Market

def test1():
    coinmarketcap = Market()
    stmp=coinmarketcap.stats(convert='EUR')
    print(stmp)
test1()
{'data': {'active_cryptocurrencies': 2054, 'active_markets': 14636, 'bitcoin_percentage_of_market_cap': 52.4, 
'quotes': {'USD': {'total_market_cap': 217201471787.0, 'total_volume_24h': 12065697858.0}, 
'EUR': {'total_market_cap': 188236569517.0, 'total_volume_24h': 10456676720.0}}, 'last_updated': 1539191305},
 'metadata': {'timestamp': 1539190712, 'error': None}, 'cached': True}

salida de .stats sin parámetros, por defecto en USD:

{'data': {'active_cryptocurrencies': 2054, 'active_markets': 14636, 'bitcoin_percentage_of_market_cap': 52.37, 
'quotes': {'USD': {'total_market_cap': 217181388279.0, 'total_volume_24h': 12076287089.0}}, 
'last_updated': 1539191486}, 'metadata': {'timestamp': 1539190896, 'error': None}, 'cached': False}

Si queremos recuperar una divisa en concreto por su ID:

stmp=coinmarketcap.ticker("1")
print(stmp)

devuelve:

{'data': {'id': 1, 'name': 'Bitcoin', 'symbol': 'BTC', 'website_slug': 
'bitcoin', 'rank': 1, 'circulating_supply': 17314875.0, 'total_supply': 
17314875.0, 'max_supply': 21000000.0, 'quotes': {'USD': 
{'price': 6571.35338876, 'volume_24h': 3815236094.3057, 'market_cap': 
113782162507.0, 'percent_change_1h': 0.18, 'percent_change_24h': -0.72, 
'percent_change_7d': 1.12}}, 'last_updated': 1539191607}, 
'metadata': {'timestamp': 1539191027, 'error': None}, 'cached': True}

O solicitar un rango, del 1 al 2 por ejemplo:

stmp=coinmarketcap.ticker(start=0, limit=2)
{'data': {'1': {'id': 1, 'name': 'Bitcoin', 'symbol': 'BTC', 'website_slug': 
'bitcoin', 'rank': 1, 'circulating_supply': 17314887.0, 'total_supply': 17314887.0, 
'max_supply': 21000000.0, 'quotes': {'USD': {'price': 6573.68821809, 'volume_24h': 
3807184185.67456, 'market_cap': 113822668669.0, 'percent_change_1h': 0.19, 
'percent_change_24h': -0.69, 'percent_change_7d': 1.16}}, 'last_updated': 
1539192083}, '1027': {'id': 1027, 'name': 'Ethereum', 'symbol': 'ETH', 
'website_slug': 'ethereum', 'rank': 2, 'circulating_supply': 102487228.0, 
'total_supply': 102487228.0, 'max_supply': None, 'quotes': {'USD': {'price': 225.582933862, 
'volume_24h': 1402975683.09003, 'market_cap': 23119369547.0, 'percent_change_1h': 0.12,
 'percent_change_24h': -0.82, 'percent_change_7d': 2.64}}, 'last_updated': 1539192101}},
 'metadata': {'timestamp': 1539191496, 'num_cryptocurrencies': 2054, 'error': None}, 
'cached': False}

Tambien es posible recuperar toda la información de las divisas, actualmente 2054, mediante listings()

print(coinmarketcap.listings())
{'data': [{'id': 1, 'name': 'Bitcoin', 'symbol': 'BTC', 'website_slug': 'bitcoin'}, 
{'id': 2, 'name': 'Litecoin', 'symbol': 'LTC', 'website_slug': 'litecoin'}, 
{'id': 3, 'name': 'Namecoin', 'symbol': 'NMC', 'website_slug': 'namecoin'}, 
{'id': 4, 'name': 'Terracoin', 'symbol': 'TRC', 'website_slug': 'terracoin'}, 
{'id': 5, 'name': 'Peercoin', 'symbol': 'PPC', 'website_slug': 'peercoin'}, 
{'id': 6, 'name': 'Novacoin', 'symbol': 'NVC', 'website_slug': 'novacoin'}, 
{'id': 8, 'name': 'Feathercoin', 'symbol': 'FTC', 'website_slug': 'feathercoin'},
 {'id': 9, 'name': 'Mincoin', 'symbol': 'MNC', 'website_slug': 'mincoin'}, 
{'id': 10, 'name': 'Freicoin', 'symbol': 'FRC', 'website_slug': 'freicoin'}, ....

Ya es cuestión de cada uno darle formato y presentarlo como guste: 

 

Por el momento eso es todo, en breve siguiente entrega, integrándolo con Mysql.

Saludos!

Referencias:

 

 

Deja un comentario

Tu dirección de correo electrónico no será publicada.