-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
199 lines (172 loc) Β· 7.14 KB
/
Copy pathstreamlit_app.py
File metadata and controls
199 lines (172 loc) Β· 7.14 KB
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
import streamlit as st
import sys
import os
sys.path.append('src')
from data_fetcher import LiquidationDataFetcher
from visualizer import LiquidationHeatmapVisualizer
import plotly.graph_objects as go
st.set_page_config(
page_title="Crypto Liquidation Heatmap",
page_icon="π",
layout="wide"
)
st.title("π₯ Cryptocurrency Liquidation Heatmap")
st.caption("Real-time liquidation analysis similar to Coinglass")
# Sidebar controls
with st.sidebar:
st.header("Settings")
symbol = st.selectbox(
"Trading Pair",
["BTC/USDT", "ETH/USDT", "BNB/USDT", "SOL/USDT"],
index=0
)
exchange = st.selectbox(
"Exchange",
["binance", "okx", "bybit"],
index=0
)
st.subheader("π Analysis Period")
duration_type = st.radio(
"Duration Type",
["Real-time Snapshot", "Historical Analysis"],
index=0
)
if duration_type == "Historical Analysis":
time_period = st.selectbox(
"Time Period",
[
("12 Hours", "12h", 720),
("24 Hours", "1d", 1440),
("2 Days", "2d", 2880),
("3 Days", "3d", 4320)
],
index=1,
format_func=lambda x: x[0]
)
selected_timeframe = time_period[1]
analysis_minutes = time_period[2]
st.info(f"π Analyzing liquidations over {time_period[0]}")
else:
selected_timeframe = "current"
analysis_minutes = 0
st.info("β‘ Real-time liquidation snapshot")
# Enhanced refresh options
refresh_mode = st.radio("Refresh Mode", ["Manual", "Auto-refresh"], index=0)
if refresh_mode == "Auto-refresh":
refresh_interval = st.selectbox(
"Update Interval",
[5, 10, 30, 60, 300],
index=2,
format_func=lambda x: f"{x} seconds" if x < 60 else f"{x//60} minute{'s' if x//60 > 1 else ''}"
)
auto_refresh = True
else:
auto_refresh = False
refresh_interval = 30
if st.button("π Refresh Data"):
st.rerun()
# Main content
try:
if duration_type == "Historical Analysis":
spinner_text = f"Analyzing {symbol} liquidations over {time_period[0]} from {exchange}..."
else:
spinner_text = f"Fetching real-time {symbol} data from {exchange}..."
with st.spinner(spinner_text):
fetcher = LiquidationDataFetcher(exchange)
if duration_type == "Historical Analysis":
data = fetcher.get_historical_liquidation_data(symbol, selected_timeframe, analysis_minutes)
else:
data = fetcher.get_liquidation_heatmap_data(symbol)
if data:
# Show analysis type and additional info
analysis_type = data.get('analysis_type', 'real-time')
if analysis_type == 'historical':
st.success(f"π Historical Analysis: {data['timeframe']} over {data.get('duration_minutes', 0)/60:.1f} hours")
# Show historical price stats if available
if 'price_stats' in data:
stats = data['price_stats']
col_stats1, col_stats2, col_stats3, col_stats4 = st.columns(4)
with col_stats1:
st.metric("Price Range Low", f"${stats['min']:,.2f}")
with col_stats2:
st.metric("Price Range High", f"${stats['max']:,.2f}")
with col_stats3:
st.metric("Average Price", f"${stats['avg']:,.2f}")
with col_stats4:
st.metric("Volatility", f"{stats['volatility']*100:.2f}%")
else:
st.info("β‘ Real-time liquidation snapshot")
# Display current price prominently
col1, col2, col3 = st.columns(3)
with col1:
st.metric(
label=f"Current {symbol} Price",
value=f"${data['current_price']:,.2f}",
delta=None
)
with col2:
long_5x = data['liquidation_levels']['long_liquidations'][0]
risk_emoji = "π΄" if long_5x.get('risk_level') == 'high' else "π‘" if long_5x.get('risk_level') == 'medium' else "π’"
st.metric(
label=f"{risk_emoji} Long 5x Liquidation",
value=f"${long_5x['price']:,.2f}",
delta=f"-{long_5x['distance_percent']:.1f}%"
)
with col3:
short_5x = data['liquidation_levels']['short_liquidations'][0]
risk_emoji = "π΄" if short_5x.get('risk_level') == 'high' else "π‘" if short_5x.get('risk_level') == 'medium' else "π’"
st.metric(
label=f"{risk_emoji} Short 5x Liquidation",
value=f"${short_5x['price']:,.2f}",
delta=f"+{short_5x['distance_percent']:.1f}%"
)
# Create visualizations
visualizer = LiquidationHeatmapVisualizer()
# Main heatmap
st.subheader("π Liquidation Heatmap")
fig_heatmap = visualizer.create_interactive_heatmap(data)
st.plotly_chart(fig_heatmap, use_container_width=True)
# Leverage analysis
st.subheader("βοΈ Leverage Distribution")
fig_leverage = visualizer.create_leverage_distribution(data)
st.plotly_chart(fig_leverage, use_container_width=True)
# Liquidation tables
col1, col2 = st.columns(2)
with col1:
st.subheader("π΄ Long Liquidations")
long_df = []
for liq in data['liquidation_levels']['long_liquidations']:
risk_level = liq.get('risk_level', 'unknown')
risk_emoji = "π΄" if risk_level == 'high' else "π‘" if risk_level == 'medium' else "π’"
long_df.append({
"Leverage": f"{liq['leverage']}x",
"Price": f"${liq['price']:,.2f}",
"Distance": f"{liq['distance_percent']:.2f}%",
"Risk": f"{risk_emoji} {risk_level.title()}"
})
st.dataframe(long_df, hide_index=True)
with col2:
st.subheader("π’ Short Liquidations")
short_df = []
for liq in data['liquidation_levels']['short_liquidations']:
risk_level = liq.get('risk_level', 'unknown')
risk_emoji = "π΄" if risk_level == 'high' else "π‘" if risk_level == 'medium' else "π’"
short_df.append({
"Leverage": f"{liq['leverage']}x",
"Price": f"${liq['price']:,.2f}",
"Distance": f"{liq['distance_percent']:.2f}%",
"Risk": f"{risk_emoji} {risk_level.title()}"
})
st.dataframe(short_df, hide_index=True)
else:
st.error("β Failed to fetch data. Please try again.")
except Exception as e:
st.error(f"β Error: {str(e)}")
# Auto-refresh with custom interval
if auto_refresh:
import time
time.sleep(refresh_interval)
st.rerun()
# Footer
st.markdown("---")
st.caption("π Built with CCXT β’ Data from live exchanges β’ Updates every refresh")