Loading...

Plus+ Python

How to Stream RealTime Trade Data from Binance API in Python

How to Stream RealTime Trade Data from Binance API in Python

Streaming Real Time Data from Binance

We are going to use websockets to stream real time (live) trade information from Binance and save the resulting information into a SQLite database using Python. This is much like we accomplished in our other Plus+ article for Kraken. We will connect to the "trade" streaming socket, which will return every transaction that takes place for the symbol that we pass. We will use BTC/USDT as the symbol in our example. Once the data is captured, it would be easy to extend this example to include some sort of display or summary of the trade data. "Tick data", literally every transaction 'print' (in lingo), can be created from the raw trade data as well. The script will save into our local database every 100 transactions that take place, and that can be modified in the main body of the script. Of course, we fully comment and make each line of python code logical and understandable.

Data Enhancements

There are a few data enhancements that we make before we save the data into our database. This will make it easier to sort or filter on the data in the future. First of all, we add a field for a human-readable date instead of using the unix server timestamp only. We also add a field for volume in USD terms (this is assuming BTC/USDT so technically in 'USD Tether' terms). This volume_usd field is calculated by multiplying the price * quantity. Binance API also returns a field called "is_buyer_marketmaker". This field can be somewhat confusing, and so we interpret it and add a field for "market sell" or "market buy" to display which side took action. "Market buy" means it was a buy marketorder on the order book.

Here is what the resulting database sample will look like as it captures trades:


Plus+ membership required

Create a Plus+ account to view the live codebase.

This article has a fully working, notebook-ready code block. Sign up for Plus+ to access it and the rest of the 20+ premium articles.

Subscribe to Plus+ Browse Plus+ articles