deanpowers commited on
Commit
e61aaca
·
1 Parent(s): 63a2715

Add /bot/<id> detail page with per-coin breakdown

Browse files
Files changed (3) hide show
  1. bybit_pnl_snapshot.py +46 -0
  2. local_app.py +53 -0
  3. templates/bot_detail.html +127 -0
bybit_pnl_snapshot.py CHANGED
@@ -10,6 +10,23 @@ import requests
10
 
11
  API_KEY = os.environ.get("BYBIT_KEY", "")
12
  API_SECRET = os.environ.get("BYBIT_SECRET", "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  BOT_ID = "638623562483108573"
14
  BUCKET = "portfolio-agent-data-388170800364"
15
 
@@ -61,8 +78,37 @@ snap = {
61
  "total_position_value": detail.get("total_position_value", ""),
62
  "run_time_duration": detail.get("run_time_duration", ""),
63
  "updated_at": int(time.time()),
 
64
  }
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  local_path = "/tmp/bybit_pnl.json"
67
  with open(local_path, "w") as f:
68
  json.dump(snap, f, indent=2)
 
10
 
11
  API_KEY = os.environ.get("BYBIT_KEY", "")
12
  API_SECRET = os.environ.get("BYBIT_SECRET", "")
13
+
14
+ def fetch_mark_price(symbol):
15
+ """Fetch current mark price from Bybit public ticker (no auth)."""
16
+ try:
17
+ r = requests.get(
18
+ "https://api.bybit.com/v5/market/tickers",
19
+ params={"category": "linear", "symbol": symbol},
20
+ timeout=10
21
+ )
22
+ d = r.json()
23
+ lst = d.get("result", {}).get("list", [])
24
+ if lst:
25
+ return float(lst[0].get("markPrice", 0))
26
+ except Exception as e:
27
+ print("mark price fetch failed for " + symbol + ": " + str(e))
28
+ return None
29
+
30
  BOT_ID = "638623562483108573"
31
  BUCKET = "portfolio-agent-data-388170800364"
32
 
 
78
  "total_position_value": detail.get("total_position_value", ""),
79
  "run_time_duration": detail.get("run_time_duration", ""),
80
  "updated_at": int(time.time()),
81
+ "coins": [],
82
  }
83
 
84
+ # Build per-coin data
85
+ symbol_settings = detail.get("symbol_settings", [])
86
+ total_pos_value = float(detail.get("total_position_value", 0) or 0)
87
+
88
+ for ss in symbol_settings:
89
+ base = ss.get("base_token", "")
90
+ if not base:
91
+ continue
92
+ symbol = base + "USDT"
93
+ weight = float(ss.get("target_position_percent", 0) or 0)
94
+ mark = fetch_mark_price(symbol)
95
+ coin_value = total_pos_value * weight if total_pos_value else None
96
+ size = (coin_value / mark) if (coin_value and mark) else None
97
+ snap["coins"].append({
98
+ "coin": base,
99
+ "symbol": symbol,
100
+ "market": "Future",
101
+ "weight": weight,
102
+ "mark_price": mark,
103
+ "value_usd": round(coin_value, 4) if coin_value else None,
104
+ "size": round(size, 8) if size else None,
105
+ "entry_price": None, # filled in only if we can detect it
106
+ "pnl": None,
107
+ "pnl_per": None,
108
+ })
109
+
110
+ print("Fetched mark prices for " + str(len(snap["coins"])) + " coins")
111
+
112
  local_path = "/tmp/bybit_pnl.json"
113
  with open(local_path, "w") as f:
114
  json.dump(snap, f, indent=2)
local_app.py CHANGED
@@ -114,7 +114,9 @@ PUBLIC_PATHS_EXACT = (
114
  PUBLIC_PATHS_PREFIX = (
115
  '/api/whoami',
116
  '/api/bot-history',
 
117
  '/dart-performance',
 
118
  '/api/win-rate',
119
  '/api/bot-pnl',
120
  '/api/debug/apis',
@@ -1113,10 +1115,61 @@ def bot_history_api():
1113
  resp.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
1114
  return resp
1115
 
 
 
 
 
1116
  @app.route('/dart-performance')
1117
  def dart_performance_page():
1118
  return render_template('dart_performance.html')
1119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1120
  @app.route('/api/whoami')
1121
  def whoami_api():
1122
  u = current_user()
 
114
  PUBLIC_PATHS_PREFIX = (
115
  '/api/whoami',
116
  '/api/bot-history',
117
+ '/api/bot/',
118
  '/dart-performance',
119
+ '/bot/',
120
  '/api/win-rate',
121
  '/api/bot-pnl',
122
  '/api/debug/apis',
 
1115
  resp.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
1116
  return resp
1117
 
1118
+ @app.route('/bot/<bot_id>')
1119
+ def bot_detail_page(bot_id):
1120
+ return render_template('bot_detail.html')
1121
+
1122
  @app.route('/dart-performance')
1123
  def dart_performance_page():
1124
  return render_template('dart_performance.html')
1125
 
1126
+ @app.route('/api/bot/<bot_id>')
1127
+ def bot_detail_api(bot_id):
1128
+ """Return bot summary + per-coin breakdown."""
1129
+ from modules.storage import load_json
1130
+
1131
+ latest = load_json("bybit_pnl.json", default=None)
1132
+ history = load_json("bybit_bots_history.json", default=None) or {"bots": []}
1133
+
1134
+ if not latest or str(latest.get("bot_id", "")) != str(bot_id):
1135
+ # Look in history
1136
+ bot_meta = None
1137
+ for b in history.get("bots", []):
1138
+ if str(b.get("bot_id", "")) == str(bot_id):
1139
+ bot_meta = b
1140
+ break
1141
+ if not bot_meta:
1142
+ return jsonify({"status": "error", "message": "bot not found"}), 404
1143
+ return jsonify({
1144
+ "status": "ok",
1145
+ "bot_id": bot_id,
1146
+ "bot_name": bot_meta.get("bot_name", ""),
1147
+ "status_text": bot_meta.get("status", ""),
1148
+ "investment": bot_meta.get("investment", 0),
1149
+ "duration_seconds": bot_meta.get("duration_seconds", 0),
1150
+ "pnl": bot_meta.get("final_pnl", 0),
1151
+ "pnl_per": round(float(bot_meta.get("final_pnl_per", 0)) * 100, 2),
1152
+ "coins": [],
1153
+ })
1154
+
1155
+ coins = latest.get("coins", [])
1156
+
1157
+ resp = jsonify({
1158
+ "status": "ok",
1159
+ "bot_id": latest.get("bot_id"),
1160
+ "bot_name": latest.get("bot_name"),
1161
+ "status_text": "running",
1162
+ "leverage": latest.get("leverage"),
1163
+ "investment": float(latest.get("total_margin", 0) or 0),
1164
+ "equity": float(latest.get("equity", 0) or 0),
1165
+ "pnl": float(latest.get("total_pnl", 0) or 0),
1166
+ "pnl_per": round(float(latest.get("total_pnl_per", 0) or 0) * 100, 2),
1167
+ "duration_seconds": int(latest.get("run_time_duration", 0) or 0),
1168
+ "coins": coins,
1169
+ })
1170
+ resp.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
1171
+ return resp
1172
+
1173
  @app.route('/api/whoami')
1174
  def whoami_api():
1175
  u = current_user()
templates/bot_detail.html ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Bot Detail — Blind Monkeys</title>
7
+ <link rel="stylesheet" href="/css/nav.css">
8
+ <style>
9
+ body { background: #0d1117; color: #e6edf3; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; margin: 0; }
10
+ .wrap { max-width: 1100px; margin: 40px auto; padding: 0 20px; }
11
+ h1 { color: #f0b90b; font-size: 24px; margin: 0 0 4px; }
12
+ .bot-id { font-family: 'SF Mono', Monaco, monospace; font-size: 13px; color: #8b949e; margin-bottom: 16px; }
13
+ .meta { display: flex; gap: 24px; flex-wrap: wrap; margin: 16px 0 24px; padding: 16px; background: #1e2329; border-radius: 12px; border-left: 4px solid #f0b90b; }
14
+ .meta-item { display: flex; flex-direction: column; }
15
+ .meta-label { font-size: 11px; color: #8b949e; text-transform: uppercase; letter-spacing: 0.5px; }
16
+ .meta-value { font-size: 16px; font-weight: 600; font-family: 'SF Mono', Monaco, monospace; margin-top: 4px; }
17
+ table { width: 100%; border-collapse: collapse; background: #1e2329; border-radius: 12px; overflow: hidden; }
18
+ th { background: #0d1117; color: #f0b90b; padding: 14px 16px; text-align: left; font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; font-weight: 700; border-bottom: 1px solid #30363d; }
19
+ td { padding: 14px 16px; border-bottom: 1px solid #21262d; font-size: 14px; }
20
+ tr:last-child td { border-bottom: none; }
21
+ .num { font-family: 'SF Mono', Monaco, monospace; text-align: right; }
22
+ .positive { color: #4ade80; }
23
+ .negative { color: #f87171; }
24
+ .neutral { color: #8b949e; }
25
+ .totals-row { background: #0d1117; border-top: 2px solid #f0b90b; }
26
+ .totals-row td { font-weight: 700; color: #f0b90b; }
27
+ .back { display: inline-block; margin-bottom: 20px; color: #f0b90b; text-decoration: none; font-size: 14px; }
28
+ .empty { padding: 40px; text-align: center; color: #8b949e; background: #1e2329; border-radius: 12px; }
29
+ </style>
30
+ </head>
31
+ <body>
32
+ <div class="wrap">
33
+ <a href="/dart-performance" class="back">← Back to Dart Performance</a>
34
+ <h1 id="bot-name">Loading…</h1>
35
+ <div class="bot-id" id="bot-id-display"></div>
36
+
37
+ <div class="meta" id="meta-row" style="display: none;">
38
+ <div class="meta-item"><span class="meta-label">Investment</span><span class="meta-value" id="meta-investment">—</span></div>
39
+ <div class="meta-item"><span class="meta-label">Equity</span><span class="meta-value" id="meta-equity">—</span></div>
40
+ <div class="meta-item"><span class="meta-label">Duration</span><span class="meta-value" id="meta-duration">—</span></div>
41
+ <div class="meta-item"><span class="meta-label">Net P/L</span><span class="meta-value" id="meta-pnl">—</span></div>
42
+ </div>
43
+
44
+ <div id="content"><div class="empty">Loading…</div></div>
45
+ </div>
46
+
47
+ <script>
48
+ function fmtPrice(p) {
49
+ if (p == null || p === undefined) return '—';
50
+ return '$' + parseFloat(p).toFixed(p >= 100 ? 2 : 4);
51
+ }
52
+ function fmtPct(v) {
53
+ if (v == null || v === undefined) return '—';
54
+ var sign = v >= 0 ? '+' : '';
55
+ return sign + parseFloat(v).toFixed(2) + '%';
56
+ }
57
+ function fmtUSD(v) {
58
+ if (v == null || v === undefined) return '—';
59
+ var sign = v >= 0 ? '+' : '-';
60
+ return sign + '$' + Math.abs(v).toFixed(2);
61
+ }
62
+ function cls(v) {
63
+ if (v == null || v === undefined) return 'neutral';
64
+ if (v > 0) return 'positive';
65
+ if (v < 0) return 'negative';
66
+ return 'neutral';
67
+ }
68
+ function fmtDuration(seconds) {
69
+ var hours = seconds / 3600.0;
70
+ return hours.toFixed(2) + ' hrs';
71
+ }
72
+
73
+ // Extract bot_id from URL: /bot/12345 → "12345"
74
+ var parts = window.location.pathname.split('/').filter(Boolean);
75
+ var botId = parts[parts.length - 1];
76
+
77
+ fetch('/api/bot/' + botId + '?_=' + Date.now(), {cache: 'no-store'})
78
+ .then(function(r){ return r.json(); })
79
+ .then(function(d) {
80
+ if (!d || d.status !== 'ok') {
81
+ document.getElementById('content').innerHTML = '<div class="empty">Bot not found.</div>';
82
+ document.getElementById('bot-name').textContent = 'Bot not found';
83
+ return;
84
+ }
85
+ document.getElementById('bot-name').textContent = '🎯 ' + (d.bot_name || 'Unnamed Bot');
86
+ document.getElementById('bot-id-display').textContent = 'ID ' + d.bot_id + ' · ' + (d.status_text || '');
87
+ document.getElementById('meta-row').style.display = 'flex';
88
+ document.getElementById('meta-investment').textContent = '$' + (d.investment || 0).toFixed(2);
89
+ document.getElementById('meta-equity').textContent = '$' + (d.equity || 0).toFixed(2);
90
+ document.getElementById('meta-duration').textContent = fmtDuration(d.duration_seconds || 0);
91
+ var pnlEl = document.getElementById('meta-pnl');
92
+ pnlEl.textContent = fmtUSD(d.pnl) + ' (' + fmtPct(d.pnl_per) + ')';
93
+ pnlEl.className = 'meta-value ' + cls(d.pnl);
94
+
95
+ var coins = d.coins || [];
96
+ if (coins.length === 0) {
97
+ document.getElementById('content').innerHTML = '<div class="empty">No per-coin data available for this bot.</div>';
98
+ return;
99
+ }
100
+ var html = '<table><thead><tr>';
101
+ html += '<th>Coin Name</th><th>Market</th><th class="num">Entry Price</th><th class="num">Exit Price</th><th class="num">Net P/L %</th><th class="num">Cumulative P/L</th>';
102
+ html += '</tr></thead><tbody>';
103
+
104
+ var totalPnl = 0;
105
+ coins.forEach(function(c) {
106
+ html += '<tr>';
107
+ html += '<td><strong>' + (c.coin || '?') + '</strong></td>';
108
+ html += '<td>' + (c.market || 'Future') + '</td>';
109
+ html += '<td class="num">' + fmtPrice(c.entry_price) + '</td>';
110
+ html += '<td class="num">' + fmtPrice(c.mark_price) + '</td>';
111
+ html += '<td class="num ' + cls(c.pnl_per) + '">' + fmtPct(c.pnl_per) + '</td>';
112
+ html += '<td class="num ' + cls(c.pnl) + '">' + fmtUSD(c.pnl) + '</td>';
113
+ html += '</tr>';
114
+ if (c.pnl) totalPnl += c.pnl;
115
+ });
116
+
117
+ html += '<tr class="totals-row"><td>TOTAL</td><td>—</td><td class="num">—</td><td class="num">—</td><td class="num">—</td><td class="num ' + cls(totalPnl) + '">' + fmtUSD(totalPnl) + '</td></tr>';
118
+ html += '</tbody></table>';
119
+ document.getElementById('content').innerHTML = html;
120
+ })
121
+ .catch(function() {
122
+ document.getElementById('content').innerHTML = '<div class="empty">Error loading bot.</div>';
123
+ });
124
+ </script>
125
+ <script src="/css/nav.js"></script>
126
+ </body>
127
+ </html>