Getting Started with Binance & Plotly

Why program by hand in five days what you can spend five years of your life automating?

from the book: “Language Translation Using PCCTS and C++: A Reference Guide”. That is very much what I love spending my spare time on (when it’s rainy outside). The objective of this article is to walk you through the setup of Binance python and eventually displaying data gathered from this API.

Environment Setup

I usually start a new project off in a new virtual python environment. Don’t ask me why — I like using virtualenvwrapper and I usually publish my code on GitHub:

PyCharm New Project Configuration

Generate aBinance API Key

If anything is going to change this is the Binance documentation link. Log into your Binance account and go to API Management:

“Hello World”

The below example is a bit more than hello world but hopefully just what you were looking for. We 1) read the historical data from the Binance API, 2) convert it into a pandas data frame, and 3) plot the result using the Plotly candlestick chart and that’s 25 lines including comments:

from binance.client import Client
import datetime
import pandas as pd
import numpy as np
import plotly.graph_objs as go
import binancekeys

client = Client(binancekeys.APIkey, binancekeys.APIsecret)
symbol='BTCEUR'
granularity = Client.KLINE_INTERVAL_30MINUTE
start_time = "1 March, 2021"
end_time = "1 April, 2021"

# get historical data from binance API
klines = np.array(client.get_historical_klines(symbol, granularity, start_time, end_time))
# reshape date to pandas
df = pd.DataFrame(klines.reshape(-1, 12), dtype=float, columns=('Open Time','Open','High','Low','Close','Volume','Close time','Quote asset volume','Number of trades','Taker buy base asset volume','Taker buy quote asset volume','Ignore'))
df['Open Time'] = pd.to_datetime(df['Open Time'], unit='ms')

# plot candlesticks using plotly
fig = go.Figure(data=[go.Candlestick(x=df['Open Time'],
open=df['Open'],
high=df['High'],
low=df['Low'],
close=df['Close'])])
fig.show()
Plotly candlestick output for the above code.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sven Kuehn

Sven Kuehn

Holds a P.h.D. in bioelectromagnetics, leads the research & development of a Zurich based enterprise, and speed-climbs the summits of the alps.