Python Websocket Client - Real Time Forex

03/09/2021 at 02:02PM

In this tutorial, I will show you how to write a program to retrieve real-time market data from TraderMades’s Forex API Market Data service. TraderMade offers real-time and historical Market Data for a large range of Forex, Metals and CFD’s.


Let’s get started

Before we start we need to set our coding environment, we will do this in 3 simple steps.

Setup

1) Setup Python

2) Install Pip

3) Setup Project


Step 1. Install Python

Python 3.9.1 is the latest stable release and we recommend you use this where possible.

                
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. Install pip

                
For Windows:
pip is installed by defualt

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



Step 3. Setup Project

Create a new dir that you wish to store your program in, I have created one called /webSocketTestClient.

Now we can install the libs we require, for this example, we only need to install one external lib and that is the WebSocket Client.

                
For Windows and Linux
pip install websocket_client

Let's write some code

Inside your directory create a new file testClient.py you can do this in your favourite editor or Notepad/VI if you are just getting started.

As this is a live WebSocket we want the program to continue to run whilst we have a live connection. For this, we use the thread class and the WebSocket run_forever() option.

Import the libs

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

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


Create Functions

We also need to create the functions that will handle the callbacks from the WebSocket-Client class. These are standard handlers and will be the same for any WebSocket. For the TraderMade WebSocket on_open, we need to send back our login details these can be obtained by signing up for a free trial at marketdata.tradermade.com/signup

                
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


Now we have the logger and the handler we need to create the WebSocket, we will do this in the main function of the program.

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



Running the program

                   
For Windows:
$python testClient.py

For Linux:
$sudo python3 testClient.py




And that is it! You will now get Live fx rates in the log and also in your 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


Below is the full code but you can also download the code pre-populated with your user key from 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/feed",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()