-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatus.py
More file actions
356 lines (295 loc) · 11.1 KB
/
status.py
File metadata and controls
356 lines (295 loc) · 11.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
#!/usr/bin/env python3
"""Bot Status — shows current state of the Polymarket trading bot.
Usage:
python3 status.py # full status
python3 status.py --json # JSON output for programmatic use
python3 status.py --short # one-line summary
Displays:
- Market hours status (active/inactive)
- Uptime (since first decision today)
- Today's statistics (decisions, wins, losses, P&L)
- Circuit breaker state
- Recent decisions (last 5)
- Recent arbitrage/movers found
- Price history status
"""
import sys
import os
import json
import argparse
from datetime import datetime, date
from zoneinfo import ZoneInfo
# Ensure imports work
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from src.audit.trade_db import TradeDB
from src.execution.circuit_breakers import CircuitBreakers
from src.pipeline import is_market_hours, get_market_hours_status
CET = ZoneInfo("Europe/Madrid")
def get_uptime(db: TradeDB) -> dict:
"""Calculate uptime based on first decision today."""
today = date.today().isoformat()
decisions = db.get_recent_decisions(limit=100)
# Find first decision today
first_today = None
for d in reversed(decisions):
if d["timestamp"].startswith(today):
first_today = d["timestamp"]
break
if first_today:
try:
start = datetime.fromisoformat(first_today.replace("Z", "+00:00"))
now = datetime.now(CET)
if start.tzinfo is None:
start = start.replace(tzinfo=CET)
delta = now - start
hours = delta.seconds // 3600
mins = (delta.seconds % 3600) // 60
return {
"running_since": first_today,
"uptime": f"{hours}h {mins}m",
"uptime_seconds": delta.seconds,
}
except Exception:
pass
return {
"running_since": None,
"uptime": "Not started today",
"uptime_seconds": 0,
}
def get_today_stats(db: TradeDB) -> dict:
"""Get today's trading statistics."""
stats = db.get_stats(days=1)
# Count verdicts
decisions = db.get_recent_decisions(limit=100)
today = date.today().isoformat()
today_decisions = [d for d in decisions if d["timestamp"].startswith(today)]
buy_yes = sum(1 for d in today_decisions if d["verdict"] == "BUY_YES")
buy_no = sum(1 for d in today_decisions if d["verdict"] == "BUY_NO")
skips = sum(1 for d in today_decisions if d["verdict"] == "SKIP")
return {
"total_decisions": stats["total_decisions"],
"buy_yes": buy_yes,
"buy_no": buy_no,
"skips": skips,
"wins": stats["wins"],
"losses": stats["losses"],
"win_rate": stats["win_rate"],
"total_pnl": stats["total_pnl"],
"pending": stats["pending"],
}
def get_circuit_breaker_status(db: TradeDB) -> dict:
"""Get circuit breaker states."""
import time
cb = CircuitBreakers(db)
state = cb.check()
paused_until = None
if state.paused_until > time.time():
paused_until = datetime.fromtimestamp(state.paused_until, CET).isoformat()
return {
"kill_switch": state.kill_switch,
"paused": state.paused_until > time.time(),
"paused_until": paused_until,
"consecutive_losses": state.consecutive_losses,
"api_errors": state.api_error_count,
"can_trade": state.can_trade,
"daily_pnl": state.daily_pnl,
"status_summary": state.status_summary(),
}
def get_recent_decisions(db: TradeDB, limit: int = 5) -> list[dict]:
"""Get recent decisions with summary info."""
decisions = db.get_recent_decisions(limit=limit)
result = []
for d in decisions:
result.append({
"id": d["id"],
"timestamp": d["timestamp"],
"symbol": d.get("crypto_symbol", "EVT"),
"verdict": d["verdict"],
"confidence": d.get("confidence_self", d.get("signal_score", 0)),
"outcome": d.get("outcome", "PENDING"),
"pnl": d.get("pnl_usd"),
})
return result
def get_price_history_status(db: TradeDB) -> dict:
"""Get price history persistence status."""
from src.utils.config import SYMBOLS
counts = {}
total = 0
for sym in SYMBOLS:
count = db.price_history_count(sym)
counts[sym] = count
total += count
return {
"total_points": total,
"by_symbol": counts,
"retention_hours": 48,
}
def get_websocket_status(db: TradeDB) -> dict:
"""Get WebSocket feed status (Sprint 3)."""
from pathlib import Path
from src.utils.config import DATA_DIR
import os
import time
# Check if WebSocket runner is active
pid_file = DATA_DIR / "ws_feed.pid"
ws_running = False
ws_pid = None
uptime_seconds = 0
try:
if pid_file.exists():
with open(pid_file, 'r') as f:
ws_pid = int(f.read().strip())
# Check if process is actually running
try:
os.kill(ws_pid, 0) # Check if PID exists
ws_running = True
# Get uptime from PID file modification time
uptime_seconds = time.time() - pid_file.stat().st_mtime
except OSError:
ws_running = False # Process doesn't exist
except Exception:
pass
# Get WebSocket price data count
ws_price_count = 0
latest_update = None
try:
ws_price_count = db.ws_prices_count()
# Get latest WebSocket update
with db._connect() as conn:
row = conn.execute(
"SELECT MAX(timestamp) as latest FROM ws_prices"
).fetchone()
if row and row["latest"]:
latest_update = row["latest"]
except Exception:
pass
# Calculate latency (time since last update)
latency_seconds = None
if latest_update:
latency_seconds = time.time() - latest_update
return {
"running": ws_running,
"pid": ws_pid,
"uptime_seconds": uptime_seconds,
"price_records": ws_price_count,
"latest_update": latest_update,
"latency_seconds": latency_seconds,
}
def format_status(status: dict) -> str:
"""Format status dict for human-readable output."""
lines = []
# Header
lines.append("=" * 60)
lines.append("🤖 POLYMARKET BOT STATUS")
lines.append("=" * 60)
lines.append("")
# Market hours
mh = status["market_hours"]
emoji = "📈" if mh["is_active"] else "🌙"
lines.append(f"{emoji} Market Hours: {mh['status']}")
lines.append(f" Current: {mh['current_time_cet']} ({mh['market_hours']})")
lines.append("")
# Uptime
up = status["uptime"]
lines.append(f"⏱️ Uptime: {up['uptime']}")
if up["running_since"]:
lines.append(f" Running since: {up['running_since']}")
lines.append("")
# Today's stats
ts = status["today_stats"]
lines.append("📊 Today's Statistics:")
lines.append(f" Decisions: {ts['total_decisions']} total")
lines.append(f" ├─ BUY_YES: {ts['buy_yes']}")
lines.append(f" ├─ BUY_NO: {ts['buy_no']}")
lines.append(f" └─ SKIP: {ts['skips']}")
lines.append(f" Results: {ts['wins']}W / {ts['losses']}L ({ts['win_rate']:.0%} WR)")
lines.append(f" P&L: ${ts['total_pnl']:+.2f}")
lines.append(f" Pending: {ts['pending']} decisions")
lines.append("")
# Circuit breakers
cb = status["circuit_breakers"]
if cb["kill_switch"]:
lines.append("🚨 Circuit Breakers: KILL SWITCH ACTIVE")
elif cb["paused"]:
lines.append(f"⏸️ Circuit Breakers: PAUSED until {cb['paused_until']}")
elif not cb["can_trade"]:
lines.append("⚠️ Circuit Breakers: CANNOT TRADE")
else:
lines.append("✅ Circuit Breakers: OK")
lines.append(f" Consecutive losses: {cb['consecutive_losses']}")
lines.append(f" API errors: {cb['api_errors']}")
lines.append("")
# Recent decisions
rd = status["recent_decisions"]
lines.append("📝 Recent Decisions:")
if rd:
for d in rd:
outcome_emoji = {"WIN": "✅", "LOSS": "❌", "PENDING": "⏳"}.get(d["outcome"], "❓")
pnl_str = f"${d['pnl']:+.2f}" if d["pnl"] is not None else ""
lines.append(
f" {outcome_emoji} {d['symbol']:<4} {d['verdict']:<8} "
f"conf:{d['confidence']:>2} {pnl_str}"
)
else:
lines.append(" (no decisions yet)")
lines.append("")
# Price history
ph = status["price_history"]
lines.append(f"💾 Price History: {ph['total_points']} points ({ph['retention_hours']}h retention)")
lines.append(f" {' / '.join(f'{s}:{c}' for s, c in ph['by_symbol'].items())}")
lines.append("")
# WebSocket status (Sprint 3)
ws = status.get("websocket", {"running": False, "pid": None})
if ws.get("running"):
uptime_str = f"{ws.get('uptime_seconds', 0):.0f}s" if ws.get('uptime_seconds', 0) < 3600 else f"{ws.get('uptime_seconds', 0)/3600:.1f}h"
latency_str = ""
if ws.get("latency_seconds") is not None:
if ws["latency_seconds"] < 60:
latency_str = f" (latest: {ws['latency_seconds']:.1f}s ago)"
else:
latency_str = f" (latest: {ws['latency_seconds']/60:.1f}m ago)"
lines.append(f"🔌 WebSocket: RUNNING (PID: {ws.get('pid')}, uptime: {uptime_str})")
lines.append(f" Price records: {ws.get('price_records', 0):,}{latency_str}")
else:
lines.append("🔌 WebSocket: NOT RUNNING")
if ws.get("price_records", 0) > 0:
lines.append(f" Cached records: {ws['price_records']:,}")
lines.append("")
lines.append("=" * 60)
return "\n".join(lines)
def format_short(status: dict) -> str:
"""One-line summary."""
ts = status["today_stats"]
mh = status["market_hours"]
cb = status["circuit_breakers"]
hours_emoji = "📈" if mh["is_active"] else "🌙"
cb_emoji = "✅" if cb["can_trade"] else "🚨"
return (
f"{hours_emoji} {ts['total_decisions']} decisions "
f"({ts['wins']}W/{ts['losses']}L, ${ts['total_pnl']:+.2f}) "
f"{cb_emoji}"
)
def main():
parser = argparse.ArgumentParser(description="Polymarket Bot Status")
parser.add_argument("--json", action="store_true", help="Output as JSON")
parser.add_argument("--short", action="store_true", help="One-line summary")
args = parser.parse_args()
db = TradeDB()
status = {
"timestamp": datetime.now(CET).isoformat(),
"market_hours": get_market_hours_status(),
"uptime": get_uptime(db),
"today_stats": get_today_stats(db),
"circuit_breakers": get_circuit_breaker_status(db),
"recent_decisions": get_recent_decisions(db, limit=5),
"price_history": get_price_history_status(db),
"websocket": get_websocket_status(db), # Sprint 3
}
if args.json:
print(json.dumps(status, indent=2, default=str))
elif args.short:
print(format_short(status))
else:
print(format_status(status))
if __name__ == "__main__":
main()