Python WebSocket Client: Real-Time Forex
Tags: python, realtimedata, forexdata, websocket
Published: 2023-03-20 07:02:09

This tutorial explains how to create a program to retrieve real-time market data from TraderMade's Forex API Market Data Service. TraderMade is the most dependable real-time and historical data vendor for Forex, CFDs, and Metals.

To begin, you must sign up for a [TraderMade WebSocket Trial Account](https://tradermade.com/signup). Please request a WebSocket key. Use our Java API for WebSocket for free for the first two weeks. Our subscription plans begin at a modest £100 
PCM.

### You can watch a video tutorial to get real-time Forex and CFD rates via Python WebSocket on our YouTube channel:
[Real-Time Forex & CFD Rates with Python WebSocket](https://www.youtube.com/watch?v=sUPJ4TVTQlM)

### So, let's get started!
Before we begin coding, we must first set up the coding environment. Let's achieve this in three simple steps:

### Arrangement
Python Installation 
Pip Set-up
Project Configuration

### Step 1: Set up Python
I recommend Python 3.9.1 whenever possible because it is the most recent and reliable version.

For Windows, you can use the python app from the Windows app store or download the Windows installer from python.org.

On Linux, execute 
$sudo apt-get update 
$sudo apt-get install python3.9 to update apt-get before installing Python.

### Step 2: Pip Installation
Pip is installed by default on Windows.

In the case of Linux:
apt-get install python3-pip $sudo

### Step 3: Project Configuration
To begin, you must construct a directory to save your software. I've called this directory /WebSocketTestClient.

We must now install the necessary library. For this example, we'll require an extra library called WebSocket Client.

Pip install websocket client for Windows and Linux.

### Let's write some code now.
Create a new file in your directory called testClient.py. Novice developers can use an editor or Notepad/VI to accomplish this.

When we establish a live connection, the software we wrote should continue to execute. The thread class and the WebSocket run forever() option should be used.

```
Importing the libraries
               
import websocket
import time
try:
     import thread
except ImportError:
    import _thread as thread

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

Developing the necessary functions
It is critical to write functions to handle the WebSocket-Client class's callbacks. Please note that these are standard handlers that would apply to any WebSocket. 

Please visit [http://tradermade.com/signup](http://tradermade.com/signup) to sign up for a free WebSocket Trial. You can receive TraderMade WebSocket on open by submitting your login information.

```
def on_message(ws, message):
    print(message)
    f.write("Live fx rates" + message  +  "
" )
    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":"USER_KEY", "symbol":"GBPUSD"}")
    thread.start_new_thread(run, ())
```
We have the logger and the handler at this point. The WebSocket must be created using the program's primary function.        

```
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()
```

Launch the program now.

$python testClient.py for Windows

$sudo python3 testClient.py on Linux

Problem solved! Real-Time Currency Rates are now available in the log and the console.

```
Connected
Live fx rates GBPUSD 1.36897 1.36897 1.368970 20210208-10:31:32.156
Live fx rates GBPUSD 1.36897 1.36898 1.368975 20210208-10:31:32.502
Live fx rates GBPUSD 1.36897 1.36897 1.368970 20210208-10:31:32.757
Live fx rates GBPUSD 1.36904 1.36904 1.369040 20210208-10:31:33.057
Live fx rates GBPUSD 1.36904 1.36905 1.369045 20210208-10:31:33.948
Live fx rates GBPUSD 1.36904 1.36904 1.369040 20210208-10:31:34.860
Live fx rates GBPUSD 1.36904 1.36905 1.369045 20210208-10:31:35.156
```
I've included the entire set of codes below. Similarly, you can get the code pre-populated with your user key by following this link:

[https://marketdata.tradermade.com/streaming-data-documentation#wsPython](https://marketdata.tradermade.com/streaming-data-documentation#wsPython)

TraderMade provides reliable and accurate Forex data via its [Forex API](https://tradermade.com/forex). You can sign up for a free API key and start exploring real-time and historical data at your fingertips.


> Also, take a look at the originally published tutorial on our website:
> [Python WebSocket Client - Real Time Forex](https://tradermade.com/tutorials/python-websocket-client)

> Curious about real-time data retrieval using other programming languages? Here are some technical tutorials to help you with that:

> 1. [C++ WebSocket Client](https://tradermade.com/tutorials/how-to-build-your-first-cpp-websocket-client)

> 2. [PHP WebSocket Client](https://tradermade.com/tutorials/your-first-php-websocket)

> 3. [WebSocket with C#](https://tradermade.com/tutorials/forex-websocket-with-c)

> 4. [Real-Time Forex and CFD Data With NodeJS WebSocket](https://tradermade.com/tutorials/real-time-forex-and-cfd-data-with-nodejs-websocket)