Blog available for sell
This blog is available for sale. Please 'contact us' if interested.
Advertise with us
api requests   2   11748
Get latest Bitcoin and other crypto-currencies rates using python Django

Everybody is investing in bitcoins. 

James Howells is trying to dig a landfill site to get 7500 bitcoins that were dumped there in 2013.

To be a good investor, it is necessary that you keep track of ups and downs in the market. '

There are multiple platforms where you can track the price of bitcoin. But for a python programmer that is no fun. Being a python programmer we will develop our own project where we can get latest bitcoin and other crypto-currency prices.

Let's start.



Virtual environment setup:

It is always recommended to use virtual environment for all your python and Django projects.

Create a virtual environment using python3 using below command.

virtualenv -p /usr/bin/python3 crypto


Now activate the virtual environment.

source crypto/bin/activate


Install the latest Django version and other required libraries.

For now only requests package is required. We will add other packages later if required.

pip install django requests


This will install Django 2.0 and requests package along with some other package.

You can verify the same by running command pip freeze .

(crypto) rana@Brahma: crypto$ pip freeze
certifi==2017.11.5
chardet==3.0.4
Django==2.0
idna==2.6
pytz==2017.3
requests==2.18.4
urllib3==1.22


Creating new Django Project:

Once virtual environment has been setup and activated, create a new django project.

django-admin startproject crypto


Go to crypto project directory and list the files.

get latest bitcoin and other crypto currencies rates using python django

Since we are working on Django 2.0 , we need to take care of few things which we will highlight as we progress.

Now create a new app 'bitcoin'.

python manage.py startapp bitcoin


Add this app to the list of installed apps in settings.py  file.



Project Setup:

URLs:

Create urls.py  file in new app bitcoin.

from django.urls import path
from . import views

app_name = 'bitcoin'

urlpatterns = [
    path('', views.index, name="index"),
]


Django 2.0 Note: Adding app_name  in urls.py  is require now, otherwise you will get the below error.

'Specifying a namespace in include() without providing an app_name '
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.
 

Include urls of bitcoin app in project's urls.py  file.  


Teamplate:

Create a directory templates/bitcoin  in bitcoin app.

Inside this directory create a new html file, index.html . You can leave this file empty as of now or to make sure things are working fine, put some text there.  


Views:

Create a new function index in views.py  file.

For now this function will only render the index.html  created in previous step.

We will add more functionality in coming steps.

from django.shortcuts import render


def index(request):
    data = {}
    return render(request, "bitcoin/index.html", data)
 


Verifying basic setup:

Once above steps are completed, run the django server.

$python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

December 28, 2017 - 09:00:43
Django version 2.0, using settings 'crypto.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.


Go to localhost:8000  and you can see the text which you putted in index.html  file.  



Getting bitcoin prices:

We will use the coinmarktecap api to fetch the latest data.

In views.py  file add a new function to get bitcoin data. This function will call the api url and get the currency data. Data returned is Json string. Convert it to Json Object.

# return the data received from api as json object
def get_crypto_data():
    api_url = "https://api.coinmarketcap.com/v1/ticker/?limit=10"

    try:
        data = requests.get(api_url).json()
    except Exception as e:
        print(e)
        data = dict()

    return data


Make a call to get_crypto_data  in index function and return the rendered response.

Complete views.py  file :

from django.shortcuts import render
import requests


def index(request):
    data = {}
    data["crypto_data"] = get_crypto_data()
    return render(request, "bitcoin/index.html", data)


# return the data received from api as json object
def get_crypto_data():
    api_url = "https://api.coinmarketcap.com/v1/ticker/?limit=10"

    try:
        data = requests.get(api_url).json()
    except Exception as e:
        print(e)
        data = dict()

    return data
 

Rendering Data in Template:

Render the coins data row wise using a for loop in template as shown in html code below.

<html>
    <head>
        <title>Latest Bitcoin Price - ThePythonDjango.Com</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    </head>
    <body style="margin:20px;">
    
        <div class="alert alert-dark" role="alert">
            <span style="font-size:30px;">Bitcoin Latest Price</span> <span style="font-size:15px;">by <a href="http://ThePythonDjango.Com" target="_blank">ThePythonDjango.Com</a></span>
        </div>
        
        <div class="list-group">
            <div class="list-group-item list-group-item-primary">
                <div class="row">
                    <div class="col-md-3">
                        <label>Name</label>
                    </div>
                    <div class="col-md-3">
                        <label>USD Price</label>
                    </div>
                    <div class="col-md-3">
                        <label>BTC Price</label>
                    </div>
                    <div class="col-md-3">
                        <label>Change in Last Hour</label>
                    </div>
                </div>
            </div>
            {% for coin in crypto_data %}
            <div class="list-group-item list-group-item-{% if coin.percent_change_1h.0 == '-'%}danger{% else %}success{% endif %}">
                <div class="row">
                    <div class="col-md-3">
                        {{coin.name}}
                    </div>
                    <div class="col-md-3">
                        {{coin.price_usd}}
                    </div>
                    <div class="col-md-3">
                        {{coin.price_btc}}
                    </div>
                    <div class="col-md-3">
                        {{coin.percent_change_1h}}
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </body>
</html>


We are using bootstrap.css  for styling. Now if you go to localhost:8000  you can see the details as in below image.

get latest bitcoin and other crypto currencies rates using python django

Complete code is available on Github.

Download and setup the project on your machine. Experiment with it and let us know in case of any query.  


References:
[1] https://coinmarketcap.com/api/
[2] Django 2.0 official documentation
api requests   2   11748
2 comments on 'Get Latest Bitcoin And Other Crypto-Currencies Rates Using Python Django'
Login to comment

Kehinde April 21, 2019, 2:38 p.m.
Just what i needed to kickoff
John Oct. 26, 2019, 8:28 a.m.
Pls is there away to get the prices of crypto currencies without using coinmarketcap api? I want to have my own standalone.

Related Articles:
Django application to automate the WhatsApp messaging
Django application with REST API endpoints to automate the WhatsApp messaging. Automating WhatsApp web using selenium to send messages. Using selenium to automate whatsapp messaging. Sending bulk messages via whatsapp using automation. Source code Django application Whatsapp Automation...
How to send bulk emails for free using Mailgun and Python Django
How to send bulk emails for free using Mailgun and Python-Django, How to send free promotional emails from your Django application. Free email Api....
How to post messages to Microsoft teams channel using Python
In this article we will see how to send alerts or messages to microsoft teams channels using connectors or incoming webhook. we used python's requests module to send post request....
Python Requests Library: Sending HTTP GET and POST requests using Python
Python requests library to send GET and POST requests, Sending query params in Python Requests GET method, Sending JSON object using python requests POST method, checking response headers and response status in python requests library...
DigitalOcean Referral Badge

© 2024-2025 Python Circle   Contact   Sponsor   Archive   Sitemap