Kivy: Develop a CryptoCurrency Price Cheker App #3

in #utopian-io7 years ago

Repository

https://github.com/kivy/kivy

What Will I Learn?

We'll take one step ahead our Crytocurrency Price Checker App, In this tutorial you'll learn to

  • Develop Search in App
  • Show Top 100 Coins
  • Show All Coins Available in the Market

Requirements

Difficulty

  • Intermediate

Tutorial Contents

  • Develop Search for the App
  • Show Top 100 Coins
  • Show All coins available in market

Develop Search for the App

First we'll develop our search in the App, When you search for specific coin it only show you that coin from the list. You can see in the App there is a search Input field and search button. You just have to write the coin name in search bar and click on Search button it returns you the coin you searched for.

So, lets start our development, open your text editor and open the both files of our App main.py (logical layer) and Cryptocurrency.kv (Presentation Layer) in the text editor . One thing you've to noted about the search is, here we are going to apply linear search for to search coins from the list.

Move to Cryptocurrency.kv and in this file go to the search Button code. Write the property of the button

on_press: app.root.topCoinsList(coinSearch.text)

coinSearch => ID of Input Field
coinSearch.text => Grabbing the text of input field

You know topCoinsList is the method of root class, here we send a parameter coinSearch.text to topCoinsList method. Actually, coinSearch.text is a value of Input Field that we write in it on run time. We grab it by coinSearch.text and pass it to topCoinsList.

Here is the code for Search Button


Button:
                text: "Search"
                size_hint_x: 20
                on_press: app.root.topCoinsList(coinSearch.text)

Now move toward main.py file, in the file go to topCoinsList(self) method in the CryptoCurrency class . As we know in the above code, we are passing a parameter to the topCoinsList(self) so there must be a variable in the in the parameter body of method that catch the value of parameter. So change the method body to

def topCoinsList(self, searchText=None):

By default we make the value of searchText variable None, this is because if when you're not passing parameter.

Next up remove the code within the for loop body and update it with the following code.

            if searchText is not None:
                if searchText == json_data['data'][i]['name'].capitalize():
                    price.append("${}".format(json_data['data'][i]['quotes']['USD']['price']))
                    marketCap.append("${}".format(json_data['data'][i]['quotes']['USD']['market_cap']))
                    changeHr.append("{}%".format(json_data['data'][i]['quotes']['USD']['percent_change_24h']))
                    allCoins.append("{}".format(json_data['data'][i]['name']))
                    break
            else:
                price.append("${}".format(json_data['data'][i]['quotes']['USD']['price']))
                marketCap.append("${}".format(json_data['data'][i]['quotes']['USD']['market_cap']))
                changeHr.append("{}%".format(json_data['data'][i]['quotes']['USD']['percent_change_24h']))
                allCoins.append("{}".format(json_data['data'][i]['name']))

if searchText is not None: check it the searchText have some value.

Then if searchText == json_data['data'][i]['name'].capitalize(): compare the coins data to parameter value and if we find the value then store only that value in the list variable.

Otherwise, is the else body store all the coins in the list variables.

Here is the whole topCoinsList method code.

    def topCoinsList(self, searchText=None):

        r = requests.get('https://api.coinmarketcap.com/v2/ticker/')

        json_data = r.json()
        keys = json_data['data'].keys()
        allCoins = []
        price = []
        marketCap = []
        changeHr = []

        for i in keys:

            #print("{}:  ${}".format(json_data['data'][i]['name'], json_data['data'][i]['quotes']['USD']['price']))

            if searchText is not None:
                if searchText == json_data['data'][i]['name'].capitalize():
                    price.append("${}".format(json_data['data'][i]['quotes']['USD']['price']))
                    marketCap.append("${}".format(json_data['data'][i]['quotes']['USD']['market_cap']))
                    changeHr.append("{}%".format(json_data['data'][i]['quotes']['USD']['percent_change_24h']))
                    allCoins.append("{}".format(json_data['data'][i]['name']))
                    break
            else:
                price.append("${}".format(json_data['data'][i]['quotes']['USD']['price']))
                marketCap.append("${}".format(json_data['data'][i]['quotes']['USD']['market_cap']))
                changeHr.append("{}%".format(json_data['data'][i]['quotes']['USD']['percent_change_24h']))
                allCoins.append("{}".format(json_data['data'][i]['name']))

        self.ids.coinList.data = [{"value": [w,x,y,z]} for w,x,y,z in zip(allCoins, price, marketCap,changeHr)]

Now run the code and check if the search it working for us or not, on my side here is the results.

CryptoCurrency_App_1.gif

Show Top 100 Coins

As in our previous tutorial we talked that when we launch the app it only show us the top 100 coins. It raise a question that why we need to show Top 100 Coins again? The answer is here, when you search for a specific coin it show the us that coin from the list but if you again want to go back to the list of top coin then what will you do.

So, this is the reason, we need to show again Top Coins List.

This is really easy to do, for this we'll develop a Top Coin Button after All Coin button, to do this go to the .kv file in the text editor write this code for button.

            Button:
                text: "Show Top"
                size_hint_x: 10

Output:

CryptoCurrency_App_2.JPG

Also change the size of the All Coin button to 10 size_hint_x: 10

Output:

CryptoCurrency_App_3.JPG

You can see both buttons are of same size, make the interface nicer.

Now to show the top coins by clicking on Top Coin Button you just have to add this property to Top Button.

on_press: app.root.topCoinsList()

On pressing call the topCoinsList method, here we didn't send any parameter to method, the method automatically assign it None value, and if the searchText=None then it'll run the else: body code. Follow see its working.

CryptoCurrency_App_4.gif

Show All Coins Available in the Market

As you we only have the list of Top coins List, but if you want to search another coin that didn't in the Top List. So, in this part of the tutorial we'll show All Coin available in the market.

You can see in the output we already have the All Coin Button, this is why we don't need to develop it. So directly move toward main.py file, create a new allCoinList method.


def allCoinsList(self):

Now in this method first grab all the coins, as you know we are using coinmarketcap.com api, the api allow us to grab the all coins name of coins having unique ID. To grab the all coins name from write this code.


    def allCoinsList(self):

        grabIds = requests.get('https://api.coinmarketcap.com/v2/listings/')
        idsData = grabIds.json()

Then count the total records totalRecords = len(idsData['data'])

    def allCoinsList(self):

        grabIds = requests.get('https://api.coinmarketcap.com/v2/listings/')
        idsData = grabIds.json()
        totalRecords = len(idsData['data'])


Then define the list variable in which we store the data.

        allCoins = []
        price = []
        marketCap = []
        changeHr = [] 
      

coinmarketcap provide us the URL(https://api.coinmarketcap.com/v2/ticker/?start=101&limit=10) that allow us to grab specific results, start GET specifies the from where you want to start result and limit GET specifies how much result you want to see from start to end. The max results you can grab is 100, but we want to show all the coins, for this we put it in loop to grab all the result.

First we start https://api.coinmarketcap.com/v2/ticker/?start=1&limit=100 , start = 1 and limit 100
2nd we make https://api.coinmarketcap.com/v2/ticker/?start=1&limit=100 , start = 101 and limit 100

and so on until it reaches the end of total records.

In the code we apply it as, as you know the each cycly cover 100 results so we divided the totalRecords /100 that we can get the proper cycles. here follow is the code.

    def allCoinsList(self):

        grabIds = requests.get('https://api.coinmarketcap.com/v2/listings/')
        idsData = grabIds.json()
        totalRecords = len(idsData['data'])

        allCoins = []
        price = []
        marketCap = []
        changeHr = []
        start = 1
        limit = 100
        for i in range(math.floor(totalRecords/100)):
            r = requests.get("https://api.coinmarketcap.com/v2/ticker/?start={}&limit={}".format(start, limit))
            coinData = r.json()
            keys = coinData['data'].keys()

            for j in keys:

                    price.append("${}".format(coinData['data'][j]['quotes']['USD']['price']))
                    marketCap.append("${}".format(coinData['data'][j]['quotes']['USD']['market_cap']))
                    changeHr.append("{}%".format(coinData['data'][j]['quotes']['USD']['percent_change_24h']))
                    allCoins.append("{}".format(coinData['data'][j]['name']))

            start = start + 100
        self.ids.coinList.data = [{"value": [w, x, y, z]} for w, x, y, z in zip(allCoins, price, marketCap, changeHr)]

At final point open the .kv file and go to All Coin button and set this property

on_press: app.root.allCoinsList()

Now, run the code and see the results, on my side here is the results. One thing you've to notice the data in big so it takes a while to load.

CryptoCurrency_App_5.gif

Curriculum

Proof of Work Done

https://github.com/faad1/Kivy-CryptocurrencyApp

Folder: https://github.com/faad1/Kivy-CryptocurrencyApp/tree/master/Tutorial%20-%203

Sort:  

Thank you for your contribution.
While I liked the content of your contribution, I would still like to extend one advice for your upcoming contributions:

  • There are parts of the code that have little explanation, try to explain as much as possible.

Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to Utopian rules and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post,Click here


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Hey @faad
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Contributing on Utopian
Learn how to contribute on our website or by watching this tutorial on Youtube.

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.23
TRX 0.21
JST 0.036
BTC 98081.40
ETH 3419.35
USDT 1.00
SBD 3.24