-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyze_hyperliquid_wallet.py
More file actions
415 lines (335 loc) · 16.1 KB
/
analyze_hyperliquid_wallet.py
File metadata and controls
415 lines (335 loc) · 16.1 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
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#!/usr/bin/env python3
"""
Hyperliquid Wallet Strategy Analyzer
Analyzes trading patterns and strategies for any Hyperliquid wallet address
"""
import requests
import json
from datetime import datetime, timedelta
from collections import defaultdict, Counter
import statistics
# Configuration
WALLET_ADDRESS = "0x833b99b27dac651d02080f5e220e929df891db06"
API_URL = "https://api.hyperliquid.xyz/info"
class HyperliquidAnalyzer:
def __init__(self, wallet_address):
self.wallet = wallet_address
self.state = None
self.fills = []
self.funding = []
def fetch_data(self):
"""Fetch all necessary data from Hyperliquid API"""
print(f"🔄 Fetching data for wallet: {self.wallet}\n")
# Get current state
self.state = self._api_call({
"type": "clearinghouseState",
"user": self.wallet
})
# Get trade history
self.fills = self._api_call({
"type": "userFills",
"user": self.wallet
})
# Get funding history
self.funding = self._api_call({
"type": "userFunding",
"user": self.wallet
})
print("✅ Data fetched successfully\n")
def _api_call(self, payload):
"""Make API call to Hyperliquid"""
try:
response = requests.post(API_URL, json=payload, timeout=10)
return response.json()
except Exception as e:
print(f"❌ Error fetching data: {e}")
return None
def analyze_account_state(self):
"""Analyze current account state"""
print("="*80)
print("📊 CURRENT ACCOUNT STATE")
print("="*80)
if not self.state or "marginSummary" not in self.state:
print("❌ No account data available\n")
return
margin = self.state["marginSummary"]
account_value = float(margin.get("accountValue", 0))
total_position = float(margin.get("totalNtlPos", 0))
raw_usd = float(margin.get("totalRawUsd", 0))
margin_used = float(margin.get("totalMarginUsed", 0))
print(f"\n💰 Account Value: ${account_value:,.2f}")
print(f"📈 Total Position Notional: ${total_position:,.2f}")
print(f"💵 Raw USD Balance: ${raw_usd:,.2f}")
print(f"🔒 Margin Used: ${margin_used:,.2f}")
if account_value > 0:
effective_leverage = total_position / account_value
margin_usage = (margin_used / account_value) * 100
print(f"⚡ Effective Leverage: {effective_leverage:.2f}x")
print(f"📊 Margin Usage: {margin_usage:.1f}%")
# Risk assessment
print(f"\n🎯 Risk Assessment:")
if effective_leverage < 3:
print(" ✅ Conservative leverage (<3x)")
elif effective_leverage < 10:
print(" ⚠️ Moderate leverage (3-10x)")
else:
print(" 🚨 High leverage (>10x) - Risky!")
# Analyze open positions
positions = self.state.get("assetPositions", [])
if positions:
print(f"\n🎯 OPEN POSITIONS ({len(positions)})")
print("-"*80)
total_unrealized = 0
longs = 0
shorts = 0
for pos in positions:
coin = pos["position"]["coin"]
size = float(pos["position"]["szi"])
entry = float(pos["position"]["entryPx"])
leverage = float(pos["position"]["leverage"]["value"])
pnl = float(pos["position"]["unrealizedPnl"])
roe = float(pos["position"]["returnOnEquity"]) * 100
liquidation = pos["position"].get("liquidationPx")
margin_used_pos = float(pos["position"]["marginUsed"])
total_unrealized += pnl
if size > 0:
side = "LONG 📈"
longs += 1
else:
side = "SHORT 📉"
shorts += 1
print(f"\n{coin} {side}")
print(f" Size: {abs(size):.4f} | Entry: ${entry:,.2f} | Leverage: {leverage:.1f}x")
print(f" Margin: ${margin_used_pos:,.2f} | PnL: ${pnl:,.2f} ({roe:+.2f}%)")
if liquidation:
liq_price = float(liquidation)
print(f" Liquidation: ${liq_price:,.2f}")
# Calculate distance to liquidation
current_price = entry + (pnl / abs(size)) # Approximate
if size > 0: # Long position
liq_distance = ((liq_price / current_price) - 1) * 100
else: # Short position
liq_distance = ((current_price / liq_price) - 1) * 100
if abs(liq_distance) < 10:
print(f" ⚠️ WARNING: Only {abs(liq_distance):.1f}% from liquidation!")
print(f"\n📊 Position Summary:")
print(f" Total Unrealized PnL: ${total_unrealized:,.2f}")
print(f" Long Positions: {longs} | Short Positions: {shorts}")
if longs + shorts > 0:
long_bias = (longs / (longs + shorts)) * 100
print(f" Long Bias: {long_bias:.0f}% | Short Bias: {100-long_bias:.0f}%")
if long_bias > 70:
print(" 📈 Heavily LONG biased - Bullish outlook")
elif long_bias < 30:
print(" 📉 Heavily SHORT biased - Bearish outlook")
else:
print(" ⚖️ Balanced positioning - Market neutral approach")
else:
print("\n❌ No open positions")
print("\n")
def analyze_trading_patterns(self):
"""Analyze trading history to identify patterns"""
print("="*80)
print("📈 TRADING PATTERN ANALYSIS")
print("="*80)
if not self.fills or len(self.fills) == 0:
print("❌ No trading history available\n")
return
print(f"\nTotal trades analyzed: {len(self.fills)}")
# Time analysis
now = datetime.now()
recent_trades = [f for f in self.fills if
datetime.fromtimestamp(f["time"]/1000) > now - timedelta(days=30)]
print(f"Trades in last 30 days: {len(recent_trades)}")
if len(recent_trades) > 0:
avg_trades_per_day = len(recent_trades) / 30
print(f"Average trades per day: {avg_trades_per_day:.1f}")
# Classify trading frequency
if avg_trades_per_day > 20:
print("🎯 Trading Style: SCALPER (>20 trades/day)")
elif avg_trades_per_day > 5:
print("🎯 Trading Style: DAY TRADER (5-20 trades/day)")
elif avg_trades_per_day > 1:
print("🎯 Trading Style: SWING TRADER (1-5 trades/day)")
else:
print("🎯 Trading Style: POSITION TRADER (<1 trade/day)")
# Asset preference
coins = [f["coin"] for f in self.fills[:200]] # Last 200 trades
coin_counts = Counter(coins)
print(f"\n📊 Most Traded Assets:")
for coin, count in coin_counts.most_common(10):
pct = (count / len(coins[:200])) * 100
print(f" {coin}: {count} trades ({pct:.1f}%)")
# Concentration analysis
top_3_pct = sum(c for _, c in coin_counts.most_common(3)) / len(coins[:200]) * 100
print(f"\n Concentration in top 3 assets: {top_3_pct:.1f}%")
if top_3_pct > 70:
print(" 🎯 Specialized trader - Focuses on few assets")
elif top_3_pct > 40:
print(" ⚖️ Balanced trader - Some diversification")
else:
print(" 🌐 Diversified trader - Trades many assets")
# PnL analysis
closed_trades = [f for f in self.fills if "closedPnl" in f and f["closedPnl"] != "0.0"]
if len(closed_trades) > 0:
print(f"\n💰 PNL ANALYSIS")
print("-"*80)
pnls = [float(f["closedPnl"]) for f in closed_trades]
winners = [p for p in pnls if p > 0]
losers = [p for p in pnls if p < 0]
win_rate = (len(winners) / len(pnls)) * 100
avg_win = statistics.mean(winners) if winners else 0
avg_loss = statistics.mean(losers) if losers else 0
total_pnl = sum(pnls)
print(f"\nTotal Closed Trades: {len(closed_trades)}")
print(f"Winners: {len(winners)} | Losers: {len(losers)}")
print(f"Win Rate: {win_rate:.1f}%")
print(f"Average Win: ${avg_win:.2f}")
print(f"Average Loss: ${avg_loss:.2f}")
print(f"Total Realized PnL: ${total_pnl:.2f}")
if avg_loss != 0:
win_loss_ratio = abs(avg_win / avg_loss)
profit_factor = abs(sum(winners) / sum(losers)) if sum(losers) != 0 else 0
print(f"Win/Loss Ratio: {win_loss_ratio:.2f}:1")
print(f"Profit Factor: {profit_factor:.2f}")
# Strategy classification
print(f"\n🎯 Strategy Classification:")
if win_rate > 60 and win_loss_ratio < 2:
print(" 📊 HIGH WIN RATE / SMALL WINS")
print(" → Likely: Mean Reversion or Scalping strategy")
print(" → Risk: Large occasional losses")
elif win_rate < 50 and win_loss_ratio > 2:
print(" 📈 LOW WIN RATE / LARGE WINS")
print(" → Likely: Trend Following strategy")
print(" → Positive: Lets winners run, cuts losers")
elif win_rate > 50 and win_loss_ratio > 2:
print(" 🌟 HIGH WIN RATE / LARGE WINS")
print(" → Excellent trader or cherry-picking trades")
else:
print(" ⚠️ LOW WIN RATE / SMALL WINS")
print(" → Warning: Unsustainable strategy")
# Profit factor assessment
print(f"\n💯 Performance Grade:")
if profit_factor > 2.0:
print(" ⭐⭐⭐ Excellent (PF > 2.0)")
elif profit_factor > 1.5:
print(" ⭐⭐ Good (PF 1.5-2.0)")
elif profit_factor > 1.0:
print(" ⭐ Profitable (PF 1.0-1.5)")
else:
print(" ❌ Losing Money (PF < 1.0)")
# Long/Short bias in trading
longs = sum(1 for f in self.fills[:200] if f["side"] == "B")
shorts = sum(1 for f in self.fills[:200] if f["side"] == "A")
if longs + shorts > 0:
long_pct = (longs / (longs + shorts)) * 100
print(f"\n📊 Trading Direction Bias:")
print(f" Long entries: {longs} ({long_pct:.1f}%)")
print(f" Short entries: {shorts} ({100-long_pct:.1f}%)")
if long_pct > 65:
print(" 📈 Primarily trades LONG - Bullish bias")
elif long_pct < 35:
print(" 📉 Primarily trades SHORT - Bearish bias")
else:
print(" ⚖️ Balanced long/short - Direction agnostic")
print("\n")
def analyze_funding_patterns(self):
"""Analyze funding payment patterns"""
print("="*80)
print("💸 FUNDING PAYMENT ANALYSIS")
print("="*80)
if not self.funding or len(self.funding) == 0:
print("❌ No funding history available\n")
return
# Calculate total funding paid/received
recent_funding = self.funding[:100] # Last 100 funding payments
total = sum(float(f.get("usdc", 0)) for f in recent_funding)
print(f"\nLast 100 funding payments: ${total:.2f}")
if total < -50:
print("⚠️ Paying significant funding - Consider position timing")
elif total > 50:
print("✅ Receiving funding - Good position timing or basis trading")
else:
print("✅ Neutral funding impact")
# Check for funding sensitivity
by_coin = defaultdict(float)
for f in recent_funding:
coin = f.get("coin", "")
amount = float(f.get("usdc", 0))
by_coin[coin] += amount
print(f"\n📊 Funding by Asset:")
for coin, amount in sorted(by_coin.items(), key=lambda x: abs(x[1]), reverse=True)[:5]:
print(f" {coin}: ${amount:.2f}")
print("\n")
def generate_summary(self):
"""Generate overall trading summary"""
print("="*80)
print("📝 OVERALL STRATEGY SUMMARY")
print("="*80)
if not self.state:
print("❌ Insufficient data for summary\n")
return
print("\n🎯 Key Takeaways:")
# Account size classification
if "marginSummary" in self.state:
account_value = float(self.state["marginSummary"].get("accountValue", 0))
if account_value > 1000000:
print(" 💰 WHALE (>$1M account)")
elif account_value > 100000:
print(" 🐋 DOLPHIN ($100K-$1M account)")
elif account_value > 10000:
print(" 🐟 FISH ($10K-$100K account)")
else:
print(" 🦐 SHRIMP (<$10K account)")
# Risk profile
positions = self.state.get("assetPositions", [])
if positions and "marginSummary" in self.state:
total_pos = float(self.state["marginSummary"].get("totalNtlPos", 0))
account_val = float(self.state["marginSummary"].get("accountValue", 1))
leverage = total_pos / account_val if account_val > 0 else 0
print(f"\n ⚡ Risk Profile:")
if leverage < 2:
print(" ✅ CONSERVATIVE - Low leverage, low risk")
elif leverage < 5:
print(" 📊 MODERATE - Balanced risk/reward")
elif leverage < 10:
print(" ⚠️ AGGRESSIVE - Higher risk appetite")
else:
print(" 🚨 VERY AGGRESSIVE - High risk of liquidation")
# Strategy recommendation
print(f"\n 🎯 Strategy Type:")
if self.fills and len(self.fills) > 100:
# Estimate hold time from recent trades
recent = self.fills[:100]
coins_traded = len(set(f["coin"] for f in recent))
if coins_traded < 3:
print(" → SPECIALIZED: Focuses on few assets")
elif coins_traded < 10:
print(" → SELECTIVE: Trades moderate variety")
else:
print(" → DIVERSIFIED: Trades many different assets")
print("\n")
print("="*80)
print("Analysis complete!")
print("="*80)
print("\n")
def main():
"""Main execution function"""
print("\n")
print("="*80)
print("HYPERLIQUID TRADING STRATEGY ANALYZER")
print("="*80)
print("\n")
analyzer = HyperliquidAnalyzer(WALLET_ADDRESS)
# Fetch all data
analyzer.fetch_data()
# Run all analyses
analyzer.analyze_account_state()
analyzer.analyze_trading_patterns()
analyzer.analyze_funding_patterns()
analyzer.generate_summary()
print("💡 TIP: Re-run this script periodically to track changes over time")
print(f" Monitor this wallet at: https://app.coinmarketman.com/hypertracker/wallet/{WALLET_ADDRESS}")
print("\n")
if __name__ == "__main__":
main()