How to Use Python With Real-Time Data and REST APIs
We take a look at how to use Python and a freely available REST API to call, manipulate, and display data on our machine.
Join the DZone community and get the full member experience.
Join For Free1. Introduction
The Forex Quote API provided by 1forge.com is one of the most generous places with free plans to get real-time currency exchange values. The https://1forge.com/forex-data-api site includes an introduction to the Forex data API.
For free accounts, the REST rate limit is 1000 requests per day returning results in JSON format. It supports more than 700 currency pairs. Unfortunately, the Peruvian Sol (PEN) is not supported.
You have to obtain an API key to submit requests. For that, you can register at https://1forge.com/register and, finally, in your free account, you can get your API key.
In order to learn which data type is returned, you can submit a raw request via your favorite web browser, including the currency pairs and your API key, such as:
https://forex.1forge.com/1.0.3/quotes?pairs=EURUSD,GBPJPY,AUDUSD&api_key="your_api_key"
[{"symbol":"EURUSD","bid":1.12333,"ask":1.12335,"price":1.12334,"timestamp":1552081127},
{"symbol":"GBPJPY","bid":144.677,"ask":144.683,"price":144.68,"timestamp":1552081127},
{"symbol":"AUDUSD","bid":0.70454,"ask":0.70456,"price":0.70455,"timestamp":1552081127}]
As you can see, the REST call returns a list of key values.
Please note that I am not using the Python client. Instead, I am using REST calls to the API. Also please note that over the weekends there are no currency updates via this API, as compared to other sites such as the XE currency converter.
REST API calls include (taken from the Forex site):
- /quotes - Get quotes for specific currency pair(s)
- /symbols - Get a list of symbols
- /convert - Convert from one currency to another
- /market_status - Check if the market is open
- /quota - Check your current usage and remaining quota
2. Analysis of Code Excerpts
In this case, I am working with a Python script that gets the currency exchange values of Euros compared to US Dollars and vice-versa. The code executes a REST request for getting the respective quotes.
2.1 Initial Code: Import Statements and Global Variables
import requests
import json
import datetime
from tkinter import *
import time
api_key = "your_api_key"
pairs = "EURUSD,USDEUR"
url = "https://forex.1forge.com/1.0.3/quotes?pairs=" + pairs + "&api_key=" + api_key
In this first code excerpt, we import the required libraries and set up the API key and the currency pairs to form the final URL where we'll send the REST request.
2.2 Get Currency Values Code Excerpt
def get_currency_values():
"""
Returns currency pair values
:return: currency pair values.
Example EURUSD 1.1239 (euro to dollar conversion)
"""
response = requests.get(url)
data = response.text
currencies = json.loads(data)
forex_currencies = []
for currency in currencies:
for key, value in currency.items():
if key == "symbol":
symbol_from = value[:3]
symbol_to = value[3:]
str_currency = symbol_from + " TO " + symbol_to + ": "
if key == "price":
price = value
forex_currencies.append(str_currency + str(price))
return forex_currencies
In this code snippet, we process the raw REST request and format it into a list of currency pairs with its respective values: for instance EUR to USD: 1.12329
2.3 Set Up GUI Window Elements
In the code excerpt depicted below, we set up the GUI Window with three labels, one containing the date/time and other labels depicting currency pair values. In this case Euro to Dollar and Dollar to Euro, the script can be customized to include the required currencies (may require you to add labels to the main window).
def setup_gui(window, symbol_pairs):
"""
Returns a window with labels representing currency pairs information (prices)
:param window: window to be setup with labels
:param symbol_pairs: the symbol pairs with associated currency values
:return: Returns a window with time, and currency pairs with associated currency values
"""
window.wm_title("Currency Table")
date_time = datetime.datetime.now().strftime("%A %d %B %Y %H:%M:%S:%f")
str_date_time = "On " + str(date_time)
l1 = Label(window, text=str_date_time)
l1.grid(row=0, column=0)
l2 = Label(window, text=symbol_pairs[0])
l2.grid(row=1, column=0)
l3 = Label(window, text=symbol_pairs[1])
l3.grid(row=2, column=0)
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
# currency window info positioned on the lower right side of the screen
# and with a given screen width and height
xpos = screen_width - 250
ypos = screen_height - 150
window.geometry("250x75+" + str(xpos) + "+" + str(ypos))
return window
2.4 Code Excerpt Setting Up A Top Window With Date/Time & Currency Pairs Values
Finally, we set up the window so that currency information is always showing at the top of other windows:
def main():
while True:
window = Tk()
symbol_pairs = get_currency_values()
window = setup_gui(window, symbol_pairs)
window.update()
# let the window be always on top of other windows
window.lift()
window.attributes('-topmost', True)
# we get the next currency pair values every 60 seconds
time.sleep(60)
window.destroy()
if __name__ == '__main__':
main()
3. Whole Code Script
And this is the whole Python script:
import requests
import json
import datetime
from tkinter import *
import time
api_key = "your_api_key"
pairs = "EURUSD,USDEUR"
url = "https://forex.1forge.com/1.0.3/quotes?pairs=" + pairs + "&api_key=" + \
api_key
def get_currency_values():
"""
Returns currency pair values
:return: currency pair values.
Example EURUSD 1.1239 (euro to dollar conversion)
"""
response = requests.get(url)
data = response.text
currencies = json.loads(data)
forex_currencies = []
for currency in currencies:
for key, value in currency.items():
if key == "symbol":
symbol_from = value[:3]
symbol_to = value[3:]
str_currency = symbol_from + " TO " + symbol_to + ": "
if key == "price":
price = value
forex_currencies.append(str_currency + str(price))
return forex_currencies
def setup_gui(window, symbol_pairs):
"""
Returns a window with labels representing currency pairs information (prices)
:param window: window to be setup with labels
:param symbol_pairs: the symbol pairs with associated currency values
:return: Returns a window with time, and currency pairs with associated currency values
"""
window.wm_title("Currency Table")
date_time = datetime.datetime.now().strftime("%A %d %B %Y %H:%M:%S:%f")
str_date_time = "On " + str(date_time)
l1 = Label(window, text=str_date_time)
l1.grid(row=0, column=0)
l2 = Label(window, text=symbol_pairs[0])
l2.grid(row=1, column=0)
l3 = Label(window, text=symbol_pairs[1])
l3.grid(row=2, column=0)
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
# currency window info positioned on the lower right side of the screen
# and with a given screen width and height
xpos = screen_width - 250
ypos = screen_height - 150
window.geometry("250x75+" + str(xpos) + "+" + str(ypos))
return window
def main():
while True:
window = Tk()
symbol_pairs = get_currency_values()
window = setup_gui(window, symbol_pairs)
window.update()
# let the window be always on top of other windows
window.lift()
window.attributes('-topmost', True)
# we get the next currency pair values every 60 seconds
time.sleep(60)
window.destroy()
if __name__ == '__main__':
main()
4. Setting Up Automatic Script Execution in a Windows 10 Environment
The final step is to rename the file to "forex.pyw" (or any name you want, really; just make sure to end the name of the file with the ".pyw" extension, because it is a GUI application):
- pythonw.exe forex.pyw
This is the final resulting window that appears on top of other windows and changes the currency values every 60 seconds:
If you are running this script on Windows, you can enable the automatic execution of the script when logging in to your user account, by following these steps:
- Press the Windows Button + R
- Open the Startup Window: "shell:startup"
Create a Windows link in "C:\Users\YourUserName\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup with the following properties:
- Target: C:\Anaconda35\pythonw.exe forex.pyw (this is my Anaconda Python installation and the Python script which is found in the "Start in" directory).
- Start in: C:\Users\YourUserName\PycharmProjects\forex (is the directory where my script is).
Given that I am no Linux expert I am not sure if you can run an equivalent "cron job."
For those that require continuous information about real-time currency exchange values, this Python script will be really helpful.
Opinions expressed by DZone contributors are their own.
Comments