|
1 |
| -import json |
2 |
| - |
3 |
| -from driftpy.constants.perp_markets import mainnet_perp_market_configs |
4 |
| -from driftpy.constants.spot_markets import mainnet_spot_market_configs |
5 |
| -from lib.api import api |
6 | 1 | import pandas as pd
|
7 |
| -from requests.exceptions import JSONDecodeError |
8 | 2 | import streamlit as st
|
| 3 | +from driftpy.constants.perp_markets import mainnet_perp_market_configs |
| 4 | +from driftpy.constants.spot_markets import mainnet_spot_market_configs |
9 | 5 |
|
| 6 | +from lib.api import api2 |
| 7 | +from utils import get_current_slot |
10 | 8 |
|
11 | 9 | options = [0, 1, 2, 3]
|
12 | 10 | labels = [
|
|
17 | 15 | ]
|
18 | 16 |
|
19 | 17 |
|
20 |
| -def asset_liab_matrix_page(): |
| 18 | +def calculate_effective_leverage(assets: float, liabilities: float) -> float: |
| 19 | + return liabilities / assets if assets != 0 else 0 |
| 20 | + |
| 21 | + |
| 22 | +def format_metric( |
| 23 | + value: float, should_highlight: bool, mode: int, financial: bool = False |
| 24 | +) -> str: |
| 25 | + formatted = f"{value:,.2f}" if financial else f"{value:.2f}" |
| 26 | + return f"{formatted} ✅" if should_highlight and mode > 0 else formatted |
| 27 | + |
| 28 | + |
| 29 | +def generate_summary_data( |
| 30 | + df: pd.DataFrame, mode: int, perp_market_index: int |
| 31 | +) -> pd.DataFrame: |
| 32 | + summary_data = {} |
| 33 | + for i in range(len(mainnet_spot_market_configs)): |
| 34 | + prefix = f"spot_{i}" |
| 35 | + assets = df[f"{prefix}_all_assets"].sum() |
| 36 | + liabilities = df[f"{prefix}_all"].sum() |
| 37 | + |
| 38 | + summary_data[f"spot{i}"] = { |
| 39 | + "all_assets": assets, |
| 40 | + "all_liabilities": format_metric( |
| 41 | + liabilities, 0 < liabilities < 1_000_000, mode, financial=True |
| 42 | + ), |
| 43 | + "effective_leverage": format_metric( |
| 44 | + calculate_effective_leverage(assets, liabilities), |
| 45 | + 0 < calculate_effective_leverage(assets, liabilities) < 2, |
| 46 | + mode, |
| 47 | + ), |
| 48 | + "all_spot": df[f"{prefix}_all_spot"].sum(), |
| 49 | + "all_perp": df[f"{prefix}_all_perp"].sum(), |
| 50 | + f"perp_{perp_market_index}_long": df[ |
| 51 | + f"{prefix}_perp_{perp_market_index}_long" |
| 52 | + ].sum(), |
| 53 | + f"perp_{perp_market_index}_short": df[ |
| 54 | + f"{prefix}_perp_{perp_market_index}_short" |
| 55 | + ].sum(), |
| 56 | + } |
| 57 | + return pd.DataFrame(summary_data).T |
| 58 | + |
| 59 | + |
| 60 | +def asset_liab_matrix_cached_page(): |
| 61 | + if "min_leverage" not in st.session_state: |
| 62 | + st.session_state.min_leverage = 0.0 |
| 63 | + if "only_high_leverage_mode_users" not in st.session_state: |
| 64 | + st.session_state.only_high_leverage_mode_users = False |
| 65 | + |
21 | 66 | params = st.query_params
|
22 | 67 | mode = int(params.get("mode", 0))
|
23 | 68 | perp_market_index = int(params.get("perp_market_index", 0))
|
24 | 69 |
|
25 | 70 | mode = st.selectbox(
|
26 | 71 | "Options", options, format_func=lambda x: labels[x], index=options.index(mode)
|
27 | 72 | )
|
28 |
| - st.query_params.update({"mode": mode}) |
| 73 | + st.query_params.update({"mode": str(mode)}) |
29 | 74 |
|
30 | 75 | perp_market_index = st.selectbox(
|
31 | 76 | "Market index",
|
32 | 77 | [x.market_index for x in mainnet_perp_market_configs],
|
33 | 78 | index=[x.market_index for x in mainnet_perp_market_configs].index(
|
34 | 79 | perp_market_index
|
35 | 80 | ),
|
| 81 | + format_func=lambda x: f"{x} ({mainnet_perp_market_configs[int(x)].symbol})", |
36 | 82 | )
|
37 |
| - st.query_params.update({"perp_market_index": perp_market_index}) |
| 83 | + st.query_params.update({"perp_market_index": str(perp_market_index)}) |
38 | 84 |
|
39 |
| - min_leverage = st.slider( |
40 |
| - "Filter by minimum leverage", 0.0, 50.0, 0.0, 0.5, key="min_leverage" |
| 85 | + result = api2( |
| 86 | + "asset-liability/matrix", |
| 87 | + _params={"mode": mode, "perp_market_index": perp_market_index}, |
| 88 | + key=f"asset-liability/matrix_{mode}_{perp_market_index}", |
41 | 89 | )
|
| 90 | + df = pd.DataFrame(result["df"]) |
42 | 91 |
|
43 |
| - try: |
44 |
| - result = api( |
45 |
| - "asset-liability", |
46 |
| - "matrix", |
47 |
| - params=params, |
48 |
| - as_json=True, |
49 |
| - ) |
50 |
| - if "result" in result and result["result"] == "miss": |
51 |
| - st.write("Fetching data for the first time...") |
52 |
| - st.image( |
53 |
| - "https://i.gifer.com/origin/8a/8a47f769c400b0b7d81a8f6f8e09a44a_w200.gif" |
54 |
| - ) |
55 |
| - st.write("Check again in one minute!") |
56 |
| - st.stop() |
57 |
| - |
58 |
| - except Exception as e: |
59 |
| - if type(e) == JSONDecodeError: |
60 |
| - print("HIT A JSONDecodeError...", e) |
61 |
| - st.write("Fetching data for the first time...") |
62 |
| - st.image( |
63 |
| - "https://i.gifer.com/origin/8a/8a47f769c400b0b7d81a8f6f8e09a44a_w200.gif" |
64 |
| - ) |
65 |
| - st.write("Check again in one minute!") |
66 |
| - st.stop() |
67 |
| - else: |
68 |
| - st.write(e) |
69 |
| - st.stop() |
| 92 | + if st.session_state.only_high_leverage_mode_users: |
| 93 | + df = df[df["is_high_leverage"]] |
70 | 94 |
|
71 |
| - res = pd.DataFrame(result["res"]) |
72 |
| - df = pd.DataFrame(result["df"]) |
| 95 | + filtered_df = df[df["leverage"] >= st.session_state.min_leverage].sort_values( |
| 96 | + "leverage", ascending=False |
| 97 | + ) |
73 | 98 |
|
74 |
| - st.write(f"{df.shape[0]} users for scenario") |
75 |
| - st.write(res) |
| 99 | + summary_df = generate_summary_data(filtered_df, mode, perp_market_index) |
| 100 | + slot = result["slot"] |
| 101 | + current_slot = get_current_slot() |
| 102 | + |
| 103 | + st.info( |
| 104 | + f"This data is for slot {slot}, which is now {int(current_slot) - int(slot)} slots old" |
| 105 | + ) |
| 106 | + st.write(f"{df.shape[0]} users") |
| 107 | + st.checkbox( |
| 108 | + "Only show high leverage mode users", key="only_high_leverage_mode_users" |
| 109 | + ) |
| 110 | + st.slider( |
| 111 | + "Filter by minimum leverage", |
| 112 | + 0.0, |
| 113 | + 110.0, |
| 114 | + 0.0, |
| 115 | + key="min_leverage", |
| 116 | + ) |
| 117 | + st.write(summary_df) |
76 | 118 |
|
77 | 119 | tabs = st.tabs(["FULL"] + [x.symbol for x in mainnet_spot_market_configs])
|
78 | 120 |
|
79 |
| - # Add leverage filter to FULL tab |
80 | 121 | with tabs[0]:
|
81 |
| - filtered_df = df[df["leverage"] >= min_leverage].sort_values( |
82 |
| - "leverage", ascending=False |
83 |
| - ) |
| 122 | + if st.session_state.only_high_leverage_mode_users: |
| 123 | + st.write( |
| 124 | + f"There are **{len(filtered_df)}** users with high leverage mode and {st.session_state.min_leverage}x leverage or more" |
| 125 | + ) |
| 126 | + else: |
| 127 | + st.write( |
| 128 | + f"There are **{len(filtered_df)}** users with this **{st.session_state.min_leverage}x** leverage or more" |
| 129 | + ) |
| 130 | + st.write(f"Total USD value: **{filtered_df['net_usd_value'].sum():,.2f}**") |
| 131 | + st.write(f"Total collateral: **{filtered_df['spot_asset'].sum():,.2f}**") |
| 132 | + st.write(f"Total liabilities: **{filtered_df['spot_liability'].sum():,.2f}**") |
84 | 133 | st.dataframe(filtered_df, hide_index=True)
|
85 | 134 |
|
86 | 135 | for idx, tab in enumerate(tabs[1:]):
|
87 |
| - important_cols = [x for x in df.columns if "spot_" + str(idx) in x] |
88 |
| - toshow = df[["spot_asset", "net_usd_value"] + important_cols] |
| 136 | + important_cols = [x for x in filtered_df.columns if "spot_" + str(idx) in x] |
| 137 | + |
| 138 | + toshow = filtered_df[ |
| 139 | + ["user_key", "spot_asset", "net_usd_value"] + important_cols |
| 140 | + ] |
89 | 141 | toshow = toshow[toshow[important_cols].abs().sum(axis=1) != 0].sort_values(
|
90 | 142 | by="spot_" + str(idx) + "_all", ascending=False
|
91 | 143 | )
|
92 |
| - tab.write(f"{ len(toshow)} users with this asset to cover liabilities") |
| 144 | + tab.write( |
| 145 | + f"{len(toshow)} users with this asset to cover liabilities (with {st.session_state.min_leverage}x leverage or more)" |
| 146 | + ) |
93 | 147 | tab.dataframe(toshow, hide_index=True)
|
0 commit comments