Hello and welcome back, as I have mentioned earlier I would like to create a method which will convert USD/world currency pairs to world currency pair/world currency pair before closing up this Forex application project and in this chapter, we will look at the source code to do the above- mentioned topic.
Before we start I have found out two things that I have overlooked previously. 1) This Coinbase API is actually returning the USD/BTC and other USD/cryptocurrency pair as well besides the USD/world currency pair so we do not need to develop another application for the USD/cryptocurrency pair with the Coinbase API anymore. 2) The currency pair converter method which I have created for this chapter will only return the approximate exchange rate for x/y currency pair because it seems like if we know the USD/x currency value and we know the USD/y currency value then x/y value is not equal to USD/x divided by USD/y. Which simply means the currency exchange rate for two individual countries will not base on the currency exchange rate of the USD/that country currency but instead that two countries have made their own agreement on the currency exchange rate separately. I have not looked into the GOLD/world currency yet which maybe is the sole commodity which all the world currency exchange rate is based upon. Nevertheless, the program which based on the USD below will demonstrate to you all that if the exchange rate of the world currency is based on USD then we can easily do the math to find out what is the exchange rate of x currency/ y currency pair if we know what is the currency exchange rate of USD/that currency. Do leave your comment under this post to let me know if the formula which I am using is wrong.
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 window background color
selectorFrame = Frame(win, background="white") # create top frame to hold search and switch combobox
selectorFrame.pack(anchor = "nw", pady = 2, padx=10)
currency_label = Label(selectorFrame, text = "Select currency pair / base currency :", background="white")
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, padx=3)
s = StringVar() # create string variable
# create currency frame and text widget to display the incoming forex data
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 to find out the currency exchange rate")
text_widget.insert(END, s.get())
buttonFrame = Frame(win) # create a bottom frame to hold the find button
buttonFrame.pack(side = BOTTOM, fill=X, pady = 6)
def search_currency(): # search currency pair
countVar = StringVar() # use to hold the character count
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)) #highlight 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) # button used to search the currency pair within the text widget
action_search.pack(side=LEFT)
# Create base currency combo box
base_currency = StringVar() # create a string variable
based = tk.Combobox(selectorFrame, textvariable=base_currency)
based.pack(side = LEFT, padx=3)
exchange_name_dict = dict() # the dictionary for currency name
base_currency_dict = dict() # the dictionary for base currency
def get_exchange_rate(): # this method will display the incoming forex data after the api called
# first get the api key and secret from the text file
f = open("coin.txt", "r")
api_key = f.readline()
api_secret = f.readline()
f.close()
api_key = api_key.replace('\n', '')
api_secret = api_secret.replace('\n', '')
global exchange_rate
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")
count = 0
found = False
curr = tuple() # the tuple which will be populated by currency pairs
curr1 = tuple() # the tuple which will be populated by base currency
usd = "USD" # populate the first base currency
curr1+= (usd,)
sell_buy = ''
for key in exchange_rate_s['data']: # populate the exchange_name_dict
id = key['id']
name = key['name']
obj_currency = {id:name}
exchange_name_dict .update(obj_currency)
for key in exchange_rate['rates']: # create a dictionary for id and rate
id = key
rate = exchange_rate['rates'][key]
obj_currency = {id: rate}
base_currency_dict.update(obj_currency)
curr1 += (id,)
curr, sell_buy = fill_display_exchange(count, curr, exchange_rate, found, sell_buy)
# fill up the data for the search currency pair combo box
preferPaired['values'] = curr
preferPaired.current(0) # select item one
# fill up data for the base currency pair
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()) # display forex rate in text widget
def fill_display_exchange(count, curr, exchange_rate, found, sell_buy): # method used to get the search combo box value and display forex rate
for key in exchange_rate['rates']:
count += 1
c_st = exchange_rate['currency'] + "/" + key
curr = curr + (c_st,) # add the search 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
return curr, sell_buy
def switch_currency(): # switch base currency
sell_buy = ''
count = 0
found = False
the_base_currency = based.get()
curr = tuple()
if(the_base_currency != '' and the_base_currency != "USD"):
for key in exchange_rate['rates']:
if (the_base_currency != key):
count += 1
c_st = the_base_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 : " + the_base_currency + "/" + key + " (" + \
exchange_name_dict[e_key] + ") : " + \
str((float(exchange_rate['rates'][key])/float(base_currency_dict[the_base_currency]))) + '\n'
found = True
break
if (found == False):
sell_buy += str(count) + ".) Pair : " + the_base_currency + "/" + key + " : " + \
str((float(exchange_rate['rates'][key]) / float(base_currency_dict[the_base_currency]))) + '\n'
else:
found = False
elif(the_base_currency != '' and the_base_currency == "USD"):
curr, sell_buy = fill_display_exchange(count, curr, exchange_rate, found, sell_buy)
if(the_base_currency != ''):
# fill up the data for the search currency pair combo box
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()) # populate the text widget with new forex data
# create the base currency switch button and the find button
action_switch = tk.Button(selectorFrame, text="Switch", command=switch_currency) # button used to switch the base currency
action_switch.pack(side=LEFT)
action_vid = tk.Button(buttonFrame, text="Find", command=get_exchange_rate) # button used to find out the exchange rate of currency pair
action_vid.pack()
win.iconbitmap(r'ico.ico')
win.mainloop()
If you run the above python program this is what you will expect.
I have finished the basic of the Forex application which has these features: 1) Get the USD/word currency price 2) Switch the base currency 3) Search for any particular currency pair! pic.twitter.com/8XkOHs9w8P— TechLikin (@ChooWhei) March 5, 2019
Like, share or follow me on twitter. I have created another website just for the stock market, Forex and cryptocurrency software written in python today, if you like to develop an application to monitor the financial market then do join me through this link!
from Planet Python
via read more
No comments:
Post a Comment