DEV Community

Cover image for A Beginner's Guide to Python Programming for Forex via REST API
Shridhar G Vatharkar
Shridhar G Vatharkar

Posted on

A Beginner's Guide to Python Programming for Forex via REST API

Forex, or FX, is a marketplace worldwide where the exchange of currencies happens. The Forex market is decentralized or over-the-counter (OTC). Developers need accurate and real-time Forex data to integrate into their digital solutions.

TraderMade provides data that can be integrated to prepare apps and charts. They deliver Forex data via the Restful API, WebSockets, FIX, and MS Excel for broader use.

In this tutorial, we can understand how to retrieve Forex data with the Python programming language using TraderMade's REST API.

Let us get Started

To begin, we need to create an account with TraderMade and acquire our unique API key. We will be able to get real-time Forex data thanks to the key.

We can now go through a hands-on demonstration to better grasp the procedure. We can divide the procedure into various stages, such as

  • Establishing the coding environment
  • Incorporating essential libraries.
  • Writing the code.
  • Debugging the code and getting results.

Establishing the coding environment.

Let us initially set up the environment before entering the coding part. We can download and install Visual Studio at https://code.visualstudio.com/download (if unavailable). We can download and install the Python Development workload and interpreter from the Extensions window if needed.

Incorporating essential libraries.

By opening the command prompt, we can type in the following command to install the request package.

pip install requests
Enter fullscreen mode Exit fullscreen mode

Please note that we need to use 'pip3' if we have Python version 3 installed.

pip3 install requests
Enter fullscreen mode Exit fullscreen mode

Writing the code.

The code helps to import the 'requests' library, a popular Python library, to make HTTP requests.

import requests
Enter fullscreen mode Exit fullscreen mode

Let us describe the "write_callback" function, which takes three parameters:

'response': Represents the response from the HTTP request in the form of bytes.
'chunk_size': Denotes the current size of the data chunk being processed.
'user_data': A list stores the response data after it's decoded from bytes to a UTF-8 encoded string.

# Callback function to write data into a string
def write_callback(response, chunk_size, user_data):
    user_data.append(response.decode('utf-8'))
Enter fullscreen mode Exit fullscreen mode

In the 'main()' function:
'api_url' is used to specify the API endpoint for requesting data. Then, the code creates an empty list called 'response_data' to collect the responses we receive. Please replace your API_KEY here.

def main():
    api_url = " https://marketdata.tradermade.com/api/v1/live?api_key=API_KEY&currency=USDAUD,BUSDJPY"
    response_data = []
Enter fullscreen mode Exit fullscreen mode

HTTP requests are made inside 'api_url' using 'requests.get()' inside the 'try' block. The 'stream=True' parameter helps to set the response stream in chunks.

try:
        response = requests.get(api_url, stream=True)

Enter fullscreen mode Exit fullscreen mode

The condition here checks if the HTTP response status code is 200, which means a successful request.

 if response.status_code == 200:
Enter fullscreen mode Exit fullscreen mode

The code enters the loop that iterates over the response content only if the response status code is 200. For each chunk, it calls the 'write_callback' function to decode and append the piece to the 'response_data' list.

for chunk in response.iter_content(chunk_size=1024):
                write_callback(chunk, len(chunk), response_data)
Enter fullscreen mode Exit fullscreen mode

The code helps to join the 'response_data' list to create a complete response text.

response_text = "".join(response_data)

Enter fullscreen mode Exit fullscreen mode

The received response finally gets printed.

print("Received response:", response_text)
Enter fullscreen mode Exit fullscreen mode

An error message gets printed if the request is unsuccessful ( HTTP code is not 200).

else:
            print(f"Request failed with status code {response.status_code}")
Enter fullscreen mode Exit fullscreen mode

The below code block catches exceptions arising during the execution, if any, and prints an error message.

except Exception as e:
        print("An error occurred:", str(e))
Enter fullscreen mode Exit fullscreen mode

The if name == "main": block ensures that the main() function is executed only if this script is run as the main program (not imported as a module in another script).

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

Debugging the code and obtaining results

Before jumping to execution, we need to save the program. I have saved it as forex.py - you can give your desired name. However, the '.ny' extension is essential as it helps the computer understand that it is a Python program.

Now, let us open a terminal or command prompt. The code helps to execute the program and gives us the output.

python forex.py
Enter fullscreen mode Exit fullscreen mode

Viola! We have our output.

Received response: {
  "endpoint": "live",
  "quotes": [
    {
      "ask": 1.560866,
      "base_currency": "USD",
      "bid": 1.5607929,
      "mid": 1.5608416,
      "quote_currency": "AUD"
    },
    {
      "ask": 149.1707186,
      "base_currency": "BUSD",
      "bid": 149.1558035,
      "mid": 149.163261,
      "quote_currency": "JPY"
    }
  ],
  "requested_time": "Thu, 12 Oct 2023 11:58:02 GMT",
  "timestamp": 1697111882
}
Enter fullscreen mode Exit fullscreen mode

In summary, this code sends an HTTP GET request to a specified API, processes the response data in chunks, and prints the entire response or an error message depending on the HTTP status code. The response data is collected in pieces to efficiently handle significant responses without loading the whole content into memory at once. If you need more assistance, please don't hesitate to contact us via live chat or email support@tradermade.com.

We have given the complete code here:

import requests

# Callback function to write data into a string
def write_callback(response, chunk_size, user_data):
    user_data.append(response.decode('utf-8'))

def main():
    api_url = " https://marketdata.tradermade.com/api/v1/live?api_key=API_KEY&currency=USDAUD,BUSDJPY"

    response_data = []

    try:
        response = requests.get(api_url, stream=True)

        if response.status_code == 200:
            for chunk in response.iter_content(chunk_size=1024):
                write_callback(chunk, len(chunk), response_data)

            response_text = "".join(response_data)
            print("Received response:", response_text)
        else:
            print(f"Request failed with status code {response.status_code}")

    except Exception as e:
        print("An error occurred:", str(e))

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)