Backdevelopers manual

A Python Developers Manual for Unleashing the Potential of Our Forex API

09 January 2024


The developer community looks for practical methodologies to enhance the performance of their applications. Ensuring access to uninterrupted currency exchange data is paramount for apps and websites enabling Forex analysis, conversions, and trading.

You are in the right place if you are a developer seeking in-detail information on setting up your developer account, making API calls, and maximizing your API usage. 

This Developer's Manual covers it, API endpoints, troubleshooting best practices, and an effective caching strategy. Stay tuned to explore various features of our Forex API and how you can make the most of it.

Comprehending the Forex API Environment

Developers need a reliable source of low-latency, accurate forex data to add data retrieval features to their websites, e-commerce portals, currency conversion tools, analytics and charting tools, and more. 

Our forex API is an effective tool, as it helps developers tap an unbiased source of forex data into their digital solutions. 

What is the Forex API?

The Forex API is an interface that allows you to communicate with our server and get real-time and historical data. It facilitates a seamless integration into applications so your users get the latest exchange rate updates at their fingertips.

The versatility of our API in the Financial Markets Landscape

As the financial markets change rapidly, users opt for up-to-second market data to make data-driven decisions. Our Forex API provides access to a curated data feed, enabling you to empower your applications with accurate data retrieval features. Thus, users can stay updated with market movements and make informed decisions.

Set up Your Developer Account

Getting started with our Forex API is simple. You need to sign up for free to get your unique API key, and you can start obtaining lightning-fast Forex data.

Also Read: How to Sign up for a REST plan and get your API key for free.

You will be taken to the Dashboard page as you sign up and log in. Your unique API key is on this page (marked in red). 

Dashboard


We provide 1000 free monthly API requests. Similarly, we offer well-thought-out data subscription plans to choose from according to your data needs.

Data_Plans

Verifying to Retrieve Forex Data Smoothly

We offer access to pristine forex and CFD data through user-friendly delivery channels. Our data is transmitted securely via HTTPS and RESTful protocols, simplifying the process of data retrieval. 

Authentication is performed through a secure HTTPS connection, and the data is delivered in JSON format for easy integration. Include your unique API Key to get data. 

API Endpoints

Another beauty of our Forex API is the API endpoints we provide to help you get the currency exchange information you require for analysis or development purposes. Here are some significant, easy-to-use API endpoints:

Live Rates

You can get live sub-second rates for over 4200 currency pairs and 20+ CFDs using our Live Rates Endpoint. We allow Node Providers, Blockchain, and Smart Contract companies to request live rates for only one currency pair or CFD. 

Historical Rates

Use our Historical Rates Endpoint to get daily exchange rates for various currency pairs. You can query any trading day over the past 20+ years except for a few exotic pairs. 

Tick Historical Rates

Get tick forex rate data for over 50 currency pairs using our Tick Historical Rates API endpoint. The Historical Tick feature, accessible through the Advanced plan, offers a month's worth of data in segments of up to 60 minutes. It uses 5 API requests per use and permits data retrieval for only one currency pair per request.

Time-Series

The Time Series API furnishes historical currency rates (OHLC) across daily, hourly, and more specific endpoints. Daily data spans up to 15 years, although specific exotic currency pairs might have a shorter history available. Each request allows a maximum of one year of data.

Pandas DF

The PandasDF API endpoint furnishes daily OHLC data for the requested currency, presenting it in a Pandas Dataframe for convenient utilization by Python developers seeking historical currency data. When the field parameter is set to "OHLC," you can request data for a single currency, while setting it to "close" enables data retrieval for multiple currencies.

Convert

Get conversions from one currency to another in real-time by using our Covert API endpoint. 

Your First API Call

Let us log into the account after verifying the email address. Now, we need to copy the API key from the dashboard to replace it in the code. API key plays a crucial role in accessing Forex data. 

Retrieve Historical and Real-time REST Forex Rates

Run the following command in the terminal (Python 3 is needed) or Google Colab. Now, we need to install SDK, a simple step. 

pip install tradermade

We can also visit PyPl for more information. Once TraderMade is installed, we need to run the following command.

import tradermade as tm

Now, let us set our API key using the following command. The key is used to authenticate the request and is needed in every call we make.

# set API key
tm.set_rest_api_key("api_key")

We are all set to retrieve data. Let us run the code below to retrieve historical Forex rates. We can change the currency pairs and date as needed. 

#get historical data
tm.historical(currency='EURUSD,GBPUSD', date= "2011-01-20",interval= "daily," fields=["open," "high," "low," "close"]) 
# returns historical data for the currency requested interval is daily, hourly, minute - fields are optional

Hurray! Here is our output

{
  "date": "2023-11-09",
  "endpoint": "historical",
  "quotes": [
    {
      "base_currency": "EUR",
      "close": 1.06678,
      "high": 1.07258,
      "low": 1.06602,
      "open": 1.07052,
      "quote_currency": "USD"
    }
  ],
  "request_time": "Wed, 22 Nov 2023 06:37:33 GMT"
}

We need to run the code below to retrieve real-time Forex data. We can change the currency pairs as required. Forex data for multiple pairs can be obtained with a request.

#get live data
tm.live(currency='EURUSD,GBPUSD',fields=["bid", "mid", "ask"]) 
# returns live data - fields are optional

And that’s it! Here is our output.

{
  "endpoint": "live",
  "quotes": [
    {
      "ask": 1.08971,
      "base_currency": "EUR",
      "bid": 1.08969,
      "mid": 1.0897,
      "quote_currency": "USD"
    } ],
  "requested_time": "Wed, 22 Nov 2023 06:40:59 GMT",
  "timestamp": 1700635260
}


Examples in Other Programming Languages

How To Build Your First C++ REST API Client

Forex REST JSON API with C#

Forex, Crypto, and CFD REST JSON with Java

Forex REST JSON API with PHP

How To Write Your First Golang REST Client


Obtain Live-Streaming Forex Data

The Python code demonstrates how to use the 'WebSocket' library to connect to the server, subscribe to a stream, and handle various events. Let us understand multiple critical components of the code.

 We include a 'websocket' module to work with WebSocket connections and a 'time' module to understand any delays in the code.

import websocket
import time

This part of the code handles compatibility issues between Python 2 and 3. The 'thread' module in python2 is changed to '_thread' in python3.

try:
    import thread
except ImportError:
    import _thread as thread

The below code opens the "WebSocketTester.log" file in the append mode. This file logs the messages received from the WebSocket.

f = open("webSocketTester.log", "a")

The 'on_message' function is called whenever messages are received. It helps print the message to the console, writes it on the log file, and flushes it to ensure the data is immediately reported. 

The 'on_error' function is called when there is an error. This function prints out the error on the console.

The 'on_close' function is called when the WebSocket is closed. It prints out the message on the console.

'on_open' is a function called when a WebSocket connection is established. It defines another function in our function called 'run,' which sends a JSON message to the server. A new thread gets started to execute the 'run' function.

def on_message(ws, message):
    print(message)
    f.write(message + "\n")
    f.flush()
def on_error(ws, error):
    print(error)
def on_close(ws):
    print("### closed ###")
def on_open(ws):
    def run(*args):
        ws.send("{"userKey":"ws-5winASFx8f8r5DDzw", "symbol":"GBPUSD"}")
    thread.start_new_thread(run, ())


This is the main block of the code to create a 'WebSocketApp' instance by passing in the WebSocket server URL along with the event handlers.

Now, the 'on_open' attribute of the web socket instance is set to the 'on_open' function defined earlier.

Finally, with the help of 'ws.run_forever()', the WebSocket connection runs indefinitely.

To summarize, the code opens a WebSocket connection and subscribes to the stream of the GBPUSD symbol.

if __name__ == "__main__":
    ws = websocket.WebSocketApp("wss://marketdata.tradermade.com/feedadv",
                                 on_message=on_message,
                                 on_error=on_error,
                                 on_close=on_close)
    ws.on_open = on_open
    ws.run_forever()

Cheers! Our output is ready:

Connected
{"symbol":"GBPUSD","ts":"1700663735017","bid":1.24876,"ask":1.2488,"mid":1.24878}
{"symbol":"GBPUSD","ts":"1700663735989","bid":1.24876,"ask":1.2488,"mid":1.24878}
{"symbol":"GBPUSD","ts":"1700663736361","bid":1.24875,"ask":1.2488,"mid":1.248775}
{"symbol":"GBPUSD","ts":"1700663740109","bid":1.24883,"ask":1.24888,"mid":1.248855}
{"symbol":"GBPUSD","ts":"1700663740198","bid":1.24885,"ask":1.24888,"mid":1.248865}
{"symbol":"GBPUSD","ts":"1700663742081","bid":1.24885,"ask":1.2489,"mid":1.248875}
{"symbol":"GBPUSD","ts":"1700663742118","bid":1.24886,"ask":1.2489,"mid":1.24888}
{"symbol":"GBPUSD","ts":"1700663742237","bid":1.24886,"ask":1.24889,"mid":1.248875}
{"symbol":"GBPUSD","ts":"1700663744240","bid":1.24879,"ask":1.24884,"mid":1.2488151}
{"symbol":"GBPUSD","ts":"1700663746335","bid":1.24879,"ask":1.2488,"mid":1.248795}
{"symbol":"GBPUSD","ts":"1700663746396","bid":1.24878,"ask":1.2488,"mid":1.24879}
{"symbol":"GBPUSD","ts":"1700663747262","bid":1.24874,"ask":1.24877,"mid":1.248755}
{"symbol":"GBPUSD","ts":"1700663747281","bid":1.24872,"ask":1.24877,"mid":1.248745}
{"symbol":"GBPUSD","ts":"1700663747336","bid":1.24873,"ask":1.24877,"mid":1.24875}
{"symbol":"GBPUSD","ts":"1700663748316","bid":1.24874,"ask":1.24879,"mid":1.248765}
{"symbol":"GBPUSD","ts":"1700663749420","bid":1.24873,"ask":1.24877,"mid":1.24875}
{"symbol":"GBPUSD","ts":"1700663750289","bid":1.24875,"ask":1.2488,"mid":1.248775}
{"symbol":"GBPUSD","ts":"1700663750334","bid":1.24876,"ask":1.2488,"mid":1.24878}
{"symbol":"GBPUSD","ts":"1700663750631","bid":1.24874,"ask":1.24879,"mid":1.248765}
{"symbol":"GBPUSD","ts":"1700663751327","bid":1.24876,"ask":1.2488,"mid":1.24878}
{"symbol":"GBPUSD","ts":"1700663752300","bid":1.24881,"ask":1.24882,"mid":1.2488151}
{"symbol":"GBPUSD","ts":"1700663752362","bid":1.24882,"ask":1.24882,"mid":1.24882}
{"symbol":"GBPUSD","ts":"1700663752384","bid":1.24882,"ask":1.24886,"mid":1.24884}
{"symbol":"GBPUSD","ts":"1700663755498","bid":1.24884,"ask":1.24889,"mid":1.248865}
{"symbol":"GBPUSD","ts":"1700663756379","bid":1.24882,"ask":1.24887,"mid":1.248845}
{"symbol":"GBPUSD","ts":"1700663757369","bid":1.24884,"ask":1.24888,"mid":1.24886}
{"symbol":"GBPUSD","ts":"1700663758329","bid":1.24883,"ask":1.24888,"mid":1.248855}
{"symbol":"GBPUSD","ts":"1700663758550","bid":1.24883,"ask":1.24889,"mid":1.24886}
{"symbol":"GBPUSD","ts":"1700663758674","bid":1.24883,"ask":1.24888,"mid":1.248855}
{"symbol":"GBPUSD","ts":"1700663759324","bid":1.24886,"ask":1.24889,"mid":1.248875}
{"symbol":"GBPUSD","ts":"1700663759415","bid":1.24886,"ask":1.2489,"mid":1.24888}


Some Examples In Other Programming Languages

Your First PHP WebSocket Client

Real-Time Forex and CFD Data with C# and FIX

Real-Time Forex and CFD Data With NodeJS WebSocket

How To Write Your First Golang WebSocket Client


Troubleshooting and Effective Error Handling

In software development, it's universally acknowledged that errors and unexpected issues will arise. Errors are integral to the development process, whether due to unforeseen circumstances, user input, or system limitations. Hence, a comprehensive approach to troubleshooting and error handling becomes indispensable. 

Proactive Error Handling: Rather than waiting for errors to manifest, developers should proactively anticipate potential pitfalls in their code or system. This proactive approach involves implementing mechanisms that catch, log, and respond to errors gracefully, ensuring end-users receive meaningful feedback rather than encountering cryptic error messages. 

Referencing Detailed Documentation and Tutorials: Developers should leverage resources like documentation, tutorials, and blogs when confronted with unfamiliar errors or complex system issues. These resources often contain valuable insights, best practices, and step-by-step guides for diagnosing and resolving specific problems. 

For instance, if a developer encounters an error related to database connectivity, referring to the documentation can guide troubleshooting connection strings, server configurations, or query optimizations. 

Logging and Monitoring: Implementing robust logging mechanisms is crucial for tracking errors, system anomalies, and performance metrics. By logging pertinent details about errors, developers can gain insights into patterns, root causes, and potential areas of improvement. 

Here is an example of an error. The error message also includes a descriptive message within the response body. Would you like to get started? Visit our TraderMade API home page and self-start your journey.

Received response: {
  "error": 401, 
  "message": "api key is invalid"
}


The Bottom Line

This developer's manual helps you unleash the potential of our Forex API, presenting the features, describing how to make API calls, and various other technical aspects. Please refer to the documents section for more details. Choose TraderMade as your Forex data partner to enrich your apps and websites with reliable and accurate data retrieval features.