"""Webhook server: TradingView alert -> news filter -> risk rules -> broker. In demo mode (DEMO_MODE=true) a built-in simulator produces the prices and signals, news is simulated, and every order goes to the fake-money paper broker. """ import hmac import json import threading from contextlib import asynccontextmanager from pathlib import Path from fastapi import FastAPI, HTTPException, Request from fastapi.responses import HTMLResponse from pydantic import BaseModel, Field from . import backtest, demo, exchanges, marketdata, news, scorecard, sentiment from .brokers import AlpacaBroker, PaperBroker from .config import INSTRUMENTS, settings from .risk import check_buy from .store import Store store = Store(settings.db_path, settings.paper_start_cash) paper = PaperBroker(store) # In demo mode no broker connection is ever made, even if keys are present. alpaca = (AlpacaBroker(settings.alpaca_key, settings.alpaca_secret, settings.alpaca_live) if settings.alpaca_key and settings.alpaca_secret and not settings.demo_mode else None) state = {"kill_switch": False} sim: demo.Simulator | None = None def broker_for(inst): if inst.broker == "alpaca" and alpaca is not None: return alpaca return paper # demo mode, AEX stocks, or no Alpaca keys def news_for(inst): if settings.demo_mode and settings.demo_data == "simulated": return demo.fake_news(inst.news_query) # Demo with real data: real headlines, keyword score if there is no DeepSeek key. return sentiment.analyze(inst.news_query, keyword_fallback=settings.demo_mode, inst=inst) def process(symbol: str, action: str, price: float, reason: str = "", at: float | None = None, enforce_hours: bool = True) -> dict: """The core decision path, shared by the webhook and the demo simulator. `at` is the moment the signal belongs to (a candle time); default is now. """ inst = INSTRUMENTS.get(symbol.upper()) if inst is None: store.log(symbol, action, price, "ignored", "symbol not in config") return {"decision": "ignored", "reason": "symbol not in config"} broker = broker_for(inst) if broker is paper: paper.mark(inst.broker_symbol, price) try: if action == "sell": # Exits are never blocked by the news filter: getting out must always work. if not broker.has_position(inst.broker_symbol): store.log(inst.tv_symbol, "sell", price, "ignored", "no open position", candle_ts=at) return {"decision": "ignored", "reason": "no open position"} info = broker.close(inst.broker_symbol, price) store.log(inst.tv_symbol, "sell", price, "executed", reason, order_info=info, candle_ts=at) return {"decision": "executed", "order": info} # Buys only while the exchange is open. For Alpaca stocks Alpaca's own clock is used # (it knows holidays), and an after-hours order would otherwise be queued until the # next open at a price that can differ a lot from the signal. ex = exchanges.EXCHANGES[inst.exchange] if inst.asset_class == "stock" and broker.name == "alpaca": if settings.us_after_hours != "queue" and not broker.market_open(): why = "US market closed (set US_AFTER_HOURS=queue to buy at the next open)" store.log(inst.tv_symbol, "buy", price, "blocked", why, candle_ts=at) return {"decision": "blocked", "reason": why} elif enforce_hours and settings.enforce_market_hours and not exchanges.is_open(ex, at): why = f"{ex.name} is closed (open {exchanges.hours_label(ex)})" store.log(inst.tv_symbol, "buy", price, "blocked", why, candle_ts=at) return {"decision": "blocked", "reason": why} verdict = news_for(inst) day_start = store.day_start_equity(broker.name, broker.equity()) d = check_buy(broker, inst.broker_symbol, verdict, day_start, state["kill_switch"]) if not d.allowed: store.log(inst.tv_symbol, "buy", price, "blocked", d.reason, verdict.as_dict(), candle_ts=at) return {"decision": "blocked", "reason": d.reason} info = broker.buy_notional(inst.broker_symbol, d.amount, price, inst.asset_class) store.log(inst.tv_symbol, "buy", price, "executed", f"{reason}; {d.reason}", verdict.as_dict(), info, candle_ts=at) return {"decision": "executed", "reason": d.reason, "order": info} except Exception as e: store.log(inst.tv_symbol, action, price, "error", str(e)) return {"decision": "error", "reason": str(e)} def _held() -> set[str]: return {p.symbol for p in paper.positions()} def start_demo(seed: int | None = None) -> demo.Simulator: global sim if sim: sim.stop() sim = demo.Simulator(process, paper.mark, mode=settings.demo_data, interval=settings.demo_interval, poll_seconds=settings.demo_poll_seconds, tick_seconds=settings.demo_tick_seconds, seed=seed, pause=0.2, on_price=store.log_price, on_equity=store.log_equity, fallback_rates={"USD": settings.eur_usd_rate, "GBP": settings.eur_gbp_rate}) sim.start(paper.equity, _held) return sim @asynccontextmanager async def lifespan(_app): if settings.demo_mode: start_demo() yield if sim: sim.stop() VERSION = "2026-11-17 live-updates" app = FastAPI(title="Yote-In-Vest", version=VERSION, lifespan=lifespan) class Alert(BaseModel): secret: str symbol: str action: str = Field(pattern="^(buy|sell)$") price: float = Field(gt=0) exchange: str = "" reason: str = "" timeframe: str = "" def _secret_ok(given: str) -> bool: return hmac.compare_digest(given.encode(), settings.webhook_secret.encode()) @app.post("/webhook") def webhook(alert: Alert): if not _secret_ok(alert.secret): raise HTTPException(401, "bad secret") r = process(alert.symbol, alert.action, alert.price, alert.reason) if r["decision"] == "error": raise HTTPException(500, f"order failed: {r['reason']}") return r def _account(b) -> dict: try: return {"name": b.name, "equity": round(b.equity(), 2), "positions": [p.__dict__ for p in b.positions()]} except Exception as e: return {"name": b.name, "error": str(e), "positions": []} @app.get("/api/state") def api_state(): accounts = [_account(paper)] + ([_account(alpaca)] if alpaca else []) start = store.invested() # starting balance plus deposits, so "since start" is fair out = {"version": VERSION, "kill_switch": state["kill_switch"], "paper_start_cash": start, "alpaca_connected": alpaca is not None, "live_trading": settings.alpaca_live and alpaca is not None, "demo_mode": settings.demo_mode, "accounts": accounts, "events": store.events(200), "exchanges": exchanges.describe(), "news_sources": news.status()} if sim: out["demo"] = {"data": sim.mode, "interval": sim.interval if sim.mode == "real" else "sim", "every_seconds": sim.wait, "updates": sim.candles, "last_update": sim.last_poll, "fx": {k: round(v, 4) for k, v in sim.rates.items()}, "prices": sim.prices(), "news": ("simulated" if sim.mode == "simulated" else "DeepSeek" if settings.deepseek_key else "keyword score"), "equity_history": list(sim.equity_history), "health": sim.health()} return out class SecretReq(BaseModel): secret: str on: bool = False @app.post("/api/kill") def kill(req: SecretReq): if not _secret_ok(req.secret): raise HTTPException(401, "bad secret") state["kill_switch"] = req.on return {"kill_switch": req.on} @app.post("/api/demo/reset") def demo_reset(req: SecretReq): """Wipe the fake account and restart the simulation from scratch.""" if not settings.demo_mode: raise HTTPException(400, "only available in demo mode") if not _secret_ok(req.secret): raise HTTPException(401, "bad secret") store.clear_history() start_demo() return {"reset": True} def money_summary() -> dict: """What went in versus what it is worth now (all accounts, euros).""" accounts = [paper] + ([alpaca] if alpaca else []) value = 0.0 for b in accounts: try: value += b.equity() except Exception: pass invested = store.invested() gain = value - invested return {"invested": round(invested, 2), "value": round(value, 2), "gain": round(gain, 2), "gain_pct": round(gain / invested * 100, 2) if invested > 0 else None, "start_cash": round(store.start_cash(), 2), "deposits": store.deposits()} @app.middleware("http") async def no_cache_for_api(request, call_next): """Browsers and proxies must never reuse an old answer for the live data.""" resp = await call_next(request) if request.url.path.startswith("/api/") or request.url.path == "/health": resp.headers["Cache-Control"] = "no-store" return resp @app.get("/api/money") def api_money(): return money_summary() class DepositReq(BaseModel): secret: str amount: float = Field(ge=-1_000_000, le=1_000_000) note: str = "" @app.post("/api/deposits") def api_deposit(req: DepositReq): """Record money added to the account (negative = taken out). Needs the secret.""" if not _secret_ok(req.secret): raise HTTPException(401, "bad secret") if req.amount == 0: raise HTTPException(422, "amount cannot be zero") try: store.add_deposit(req.amount, req.note, to_paper=alpaca is None) except ValueError as e: raise HTTPException(400, str(e)) return money_summary() BACKTEST_FILE = Path(settings.db_path).resolve().parent / "backtest.json" bt = {"running": False, "done": 0, "total": 0, "error": ""} def _load_backtest() -> dict | None: try: return json.loads(BACKTEST_FILE.read_text()) except (OSError, ValueError): return None @app.get("/api/scorecard") def api_scorecard(): start = store.q("SELECT start_cash FROM paper_account WHERE id=1")[0]["start_cash"] return scorecard.build(store, start) @app.get("/api/backtest") def api_backtest(): return {**bt, "result": _load_backtest()} class BacktestReq(BaseModel): secret: str interval: str = Field(default="1d", pattern="^(1d|1h)$") years: int = Field(default=5, ge=1, le=10) def _run_backtest(interval: str, years: int, fetch=marketdata.fetch): try: r = backtest.run(fetch, None, interval, years, progress=lambda n, t: bt.update(done=n, total=t)) BACKTEST_FILE.write_text(json.dumps(r)) bt["error"] = "" except Exception as e: bt["error"] = str(e)[:300] finally: bt["running"] = False @app.post("/api/backtest/run") def api_backtest_run(req: BacktestReq): """Start a backtest in the background (takes a minute or two). Needs the secret.""" if not _secret_ok(req.secret): raise HTTPException(401, "bad secret") if bt["running"]: raise HTTPException(409, "a backtest is already running") bt.update(running=True, done=0, total=0, error="") threading.Thread(target=_run_backtest, args=(req.interval, req.years), daemon=True).start() return {"started": True} @app.get("/health") def health(): return {"ok": True, "version": VERSION} @app.get("/", response_class=HTMLResponse) def dashboard(request: Request): return (Path(__file__).parent / "dashboard.html").read_text()