1. Create a market combo box for all the available currency market.
  2. Create a search function to retrieve the cryptocurrency-currency pair data from a particular market.

Hello and welcome back, in this chapter we will continue to develop our cryptocurrency project with the above new features.

Before we start we will create a new loader class which will load the currency’s market data as well as the cryptocurrency data into the combo box at the beginning of the main program to further tidy up the main program file.

class Loader(object):

    def __init__(self, crypto, market):
        self.crypto = crypto
        self.market = market

    def load_data(self):

        # read the data from crypto.txt file then populate the crypto combo box
        curr = tuple()  # the tuple which will be populated by cryptocurrencies
        with open('crypto.txt') as fp:
            for currency in fp.readlines():
                curr += (currency[:-1],)
        self.crypto['values'] = curr
        self.crypto.current(0)

        # read the data from market.txt file then populate the market combo box
        curr = tuple()  # the tuple which will be populated by market symbols
        with open('market.txt') as fp:
            for currency in fp.readlines():
                curr += (currency[:-1],)
        self.market['values'] = curr
        self.market.current(0)

If you have read the previous article then you know that the program will load the cryptocurrency symbols from a file to the combo box, the same technique will apply for the market’s combo box as well under the above function.

In the main program, we will create the instance of the loader class and call the load data method of this class to populate those combo boxes.

# create loader object then load the data into the crypto and market combo box
loader = Loader(crypto, market)
loader.load_data()

We need to further organize our project in the next chapter but for now this should be good enough.

The next step is to create the market combo box above the loader object like so. This box will besituated on the left side of the currency combo box.

# Create a combo box for markets
market = tk.Combobox(selectorFrame)
market.pack(side = LEFT, padx=3)

Besides that, we have also rearranged the currency combo box and the search button position as well as moved the cryptocurrency combo box to the bottom of the display panel.

Next we will create the search function which will retrieve the crytocurrency-currency pair data plus display those data on the display panel.

def search_currency(): # display all market data of the cryptocurrency-currency pair

    sell_buy = ''
    try:
        base_crypto = crypto.get()  # get the desired crypto currency
        currency_symbol = based.get() # get the currency symbol
        market_exchange = market.get() # get the market
        url = "https://min-api.cryptocompare.com/data/generateAvg"
        data = {'fsym' : base_crypto, 'tsym':currency_symbol, 'e' : market_exchange}
        r = requests.get(url, params=data)
        exchange_rate_s = json.loads(json.dumps(r.json()))
    except:
        print("An exception occurred")

    for key, value in exchange_rate_s.items():  # populate exchange rate string and the currency tuple
        for key1, value1 in value.items():
            sell_buy += str(key1) + " : " + str(value1) + "\n"

    text_widget.delete('1.0', END)  # clear all those previous text first
    s.set(sell_buy)
    text_widget.insert(INSERT, s.get())  # populate the text widget with new exchange rate data

We also will disable the search button and only enable it after the program has loaded the bitcoin-currencies exchange rate data for the first time after the user has clicked on the load button. We might further change this mechanism in the next chapter but for now, this should be sufficient enough.

This is how the program work at this moment, when the user has started the program, he needs to click on the Load button to load the bitcoin-currencies pair data for the first time, then the currency combo box will be filled up with currency symbols and the search button will be enabled where the user can now select the market, any cryptocurrency and any currency symbol then press the search button to display the one on one detail data of the cryptocurrency-currency pair.

import json
from tkinter import *
import tkinter.ttk as tk
import requests
from Loader import Loader

win = Tk() # Create tk instance
win.title("Crypto Calculator") # Add a title
win.resizable(0, 0) # Disable resizing the GUI
win.configure(background='white') # change window background color

selectorFrame = Frame(win, background="white") # create top frame to hold search button and combobox
selectorFrame.pack(anchor = "nw", pady = 2, padx=10)
currency_label = Label(selectorFrame, text = "Select market / currency pair :", background="white")
currency_label.pack(anchor="w")

# create currency frame and text widget to display the incoming exchange rate data
s = StringVar() # create string variable
currencyFrame = Frame(win)
currencyFrame.pack(side=TOP)
currency = Label(currencyFrame)
currency.pack()
text_widget = Text(currency, fg='white', background='black')
text_widget.pack()
s.set("Click the find button below to load the crypto currency - currency exchange rate from CCCAGG market")
text_widget.insert(END, s.get())

buttonFrame = Frame(win) # create a bottom frame to hold the load button
buttonFrame.pack(side = BOTTOM, fill=X, pady = 6)

# Create a combo box for crypto currency
crypto = tk.Combobox(buttonFrame)
crypto.pack(side = LEFT, padx=3)

# Create a combo box for markets
market = tk.Combobox(selectorFrame)
market.pack(side = LEFT, padx=3)

# create loader object then load the data into the crypto and market combo box
loader = Loader(crypto, market)
loader.load_data()

def search_currency(): # display all market data of the cryptocurrency-currency pair

    sell_buy = ''
    try:
        base_crypto = crypto.get()  # get the desired crypto currency
        currency_symbol = based.get() # get the currency symbol
        market_exchange = market.get() # get the market
        url = "https://min-api.cryptocompare.com/data/generateAvg"
        data = {'fsym' : base_crypto, 'tsym':currency_symbol, 'e' : market_exchange}
        r = requests.get(url, params=data)
        exchange_rate_s = json.loads(json.dumps(r.json()))
    except:
        print("An exception occurred")

    for key, value in exchange_rate_s.items():  # populate exchange rate string and the currency tuple
        for key1, value1 in value.items():
            sell_buy += str(key1) + " : " + str(value1) + "\n"

    text_widget.delete('1.0', END)  # clear all those previous text first
    s.set(sell_buy)
    text_widget.insert(INSERT, s.get())  # populate the text widget with new exchange rate data

# Create currency combo box
base_currency = StringVar() # create a string variable
based = tk.Combobox(selectorFrame, textvariable=base_currency)
based.pack(side = LEFT, padx=3)

action_search = tk.Button(selectorFrame, text="Search", command=search_currency, state=DISABLED) # button used to get the cryptocurrency/currency pair exchange rate
action_search.pack(side=LEFT)

def get_exchange_rate(): # this method will display the incoming exchange rate data after the api called

    global exchange_rate
    global base_crypto

    # read the currency file
    c_string = ''
    with open('currency.txt') as fp:
        for currency in fp.readlines():
            c_string += currency[:-1] + ","
    c_string = c_string[:-1]

    base_crypto = crypto.get()  # get the desired crypto currency
    try:
        url = "https://min-api.cryptocompare.com/data/price" #url for API call
        data = {'fsym' : base_crypto, 'tsyms':c_string}
        r = requests.get(url, params=data)
        exchange_rate_s = json.loads(json.dumps(r.json()))

    except:
        print("An exception occurred")

    curr1 = tuple() # the tuple which will be populated by currency
    sell_buy = ''

    for key, value in exchange_rate_s.items():  # populate exchange rate string and the currency tuple
        sell_buy += base_crypto + ":" + key + "  " + str(value) + "\n"
        curr1 += (key,)

    # fill up combo boxes for both currency and cryptocurrency
    based['values'] = curr1
    based.current(0)

    text_widget.delete('1.0', END)  # clear all those previous text first
    s.set(sell_buy)
    text_widget.insert(INSERT, s.get())  # populate the text widget with new exchange rate data

    action_search.config(state=NORMAL)

action_vid = tk.Button(buttonFrame, text="Load", command=get_exchange_rate) # button used to load the exchange rate of currency pairs
action_vid.pack()

win.iconbitmap(r'ico.ico')
win.mainloop()
The details Kraken market data for the BTC-USD pair

In the next chapter, we will use Pandas to plot the currency graph of those data.

Click to rate this post!
[Total: 0 Average: 0]
Please follow and like us:
error0

Leave a Reply

Your email address will not be published. Required fields are marked *