Files
2026-10-21 20:52:11 -04:00

165 lines
6.0 KiB
Python
Executable File

"""Read-only web dashboard and JSON API."""
from __future__ import annotations
import base64
import binascii
import secrets
from datetime import datetime
from pathlib import Path
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse, Response
from fastapi.templating import Jinja2Templates
from .engine import Engine, StrategyRunner
from .stats import compute_stats, downsample
from .storage import Store
TEMPLATES = Jinja2Templates(directory=Path(__file__).parent / "templates")
def _usd(value: float | None) -> str:
return "—" if value is None else f"{'-' if value < 0 else ''}${abs(value):,.2f}"
def _pct(value: float | None) -> str:
return "—" if value is None else f"{value * 100:+.2f}%"
def _num(value: float | None, digits: int = 2) -> str:
return "—" if value is None else f"{value:,.{digits}f}"
def _dt(value: datetime | str | None) -> str:
if value is None:
return "—"
if isinstance(value, str):
value = datetime.fromisoformat(value)
return value.strftime("%Y-%m-%d %H:%M UTC")
TEMPLATES.env.filters.update(usd=_usd, pct=_pct, num=_num, dt=_dt)
TEMPLATES.env.globals.update(usd=_usd, pct=_pct)
def _series(points: list[tuple[datetime, float]]) -> list[list]:
return [[t.isoformat(), v] for t, v in downsample(points)]
def strategy_view(runner: StrategyRunner, engine: Engine, store: Store, detail: bool = False) -> dict:
series = store.equity_series(runner.id)
prices = engine.prices
portfolio = runner.portfolio
if all(p in prices for p in portfolio.positions):
equity = portfolio.equity(prices)
else:
equity = series[-1][1] if series else runner.starting_capital
trades = store.trades(runner.id)
view = {
"id": runner.id,
"type": runner.cfg.type,
"mode": runner.cfg.mode,
"pairs": runner.cfg.pairs,
"interval": runner.cfg.interval,
"params": runner.strategy.params,
"cash": portfolio.cash,
"last_decision": runner.last_decision.isoformat() if runner.last_decision else None,
"last_targets": runner.last_targets,
"last_error": runner.last_error,
"stats": compute_stats(runner.starting_capital, equity, series, trades),
"series": _series(series),
}
if detail:
view["positions"] = [
{
"pair": pair,
"volume": pos.volume,
"avg_price": pos.avg_price,
"price": prices.get(pair),
"value": pos.volume * prices[pair] if pair in prices else None,
"unrealized_pnl": pos.volume * (prices[pair] - pos.avg_price) if pair in prices else None,
}
for pair, pos in portfolio.positions.items()
]
view["trades"] = trades[:200]
return view
def overview(engine: Engine, store: Store) -> dict:
return {
"engine": {
"ready": engine.ready,
"started": engine.started.isoformat(),
"last_tick": engine.last_tick.isoformat() if engine.last_tick else None,
"last_error": engine.last_error,
},
"has_credentials": engine.client.has_credentials,
"account": store.latest_account(),
"account_series": _series(store.account_series()),
"strategies": [strategy_view(r, engine, store) for r in engine.runners],
}
def check_basic_auth(header: str | None, username: str, password: str) -> bool:
if not header or not header.startswith("Basic "):
return False
try:
user, sep, pwd = base64.b64decode(header[6:], validate=True).decode().partition(":")
except (binascii.Error, UnicodeDecodeError):
return False
# Compare both fields unconditionally so timing doesn't reveal which one was wrong.
user_ok = secrets.compare_digest(user.encode(), username.encode())
pwd_ok = secrets.compare_digest(pwd.encode(), password.encode())
return bool(sep) and user_ok and pwd_ok
def create_app(engine: Engine, store: Store, username: str, password: str) -> FastAPI:
if not password:
raise ValueError("A dashboard password is required")
app = FastAPI(title="Kraken Trader", docs_url="/api/docs", redoc_url=None)
@app.middleware("http")
async def basic_auth(request: Request, call_next):
# Kubernetes probes can't send credentials.
if request.url.path == "/healthz" or check_basic_auth(
request.headers.get("authorization"), username, password
):
return await call_next(request)
return Response(
"Authentication required",
status_code=401,
headers={"WWW-Authenticate": 'Basic realm="Kraken Trader", charset="UTF-8"'},
)
def _runner(strategy_id: str) -> StrategyRunner:
runner = engine.runner(strategy_id)
if runner is None:
raise HTTPException(status_code=404, detail="Strategy not found")
return runner
@app.get("/", response_class=HTMLResponse)
def index(request: Request):
return TEMPLATES.TemplateResponse(request, "index.html", {"data": overview(engine, store)})
@app.get("/strategies/{strategy_id}", response_class=HTMLResponse)
def strategy_page(request: Request, strategy_id: str):
view = strategy_view(_runner(strategy_id), engine, store, detail=True)
return TEMPLATES.TemplateResponse(request, "strategy.html", {"s": view})
@app.get("/api/overview")
def api_overview():
return overview(engine, store)
@app.get("/api/strategies/{strategy_id}")
def api_strategy(strategy_id: str):
return strategy_view(_runner(strategy_id), engine, store, detail=True)
@app.get("/healthz")
def healthz():
ok = engine.healthy()
return JSONResponse({"status": "ok" if ok else "stalled"}, status_code=200 if ok else 503)
return app