Skip to content

Instantly share code, notes, and snippets.

@tacomonster
Created August 21, 2018 12:39
Show Gist options
  • Save tacomonster/3c88f372a0881b229d4e62f1ef43d328 to your computer and use it in GitHub Desktop.
Save tacomonster/3c88f372a0881b229d4e62f1ef43d328 to your computer and use it in GitHub Desktop.
Grabbing Binance price data and graphing it using Dash
import dash
from dash.dependencies import Output, Event, Input
import dash_core_components as dcc
import dash_html_components as html
import plotly
import plotly.graph_objs as go
from collections import deque
import datetime
import pandas as pd
from dataGrab import DataGrab
n_q = 100
x_values = deque(maxlen=n_q)
price_list = deque(maxlen=n_q)
spread_list = deque(maxlen=n_q)
"""------------------------Graph Start-----------------------------"""
app = dash.Dash(__name__)
app.layout = html.Div(
[
html.Div(id='output-container'),
dcc.Graph(id='live-graph-1', animate=True),
dcc.Interval(
id='graph-update-1',
interval=10000
),
]
)
@app.callback(Output('live-graph-1', 'figure'),
events=[Event('graph-update-1', 'interval')])
def update_graph_scatter():
dg = DataGrab().getBinanceSpot()
x_values.append(datetime.datetime.now())
price_list.append(dg.loc['eth-usd', 'price'])
spread_list.append(dg.loc['eth-usd', 'spread'])
# Main datapoints on graph
data1 = plotly.graph_objs.Scatter(
x=list(x_values),
y=list(price_list),
name='Price',
mode='lines',
marker={'size': 12, 'color': '#cd9045'},
)
data2 = plotly.graph_objs.Scatter(
x=list(x_values),
y=list(spread_list),
name='spread',
mode='markers',
marker={'size': 10, 'color': 'rgb(27, 135, 4)'},
yaxis='y2'
)
# Putting everything together into a graph
return {'data': [data1, data2],
'layout': go.Layout(xaxis={'range': [x_values[0], x_values[-1]]},
yaxis={'range': [int(min(price_list) * 0.95), int(max(price_list) * 1.05)],
'title': 'Price',
'nticks': 5
},
yaxis2={'range': [int(min(spread_list) * 0.99), int(min(spread_list) * 1.01)],
'title': 'Spread',
'side': 'right',
'overlaying': 'y',
'nticks': 4,
},
title='Price vs Spread',
showlegend=True,
paper_bgcolor='#2a313b',
plot_bgcolor='#2a313b',
font={'color':'#a8b4c4'}),
}
if __name__ == '__main__':
app.run_server(debug=True)
import copy
import pandas as pd
import numpy as np
import requests
class DataGrab:
def getBinanceSpot(self):
"""
Pulls Binance Spot Prices. Returns Datafram with: ask, bid, price, volume, base, quote, spread, exchange.
Requests all data at once w/ 1 API pull
Reference: https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.m
"""
def splitPair(tickerString):
if tickerString[-4:] == 'USDT':
return [tickerString.split('USDT')[0].lower(), 'usdt']
elif tickerString[-3:] == 'ETH':
return [tickerString.split('ETH')[0].lower(), 'eth']
elif tickerString[-3:] == 'BTC':
return [tickerString.split('BTC')[0].lower(), 'btc']
elif tickerString[-3:] == 'BNB':
return [tickerString.split('BNB')[0].lower(), 'bnb']
return np.nan
url = 'https://api.binance.com/api/v1/ticker/24hr'
bnn_df = pd.DataFrame(requests.get(url).json())
# print(bnn_df)
bnn_df['symbol'] = bnn_df.apply(lambda x: splitPair(x['symbol']), axis=1)
bnn_df = bnn_df.dropna()
bnn_df['base'] = bnn_df.apply(lambda x: x['symbol'][0], axis=1)
bnn_df['quote'] = bnn_df.apply(lambda x: x['symbol'][1], axis=1)
bnn_df['quote'] = bnn_df['quote'].str.replace('usdt', 'usd')
bnn_df = bnn_df.rename(index=str, columns={'askPrice': 'ask',
'bidPrice': 'bid',
'lastPrice': 'price'})
columns = ['ask', 'bid', 'price', 'volume']
bnn_df['exchange'] = 'binance'
bnn_df[columns] = bnn_df[columns].astype(float)
bnn_df['spread'] = bnn_df.ask - bnn_df.bid
columns.extend(['base', 'quote', 'spread', 'exchange'])
bnn_df = bnn_df[columns]
bnn_df['ticker'] = bnn_df.apply(lambda x: x['base'] + '-' + x['quote'], axis=1).tolist()
bnn_df = bnn_df[['base', 'quote', 'exchange', 'price', 'ask', 'bid', 'spread', 'volume', 'ticker']].set_index('ticker')
del bnn_df.index.name
return bnn_df
if __name__ == '__main__':
a = DataGrab().getBinanceSpot()
print(a)
@miningseven
Copy link

Thanks dude!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment