Kivy: Develop a CryptoCurrency Price Cheker App #4

in #utopian-io7 years ago

Repository

https://github.com/kivy/kivy

What Will I Learn?

Hy, how are you? Today we come up with our next tutorial, an addition to over CryptoCurrency Price Cheker App tutorial series. In this chapter you'll learn some of interesting stuff, we are going to develop:

  • Pagination for Coins Records
  • Fast and Separate Search in the App
  • Remove the junk code

Requirements

Difficulty

  • Intermediate

Tutorial Contents

  • Pagination for Records
  • Fast and Separate Search
  • Remove the junk code

Pagination for Records

As you in our previous tutorial part 3 we have a allCoinsList(self, searchText=None): method that loads all the coins available in the market, when it loads records it take really huge amount of time and some times it stuck. So, here we are going to develop pagination for our records.

So, here start, open up the text editor and then open the both files main.py and CryptoCurrency.kv. Now move to main.py file and then jump over allCoinsList method and remove the code within the method.

Now, first we analyze the api of coinmarketcap, here we find a URL https://api.coinmarketcap.com/v2/ticker/?start=101&limit=10 in, with the help of this URL we can load a specific records and also the specific number of record.

Yes, start is the GET that tells from where you want to start the record to show and limit sets the how many records you want to show, maximum records you can show is 100. If we test this URL in our code. Write following code in the allCoinsList and run the code then click over the All Coin Button to trigger the method.


        r = requests.get('https://api.coinmarketcap.com/v2/ticker/?start=101&limit=10')

        coinData = r.json()

        print(coinData )

Output:

CryptoCurrency_App_1.JPG

You can see it show us the records start from 101, as we set limit 10 so it only show the 10 records.

Now we Implement this in our GUI, for this write this write this code within the allCoinsList.



        r = requests.get('https://api.coinmarketcap.com/v2/ticker/?start=101&limit=10')

        coinData = r.json()
        keys = coinData['data'].keys()

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

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

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

Click over the Show All Button, you can see the output

CryptoCurrency_App_2.JPG

You can see it show us the only 10 records start from 101.

Now to make it dynamic and develop pagination, first move to CryptoCurrency.kv file, and develop GUI for pagination for this change the rows:3 to rows:4 in root widget. Then write this code at the end of the ROOT Widget.

       BoxLayout:
           height: "50"
           size_hint_y: None
           Button:
               id: pre
               text: "Previous"
               on_release: root.allCoinsList('pre')
           Button:
               id: next
               text: "Next"
               on_release: root.allCoinsList('next') 

Output:

CryptoCurrency_App_3.JPG

You can see at the end we have two Button Next and Previous, In the coding we set on_release: on_release: root.allCoinsList('pre') and on_release: on_release: root.allCoinsList('next') in order to call the method and we pass it a string 'pre' and 'next' as parameter. As we are passing a parameter so we set a variable in the method to catch this parameter.

    def allCoinsList(self, page=None):

We assign 'None' as default value, when you are not passing the parameter.

Now move to main.py file and for pagination first of all define a global variable and assign it a value 1 start = 1 at the start of the class CryptoCurrency(GridLayout).

Then move to allCoinsListmethod and grab the total records by writing this piece of code in the top of method.

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

Now, define a variable limit = 100, we set limit to 100 because we want to show 100 records in each page. Then write this code in order to move the start point.


       if page is not None: # if page haven't default value None 
           if page == 'pre' and self.start > 1:
               self.start = self.start - 100
           elif page == 'next' and self.start < 1601:
               self.start = self.start + 100

Output:

CryptoCurrency_App_4.gif

Now here we've to disable the button when they reach at their ends, for this write this code under the for loop not within it.


        if self.start == 1:
            self.ids.pre.disabled = True
        elif self.start == 1501:
            self.ids.next.disabled = True
        else:
            self.ids.pre.disabled = False
            self.ids.next.disabled = False

Now see the output:

CryptoCurrency_App_5.gif

You can see when record reach at one our previous button got disabled, same as the with the Next button when you reach at the end page our Next button will be disabled. The end point we got from total records we got at the from start code in the method.

Fast and Separate Search

As you know we've two methods one for Top Coins and other for All Coins, so this is why we've to search the coin in the both methods this make our code lengthy and redundant. So, here we got idea and start to develop our search separate this will be fast from the previous search.

For this code a new method call searchCoin() and first of all in this method we'll grab all the coins available in the market for this write following code in the method, this we've already done in the previous chapter so this no need to explain.

def searchCoin(self):

        r1 = requests.get('https://api.coinmarketcap.com/v2/listings/')

        json_data = r1.json()

Now move to our CryptoCurrency.kv file and set this property to Search button on_release: root.searchCoin(coinSearch.text)``. Here you can see we are passing the text of the Input Field as parameter to searchCoin() so go to the searchCoin() ``` method and define a variable that catch the parameter.


    def searchCoin(self, searchText=None): #parameter catcher

        r1 = requests.get('https://api.coinmarketcap.com/v2/listings/')

        json_data = r1.json()

Now check weather we have searched coin in the list or not, for this write the code


    def searchCoin(self, searchText=None):

        r1 = requests.get('https://api.coinmarketcap.com/v2/listings/')

        json_data = r1.json()
        id_ = None
        total = len(json_data['data'])

        for i in range(total):
            if searchText is not None:
                if searchText.capitalize() == json_data['data'][i]['name'].capitalize():
                    id_ = json_data['data'][i]['id']
                    print(json_data['data'][i]['id'])


Now, if we have the search coin in our list then show all the details of it in GUI, to do this write this code.


        r2 = requests.get('https://api.coinmarketcap.com/v2/ticker/{}'.format(id_))
        data = r2.json()

        self.ids.coinList.data = [{'value':[data['data']['name'],str(data['data']['quotes']['USD']['price']),
                                            str(data['data']['quotes']['USD']['market_cap']),
                                            str(data['data']['quotes']['USD']['percent_change_24h'])]}]
        print(data['data']['name'])
        print(data['data']['quotes']['USD']['price'])
        print(data['data']['quotes']['USD']['market_cap'])
        print(data['data']['quotes']['USD']['percent_change_24h'])

Output:

CryptoCurrency_App_6.gif

Remove the junk code

If you noticed that we've two method on for show top coins and other for All the coins, but you notice our allCoinsListmethod first show the top 100 coins same as topCoinsListmethod do. So, here we decided to remove the topCoinsListfrom the code and its relevant button.

And replace the method in the constructor.

    def __init__(self, **kwargs):
        super(CryptoCurrency, self).__init__(**kwargs)
        self.allCoinsList()

Remove this code from CryptoCurerncy.kv file

            Button:
                text: "Show Top"
                on_press: app.root.topCoinsList()
                size_hint_x: 10

Now run the App.

CryptoCurrency_App_6.JPG

Curriculum

Proof of Work Done

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

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

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!

Just wondering about your opinion:
How long the cryptocurrency buzz is going to last?
Or it will be one of those "forever" things?
@faad