-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathterminal_dashboard.py
More file actions
194 lines (164 loc) · 6.53 KB
/
Copy pathterminal_dashboard.py
File metadata and controls
194 lines (164 loc) · 6.53 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
#!/usr/bin/env python3
"""
terminal_dashboard.py — Live terminal dashboard for SignalScanner.
Shows:
- Market Pulse banner (BTC dominance, trend, decorrelation count)
- Per-pair table with full indicator state + BTC correlation
Refreshes every 10s. Ctrl-C to exit.
"""
from __future__ import annotations
import json
import sqlite3
import time
from datetime import datetime
from pathlib import Path
from rich.console import Console, Group
from rich.live import Live
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from rich import box
BASE_DIR = Path(__file__).parent.resolve()
DB_PATH = BASE_DIR / "state.sqlite"
REFRESH_SECONDS = 10
def fetch_signals():
if not DB_PATH.exists():
return [], {}, {}
with sqlite3.connect(DB_PATH) as conn:
conn.row_factory = sqlite3.Row
signals = conn.execute("""
SELECT s.*
FROM signals s
INNER JOIN (
SELECT pair, MAX(timestamp_utc) AS max_ts
FROM signals GROUP BY pair
) latest ON s.pair = latest.pair AND s.timestamp_utc = latest.max_ts
ORDER BY s.rank_24h ASC
""").fetchall()
last_run = conn.execute(
"SELECT * FROM scanner_runs ORDER BY id DESC LIMIT 1"
).fetchone()
pulse = conn.execute(
"SELECT * FROM market_pulse ORDER BY timestamp_utc DESC LIMIT 1"
).fetchone()
pulse_dict = dict(pulse) if pulse else {}
if pulse_dict:
try:
pulse_dict["decorrelation_events"] = json.loads(
pulse_dict.get("decorrelation_events_json") or "[]"
)
except Exception:
pulse_dict["decorrelation_events"] = []
return [dict(s) for s in signals], dict(last_run) if last_run else {}, pulse_dict
def color_rsi(rsi):
if rsi is None:
return Text("-", style="dim")
if rsi < 25:
return Text(f"{rsi:.0f}", style="bold green")
if rsi > 75:
return Text(f"{rsi:.0f}", style="bold red")
return Text(f"{rsi:.0f}", style="white")
def color_change(pct):
if pct is None:
return Text("-")
color = "green" if pct >= 0 else "red"
return Text(f"{pct:+.2f}%", style=color)
def color_alignment(val):
colors = {"bullish": "green", "bearish": "red", "mixed": "yellow"}
return Text(val or "-", style=colors.get(val, "white"))
def color_correlation(corr):
if corr is None:
return Text("-", style="dim")
if abs(corr) > 0.8:
return Text(f"{corr:+.2f}", style="bold white") # strong
if abs(corr) > 0.5:
return Text(f"{corr:+.2f}", style="white")
if abs(corr) < 0.3:
return Text(f"{corr:+.2f}", style="yellow") # decorrelated
return Text(f"{corr:+.2f}", style="dim white")
def build_table(signals: list[dict]) -> Table:
table = Table(
title="SignalScanner — live indicator snapshot",
box=box.SIMPLE_HEAD,
expand=True,
pad_edge=False,
header_style="bold cyan",
)
table.add_column("Pair", style="bold white", no_wrap=True)
table.add_column("Price", justify="right")
table.add_column("24h%", justify="right")
table.add_column("RSI1h", justify="right")
table.add_column("RSI4h", justify="right")
table.add_column("RSI1d", justify="right")
table.add_column("vs EMA200", justify="right")
table.add_column("Trend", justify="center")
table.add_column("BB", justify="right")
table.add_column("Vol×", justify="right")
table.add_column("BTC corr", justify="right")
table.add_column("#Sig", justify="right")
table.add_column("Tags", style="yellow", no_wrap=False, overflow="fold")
for s in signals:
price = format(s.get("close_price") or 0, ",.4f")
dist_ema = s.get("dist_from_ema200_pct") or 0
dist_style = "green" if dist_ema > 0 else "red"
active = s.get("active_signal_count", 0)
sig_style = "bold red" if active >= 3 else "bold yellow" if active >= 1 else "dim"
table.add_row(
s["pair"],
f"${price}",
color_change(s.get("pct_change_24h")),
color_rsi(s.get("rsi_1h")),
color_rsi(s.get("rsi_4h")),
color_rsi(s.get("rsi_1d")),
Text(f"{dist_ema:+.1f}%", style=dist_style),
color_alignment(s.get("ema_alignment")),
f"{(s.get('bb_position') or 0) * 100:.0f}%",
f"{(s.get('volume_ratio_20') or 0):.1f}",
color_correlation(s.get("btc_correlation")),
Text(str(active), style=sig_style),
(s.get("signal_tags") or "").replace(",", " · "),
)
return table
def build_header(last_run: dict, pulse: dict, num_signals: int) -> Panel:
last_scan = last_run.get("end_utc", "never")
if last_scan and last_scan != "never":
dt = datetime.fromisoformat(last_scan.replace("Z", "+00:00"))
last_scan = dt.strftime("%H:%M:%S UTC")
dom = pulse.get("btc_dominance_pct")
delta = pulse.get("btc_dominance_delta_24h")
trend = pulse.get("btc_dominance_trend") or "—"
decorrel_count = len(pulse.get("decorrelation_events", []))
dom_str = f"{dom:.2f}%" if dom is not None else "—"
delta_str = f"({delta:+.2f}pp 24h)" if delta is not None else ""
trend_color = {"rising": "red", "falling": "green", "flat": "white"}.get(trend, "white")
decorrel_color = "red" if decorrel_count > 0 else "white"
text = (
f"Last scan: [cyan]{last_scan}[/] | "
f"Pairs: [cyan]{num_signals}[/] | "
f"BTC dom: [bold]{dom_str}[/] {delta_str} [{trend_color}]{trend}[/] | "
f"Decorrel: [{decorrel_color}]{decorrel_count}[/] | "
f"Refresh: {REFRESH_SECONDS}s | Ctrl-C to exit"
)
return Panel(text, title="[bold]SignalScanner v1 + Market Pulse[/]", border_style="cyan")
def render():
signals, last_run, pulse = fetch_signals()
if not signals:
return Panel(
"[yellow]No data yet.[/] Run scanner.py first — state.sqlite is empty.",
title="[bold]SignalScanner v1[/]",
border_style="yellow",
)
header = build_header(last_run, pulse, len(signals))
table = build_table(signals)
return Group(header, table)
def main():
console = Console()
try:
with Live(render(), console=console, refresh_per_second=1, screen=False) as live:
while True:
time.sleep(REFRESH_SECONDS)
live.update(render())
except KeyboardInterrupt:
console.print("\n[cyan]Dashboard closed.[/]")
if __name__ == "__main__":
main()