-
Notifications
You must be signed in to change notification settings - Fork 1
/
webserver.py
393 lines (343 loc) · 14.7 KB
/
webserver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
import threading
import time
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_table
import pandas
import plotly.express as px
from dash.dependencies import Input, Output
from cryptofeed_worker import OrderBook, start_feed, TimeKeeper
from coins import MasterObject
from CB_candle_worker import CandleWorker
import logging
import plotly.graph_objects as go
# Stop DASH from printing every POST result which is often due to interval callbacks
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
# Object which acts as the carrier through the app and is passed between child threads
master = MasterObject()
timeKeeperObject = TimeKeeper()
# Function which holds the Dash web server and starts the web server
def run_server():
base_trade = [({'Currency Pair': 'BTC-USD', 'Side': 'bid', 'Amount': '100', 'Price': '3000'})]
base_df = pandas.DataFrame(base_trade)
app = dash.Dash(__name__, update_title=None, external_stylesheets=[dbc.themes.SLATE])
app.layout = html.Div([
html.Div(
className='split left',
children=[
html.Div(children=[html.H3('ETH-USD Live Depth Chart',
id='header')]),
html.Div(
id='dropdowns',
children=
[
dcc.Dropdown(
id='token-selector',
placeholder='Token',
options=[
{'label': 'BTC', 'value': 'btc'},
{'label': 'ETH', 'value': 'eth'},
{'label': 'ADA', 'value': 'ada'},
{'label': 'MATIC', 'value': 'matic'},
{'label': 'BAT', 'value': 'bat'},
{'label': 'DOT', 'value': 'dot'},
{'label': 'ALGO', 'value': 'algo'},
{'label': 'UNI', 'value': 'uni'},
{'label': 'SOL', 'value': 'sol'},
{'label': 'CHZ', 'value': 'chz'},
{'label': 'MANA', 'value': 'mana'},
{'label': 'ETC', 'value': 'etc'},
{'label': 'XTZ', 'value': 'xtz'}
]
),
dcc.Dropdown(
id='graph-selector',
placeholder='Chart Type',
options=[
{'label': 'Depth chart', 'value': 'depth'},
{'label': 'Wall chart', 'value': 'wall'},
{'label': 'Daily Candlestick', 'value': 'candle'}
]
)
]
),
html.Div([
dcc.Graph(id='live-update-graph',
figure=px.ecdf(master.get_books("eth").get_asks(), x='ETH-USD Price', y="size",
ecdfnorm=None,
color="side",
labels={
"size": "ETH",
"side": "Side",
"value": "ETH-USD Price"
},
title="ETH-USD Depth Chart using cryptofeed and Dash"),
style={'width': '90%'}
),
html.Div(id='gran-slider',
children=[dcc.Slider(id='get-slider-value',
min=0,
max=5,
step=None,
marks={
0: '1 Min',
1: '5 Min',
2: '15 Min',
3: '1 Hour',
4: '6 Hour',
5: '24 Hour'
},
vertical=True,
value=0
)], style={'display': 'none'})
]),
html.Div([
dash_table.DataTable(
id='trade_table',
columns=[{"name": i, "id": i} for i in base_df],
data=base_df.to_dict('records'),
style_cell={'textAlign': 'center', 'background-color': '#525252', 'text-color': 'white',
'fontWeight': 'bold'},
style_table={'width': '95%'}
)
]),
dcc.Interval(
id='interval-component',
interval=1 * 500, # Updates every half a second
n_intervals=0
),
dcc.Interval(
id='stats-interval',
interval=1 * 1000,
n_intervals=0
)
]),
html.Div(
className='split right',
children=[
html.Div(
className='stats',
children=[
html.H3('Session Stats')
]),
html.Div(
className='stats_area',
children=[
html.Output(
id='statsBox',
children=['Time elapsed']
),
html.Output(
id='buysBox',
children=['Number of buys:']
),
html.Output(
id='sellsBox',
children=['Number of sells:']
),
html.Output(
id='buysValue',
children=['Value of buys:']
),
html.Output(
id='sellsValue',
children=['Value of sells:']
)
])
])
])
@app.callback(Output('gran-slider', 'style'),
Input('graph-selector', 'value'))
def update_slider(value):
if value == 'candle':
return {'display': 'inline-block'}
else:
return {'display': 'none'}
@app.callback([Output('statsBox', "children"),
Output('buysBox', "children"),
Output('sellsBox', "children"),
Output('buysValue', "children"),
Output('sellsValue', "children")],
[Input('stats-interval', 'n_intervals'),
Input('token-selector', 'value')])
def update_stats(n, value):
if value is not None:
return get_book_stats_data(master.get_books(value))
else:
return get_book_stats_data(master.get_books("eth"))
# Callback to update the graph with any updates to the L2 Book or candles
@app.callback([Output('live-update-graph', 'figure'),
Output('header', 'children'),
Output('trade_table', "data")],
[Input('interval-component', 'n_intervals'),
Input('token-selector', 'value'),
Input('graph-selector', 'value'),
Input('get-slider-value', 'value')])
def update_graph(n, value, g_value, s_value):
# Layout the graph
# BTC
if value is not None:
return build_graph(master.get_books(value), g_value, s_value)
else:
return build_graph(master.get_books("eth"), g_value, s_value)
# Run DASH server
app.run_server()
def build_graph(order_book, g_value, s_value):
if g_value == 'wall':
frames = [order_book.get_asks(), order_book.get_bids()]
result = pandas.concat(frames)
fig = px.line(result, x=order_book.get_symbol_string(), y='size', color='side',
color_discrete_map={
'bid': 'rgb(34, 139, 34)',
'ask': 'rgb(255, 160, 122)'
})
# Display the mid-market price
fig.add_vline(x=order_book.mid_market,
annotation_text='Mid-Market Price: ' + "{:.2f}".format(order_book.mid_market),
annotation_position='top')
fig.update_layout(
plot_bgcolor='#262626',
paper_bgcolor='#262626',
font_color='white'
)
fig.add_layout_image(
dict(
source=order_book.get_logo(),
xref='paper',
yref='paper',
x=0.25,
y=1,
sizex=1,
sizey=1,
layer='below',
sizing='contain',
opacity=0.075
)
)
new_df = pandas.DataFrame(order_book.trade_list)
return fig, order_book.get_subtitle(), new_df.to_dict('records')
elif g_value == 'candle':
allowed_nums = {
0: 60,
1: 300,
2: 900,
3: 3600,
4: 21600,
5: 86400
}
gran = 0
if int(s_value) in allowed_nums.keys():
gran = allowed_nums.get(int(s_value))
candle = order_book.get_candle_worker()
df = candle.get_data(gran)
fig = go.Figure(data=[go.Candlestick(x=df['date'],
open=df['open'],
high=df['high'],
low=df['low'],
close=df['close'])])
fig.update_layout(xaxis_rangeslider_visible=False)
fig.update_layout(
plot_bgcolor='#262626',
paper_bgcolor='#262626',
font_color='white',
autosize=True
)
fig.add_layout_image(
dict(
source=order_book.get_logo(),
xref='paper',
yref='paper',
x=0.25,
y=1,
sizex=1,
sizey=1,
layer='below',
sizing='contain',
opacity=0.075
)
)
new_df = pandas.DataFrame(order_book.trade_list)
return fig, order_book.get_subtitle(), new_df.to_dict('records')
else:
fig = px.ecdf(order_book.get_asks(), x=order_book.get_symbol_string(), y="size", ecdfnorm=None, color="side",
labels={
"size": order_book.get_size(),
"side": "Side",
"value": order_book.get_symbol_string()
},
color_discrete_map={
'ask': 'rgb(255, 160, 122)'
})
# fig.data[0].line.color = 'rgb(255, 160, 122)' # red
fig.data[0].line.width = 5
# Opposing side of the graph
fig2 = px.ecdf(order_book.get_bids(), x=order_book.get_symbol_string(), y="size", ecdfmode='reversed',
ecdfnorm=None,
color="side",
color_discrete_map={
'bid': 'rgb(34, 139, 34)'
}
)
# fig2.data[0].line.color = 'rgb(34, 139, 34)' # green
fig2.data[0].line.width = 5
# Merge the figures together
fig.add_trace(fig2.data[0])
# Display the mid-market price
fig.add_vline(x=order_book.mid_market,
annotation_text='Mid-Market Price: ' + "{:.2f}".format(order_book.mid_market),
annotation_position='top')
fig.update_layout(
plot_bgcolor='#262626',
paper_bgcolor='#262626',
font_color='white'
)
fig.add_layout_image(
dict(
source=order_book.get_logo(),
xref='paper',
yref='paper',
x=0.25,
y=1,
sizex=1,
sizey=1,
layer='below',
sizing='contain',
opacity=0.075
)
)
new_df = pandas.DataFrame(order_book.trade_list)
return fig, order_book.get_subtitle(), new_df.to_dict('records')
def get_book_stats_data(orderbook):
return timeKeeperObject.get_time_elapse(), \
orderbook.get_num_buys(), \
orderbook.get_num_sells(), \
orderbook.get_value_buys(), \
orderbook.get_value_sells()
if __name__ == "__main__":
# Web server thread
t2 = threading.Thread(target=run_server)
t2.start()
time.sleep(1)
# Start threading for both the cryptofeed worker and web server
# Cryptofeed thread takes the global carrier object as a parameter which is passed in as a callback
# This object is then passed back and forth between cryptofeed and the webserver
t1 = threading.Thread(target=start_feed, args=[master.get_books("btc"),
master.get_books('eth'),
master.get_books('ada'),
master.get_books('matic'),
master.get_books('bat'),
master.get_books('dot'),
master.get_books('algo'),
master.get_books('uni'),
master.get_books('sol'),
master.get_books('chz'),
master.get_books('mana'),
master.get_books('etc'),
master.get_books('xtz')])
t1.start()
t2.join()
t1.join()
# run_server()