-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
281 lines (248 loc) · 10.2 KB
/
app.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
import dash_bootstrap_components as dbc
from dash import Dash, html, dcc, Input, Output, dash_table
from dash_bootstrap_templates import load_figure_template
from json import dump, loads
from json.decoder import JSONDecodeError
import plotly.express as px
from random import randint
from flask import request, jsonify
from pathlib import Path
from os import environ
from payload import Payload
DATA_DIR = Path("." if not environ.get("DATA_DIR") else environ['DATA_DIR'])
DATA = DATA_DIR.joinpath("data.json")
dbc_css = ("https://cdn.jsdelivr.net/gh/AnnMarieW/[email protected]/dbc.min.css")
app = Dash(__name__, external_stylesheets=[dbc.themes.SLATE, dbc_css])
server = app.server
load_figure_template("slate")
payload = Payload()
payload.read_json(DATA)
payload.compute_table()
@server.route("/update-jobs", methods=['PUT'])
def update_jobs():
try:
record = loads(request.data)
except JSONDecodeError:
server.logger.error(f"Error in decoding data: {request.data}")
return "Can't decode object", 500
if record is not None:
with open(DATA, 'w') as file:
dump(record, file)
server.logger.info(f"{DATA.absolute()} updated!")
return jsonify({"response": "Jobs updated"})
else:
server.logger.error(f"Error in decoding data: {request.data}")
return "Can't decode object", 500
schema = [
Output('borr-uti-graph', 'figure'),
Output('table-div', 'children'),
Output("update-time", "children")
]
schema.extend(
Output(f"{category}-num-range-{i}", "children") for category in payload.categories for i in range(payload.n_ranges[category])
)
schema.extend([
Output(f"{category}-tot-borrow", "children") for category in payload.categories
])
schema.extend([
Output(f"{category}-tot-collateral", "children") for category in payload.categories
])
schema.append(
Input('refresh-btn', 'n_clicks')
)
@app.callback(schema)
def update_graph(n_clicks: int):
payload.read_json(DATA)
payload.compute_table()
df = payload.df
counts = {
"stable": [len(df[(df["range"] == i) & (df["category"] == "stable")]) for i in range(payload.n_ranges["stable"])],
"other": [len(df[(df["range"] == i) & (df["category"] == "other")]) for i in range(payload.n_ranges["other"])]
}
stable_tot_borrow = df[df["category"] == "stable"]['total_borrow_usd'].sum()
stable_tot_collateral = df[df["category"] == "stable"]['total_collateral_usd'].sum()
other_tot_borrow = df[df["category"] == "other"]['total_borrow_usd'].sum()
other_tot_collateral = df[df["category"] == "other"]['total_collateral_usd'].sum()
light_df = df.drop(["range", "category", "st_ratio"], axis=1)
output = [
px.scatter(
data_frame=df[["utilization_ratio", "total_borrow_usd", "storage_address", "category"]],
x="utilization_ratio",
y="total_borrow_usd",
color="category",
color_discrete_map={
"stable": "#a0a0a0", # Green for stable
"other": "#4b4b4b" # Red for other
},
custom_data=["storage_address"],
title="Liquidation Bot Dashboard",
).update_traces(hovertemplate=None),
dash_table.DataTable(
data=light_df.to_dict("records"),
columns=[{'id': c, 'name': c} for c in light_df.columns],
id="accounts-table",
sort_action="native",
style_table={'overflowY': 'scroll'},
),
html.Div(f"Last update: {payload.timestamp}")]
for category in payload.categories:
output.extend(
dbc.Card([
dbc.CardHeader(f"{payload.ranges[category][i]}", style={'font-weight': 'bold', 'font-size': '150%'}),
dbc.CardBody([
html.H1(counts[category][i], className="card-title"),
html.P("loans", className="card-text"),
html.H1(f"{int(payload.runtimes_single[category][i])}ms" if payload.runtimes_single[category][i] else 'NaN', className="card-title"),
html.P("rolling runtime single", className="card-text"),
])
]) for i in range(payload.n_ranges[category])
)
output.extend([
dbc.Card([
dbc.CardHeader("Borrow", style={'font-weight': 'bold', 'font-size': '150%'}),
dbc.CardBody([
html.H1(f"{stable_tot_borrow:,.2f}$", className="card-title"),
])
]),
dbc.Card([
dbc.CardHeader("Collateral", style={'font-weight': 'bold', 'font-size': '150%'}),
dbc.CardBody([
html.H1(f"{stable_tot_collateral:,.2f}$", className="card-title"),
])
]),
dbc.Card([
dbc.CardHeader("Borrow", style={'font-weight': 'bold', 'font-size': '150%'}),
dbc.CardBody([
html.H1(f"{other_tot_borrow:,.2f}$", className="card-title"),
])
]),
dbc.Card([
dbc.CardHeader("Collateral", style={'font-weight': 'bold', 'font-size': '150%'}),
dbc.CardBody([
html.H1(f"{other_tot_collateral:,.2f}$", className="card-title"),
])
]),
])
return output
@app.callback(
Output("details-div", "children"),
Input("borr-uti-graph", "clickData"),
Input('refresh-btn', 'n_clicks')
)
def change_lookup_address(click_data: 'str | None', n_clicks: int):
payload.read_json(DATA)
payload.compute_table()
df = payload.df
symbols = payload.symbols
if click_data == None and df.empty:
storage_address, user_address, ut_ratio, st_ratio, total_b, total_c, cl = "", "", 0, 0, 0, 0, ""
elif click_data == None and not df.empty:
filtered_data = [df.to_dict("records")[randint(0, len(df.to_dict("records")) - 1)]]
storage_address = filtered_data[0]['storage_address']
user_address = filtered_data[0]['user_address']
ut_ratio = filtered_data[0]['utilization_ratio']
st_ratio = filtered_data[0]['st_ratio']
total_b = filtered_data[0]['total_borrow_usd']
total_c = filtered_data[0]['total_collateral_usd']
cl = filtered_data[0]['category']
else:
filtered_data = df[df["storage_address"] == click_data["points"][0]["customdata"][-1]].to_dict("records")
if not filtered_data:
filtered_data = [df.to_dict("records")[randint(0, len(df.to_dict("records")) - 1)]]
storage_address = filtered_data[0]['storage_address']
user_address = filtered_data[0]['user_address']
ut_ratio = filtered_data[0]['utilization_ratio']
st_ratio = filtered_data[0]['st_ratio']
total_b = filtered_data[0]['total_borrow_usd']
total_c = filtered_data[0]['total_collateral_usd']
cl = filtered_data[0]['category']
first_row = {"TYPE": "collateral usd", **{symbol: filtered_data[0][symbol + "_collateral_usd"] for symbol in symbols.values()}}
second_row = {"TYPE": "borrow usd", **{symbol: filtered_data[0][symbol + "_borrow_usd"] for symbol in symbols.values()}}
return html.Div([
html.H6(
dcc.Markdown(f"""
_Loan class_: {cl}
_Storage address_: [{storage_address[:8]}...{storage_address[-8:]}](https://allo.info/account/{storage_address})
_User address_: [{user_address[:8]}...{user_address[-8:]}](https://allo.info/account/{user_address})
_Utilization ratio_: {ut_ratio}
_Stability ratio_: {st_ratio}
_Total collateral_: {total_c}$
_Total borrow_: {total_b}$"""),
),
html.Br(),
dash_table.DataTable(
data=[first_row, second_row],
columns=[{'id': c, 'name': c} for c in first_row.keys()],
style_cell={'textAlign': 'center'},
style_cell_conditional=[{"if": {"column_id": "TYPE"}, "textAlign": "left"}],
id="details-table",
style_table={'overflowY': 'scroll'}
)
])
def get_metrics_tab(cl: str):
return dcc.Tab(
label=cl,
className="dbc",
children=[
html.Div([
dbc.Row([
dbc.Col(dbc.Card(
id=f"{cl}-num-range-{i}",
)) for i, _ in enumerate(payload.ranges[cl])
], style={"margin": "10px"}),
dbc.Row([
dbc.Col(dbc.Card(
id=f"{cl}-tot-borrow"
)),
dbc.Col(dbc.Card(
id=f"{cl}-tot-collateral"
)),
], style={"margin-top": "20px", "margin-left": "10px", "margin-right": "10px"})
], style={'text-align': 'center', 'margin-top': "20px"})
]
)
app.layout = html.Div([
dbc.Row([
dbc.Col(
html.Div("", id="update-time", className='dbc'),
width='auto',
),
dbc.Col(
html.Button("Refresh", id='refresh-btn', className="dbc"),
width='auto'
),
], className="dbc", style={'padding': 10}, justify='center'),
dcc.Tabs([
dcc.Tab(label="Totals", className="dbc", children=[
dcc.Tabs([
get_metrics_tab("stable"),
get_metrics_tab("other")
])
]),
dcc.Tab(label="Graph", className="dbc", children=[
dcc.Graph(
id="borr-uti-graph",
),
html.Div(
id="details-div",
className="dbc"
)
]),
dcc.Tab(label="Table", className="dbc", children=[
html.Div([
dash_table.DataTable(
id="accounts-table",
sort_action="native",
style_table={'overflowY': 'scroll'},
)
], className="dbc", id="table-div")
]),
], className="dbc"),
#dcc.Interval(
# id='interval-component',
# interval=10*1000, # in milliseconds
# n_intervals=0
#)
], className="dbc", style={"margin-left": "15px", "margin-right": "15px"})
if __name__ == '__main__':
app.run(debug=True)