Python Websocket Client - Real Time Forex

03/09/2021 at 02:02PM

This tutorial guides you to write a program to obtain real-time market data using TraderMade’s Forex API Market Data Service. TraderMade is the most reliable real-time and historical data provider for Forex, CFDs, and Metals.

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

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

Step 1. Installing Python

I recommend Python 3.9.1 wherever possible, as this is the latest and most stable version. 

                
For Windows:
You can download the windows installer from python.org or
alternatively use the python app from the windows app store.

For Linux:
It's best to update apt-get before the install so run
$sudo apt-get update
$sudo apt-get install python3.9



Step 2. Installing Pip

                
For Windows:
pip is installed by defualt

For Linux:
$sudo apt-get install python3-pip



Step 3. Project Set-up

To begin with, you need to create a directory to store your program. Here, I’ve created a dir named /WebSocketTestClient.

Now, we need to install the required library. We need an external library, WebSocket Client, for this example. 

                
For Windows and Linux
pip install websocket_client

Now, write some code, shall we?

Generate a new file, testClient.py, within your directory. To do that, you can use your editor or Notepad/VI if you are a beginner. 

The program we write should continue running when we establish a live connection. We should use the thread class and the WebSocket run_forever() option.

Importing the libraries

                
import websocket
import time
try:
     import thread
except ImportError:
    import _thread as thread

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


Creating the required functions

It is essential to create functions to handle the callbacks from the WebSocket-Client class. Notably, these are standard handlers and would be identical for any WebSocket. Please sign up for a free WebSocket Trial at https://tradermade.com/signup. You can submit your login details to get TraderMade WebSocket on_open. 

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

                I


At this stage, we have the logger and the handler. We need to create the WebSocket through the primary function of the program.

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



Run the program now

                   
For Windows:
$python testClient.py

For Linux:
$sudo python3 testClient.py




Voila! Now, you can obtain Live Forex Rates 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 am giving the complete set of codes below. Similarly, you can download the code pre-populated with your user key from this link:

https://marketdata.tradermade.com/streaming-data-documentation#wsPython

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  +  "
" )
    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, ())

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