Python WebSocket Client - Real-Time Order Flow (Trade Tape)
Tags: python, websocket, forex, orderflowdata
Published: 2023-02-28 14:47:20

In this tutorial, I will demonstrate how to develop a Python application that retrieves real-time Order Flow (Trade Tape) data from TraderMades' Forex API Order Flow (Trade Tape) Service. TraderMade provides real-time Order Flow (Trade Tape) data for a wide variety of Forex, Metals, and CFD products. Further information is available on our order flow webpage.

### Let's begin!
Before we proceed, we must first configure our coding environment, which will be accomplished in three simple stages.
Setup
1) Install Python 
2) Install Pip 
3) Setup Project 

### Step 1. Install Python 

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: Set up pip
Pip is installed by default on Windows.

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

### Step 3. Setup the Project
Make a new directory in which to keep your software; I named mine /webSocketOrderFlowClient.
Now we may install the libraries we need; in this case, we just need to install one external library, the WebSocket Client.

Pip install WebSocket client for Windows and Linux.

It is time to write some code.

Create a new file arrangement within your directory.
FlowTestClient.py If you're just getting started, you can accomplish this in your favourite editor or Notepad/VI.

Because this is a live WebSocket, we want the program to keep running as long as we have a live connection. We use the thread class and the WebSocket run forever() option to accomplish this.

Import the libraries.

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

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

### Make Functions
We must additionally write the routines that will handle the WebSocket-OrderFlowClient class's callbacks. These are standard handlers that will apply to any WebSocket. We need to give back our login details to the TraderMade WebSocket on open, which we can get by joining up for a free order flow trial.

```
def on_message(ws, message):
    print(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")
    thread.start_new_thread(run, ())
```
Now that we have the logger and the handler, we can construct the WebSocket, which we will accomplish in the program's main method. When you sign up for a trial of the Order Flow (Trade Tape) feed, you will be given a connection URL that must be entered into the code block below.

```
if __name__ == "__main__":
    ws = websocket.WebSocketApp("ORDER_FEED_ADDRESS",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()
```
Starting the program
For Microsoft Windows:
orderFlowTestClient.py $python

In the case of Linux:
orderFlowTestClient.py $sudo python3

That's all there is to it! You will now see Live Order Flow (Trade Tape) rates in both the log and the console.

```
Connected
{'id':4208407324,'acc':'0159809','s':'AUDJPY','amt':-10000.0,'ts':'20210819-08:06:38.039000','price':78.596,'time':1629360398}
{'id':4208407344,'acc':'0319192','s':'AUDJPY','amt':-11000.0,'ts':'20210819-08:06:38.509000','price':78.599,'time':1629360398}
{'id':4208407354,'acc':'0901885','s':'EURCHF','amt':-2000.0,'ts':'20210819-08:06:38.524000','price':1.07085,'time':1629360398}
{'id':4208407374,'acc':'0159809','s':'AUDJPY','amt':-50000.0,'ts':'20210819-08:06:39.679000','price':78.602,'time':1629360399}
{'id':4208407384,'acc':'0159809','s':'AUDJPY','amt':-500000.0,'ts':'20210819-08:06:39.679000'price':78.602,'time':1629360399}
{'id':4208407394,'acc':'0159809','s':'AUDJPY','amt':-45000.0,'ts':'20210819-08:06:39.679000','price':78.602,'time':1629360399}
{'id':4208407404,'acc':'0175519','s':'GBPJPY','amt':15000.0,'ts':'20210819-08:06:40.382000','price':150.21,'time':1629360400}
{'id':4208407414,'acc':'0319192','s':'AUDJPY','amt':-10000.0,'ts':'20210819-08:06:40.970000','price':78.599,'time':1629360400}
```
The complete code is as below:

```
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")
    thread.start_new_thread(run, ())

if __name__ == "__main__":
    ws = websocket.WebSocketApp("ORDER_FEED_ADDRESS",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()
```
TraderMade provides reliable and accurate Forex data via [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, visit the tutorial published on our website:
> [Forex Order Flow Using Python WebSocket](https://tradermade.com/tutorials/python-websocket-client-real-time-order-flow)

> Visit the other tutorials:
> 1. [Data Visualization Python](https://dev.to/shridhargv/data-visualization-python-2ief)
> 2. [Python Development Kit for Forex and CFDs](https://dev.to/shridhargv/python-development-kit-for-forex-and-cfds-n76)

> Here are some technical tutorials for real-time forex data retrieval using other programming languages:
> 1. [PHP WebSocket Client](https://tradermade.com/tutorials/your-first-php-websocket)
> 2. [WebSocket with Java Tutorial](https://tradermade.com/tutorials/real-time-forex-cfd-and-crypto-websocket-with-java)
> 3. [WebSocket with C# Tutorial](https://tradermade.com/tutorials/forex-websocket-with-c)