DEV Community

Cover image for Streaming Forex with Python SocketIO
Shridhar G Vatharkar
Shridhar G Vatharkar

Posted on • Edited on

Streaming Forex with Python SocketIO

This tutorial takes you through a Python SocketIO implementation. Understanding the difference between SocketIO and WebSocket is essential. However, that is not the scope of this article. Please go through this tutorial to explore more about it. To realise the reason behind the increasing popularity of SocketIO, I would like to request you work along with this tutorial.

We will use the client code and SocketIO server responding with TraderMade’s forex data. I am clarifying these aspects in the beginning as it is easy to work on one side of the example before diving deeper into the topic. At the same time, you will experience a practically used, real-life example.

On this note, let’s start.

Acquire Your SocketIO Key

It is essential to obtain your API key to retrieve live forex data from the SocketIO server. Please sign up for free by visiting https://tradermade.com/signup. Then, select SocketIO trial. You will get an API key. It is advisable to note this key securely for future reference.

Code Setup
We will begin the process by installing the required libraries. It is important to note that TraderMade’s SocketIO is compatible with Version 2X only.

python-engineio==3.14.2
python-socketio==4.3.1

Enter fullscreen mode Exit fullscreen mode

We may need other dependencies, yet these two should be exactly the same to work with this example.

A brief on the method to retrieve live forex data

Let’s understand how real-time forex data is obtained through SocketIO using Python:
The data transfer between client and server occurs as events in SocketIO.
The events establish communication between the client and server.
Read this tutorial further to know more about how events help execute communication between client and server.

Client-side Code

We will go step by step. To start with, we will import SocketIO. Then create an object - “Sio,” to create a client. We will use this to connect to the URL.

import socketio

# standard Python
sio = socketio.Client()

Enter fullscreen mode Exit fullscreen mode

Firstly, we will obtain an object and then set up an event to initiate a connection with TraderMade’s SocketIO server. We will place an event with def connect (). When we connect with the server, this function will be called on.

@sio.event
def connect():
    print("I'm connected!")
    sio.emit('login', {'userKey': 'Your Streaming API Key'})

Enter fullscreen mode Exit fullscreen mode

After getting connected, we will release an event to the server - “login.” After signing up initially, we received an API key. We will send that API key in JSON format to the server to set our identity. You might have realised that some events listen to specific information. We will keep perceiving the next steps.

@sio.even
def connect_error():
    print("The connection failed!")

@sio.on('handshake')
def on_message(data):
    print('HandShake', data)
    sio.emit('symbolSub', {'symbol': 'EURUSD'})

Enter fullscreen mode Exit fullscreen mode

We can easily make out what ‘Connect-error’ is. TraderMade’s server sends or emits an event - handshake. We need this event on the SocketIO client-side code. It is essential to maintain the communication chain and obtain data.

Thus, you can realise that some events send data. After receiving the ‘handshake’ event, we will print the data transmitted.

Received from Server

Welcome to the TMS Data Feed
Enter fullscreen mode Exit fullscreen mode

It is possible to obtain forex data. However, the server should know that we need that. At this stage, we need to subscribe to a Symbol by discharging an event - “SymbolSub.” Along with that, we will send {‘symbol’: ‘EURUSD’} as the data from the client side.

@sio.on('price')
def on_message(data):
    print('Price Data ', data)

sio.connect('https://marketdata.tradermade.com')

Enter fullscreen mode Exit fullscreen mode

We can see how the above event pushes data. We require the URL at the end to set up the connection once we know the code. There it is! We can now obtain forex rates for EURUSD also with a timestamp.

Received from Server

Price Data EURUSD 1.20543 1.20543 1.20543 20210303–14:27:59.496
Enter fullscreen mode Exit fullscreen mode

Please have a glance at the complete set of codes here:

import socketio

# standard Python
sio = socketio.Client()

@sio.event
def connect():
    print("I'm connected!")
    sio.emit('login', {'userKey': 'streaming_api_key'})

@sio.event
def connect_error():
    print("The connection failed!")

@sio.event
def message(data):
    print('I received a message!')

@sio.on('handshake')
def on_message(data):
    print('HandShake', data)
    sio.emit('symbolSub', {'symbol': 'USDJPY'})
    sio.emit('symbolSub', {'symbol': 'GBPUSD'})
    sio.emit('symbolSub', {'symbol': 'EURUSD'})

@sio.on('price')
def on_message(data):
    print('Price Data ', data)


sio.connect('https://marketdata.tradermade.com')

Enter fullscreen mode Exit fullscreen mode

I anticipate that the tutorial will help you. We will come back with more such tutorials.

Also, refer to our other tutorials:

  1. Data Visualization Python

  2. Python Development Kit for Forex and CFDs

  3. Streaming Forex with Python SocketIO

Please go through the following tutorial to understand the data delivery methods:
SocketIO vs WebSocket

Top comments (1)

Collapse
 
anahale23 profile image
anahale23

A well-defined fbs trading plan serves as your roadmap. Clearly outline your trading goals, risk tolerance, entry and exit strategies, and position sizing rules. Regularly review and adjust your plan to adapt to changing market conditions and personal growth. Protecting your capital should be your top priority. Implement stop-loss orders, set realistic risk-reward ratios, diversify your portfolio, and avoid emotional decision-making. Consistent risk management can help you weather downturns and preserve your trading capital.