DEV Community

Cover image for Stream Data using Python in 8 lines of Code
Shridhar G Vatharkar
Shridhar G Vatharkar

Posted on

Stream Data using Python in 8 lines of Code

Given the increasing prevalence of WebSockets, it is natural for novice developers to seek access. Creating a server and client for experimenting with data via WebSockets seems straightforward. Yet, it is significantly more advantageous to utilize a WebSocket that delivers real-time data.

Now, let's dive in.
To engage with this guide, ensure you have:

  • Access to Google Colab or have Jupyter Notebook or Python installed.
  • Fundamental proficiency in Python.

We will leverage Google Colab to make this tutorial exceptionally user-friendly.

!pip install tradermade==0.8.0
Enter fullscreen mode Exit fullscreen mode

Image description

After installing tradermade, import the stream from the library.

from tradermade import stream
Enter fullscreen mode Exit fullscreen mode

Obtain your WebSocket API key from TraderMade by initiating a trial (a process that only takes seconds) and commence streaming live data. Use the "set_ws_key" command to establish the key, as demonstrated below.

api_key = “api_key”
# set streaming key — not the same as rest API key
stream.set_ws_key(api_key)
Enter fullscreen mode Exit fullscreen mode

Specify the symbols you wish to reference, separated by commas. You have the option to utilize up to 10 currency pair symbols free of charge for a duration of two weeks.

stream.set_symbols(“USDJPY,EURGBP”)
Enter fullscreen mode Exit fullscreen mode

After configuring the symbols and API key, we can establish a function that can be passed to the stream_data function, as illustrated below.

In this instance, we've employed the print_message function. However, you can use it for tasks like writing to a file or a Redis database.

def print_message(data):
print(f”Received: {data}”)
# Set the callback for receiving messages
stream.stream_data(print_message)
Enter fullscreen mode Exit fullscreen mode

Initiate your program using the connect command after defining the function and passing it to the stream_data function.

Image description

And that’s it! You can see live data streaming instantly. You can further modify this function to parse the JSON responses and format the timestamp as you deem fit.

Hope this tutorial is helpful. Please leave your comments, like, and share this tutorial. We would love to hear from you.

Also, take a glance at the original tutorial by Rahul Khanna on Medium:

Stream Data using Python in 8 lines of Code

Top comments (0)