DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Join us today at 1 PM EST: "3-Step Approach to Comprehensive Runtime Application Security"
Save your seat
  1. DZone
  2. Data Engineering
  3. Data
  4. How to Use Python With Real-Time Data and REST APIs

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.

Carlos F. Enguix user avatar by
Carlos F. Enguix
·
Mar. 18, 19 · Tutorial
Like (5)
Save
Tweet
Share
37.62K Views

Join the DZone community and get the full member experience.

Join For Free

Python Tutorial

1. 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.

REST Web Protocols Python (language) Data (computing)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Iptables Basic Commands for Novice
  • Java Development Trends 2023
  • Real-Time Stream Processing With Hazelcast and StreamNative
  • Fraud Detection With Apache Kafka, KSQL, and Apache Flink

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: