Saturday, March 2, 2019

codingdirectional: Search for any particular currency pair within the Forex data

Before we start this chapter I just want to tell you people that I have extended this website for another year by paying the full year rent for web hosting. The goal I start this website is not to make money from it but to share what I know in programming with all of you, therefore I certainly do not expect any large income from a site like this. I myself is a tech and programming lover and I like to play with new tech stuff and create cool software to use in every day life. Although all the above statements are true there is one thing we all need to know which is although I can always provide free code for the readers but I do need to pay rent for this website every month, thus I would like to take this opportunity to ask for your kind donation to help this site out, the donation form is located at the sidebar of this website, I really don’t mind how much money you donate to me, 1 usd is as good as 100 USD as long as there is enough money to finance this website to keep it going. So friend, kindly provide your support to me through donation, thank you in advance. Alright, without wasting anymore time, let us begin this new chapter.

If you still remember we have created a combo box for the currency pair in the last chapter, then now we will use that list of items to search for a particular currency pair from the incoming data from Coinbase. We will create a button which when pressed will show you the currency pair which you have selected from the combo box on the outcome label of this tkinter interface. We will use the search method from the Text widget to look for that currency pair and highlight the outcome. Below is the entire revised program.

from coinbase.wallet.client import Client
import json
from tkinter import *
import tkinter.ttk as tk

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

selectorFrame = Frame(win) # create a button frame
selectorFrame.pack(side = TOP, fill=X, pady = 6)
currency_label = Label(selectorFrame, text = "Select your currency pair :")
currency_label.pack(anchor="w") # the currency pair label
# Create a combo box for currency pair
select_currency = StringVar() # create a string variable
preferPaired = tk.Combobox(selectorFrame, textvariable=select_currency)
preferPaired.pack(side = LEFT)

s = StringVar() # change text
currencyFrame = Frame(win) # create currency frame
currencyFrame.pack(side=TOP)
currency = Label(currencyFrame)
currency.pack()
text_widget = Text(currency, fg='white', background='black')
text_widget.pack()

s.set("Click the below button to find out the bitcoin exchange rate")
text_widget.insert(END, s.get())

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

def search_currency():
    countVar = StringVar() # for future use
    text_widget.tag_remove("search", "1.0", "end") # cleared the hightlighted currency pair
    if(preferPaired.get() != ''):

        pos = text_widget.search(preferPaired.get(), "1.0", stopindex="end", count=countVar)
        text_widget.tag_configure("search", background="green")
        new_pos = float(pos) + float(0.7)
        text_widget.tag_add("search", pos, str(new_pos)) #highlighted the background of the searched currency pair
        pos = float(pos) + 2.0
        text_widget.see(str(pos))

action_search = tk.Button(selectorFrame, text="Search", command=search_currency) # find out the exchange rate of bitcoin
action_search.pack(side=LEFT)

def get_exchange_rate():

    f = open("coin.txt", "r")
    api_key = f.readline()
    api_secret = f.readline()
    f.close()

    sell_buy = ''

    api_key = api_key.replace('\n', '')
    api_secret = api_secret.replace('\n', '')

    try:
        client = Client(api_key, api_secret)
        market_currencies_o = client.get_exchange_rates()
        market_currencies_s = json.dumps(market_currencies_o)
        exchange_rate = json.loads(market_currencies_s)
        supported_currency = client.get_currencies() # get all the available currencies from coinbase
        exchange_rate_s = json.loads(json.dumps(supported_currency))

    except:
        print("An exception occurred")

    exchange_name_dict = dict()

    for key in exchange_rate_s['data']:
        id = key['id']
        name = key['name']
        obj_currency = {id:name}
        exchange_name_dict.update(obj_currency)

    count = 0
    found = False
    curr = tuple() # the tuple which will be populated by currency pairs

    for key in exchange_rate['rates']:
        count += 1
        c_st = exchange_rate['currency'] + "/" + key
        curr = curr + (c_st,)  # add the currency pairs
        for e_key in exchange_name_dict:
            if(e_key == key):
                sell_buy += str(count) + ".) Pair : " + exchange_rate['currency'] + "/" + key + " (" + exchange_name_dict[e_key] + ") : " + \
                exchange_rate['rates'][key] + '\n'
                found = True
                break
        if(found == False):
            sell_buy += str(count) + ".) Pair : " + exchange_rate['currency'] + "/" + key + " : " + \
                exchange_rate['rates'][key] + '\n'
        else:
            found = False
    preferPaired['values'] = curr
    preferPaired.current(0)  # select item one
    text_widget.delete('1.0', END) # clear all those previous text first
    s.set(sell_buy)
    text_widget.insert(INSERT, s.get())

action_vid = tk.Button(buttonFrame, text="Find", command=get_exchange_rate) # find out the exchange rate of bitcoin
action_vid.pack(fill=X)
win.mainloop()

If you run the above program to find the Forex data and then select any currency pair then pressed the search button you will get the below outcome.

If you are new to this tutorial then you need to get the API key and secret from Coinbase before you can start to develop this application for your own use. The Coinbase account is free, you can sign up through this sign-up link.

I am a python developer and if you are a company founder then I am very keen to help you to promote your company product by creating free software on this website, if your product has provided any free API then do leave your comment under this post or any other post on this website so I can take a look at your product. Again, this site needs support from you all, readers, do consider to donate to this site to help this site pays for the rent. Thank you.

We will continue developing this Forex application in the next chapter!



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...