Real-time financial data streaming using WebSockets

midassss

midasSSS

Posted on September 20, 2020

Real-time financial data streaming using WebSockets

This short article was written to cover the lack of any tutorial of how to simply begin receiving stocks, forex, and crypto quotes in under 5 minutes. We will mainly focus on Python implementation, however, the same logic can be easily extended to other languages.

WebSockets might be a crucial part of the apps which rely on accurate real-time data, such as chart application, portfolio management, and algorithmic trading systems.

Preparation

We will be using the service Twelve Data. Make sure to have your API Key upgraded to be eligible for the usage of WebSockets.

For python users, install the library pip install twelvedata - GitHub.

Python

First things first, define the function which will be used when new data is received.

def on_event(e):
    print(e)
Enter fullscreen mode Exit fullscreen mode

This function should perform any consecutive actions according to your logic: update the price, update a record, display the changes, etc.

Remember that all data received is in json format or to be more precise a dict object.

The main block should initialize the TDClient object and perform the consecutive connection to the server.

from twelvedata import TDClient

td = TDClient('your_api_key')

ws = td.websocket(symbols=['BTC/USD', 'AAPL', 'EUR/USD'], on_event=on_event)
ws.connect()
ws.keep_alive()
Enter fullscreen mode Exit fullscreen mode

WebSocket supports the following methods:
subscribe - new symbols to be included.
unsubscribe - remove old symbols from the subscription.
reset - unsubscribe from all symbols.
connect - open a new connection with the server.
disconnect - close existing connection with the server.
keep_alive - run an infinite loop to receive all the data.

Response

In response, you will be getting an object with basic meta-information, tick price, and daily volume. E.g:

{'event': 'price', 'symbol': 'BTC/USD', 'currency_base': 'Bitcoin', 'currency_quote': 'US Dollar', 'exchange': 'Binance', 'type': 'Digital Currency', 'timestamp': 1600595462, 'price': 10964.8, 'day_volume': 38279}
Enter fullscreen mode Exit fullscreen mode

Do not forget about market open hours, for instance over the weekends only crypto markets are opened.

Alt Text

The average latency is about ~150ms, which makes the data reliable and applicable to any usage. Moreover, the single format allows flexibility in streaming data from across different types of assets.
Now you can easily use it for your application, e.g. charting.

💖 💪 🙅 🚩
midassss
midasSSS

Posted on September 20, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related