Stream Data Using Python in 8 Lines of Code
20 November 2023
With the rising popularity of WebSockets, it is reasonable to expect new developers to try to get access to one. Though it’s easy to make a server and a client and try and play around with data using WebSockets, it’s much better to have access to a WebSockets that provides real-time data.
So let's get to it
To follow this tutorial, you'll need:
1) Access to Google Colab or have Jupyter Notebook or Python installed
2) Basic knowledge of Python
We will use Google Colab which will make this tutorial very easy to follow.
!pip install tradermade==0.8.0
For Python 3.8 or higher and websockets 13.1 use Tradermade latest version - tradermade==1.0 . You would not be able to run 1.0 version on Google Colab
Once you install tradermade import stream from the library.
from tradermade import stream
Get your WebSocket API key from TraderMade by setting up a trial (it takes seconds) and start streaming live data. We will use the set_ws_key command to set the key as shown below.
api_key = “api_key” # set streaming key — not the same as rest API key stream.set_ws_key(api_key)
Set symbols you want to call, separated by a comma, you can use up to 10 symbols for free for up to two weeks.
stream.set_symbols(“USDJPY,EURGBP”)
Once we have set the symbols and the API key, we can define a function that we can pass to the stream_data function as shown below.
In this example, we have only used the print_message function but you can use it to write a function to write to a file or Redis database.
def print_message(data): print(f”Received: {data}”) # Set the callback for receiving messages stream.stream_data(print_message)
Once the function is defined and passed on to the stream_data function, use the connect command to start your program.
Voila, you have live data streaming in. You can modify the function to parse the JSON and format the timestamp as you please.
Hope this tutorial is helpful. If you have any technical queries, please feel free to get in touch with our market data experts via our contact form, live chat, or email to support@tradermade.com. We are always keen to hear from you.