Backpython sdk

Python WebSocket Client - Real-Time Forex

09 March 2021


Websockets are a strong communication protocol that allows for real-time duplex communication between clients and servers over one long-lasting connection. This is unlike traditional HTTP, where the server responds to the client's request. 

WebSockets allow both ends to initiate communication; hence, they are ideal for applications with low latency needs that require frequent updates, such as chat apps, multiplayer games, financial tickers or live data streaming services. 

Learn how to use a Python WebSocket client with real-time forex data. In Python, you can use websockets by using libraries like websockets; it provides an easy-to-use API that makes building websocket servers and clients simple yet powerful.

This tutorial will help improve your understanding of live streaming forex data and WebSockets. The WebSocket Python guide would help you retrieve real-time rates.

So, let’s begin!

It is essential to set up the coding environment before we start coding. Let’s do this in 3 easy steps as follows: 

Arrangement

1) Setting up Python

2) Installing Pip

3) Project Set-up

Setting Up Python

I recommend Python 3.9.1 wherever possible, as this is the latest and most stable version. You can download and install Python from the official site.

Installing Pip

For Windows: pip is installed by defualt

For Linux:

$sudo apt-get install python3-pip

Getting the Key

Initially, you need to register for a WebSocket Trial Account with TraderMade. Please sign up for a WebSocket key. For the first two weeks, you can try our WebSocket API  for free. Our subscription plans start at a reasonable cost of £100 PCM.

 Please note that during this trial period, you can access live Forex data; however, CFD data will not be accessible unless you upgrade your subscription. Importantly, the code explained in this tutorial connects with the client side and retrieves the data for you. Our coroutine-based API helps simplify the code.

Note: Please visit our documentation for further information.

Project Set-up

To begin with, you need to create a directory to store your program. Here, I’ve created a directory named /WebSocketTestClient. Now, we need to install the required library. For this example, we need an external library, WebSocket Client.         

                
pip install websocket_client

Now Let Us Code

Create a new file, testClient.py, within your directory. You can use a notepad to save the code using the .py extension. 

Step 1: Importing Required Libraries: 

This code helps import the WebSocket library along with the time and thread.  The WebSocket library is a library for building websocket servers and clients in python.    

1) websocket: It offers WebSocket communication capabilities.

2) Time: It is used for time-related operations.

3) Thread: This helps implement multi-threading in Python.

                
import websocket
import time

try:
    import thread
except ImportError:
    Import _thread as thread

Step 2: Opening a Log File:

Next, we open a log file where we will store received messages:

We are opening the "webSocketTester.log" file in append mode ("a") so that new messages can be added without erasing existing content. This code helps you connect to the server side and retrieve data. 

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

Step 3: Defining Callback Functions:

We define several callback functions to handle different WebSocket events:

1) on_message: This function receives the incoming messages, prints them on the console, and writes them into a log file.

2) on_error: This function prints WebSocket errors on the console.

3) on_close: This function triggers a closure event by printing out a closure message.

4) on_open: This function initiates WebSocket opening by defining a function to be run upon connection.

Step 4: Implementing Callback Functions:

Each of the callback functions is implemented according to its purpose. In the on_message function, apart from printing a received message on the console and writing it into a log file, the buffer is flushed for immediate write operation.

                
def on_message(ws, message):
    print(message)
    f.write(message + "\n")
    f.flush()


Step 5: Sending Data on WebSocket Open:

. In the on_open function, we define a run function which sends a message when WebSocket connects: A JSON-formatted message containing user authentication information and the desired symbol is sent to the WebSocket server.

Note: API Key cannot be used for multiple WebSocket connections.       

                
def on_open(ws):
    def run(*args):
        ws.send('{"userKey":"API_KEY", "symbol":"GBPUSD"}')
    thread.start_new_thread(run, ())

Step 6: Setting Up WebSocket Connection:

At last, we connect using WebSocket and have callback functions. We make a WebSocketApp instance with the server URL and set callbacks for events. After that, we begin the WebSocket link and let it run endlessly to get and handle incoming data.

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

Executing the program now

The below code is used to execute the data. 

python testClient.py

Voila! Now, you have the Live Forex Rates in the log and the console. 

                   
Connected
{"symbol":"GBPUSD","ts":"1714657148317","bid":1.24975,"ask":1.2498,"mid":1.2497749}
{"symbol":"GBPUSD","ts":"1714657148420","bid":1.24975,"ask":1.24979,"mid":1.2497699}
{"symbol":"GBPUSD","ts":"1714657149198","bid":1.24968,"ask":1.24971,"mid":1.2496951}
{"symbol":"GBPUSD","ts":"1714657149231","bid":1.24967,"ask":1.24969,"mid":1.24968}
{"symbol":"GBPUSD","ts":"1714657150276","bid":1.24965,"ask":1.2497,"mid":1.249675}
{"symbol":"GBPUSD","ts":"1714657150283","bid":1.24966,"ask":1.2497,"mid":1.24968}
{"symbol":"GBPUSD","ts":"1714657150328","bid":1.24966,"ask":1.24969,"mid":1.249675}
{"symbol":"GBPUSD","ts":"1714657151315","bid":1.24969,"ask":1.2497,"mid":1.2496951}
{"symbol":"GBPUSD","ts":"1714657151322","bid":1.24969,"ask":1.24971,"mid":1.2497001}
{"symbol":"GBPUSD","ts":"1714657151332","bid":1.24969,"ask":1.24972,"mid":1.2497051}
{"symbol":"GBPUSD","ts":"1714657151360","bid":1.24971,"ask":1.24972,"mid":1.249715}
{"symbol":"GBPUSD","ts":"1714657151397","bid":1.24972,"ask":1.24972,"mid":1.24972}
{"symbol":"GBPUSD","ts":"1714657152301","bid":1.24976,"ask":1.24979,"mid":1.2497749}
{"symbol":"GBPUSD","ts":"1714657152637","bid":1.24976,"ask":1.2498,"mid":1.2497799}
{"symbol":"GBPUSD","ts":"1714657152658","bid":1.24976,"ask":1.24979,"mid":1.2497749}

Conclusion

It is important to note that our WebSocket server is a simple echo server. Websocket protocol creates full duplex connections between WebSocket servers and clients effectively. After a connection is established, you can see streaming data output in your terminal for your desired currency pair in real time. 

Similar tutorials are available in various other programming languages, such as C++, Java, PHP, C#, R, Go, and NodeJS.

You can also watch our video on the same topic.


I am giving the complete set of codes below. Also, you can download the code pre-populated with your user key from this link:

https://tradermade.com/docs/streaming-data-api#examples

import websocket
import time

try:
    import thread
except ImportError:
    import _thread as thread

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

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":"API_key", "symbol":"GBPUSD"}')
    thread.start_new_thread(run, ())

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