Files
local-trading-agent/validate.py
T

173 lines
8.0 KiB
Python

#!/usr/bin/env python3
import json
import subprocess
import sys
from datetime import datetime
from pathlib import Path
from urllib.request import urlopen
from zoneinfo import ZoneInfo
ROOT = Path(__file__).resolve().parent
STATE = ROOT / "data" / "state.json"
TRADES = ROOT / "data" / "trades.jsonl"
CONFIG = ROOT / "config.json"
LOCAL_TZ = ZoneInfo("America/New_York")
def sh(cmd, timeout=20):
return subprocess.run(cmd, shell=True, cwd=str(ROOT), text=True, capture_output=True, timeout=timeout)
def money(x):
return f"${float(x):.2f}"
def load_json(path, default):
try:
return json.loads(path.read_text())
except Exception:
return default
def main():
now = datetime.now(LOCAL_TZ).isoformat()
cfg = load_json(CONFIG, {})
st = load_json(STATE, {})
lines = []
problems = []
services = ["local-trading-agent.service", "local-trading-dashboard.service", "trader-reverse-tunnel.service"]
svc = sh("systemctl is-active " + " ".join(services), timeout=20)
svc_states = svc.stdout.strip().splitlines()
for name, state in zip(services, svc_states):
if state != "active":
problems.append(f"{name} is {state or 'unknown'}")
public_ok = False
public_code = "ERR"
try:
with urlopen("https://trader.nannery.pro", timeout=20) as r:
body = r.read(200).decode("utf-8", "ignore")
public_code = str(r.status)
public_ok = r.status == 200 and "Local Crypto Dip Agent" in body
except Exception as e:
public_code = type(e).__name__
if not public_ok:
problems.append(f"public dashboard validation failed: {public_code}")
cfg_check = sh("python3 bot.py --config-check", timeout=30)
if cfg_check.returncode != 0:
problems.append("bot config-check failed")
last_scan = st.get("last_scan") or {}
scan_age = None
stale_after = max(900.0, 3 * float(cfg.get("scan_interval_seconds", 300)))
try:
stamp = datetime.fromisoformat(last_scan.get("ts") or "")
if stamp.tzinfo is None:
raise ValueError("timezone missing")
scan_age = (datetime.fromisoformat(now) - stamp).total_seconds()
if scan_age < -60:
problems.append("scan timestamp is in the future")
elif scan_age > stale_after:
problems.append(f"scan timestamp is stale: {scan_age / 60:.1f} minutes old")
except (ValueError, TypeError):
problems.append("scan timestamp missing or invalid")
lines.append(f"Last scan: {last_scan.get('ts') or 'unknown'} | stale threshold {stale_after / 60:.1f} minutes")
signals = st.get("last_signals") or []
bad_signals = [x for x in signals if x.get("status") == "error"]
if bad_signals:
problems.append("bad market signals: " + ", ".join(x.get("symbol", "?") for x in bad_signals))
cash = float(st.get("cash_usd", 0))
start = float(st.get("starting_cash_usd", cfg.get("starting_cash_usd", 0) or 0))
equity = float(last_scan.get("equity_usd", cash))
realized = float(st.get("realized_pnl_usd", 0))
return_pct = ((equity - start) / start * 100) if start else 0.0
peak = max(float(st.get("equity_high_watermark_usd", start)), equity)
drawdown_pct = ((peak - equity) / peak * 100) if peak else 0.0
positions = st.get("positions", {})
exposure = sum(float(p.get("notional_usd", 0)) for p in positions.values())
max_exposure = equity * float(cfg.get("max_total_position_pct_of_equity", 1.0))
if exposure > max_exposure + 0.01:
problems.append(f"exposure too high: {money(exposure)} > cap {money(max_exposure)}")
# Summarize closed losses since log start.
events = []
if TRADES.exists():
for line in TRADES.read_text().splitlines():
line = line.strip()
if not line:
continue
try:
events.append(json.loads(line))
except Exception:
pass
sells = [e for e in events if e.get("type") == "paper_sell"]
losses = [e for e in sells if float(e.get("realized_pnl_usd", 0)) < 0]
wins = [e for e in sells if float(e.get("realized_pnl_usd", 0)) >= 0]
shadow_sells = [e for e in events if e.get("type") == "shadow_sell"]
shadow_wins = [e for e in shadow_sells if float(e.get("realized_pnl_usd", 0)) >= 0]
shadow_losses = [e for e in shadow_sells if float(e.get("realized_pnl_usd", 0)) < 0]
shadow_positions = st.get("shadow_positions", {})
def fee_adjusted_net(prefix):
pending_buy_fees = {}
net = 0.0
for e in events:
sym = e.get("symbol")
if e.get("type") == prefix + "_buy":
pending_buy_fees.setdefault(sym, []).append(float(e.get("fee_usd", 0)))
elif e.get("type") == prefix + "_sell":
# Consume the matching entry even when the sell is already net.
matched_fee = pending_buy_fees[sym].pop(0) if pending_buy_fees.get(sym) else 0.0
# Current engine events include entry fees in realized P&L.
# Legacy sells lack buy_fee_usd and need the entry fee deducted.
buy_fee = 0.0 if "buy_fee_usd" in e else matched_fee
net += float(e.get("realized_pnl_usd", 0)) - buy_fee
return net
paper_buy_fees = sum(float(e.get("fee_usd", 0)) for e in events if e.get("type") == "paper_buy")
shadow_buy_fees = sum(float(e.get("fee_usd", 0)) for e in events if e.get("type") == "shadow_buy")
net_paper = fee_adjusted_net("paper")
net_shadow = fee_adjusted_net("shadow")
status = "OK" if not problems else "ATTENTION"
performance = "UNKNOWN" if start <= 0 else "BELOW START" if equity < start else "ABOVE START" if equity > start else "FLAT"
lines.append(f"Trader hourly validation — Operational checks: {status} | Performance: {performance}")
lines.append(f"Mode: {st.get('mode', 'unknown')}")
lines.append(f"Local time: {now}")
lines.append(f"Public: https://trader.nannery.pro ({public_code})")
lines.append(f"Capital: start {money(start)} | equity {money(equity)} | cash {money(cash)} | realized {money(realized)} | return {return_pct:+.2f}% | drawdown from recorded peak {drawdown_pct:.2f}%")
lines.append(f"Open: {len(positions)} positions | exposure {money(exposure)}")
if positions:
for sym, p in positions.items():
entry = float(p.get("avg_entry", 0)); last = float(p.get("last_price", entry)); qty = float(p.get("qty", 0))
pnl = (last - entry) * qty
pct = ((last / entry - 1) * 100) if entry else 0
lines.append(f"- {sym}: unreal {money(pnl)} ({pct:.2f}%)")
lines.append(f"Closed trades: {len(sells)} total | wins {len(wins)} | losses {len(losses)} | loss total {money(sum(float(e.get('realized_pnl_usd',0)) for e in losses))}")
lines.append(f"Fee-adjusted closed net: paper {money(net_paper)} | paper buy fees paid {money(paper_buy_fees)}")
if cfg.get("watch_only_symbols"):
shadow_pnl = float(st.get("shadow_realized_pnl_usd", 0.0))
lines.append(f"Watch-only shadow: realized {money(shadow_pnl)} | closed {len(shadow_sells)} | wins {len(shadow_wins)} | losses {len(shadow_losses)} | open {len(shadow_positions)}")
lines.append(f"Fee-adjusted shadow net: {money(net_shadow)} | shadow buy fees paid {money(shadow_buy_fees)}")
for sym, p in shadow_positions.items():
entry = float(p.get("avg_entry", 0)); last = float(p.get("last_price", entry)); qty = float(p.get("qty", 0))
pnl = (last - entry) * qty
pct = ((last / entry - 1) * 100) if entry else 0
lines.append(f"- WATCH {sym}: unreal {money(pnl)} ({pct:.2f}%)")
if bad_signals:
lines.append("Signal errors: " + ", ".join(f"{x.get('symbol')}={x.get('error')}" for x in bad_signals))
if problems:
lines.append("Problems:")
lines.extend(f"- {p}" for p in problems)
else:
lines.append("No service/config/public-route problems detected.")
print("\n".join(lines))
return 1 if problems else 0
if __name__ == "__main__":
raise SystemExit(main())