Files
OpenFin/backend/main.py
OpenSquared 05a475fb04 feat: system logs page + dynamic IV watchlist with auto-add from cycle
Backend:
- DB: add system_logs table (level/source/cycle_id/ticker/message) and
  iv_watchlist table (ticker/added_by/is_active); seed builtin 18 tickers
- DBLogHandler attached at startup — all WARNING+ logs auto-persist to DB
- log_system_event() helper for structured manual events
- New router /api/logs: GET with filters (level, source, cycle_id, ticker,
  date range), GET /sources, GET /cycles for dropdowns, DELETE /clear
- iv_watchlist now read from DB instead of hardcoded constant; options_vol
  watchlist/refresh/bootstrap endpoints all use get_watchlist_tickers()
- New endpoints: POST/DELETE /options-vol/watchlist-tickers/{ticker} to
  add/remove tickers; adding triggers background 1-year bootstrap
- auto_cycle: after log_trade_entries(), auto-detect new underlying proxies
  not yet in watchlist, add them and bootstrap their IV history

Frontend:
- New page SystemLogs (/logs): log table with level/source/cycle/ticker/date
  filters, color-coded rows, expandable JSON details, auto-refresh 30s
- Options Lab: WatchlistManager section — add ticker input, chip list with
  builtin/auto/manual color coding, remove button for non-builtins
- Sidebar: Logs Système nav link (ScrollText icon)
- useApi: useSystemLogs, useLogSources, useLogCycles, useClearLogs,
  useWatchlistTickers, useAddWatchlistTicker, useRemoveWatchlistTicker

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-18 13:07:35 +02:00

116 lines
3.9 KiB
Python

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from routers import market_data, geopolitical, options, backtest, ai, portfolio, config, patterns, journal, cycle as cycle_router, profiles as profiles_router, reasoning as reasoning_router, knowledge as knowledge_router, options_vol as options_vol_router, analytics as analytics_router, risk as risk_router
from routers import logs as logs_router
from services.database import init_db, get_config, cleanup_stale_running_cycles
import os
import logging
import uvicorn
class _DBLogHandler(logging.Handler):
"""Persist WARNING+ log records to system_logs table."""
def emit(self, record: logging.LogRecord):
if record.levelno < logging.WARNING:
return
try:
from services.database import log_system_event
log_system_event(
level=record.levelname,
source=record.name,
message=self.format(record),
cycle_id=getattr(record, "cycle_id", None),
ticker=getattr(record, "ticker", None),
)
except Exception:
pass # Never raise from inside a log handler
app = FastAPI(
title="GeoOptions Intelligence",
description="Geopolitical Options Trading Cockpit API",
version="2.0.0",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173", "http://localhost:3000", "http://127.0.0.1:5173"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
def startup():
# Attach DB log handler to root logger (captures WARNING+ from all modules)
_db_handler = _DBLogHandler()
_db_handler.setFormatter(logging.Formatter("%(message)s"))
logging.getLogger().addHandler(_db_handler)
_log = logging.getLogger(__name__)
init_db()
# Clean up cycles that were left in 'running' state by a previous crashed process
stale = cleanup_stale_running_cycles()
if stale:
_log.warning(f"[Startup] Cleaned up {stale} stale 'running' cycle(s) — server likely reloaded mid-cycle")
# Sync OpenAI key: env var → DB (useful on fresh VPS deployments)
key = get_config("openai_api_key") or ""
if not key:
env_key = os.environ.get("OPENAI_API_KEY", "")
if env_key:
from services.database import set_config
set_config("openai_api_key", env_key)
key = env_key
_log.info("[Startup] OPENAI_API_KEY synced from environment to DB config")
if key:
os.environ["OPENAI_API_KEY"] = key
# Seed built-in patterns into DB (idempotent)
from services.geo_analyzer import GEO_PATTERNS
from services.database import seed_builtin_patterns
seed_builtin_patterns(GEO_PATTERNS)
# Start auto-cycle scheduler if enabled
from services.auto_cycle import start_scheduler
start_scheduler()
@app.on_event("shutdown")
def shutdown():
from services.auto_cycle import stop_scheduler
stop_scheduler()
app.include_router(market_data.router)
app.include_router(geopolitical.router)
app.include_router(options.router)
app.include_router(backtest.router)
app.include_router(ai.router)
app.include_router(portfolio.router)
app.include_router(config.router)
app.include_router(patterns.router)
app.include_router(journal.router)
app.include_router(cycle_router.router)
app.include_router(profiles_router.router)
app.include_router(reasoning_router.router)
app.include_router(knowledge_router.router)
app.include_router(options_vol_router.router)
app.include_router(analytics_router.router)
app.include_router(risk_router.router)
app.include_router(logs_router.router)
@app.get("/")
def root():
return {"app": "GeoOptions Intelligence Cockpit", "version": "2.0.0", "docs": "/docs"}
@app.get("/api/health")
def health():
return {"status": "ok", "version": "2.0.0"}
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)