-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfleet_dashboard.py
More file actions
276 lines (228 loc) · 8.6 KB
/
Copy pathfleet_dashboard.py
File metadata and controls
276 lines (228 loc) · 8.6 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
#!/usr/bin/env python3
"""
fleet_dashboard.py — Live terminal dashboard for monitoring a LITCOIN mining fleet.
Shows balances, mining status, earnings, staking yields, and fleet totals in real-time.
Requires: pip install rich
Usage:
python fleet_dashboard.py
python fleet_dashboard.py --interval 10
python fleet_dashboard.py --config path/to/config.json
"""
import json
import sys
import uuid
import time
import argparse
from pathlib import Path
from datetime import datetime, timezone, timedelta
try:
from litcoin import Agent
from litcoin.api import APIError
except ImportError:
print("ERROR: litcoin package not installed. Run: pip install litcoin")
sys.exit(1)
try:
from rich.console import Console
from rich.table import Table
from rich.live import Live
from rich.panel import Panel
from rich.text import Text
from rich import box
except ImportError:
print("ERROR: rich package not installed. Run: pip install rich")
sys.exit(1)
def load_config(path="config.json"):
p = Path(path)
if not p.exists():
print(f"ERROR: Config file not found: {path}")
print("Copy config.example.json to config.json and fill in your values.")
sys.exit(1)
with open(p) as f:
return json.load(f)
# Cache agents to avoid re-auth every refresh
_agent_cache = {}
def get_agent(api_key):
if api_key not in _agent_cache:
_agent_cache[api_key] = Agent(api_key)
return _agent_cache[api_key]
def fetch_bot_data(bot_cfg):
"""Fetch all data for a single bot."""
result = {
"name": bot_cfg["name"],
"error": None,
"free_lit": 0, "staked": 0, "total": 0,
"tier": 0, "mining_status": "UNKNOWN",
"earned_today": 0, "daily_cap": 0,
"boost": 0, "daily_yield": 0, "apy": 0,
}
try:
agent = get_agent(bot_cfg["api_key"])
bal = agent.balance()
result["free_lit"] = bal.get("litcoin", 0)
try:
stk = agent.stake_info()
result["staked"] = stk.get("amount", 0)
except Exception:
pass
result["total"] = result["free_lit"] + result["staked"]
try:
result["tier"] = agent.tier()
except Exception:
pass
try:
sy = agent.staking_yield()
result["daily_yield"] = sy.get("dailyYield", 0)
result["apy"] = sy.get("apy", 0)
except Exception:
pass
try:
result["boost"] = agent.mining_boost()
except Exception:
pass
nonce = uuid.uuid4().hex[:32]
try:
ch = agent.api.get_challenge(nonce, agent.auth.token)
result["earned_today"] = ch.get("earnedToday", 0)
result["daily_cap"] = ch.get("dailyCap", 0)
if ch.get("capped"):
result["mining_status"] = "CAPPED"
elif ch.get("poolExhausted"):
result["mining_status"] = "POOL EMPTY"
else:
result["mining_status"] = "MINING"
except APIError as e:
if "Insufficient" in str(getattr(e, "message", e)):
result["mining_status"] = "BLOCKED"
else:
result["mining_status"] = f"ERR"
except Exception:
result["mining_status"] = "ERROR"
except Exception as e:
result["error"] = str(e)[:40]
return result
def format_lit(amount):
if amount >= 1_000_000:
return f"{amount / 1_000_000:.2f}M"
elif amount >= 1_000:
return f"{amount / 1_000:.1f}K"
return f"{amount:,.0f}"
TIER_NAMES = {0: "None", 1: "Spark", 2: "Circuit", 3: "Core", 4: "Architect"}
def build_display(bot_data_list, refresh_count, interval):
"""Build the rich display."""
now = datetime.now()
utc_now = datetime.now(timezone.utc)
# Time until midnight UTC
midnight = utc_now.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)
delta = midnight - utc_now
hrs = int(delta.total_seconds() // 3600)
mins = int((delta.total_seconds() % 3600) // 60)
table = Table(
box=box.ROUNDED,
show_header=True,
header_style="bold white on dark_blue",
border_style="blue",
expand=True,
)
table.add_column("Bot", style="bold", width=10)
table.add_column("Free LIT", justify="right", width=10)
table.add_column("Staked", justify="right", width=10)
table.add_column("Total", justify="right", width=10)
table.add_column("Tier", justify="center", width=10)
table.add_column("Mining", justify="center", width=10)
table.add_column("Earned", justify="right", width=14)
table.add_column("Cap", justify="right", width=8)
t_free = t_staked = t_earned = t_cap = t_yield = 0
mining_count = 0
for d in bot_data_list:
t_free += d["free_lit"]
t_staked += d["staked"]
t_earned += d["earned_today"]
t_cap += d["daily_cap"]
t_yield += d["daily_yield"]
ms = d["mining_status"]
if ms == "MINING":
mining_styled = "[bold green]MINING[/]"
mining_count += 1
elif ms == "CAPPED":
mining_styled = "[bold yellow]CAPPED[/]"
mining_count += 1
elif ms == "BLOCKED":
mining_styled = "[bold red]BLOCKED[/]"
else:
mining_styled = f"[red]{ms}[/]"
tier_text = f"T{d['tier']} {TIER_NAMES.get(d['tier'], '?')}"
if d["daily_cap"] > 0:
pct = min(100, d["earned_today"] / d["daily_cap"] * 100)
earned_text = f"{format_lit(d['earned_today'])} ({pct:.0f}%)"
else:
earned_text = format_lit(d["earned_today"])
if d["error"]:
table.add_row(d["name"], "[red]ERR[/]", "-", "-", "-", f"[red]{d['error'][:20]}[/]", "-", "-")
else:
table.add_row(
d["name"], format_lit(d["free_lit"]), format_lit(d["staked"]),
format_lit(d["total"]), tier_text, mining_styled,
earned_text, format_lit(d["daily_cap"]),
)
# Fleet totals
bot_count = len(bot_data_list)
table.add_section()
table.add_row(
"[bold]FLEET[/]",
f"[bold]{format_lit(t_free)}[/]", f"[bold]{format_lit(t_staked)}[/]",
f"[bold]{format_lit(t_free + t_staked)}[/]", "",
f"[bold]{mining_count}/{bot_count}[/]",
f"[bold]{format_lit(t_earned)}[/]", f"[bold]{format_lit(t_cap)}[/]",
)
# Yield summary
yield_table = Table(box=box.SIMPLE, show_header=True, header_style="bold", expand=True)
yield_table.add_column("Bot", width=10)
yield_table.add_column("Daily Yield", justify="right", width=12)
yield_table.add_column("APY", justify="right", width=8)
yield_table.add_column("Boost", justify="right", width=8)
for d in bot_data_list:
if not d["error"]:
boost_pct = d["boost"] / 100 if d["boost"] else 0
yield_table.add_row(
d["name"],
f"{d['daily_yield']:,.0f} LIT",
f"{d['apy']:.1f}%",
f"{boost_pct:.0f}%" if boost_pct else "-",
)
yield_table.add_section()
yield_table.add_row("[bold]TOTAL[/]", f"[bold]{t_yield:,.0f} LIT[/]", "", "")
header = Text()
header.append("LITCOIN FLEET DASHBOARD", style="bold white")
header.append(f" | {now.strftime('%H:%M:%S')}", style="bold cyan")
header.append(f" | Cap reset in {hrs}h {mins}m", style="bold yellow")
header.append(f" | Refresh #{refresh_count} (every {interval}s)", style="dim")
return Panel(
table,
title=header,
subtitle=f"Daily staking yield: {t_yield:,.0f} LIT",
border_style="bright_blue",
)
def main():
parser = argparse.ArgumentParser(description="LITCOIN fleet dashboard")
parser.add_argument("--config", default="config.json", help="Config file path")
parser.add_argument("--interval", type=int, default=30, help="Refresh interval in seconds")
args = parser.parse_args()
config = load_config(args.config)
bots = [b for b in config.get("bots", []) if b.get("enabled", True)]
if not bots:
print("No enabled bots found in config.")
sys.exit(1)
console = Console()
count = 0
try:
with Live(console=console, refresh_per_second=1, screen=True) as live:
while True:
count += 1
data = [fetch_bot_data(b) for b in bots]
panel = build_display(data, count, args.interval)
live.update(panel)
time.sleep(args.interval)
except KeyboardInterrupt:
console.print("\n[bold]Dashboard stopped.[/]")
if __name__ == "__main__":
main()