|
| 1 | +from hydradx.model.indexer_utils import query_indexer, get_blocks_at_timestamps, get_asset_info_by_ids |
| 2 | +import datetime |
| 3 | +from matplotlib import pyplot as plt |
| 4 | +from pathlib import Path |
| 5 | +import streamlit as st |
| 6 | +import json |
| 7 | +import math |
| 8 | + |
| 9 | +LIQUIDITY_GRAPH_TARGET_POINTS = 1000 |
| 10 | + |
| 11 | + |
| 12 | +def _sort_key(value): |
| 13 | + try: |
| 14 | + return int(value) |
| 15 | + except (TypeError, ValueError): |
| 16 | + return value |
| 17 | + |
| 18 | + |
| 19 | +def compress_liquidity_series(liquidity_series: dict, target_points: int) -> dict: |
| 20 | + if target_points <= 0: |
| 21 | + raise ValueError("target_points must be > 0") |
| 22 | + if len(liquidity_series) <= target_points: |
| 23 | + return dict(liquidity_series) |
| 24 | + |
| 25 | + items = sorted(liquidity_series.items(), key=lambda item: _sort_key(item[0])) |
| 26 | + total = len(items) |
| 27 | + batch_size = max(1, math.ceil(total / target_points)) |
| 28 | + compressed = {} |
| 29 | + |
| 30 | + for idx in range(0, total, batch_size): |
| 31 | + batch = items[idx: idx + batch_size] |
| 32 | + first_key = batch[0][0] |
| 33 | + avg_value = sum(value for _, value in batch) / len(batch) |
| 34 | + compressed[first_key] = avg_value |
| 35 | + |
| 36 | + last_key, last_value = items[-1] |
| 37 | + compressed[last_key] = last_value |
| 38 | + return compressed |
| 39 | + |
| 40 | + |
| 41 | +def _to_int_keyed(series: dict) -> dict: |
| 42 | + return {int(k): v for k, v in series.items()} |
| 43 | + |
| 44 | + |
| 45 | +def get_liquidity_over_time(): |
| 46 | + dates = [ |
| 47 | + datetime.datetime(2025, 11, day=i + 1) for i in range(30) |
| 48 | + ] + [ |
| 49 | + datetime.datetime(year=2025, month=12, day=i + 1) for i in range(31) |
| 50 | + ] |
| 51 | + block_map = get_blocks_at_timestamps(dates) |
| 52 | + ordered_blocks = sorted(block_map.items(), key=lambda item: item[0]) |
| 53 | + ordered_dates = [item[0] for item in ordered_blocks] |
| 54 | + block_numbers = [item[1] for item in ordered_blocks] |
| 55 | + liquidity = {} |
| 56 | + |
| 57 | + if not Path.exists(Path(__file__).parent / 'cached data' / 'liquidity.json'): |
| 58 | + for i, start_block in enumerate(block_numbers[:-1]): |
| 59 | + date = dates[i] |
| 60 | + print(f"scanning {date}") |
| 61 | + blocks_per_query = 1000 |
| 62 | + end_block = block_numbers[1 + 1] |
| 63 | + for block in range(start_block, end_block, blocks_per_query): |
| 64 | + query_start = block |
| 65 | + query_end = min(block + blocks_per_query, end_block) |
| 66 | + query = f""" |
| 67 | + query AssetBalancesByBlockHeight {{ |
| 68 | + omnipoolAssetHistoricalData( |
| 69 | + filter: {{paraBlockHeight: {{greaterThanOrEqualTo: {query_start}, lessThan: {query_end}}}}} |
| 70 | + ) {{ |
| 71 | + nodes |
| 72 | + {{ |
| 73 | + freeBalance |
| 74 | + assetId |
| 75 | + paraBlockHeight |
| 76 | + }} |
| 77 | + }} |
| 78 | + }} |
| 79 | + """ |
| 80 | + |
| 81 | + results = query_indexer("https://galacticcouncil.squids.live/hydration-pools:unified-prod/api/graphql", query) |
| 82 | + for result in results["data"]["omnipoolAssetHistoricalData"]["nodes"]: |
| 83 | + asset_id = result["assetId"] |
| 84 | + free_balance = int(result["freeBalance"]) |
| 85 | + result_block = int(result["paraBlockHeight"]) |
| 86 | + if asset_id not in liquidity: |
| 87 | + liquidity[asset_id] = {} |
| 88 | + liquidity[asset_id][result_block] = free_balance |
| 89 | + |
| 90 | + with open (Path(__file__).parent / 'cached data' / 'liquidity.json', 'w') as f: |
| 91 | + json.dump(liquidity, f) |
| 92 | + else: |
| 93 | + with open (Path(__file__).parent / 'cached data' / 'liquidity.json', 'r') as f: |
| 94 | + liquidity = json.load(f) |
| 95 | + |
| 96 | + asset_names = {tkn.id: tkn.unique_id for tkn in get_asset_info_by_ids(list(liquidity.keys())).values()} |
| 97 | + graph_liquidity = {} |
| 98 | + for tkn in liquidity: |
| 99 | + raw_series = _to_int_keyed(liquidity[tkn]) |
| 100 | + if len(raw_series) > LIQUIDITY_GRAPH_TARGET_POINTS: |
| 101 | + graph_liquidity[tkn] = compress_liquidity_series( |
| 102 | + raw_series, |
| 103 | + target_points=LIQUIDITY_GRAPH_TARGET_POINTS, |
| 104 | + ) |
| 105 | + else: |
| 106 | + graph_liquidity[tkn] = dict(raw_series) |
| 107 | + graph_liquidity[tkn][block_numbers[0]] = list(raw_series.values())[0] |
| 108 | + graph_liquidity[tkn][block_numbers[-1]] = list(raw_series.values())[-1] |
| 109 | + sorted_items = sorted(graph_liquidity[tkn].items(), key=lambda item: _sort_key(item[0])) |
| 110 | + fig, ax = plt.subplots(figsize=(12, 4)) |
| 111 | + ax.plot([item[0] for item in sorted_items], [item[1] for item in sorted_items]) |
| 112 | + ax.set_title(f"Liquidity of {asset_names[tkn]} in Omnipool") |
| 113 | + ax.set_xlabel("Date") |
| 114 | + ax.set_ylabel("Free Balance") |
| 115 | + ax.set_xticks(block_numbers) |
| 116 | + ax.set_xticklabels([date.strftime('%Y-%m-%d') for date in ordered_dates]) |
| 117 | + ax.tick_params(axis="x", labelsize=8) |
| 118 | + |
| 119 | + plt.tight_layout() |
| 120 | + plt.show() |
| 121 | + st.pyplot(fig) |
| 122 | + pass |
| 123 | + |
0 commit comments