DEV Community

Cover image for Python WebSocket Client: Real-Time Forex
Shridhar G Vatharkar
Shridhar G Vatharkar

Posted on • Edited on

Python WebSocket Client: Real-Time Forex

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

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")
Enter fullscreen mode Exit fullscreen mode

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 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, ())
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

TraderMade provides reliable and accurate Forex data via its Forex API. 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

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

  1. C++ WebSocket Client

  2. PHP WebSocket Client

  3. WebSocket with C#

  4. Real-Time Forex and CFD Data With NodeJS WebSocket

Top comments (1)

Collapse
 
anahale23 profile image
anahale23

The forex trading community benefits from a variety of educational resources, including books, online courses, webinars, seminars, forums, demo accounts, mentorship programs, and educational platforms like fbs, Babypips, Investopedia, and TradingView. Risk management is a cornerstone of successful trading. Traders implement various risk management techniques, such as setting stop-loss and take-profit levels, diversifying portfolios, using leverage judiciously, avoiding overtrading, maintaining a consistent risk-reward ratio, and employing risk management tools and calculators. Trading psychology is a crucial aspect of trading success. Traders focus on maintaining emotional discipline, avoiding emotional decision-making, adhering to trading plans, managing expectations, accepting losses, practicing patience, developing resilience, and cultivating a growth mindset to navigate the psychological challenges of trading.