"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat: add Options Lab panel with payoff diagram, spot-IV scenarios, Greeks and live chain
shadowinlifedad36b50c89d
diff --git a/agent/api_server.py b/agent/api_server.pyindex 8ff2c3ac7..25fe50872 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -283,6 +283,10 @@ from src.api.live_routes import ( # noqa: F401, E402from src.api.alpha_routes import register_alpha_routes # noqa: E402register_alpha_routes(app)+# --- Options analysis ---+from src.api.options_routes import register_options_routes # noqa: E402+register_options_routes(app)+# --- Auth helpers (SSE tickets) ---from src.api.auth_routes import register_auth_routes # noqa: E402register_auth_routes(app)diff --git a/agent/src/api/options_routes.py b/agent/src/api/options_routes.pynew file mode 100644index 000000000..2b307ae96--- /dev/null+++ b/agent/src/api/options_routes.py@@ -0,0 +1,235 @@+"""Options analysis HTTP routes for the Web UI.++Mounted by ``agent/api_server.py`` via ``register_options_routes(app, ...)``.+Pulled into its own module because ``api_server.py`` is already huge, matching+the ``alpha_routes.py`` slice pattern.++Routes (auth via the caller-supplied ``require_auth`` dependency):++- ``POST /options/payoff`` — multi-leg expiry payoff + spot/IV scenario analysis+- ``GET /options/chain`` — US-listed options chain for one expiration (Yahoo)++Both routes are thin HTTP wrappers around the existing agent tools+(``OptionsPayoffTool`` / ``OptionsChainTool``) so validation and math stay+identical to the MCP surface — no formula is reimplemented here.++``POST /options/payoff`` returns the tool's envelope verbatim plus one additive+top-level ``greeks`` object: portfolio Greeks at entry (sum of ``qty * greek``+per leg, scaled by ``multiplier`` so cards show dollar exposure). Computed via+``src.quantlib.options.bs_greeks`` — theta per calendar day, vega/rho per 1+percentage point, the quantlib native convention.++Error surface:++- Payoff: pydantic request validation → 422 (FastAPI default). A tool-level+ error envelope (``{"status": "error", ...}``) → 400 with that same body.+- Chain: missing/blank ticker → 400 ``{"ok": false, "error": "ticker is+ required"}``; a tool failure envelope (``ok: false``) → 502 with the tool's+ body; an unexpected exception inside the tool call → 502 with a generic+ envelope. Success → 200 with the tool envelope verbatim.++The chain call does Yahoo network I/O and runs in ``asyncio.to_thread``; the+payoff call is CPU-light but also runs in a worker thread so both endpoints+keep the event loop free under concurrent use.+"""++from __future__ import annotations++import asyncio+import json+import logging+from typing import Annotated, Any, Awaitable, Callable, Literal++from fastapi import Depends, FastAPI, Query+from fastapi.responses import JSONResponse, Response+from pydantic import BaseModel, Field, field_validator++from src.quantlib.options import bs_greeks+from src.tools.options_chain_tool import OptionsChainTool+from src.tools.options_payoff_tool import OptionsPayoffTool, _coerce_legs++logger = logging.getLogger(__name__)++# Keep in sync with OptionsPayoffTool's parameter schema. Duplicated as pydantic+# constraints so bad requests fail fast with 422 before any tool work happens;+# the tool re-validates everything, so drift degrades to its error envelope.+_MAX_LEGS = 20+_MIN_SPOT_POINTS = 21+_MAX_SPOT_POINTS = 501+_DEFAULT_SPOT_POINTS = 121+_MAX_IV_SCENARIOS = 9++_GREEK_KEYS = ("delta", "gamma", "theta", "vega", "rho")+++# ---------------------------------------------------------------------------+# Request schemas+# ---------------------------------------------------------------------------+++class PayoffLeg(BaseModel):+ """One signed option leg of a payoff request."""++ option_type: Literal["call", "put"]+ strike: float = Field(..., gt=0)+ qty: int+ premium: float | None = Field(None, ge=0)++ @field_validator("qty")+ @classmethod+ def _qty_nonzero(cls, v: int) -> int:+ if v == 0:+ raise ValueError("qty must be a non-zero integer")+ return v+++class PayoffRequest(BaseModel):+ """POST /options/payoff body — mirrors ``OptionsPayoffTool.parameters``."""++ legs: list[PayoffLeg] = Field(..., min_length=1, max_length=_MAX_LEGS)+ entry_spot: float = Field(..., gt=0)+ expiry_days: float = Field(..., ge=0)+ risk_free_rate: float = Field(0.05)+ volatility: float = Field(0.3, gt=0)+ multiplier: float = Field(1.0, gt=0)+ commission_rate: float = Field(0.001, ge=0, lt=1)+ spot_min: float | None = Field(None, ge=0)+ spot_max: float | None = Field(None, gt=0)+ spot_points: int = Field(_DEFAULT_SPOT_POINTS, ge=_MIN_SPOT_POINTS, le=_MAX_SPOT_POINTS)+ scenario_iv_values: (+ list[Annotated[float, Field(gt=0)]] | None+ ) = Field(None, min_length=1, max_length=_MAX_IV_SCENARIOS)+++def _tool_params(payload: PayoffRequest) -> dict[str, Any]:+ """Project the validated request onto the tool's execute() kwargs.++ Optional fields left at ``None`` are omitted so the tool applies its own+ defaults (chart bounds derived from strikes/spot, the five default IV+ scenarios), exactly as on the MCP surface.+ """+ params: dict[str, Any] = {+ "legs": [leg.model_dump(exclude_none=True) for leg in payload.legs],+ "entry_spot": payload.entry_spot,+ "expiry_days": payload.expiry_days,+ "risk_free_rate": payload.risk_free_rate,+ "volatility": payload.volatility,+ "multiplier": payload.multiplier,+ "commission_rate": payload.commission_rate,+ "spot_points": payload.spot_points,+ }+ if payload.spot_min is not None:+ params["spot_min"] = payload.spot_min+ if payload.spot_max is not None:+ params["spot_max"] = payload.spot_max+ if payload.scenario_iv_values is not None:+ params["scenario_iv_values"] = payload.scenario_iv_values+ return params+++def _portfolio_greeks(payload: PayoffRequest) -> dict[str, float]:+ """Portfolio Greeks at entry, in dollar exposure per unit of ``multiplier``.++ Legs are re-run through the tool's own ``_coerce_legs`` so the Greeks use+ exactly the same leg values the payoff envelope was built from. ``qty`` is+ already signed, so summing ``qty * greek`` nets longs against shorts.+ Conventions are ``bs_greeks``' native ones: theta per calendar day,+ vega/rho per 1 percentage point — no conversion applied.+ """+ legs = _coerce_legs([leg.model_dump(exclude_none=True) for leg in payload.legs])+ time_to_expiry = payload.expiry_days / 365.0+ totals = {key: 0.0 for key in _GREEK_KEYS}+ for leg in legs:+ greeks = bs_greeks(+ S=payload.entry_spot,+ K=leg.strike,+ T=time_to_expiry,+ r=payload.risk_free_rate,+ sigma=payload.volatility,+ option_type=leg.option_type,+ )+ for key in _GREEK_KEYS:+ totals[key] += leg.qty * greeks[key]+ return {key: round(value * payload.multiplier, 6) for key, value in totals.items()}+++# ---------------------------------------------------------------------------+# Registration+# ---------------------------------------------------------------------------++AuthDep = Callable[..., Awaitable[Any] | Any]+++def register_options_routes(+ app: FastAPI,+ require_auth: AuthDep | None = None,+) -> None:+ """Mount the options routes onto ``app``.++ Args:+ app: The host FastAPI app.+ require_auth: Header-auth dependency for both endpoints.++ For backwards compatibility, when the dependency callable is not passed+ explicitly we resolve it from the host ``api_server`` module via+ ``sys.modules``. Prefer the explicit form in new call sites.+ """+ if require_auth is None:+ import sys as _sys++ host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")+ if host is None: # pragma: no cover — only triggers on weird import setups+ raise RuntimeError(+ "register_options_routes: api_server module not in sys.modules; "+ "pass require_auth explicitly"+ )+ require_auth = host.require_auth++ # -----------------------------------------------------------------------+ # POST /options/payoff+ # -----------------------------------------------------------------------++ @app.post("/options/payoff", dependencies=[Depends(require_auth)])+ async def options_payoff(payload: PayoffRequest) -> Response:+ """Tool-identical payoff analysis plus portfolio Greeks at entry."""+ params = _tool_params(payload)+ tool = OptionsPayoffTool()+ raw = await asyncio.to_thread(tool.execute, **params)+ envelope = json.loads(raw)+ if envelope.get("status") != "ok":+ # Curated tool error envelope (bad bounds, bad scenarios, ...) —+ # surface it verbatim as a client error.+ return JSONResponse(status_code=400, content=envelope)+ envelope["greeks"] = _portfolio_greeks(payload)+ return envelope++ # -----------------------------------------------------------------------+ # GET /options/chain+ # -----------------------------------------------------------------------++ @app.get("/options/chain", dependencies=[Depends(require_auth)])+ async def options_chain(+ ticker: str | None = Query(None, max_length=64),+ expiration: int | None = Query(None),+ ) -> Response:+ """Wrap ``OptionsChainTool`` (Yahoo network I/O, run in a thread)."""+ if ticker is None or not ticker.strip():+ return JSONResponse(+ status_code=400, content={"ok": False, "error": "ticker is required"}+ )+ kwargs: dict[str, Any] = {"ticker": ticker}+ if expiration is not None:+ kwargs["expiration"] = expiration+ tool = OptionsChainTool()+ try:+ raw = await asyncio.to_thread(tool.execute, **kwargs)+ envelope = json.loads(raw)+ except Exception: # noqa: BLE001 — never leak a stack frame to clients+ logger.exception("options chain tool call failed (ticker=%s)", ticker)+ return JSONResponse(+ status_code=502,+ content={"ok": False, "error": "options chain request failed"},+ )+ if not envelope.get("ok"):+ return JSONResponse(status_code=502, content=envelope)+ return envelopediff --git a/agent/tests/test_options_routes.py b/agent/tests/test_options_routes.pynew file mode 100644index 000000000..4b400c1dd--- /dev/null+++ b/agent/tests/test_options_routes.py@@ -0,0 +1,229 @@+"""API tests for ``POST /options/payoff`` + ``GET /options/chain``.++Deterministic by construction — no network anywhere:++* the payoff route runs the REAL ``OptionsPayoffTool`` (pure math), so happy+ path, multi-leg, validation and tool-error mapping are exercised end to end;+* greeks parity is asserted against a direct ``bs_greeks`` call;+* the chain route's ``OptionsChainTool.execute`` is monkeypatched where the+ route module binds it (``src.api.options_routes.OptionsChainTool``), so the+ Yahoo I/O never happens.++Loopback ``TestClient`` (127.0.0.1) bypasses dev-mode auth, matching the+convention in ``test_alpha_compare_api.py``.+"""++from __future__ import annotations++import json+from typing import Any++import pytest+from fastapi.testclient import TestClient++import api_server+from src.quantlib.options import bs_greeks+++def _client() -> TestClient:+ return TestClient(api_server.app, client=("127.0.0.1", 50000))++[email protected](autouse=True)+def _dev_mode_auth(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("API_AUTH_KEY", raising=False)+ monkeypatch.setattr(api_server, "_API_KEY", "")+++def _long_call_body(**over: Any) -> dict[str, Any]:+ body: dict[str, Any] = {+ "legs": [{"option_type": "call", "strike": 100.0, "qty": 1}],+ "entry_spot": 100.0,+ "expiry_days": 30.0,+ "risk_free_rate": 0.05,+ "volatility": 0.3,+ "multiplier": 1.0,+ }+ body.update(over)+ return body+++# ── POST /options/payoff — happy path ───────────────────────────────────────+++def test_payoff_single_long_call_happy_path() -> None:+ r = _client().post("/options/payoff", json=_long_call_body())++ assert r.status_code == 200+ body = r.json()+ assert body["status"] == "ok"++ summary = body["summary"]+ assert summary["entry_side"] == "debit"+ assert len(summary["breakevens"]) == 1+ assert summary["breakevens"][0] > 100.0++ curve = body["expiry_curve"]+ assert len(curve["spot"]) == len(curve["pnl"])+ assert len(curve["spot"]) == 121 # default spot_points++ grid = body["scenario_grid"]+ assert len(grid["iv_values"]) == 5 # default: 50/75/100/125/150% of entry vol+ assert len(grid["pnl"]) == 5+ assert all(len(row) == len(grid["spot"]) for row in grid["pnl"])++ greeks = body["greeks"]+ assert set(greeks) == {"delta", "gamma", "theta", "vega", "rho"}+ assert 0.0 < greeks["delta"] < 1.0+ assert greeks["theta"] < 0.0+++def test_payoff_iron_condor_bounded_two_breakevens() -> None:+ body = _long_call_body(+ legs=[+ {"option_type": "put", "strike": 85.0, "qty": 1},+ {"option_type": "put", "strike": 90.0, "qty": -1},+ {"option_type": "call", "strike": 110.0, "qty": -1},+ {"option_type": "call", "strike": 115.0, "qty": 1},+ ],+ )++ r = _client().post("/options/payoff", json=body)++ assert r.status_code == 200+ summary = r.json()["summary"]+ assert summary["profit_unbounded"] is False+ assert summary["loss_unbounded"] is False+ assert summary["max_profit"] is not None+ assert summary["max_loss"] is not None+ assert len(summary["breakevens"]) == 2+++def test_payoff_greeks_match_bs_greeks_with_multiplier() -> None:+ legs = [+ {"option_type": "call", "strike": 100.0, "qty": 2},+ {"option_type": "put", "strike": 95.0, "qty": -1},+ ]+ multiplier = 100.0++ r = _client().post(+ "/options/payoff", json=_long_call_body(legs=legs, multiplier=multiplier)+ )+ assert r.status_code == 200+ got = r.json()["greeks"]++ expected = {key: 0.0 for key in ("delta", "gamma", "theta", "vega", "rho")}+ for leg in legs:+ g = bs_greeks(+ S=100.0, K=leg["strike"], T=30.0 / 365.0, r=0.05, sigma=0.3,+ option_type=leg["option_type"],+ )+ for key in expected:+ expected[key] += leg["qty"] * g[key]+ for key in expected:+ expected[key] *= multiplier++ for key in expected:+ assert got[key] == pytest.approx(expected[key], abs=1e-6), key+++# ── POST /options/payoff — validation & tool errors ─────────────────────────+++def test_payoff_rejects_negative_strike() -> None:+ body = _long_call_body(+ legs=[{"option_type": "call", "strike": -1.0, "qty": 1}],+ )+ assert _client().post("/options/payoff", json=body).status_code == 422+++def test_payoff_rejects_empty_legs() -> None:+ assert _client().post("/options/payoff", json=_long_call_body(legs=[])).status_code == 422+++def test_payoff_rejects_zero_qty_and_spot_points_below_min() -> None:+ client = _client()+ zero_qty = _long_call_body(legs=[{"option_type": "call", "strike": 100.0, "qty": 0}])+ assert client.post("/options/payoff", json=zero_qty).status_code == 422++ # spot_points=5 is below the tool's minimum; the pydantic mirror rejects it+ # first, so the route answers 422 (not the tool's 400 envelope).+ small_grid = _long_call_body(spot_points=5)+ assert client.post("/options/payoff", json=small_grid).status_code == 422+++def test_payoff_tool_error_maps_to_400() -> None:+ # Passes pydantic (bounds are independently valid) but the tool refuses an+ # inverted chart window: spot_max must be greater than spot_min.+ body = _long_call_body(spot_min=150.0, spot_max=100.0)++ r = _client().post("/options/payoff", json=body)++ assert r.status_code == 400+ payload = r.json()+ assert payload["status"] == "error"+ assert "spot_max" in payload["error"]+++# ── GET /options/chain ───────────────────────────────────────────────────────++_OK_CHAIN = json.dumps(+ {+ "ok": True,+ "market": "us",+ "source": "yahoo",+ "data": {+ "ticker": "AAPL",+ "expiration": 1765584000,+ "expirations": [1765584000],+ "calls_count": 1,+ "puts_count": 1,+ "calls": [{"contract_symbol": "AAPL260101C00100000", "strike": 100.0}],+ "puts": [{"contract_symbol": "AAPL260101P00100000", "strike": 100.0}],+ },+ }+)+_ERR_CHAIN = json.dumps({"ok": False, "error": "yahoo options request failed: boom"})+++def test_chain_success_returns_tool_envelope(monkeypatch: pytest.MonkeyPatch) -> None:+ seen: dict[str, Any] = {}++ def fake_execute(self: Any, **kwargs: Any) -> str:+ seen.update(kwargs)+ return _OK_CHAIN++ monkeypatch.setattr("src.api.options_routes.OptionsChainTool.execute", fake_execute)++ r = _client().get("/options/chain", params={"ticker": "AAPL", "expiration": 1765584000})++ assert r.status_code == 200+ body = r.json()+ assert body["ok"] is True+ assert body["data"]["ticker"] == "AAPL"+ assert seen == {"ticker": "AAPL", "expiration": 1765584000}+++def test_chain_tool_failure_maps_to_502(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ "src.api.options_routes.OptionsChainTool.execute",+ lambda self, **kwargs: _ERR_CHAIN,+ )++ r = _client().get("/options/chain", params={"ticker": "AAPL"})++ assert r.status_code == 502+ assert r.json() == {"ok": False, "error": "yahoo options request failed: boom"}+++def test_chain_missing_ticker_is_400(monkeypatch: pytest.MonkeyPatch) -> None:+ def explode(self: Any, **kwargs: Any) -> str: # pragma: no cover - must not run+ raise AssertionError("tool must not be called for a blank ticker")++ monkeypatch.setattr("src.api.options_routes.OptionsChainTool.execute", explode)++ client = _client()+ for params in ({}, {"ticker": ""}, {"ticker": " "}):+ r = client.get("/options/chain", params=params)+ assert r.status_code == 400+ assert r.json() == {"ok": False, "error": "ticker is required"}diff --git a/frontend/src/components/charts/OptionsPayoffChart.tsx b/frontend/src/components/charts/OptionsPayoffChart.tsxnew file mode 100644index 000000000..987d05642--- /dev/null+++ b/frontend/src/components/charts/OptionsPayoffChart.tsx@@ -0,0 +1,175 @@+import { useEffect, useRef } from "react";+import i18n from "@/i18n";+import type { ExpiryCurve } from "@/lib/options";+import { getChartTheme } from "@/lib/chart-theme";+import { getPnlColors } from "@/lib/pnl-colors";+import { abbreviateNum } from "@/lib/formatters";+import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";+import { useThemeDark } from "@/lib/theme-store";++interface Props {+ curve: ExpiryCurve;+ entrySpot: number;+ breakevens: number[];+ height?: number;+}++export function OptionsPayoffChart({ curve, entrySpot, breakevens, height = 340 }: Props) {+ const ref = useRef<HTMLDivElement>(null);+ const dark = useThemeDark();++ useEffect(() => {+ if (!ref.current || curve.spot.length === 0 || curve.pnl.length === 0) return;+ const t = getChartTheme();+ const pnlC = getPnlColors();+ const chart = echarts.init(ref.current);+ chart.group = CHART_GROUP;+ connectCharts();++ const pnlLabel = i18n.t("options.payoff.pnl");+ const spotLabel = i18n.t("options.payoff.entrySpot");+ const beLabel = i18n.t("options.payoff.breakeven");++ const pairs: [number, number][] = curve.spot.map((s, idx) => [s, curve.pnl[idx] ?? 0]);+ const profitData = pairs.map(([s, v]) => [s, v >= 0 ? v : null]);+ const lossData = pairs.map(([s, v]) => [s, v <= 0 ? v : null]);++ chart.setOption({+ backgroundColor: "transparent",+ tooltip: {+ trigger: "axis",+ axisPointer: { type: "cross" },+ backgroundColor: t.tooltipBg,+ borderColor: t.tooltipBorder,+ textStyle: { color: t.tooltipText, fontSize: 11 },+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ formatter: (params: any) => {+ if (!Array.isArray(params) || !params.length) return "";+ const main = params.find((p) => p.seriesName === pnlLabel) ?? params[0];+ const [spotVal, pnlVal] = Array.isArray(main.value) ? main.value : [main.axisValue, NaN];+ const pnlNum = Number(pnlVal);+ const pnlText = Number.isFinite(pnlNum)+ ? pnlNum.toLocaleString(undefined, { maximumFractionDigits: 2 })+ : "–";+ return `<b>${Number(spotVal).toLocaleString()}</b><br/>${main.marker} ${pnlLabel}: <b>${pnlText}</b>`;+ },+ },+ legend: {+ data: [pnlLabel],+ textStyle: { color: t.textColor, fontSize: 11 },+ right: 60,+ top: 4,+ },+ toolbox: {+ feature: {+ saveAsImage: { title: "Save" },+ restore: { title: "Reset" },+ },+ right: 8,+ top: 0,+ iconStyle: { borderColor: t.textColor },+ },+ grid: { left: 8, right: 16, top: 36, bottom: 8, containLabel: true },+ xAxis: {+ type: "value",+ name: i18n.t("options.payoff.spot"),+ nameTextStyle: { color: t.textColor, fontSize: 10 },+ nameLocation: "middle",+ nameGap: 26,+ axisLine: { lineStyle: { color: t.axisColor } },+ axisLabel: {+ color: t.textColor,+ fontSize: 10,+ formatter: (v: number) => v.toLocaleString(),+ },+ splitLine: { show: false },+ },+ yAxis: {+ type: "value",+ splitLine: { lineStyle: { color: t.gridColor } },+ axisLabel: { color: t.textColor, fontSize: 10, formatter: (v: number) => abbreviateNum(v) },+ },+ series: [+ {+ name: pnlLabel,+ type: "line",+ data: pairs,+ smooth: false,+ symbol: "none",+ lineStyle: { color: t.infoColor, width: 2 },+ markLine: {+ silent: true,+ symbol: "none",+ data: [+ {+ yAxis: 0,+ lineStyle: { color: t.axisColor, type: "solid", width: 1 },+ label: { show: false },+ },+ {+ xAxis: entrySpot,+ lineStyle: { color: t.textColor, type: "dashed", width: 1 },+ label: {+ formatter: spotLabel,+ position: "end",+ fontSize: 10,+ color: t.textColor,+ },+ },+ ...breakevens.map((be) => ({+ xAxis: be,+ lineStyle: { color: t.warningColor, type: "dashed", width: 1 },+ label: {+ formatter: `${beLabel} ${be.toLocaleString()}`,+ position: "middle" as const,+ fontSize: 10,+ color: t.warningColor,+ },+ })),+ ],+ },+ },+ {+ name: "profit-fill",+ type: "line",+ data: profitData,+ silent: true,+ symbol: "none",+ lineStyle: { width: 0 },+ areaStyle: { origin: 0, color: pnlC.profit + "30" },+ tooltip: { show: false },+ },+ {+ name: "loss-fill",+ type: "line",+ data: lossData,+ silent: true,+ symbol: "none",+ lineStyle: { width: 0 },+ areaStyle: { origin: 0, color: pnlC.loss + "30" },+ tooltip: { show: false },+ },+ ],+ });++ let resizeFrame: number | null = null;+ const ro = new ResizeObserver(() => {+ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);+ resizeFrame = requestAnimationFrame(() => {+ resizeFrame = null;+ chart.resize();+ });+ });+ ro.observe(ref.current!);+ return () => {+ ro.disconnect();+ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);+ chart.dispose();+ };+ }, [curve, entrySpot, breakevens, dark]);++ if (curve.spot.length === 0 || curve.pnl.length === 0) {+ return <div className="text-muted-foreground text-sm p-4">{i18n.t("options.payoff.noData")}</div>;+ }+ return <div ref={ref} style={{ height }} />;+}diff --git a/frontend/src/components/charts/OptionsScenarioMatrix.tsx b/frontend/src/components/charts/OptionsScenarioMatrix.tsxnew file mode 100644index 000000000..cad408aa3--- /dev/null+++ b/frontend/src/components/charts/OptionsScenarioMatrix.tsx@@ -0,0 +1,142 @@+import { useEffect, useRef } from "react";+import i18n from "@/i18n";+import { downsampleIndices, ivLabel, type ScenarioGrid } from "@/lib/options";+import { getChartTheme } from "@/lib/chart-theme";+import { getPnlColors } from "@/lib/pnl-colors";+import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";+import { useThemeDark } from "@/lib/theme-store";++const MAX_DISPLAY_COLUMNS = 61;++interface Props {+ grid: ScenarioGrid;+ height?: number;+}++export function OptionsScenarioMatrix({ grid, height = 380 }: Props) {+ const ref = useRef<HTMLDivElement>(null);+ const dark = useThemeDark();++ const hasData =+ grid.iv_values.length > 0 && grid.spot.length > 0 && grid.pnl.length > 0;++ useEffect(() => {+ if (!ref.current || !hasData) return;+ const t = getChartTheme();+ const pnlC = getPnlColors();+ const chart = echarts.init(ref.current);+ chart.group = CHART_GROUP;+ connectCharts();++ // Downsample the spot axis for display only; cell values keep reading the+ // original grid at the retained indices, so labels stay honest.+ const colIdx = downsampleIndices(grid.spot.length, MAX_DISPLAY_COLUMNS);+ const spotLabels = colIdx.map((i) => grid.spot[i].toLocaleString());+ const ivLabels = grid.iv_values.map((iv) => ivLabel(iv));++ const data: [number, number, number][] = [];+ let minVal = 0;+ let maxVal = 0;+ for (let r = 0; r < grid.iv_values.length; r++) {+ const row = grid.pnl[r] ?? [];+ for (let c = 0; c < colIdx.length; c++) {+ const v = row[colIdx[c]];+ if (!Number.isFinite(v)) continue;+ data.push([c, r, Number(v.toFixed(2))]);+ if (v < minVal) minVal = v;+ if (v > maxVal) maxVal = v;+ }+ }+ const bound = Math.max(Math.abs(minVal), Math.abs(maxVal), 1e-9);++ chart.setOption({+ backgroundColor: "transparent",+ tooltip: {+ position: "top",+ backgroundColor: t.tooltipBg,+ borderColor: t.tooltipBorder,+ textStyle: { color: t.tooltipText, fontSize: 12 },+ formatter: (params: unknown) => {+ const p = params as { data: [number, number, number] };+ const [x, y, v] = p.data;+ return (+ `<b>${i18n.t("options.scenario.spotAxis")}</b>: ${spotLabels[x] ?? "?"}` ++ `<br/><b>${i18n.t("options.scenario.ivAxis")}</b>: ${ivLabels[y] ?? "?"}` ++ `<br/><b>${i18n.t("options.scenario.pnl")}</b>: ${v.toLocaleString()}`+ );+ },+ },+ grid: { left: "3%", right: "10%", top: "8%", bottom: "14%", containLabel: true },+ xAxis: {+ type: "category",+ data: spotLabels,+ name: i18n.t("options.scenario.spotAxis"),+ nameTextStyle: { color: t.textColor, fontSize: 10 },+ nameLocation: "middle",+ nameGap: 30,+ axisLabel: { color: t.textColor, fontSize: 10, rotate: 30 },+ axisLine: { lineStyle: { color: t.axisColor } },+ splitArea: { show: false },+ },+ yAxis: {+ type: "category",+ data: ivLabels,+ name: i18n.t("options.scenario.ivAxis"),+ nameTextStyle: { color: t.textColor, fontSize: 10 },+ axisLabel: { color: t.textColor, fontSize: 10, interval: 0 },+ axisLine: { lineStyle: { color: t.axisColor } },+ splitArea: { show: false },+ },+ visualMap: {+ min: -bound,+ max: bound,+ precision: 0,+ calculable: true,+ orient: "vertical",+ right: 8,+ top: "center",+ textStyle: { color: t.textColor, fontSize: 11 },+ inRange: { color: [pnlC.loss, pnlC.neutral, pnlC.profit] },+ },+ series: [+ {+ name: i18n.t("options.scenario.pnl"),+ type: "heatmap",+ data,+ label: {+ show: colIdx.length <= 16 && grid.iv_values.length <= 6,+ fontSize: 10,+ color: t.textColor,+ formatter: (params: unknown) => {+ const p = params as { value: [number, number, number] };+ return p.value[2].toLocaleString(undefined, { maximumFractionDigits: 0 });+ },+ },+ emphasis: {+ itemStyle: { shadowBlur: 10, shadowColor: "rgba(0, 0, 0, 0.5)" },+ },+ },+ ],+ });++ let resizeFrame: number | null = null;+ const ro = new ResizeObserver(() => {+ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);+ resizeFrame = requestAnimationFrame(() => {+ resizeFrame = null;+ chart.resize();+ });+ });+ ro.observe(ref.current!);+ return () => {+ ro.disconnect();+ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);+ chart.dispose();+ };+ }, [grid, hasData, dark]);++ if (!hasData) {+ return <div className="text-muted-foreground text-sm p-4">{i18n.t("options.scenario.noData")}</div>;+ }+ return <div ref={ref} style={{ height }} />;+}diff --git a/frontend/src/components/layout/Layout.tsx b/frontend/src/components/layout/Layout.tsxindex 65fa99901..eda13e248 100644--- a/frontend/src/components/layout/Layout.tsx+++ b/frontend/src/components/layout/Layout.tsx@@ -1,7 +1,7 @@import { useTranslation } from "react-i18next";import { useEffect, useRef, useState } from "react";import { Link, Outlet, useLocation, useSearchParams } from "react-router";-import { Activity, BarChart3, Bot, CalendarClock, Check, ChevronDown, FileText, Languages, Moon, Sun, Plus, Trash2, Pencil, MessageSquare, ChevronsLeft, ChevronsRight, Settings, Layers, Loader2 } from "lucide-react";+import { Activity, BarChart3, Bot, CalendarClock, CandlestickChart, Check, ChevronDown, FileText, Languages, Moon, Sun, Plus, Trash2, Pencil, MessageSquare, ChevronsLeft, ChevronsRight, Settings, Layers, Loader2 } from "lucide-react";import { cn } from "@/lib/utils";import { useDarkMode } from "@/hooks/useDarkMode";import { api, type SessionItem } from "@/lib/api";@@ -25,6 +25,7 @@ export function Layout() {{ to: "/scheduled", icon: CalendarClock, label: t('layout.scheduled') },{ to: "/reports", icon: FileText, label: t('layout.reports') },{ to: "/alpha-zoo", icon: Layers, label: t('layout.alphaZoo') },+ { to: "/options", icon: CandlestickChart, label: t('layout.optionsLab') },{ to: "/settings", icon: Settings, label: t('layout.settings') },{ to: "/correlation", icon: BarChart3, label: t('layout.correlation') },];diff --git a/frontend/src/components/options/GreeksCards.tsx b/frontend/src/components/options/GreeksCards.tsxnew file mode 100644index 000000000..acce979b2--- /dev/null+++ b/frontend/src/components/options/GreeksCards.tsx@@ -0,0 +1,70 @@+import { useTranslation } from "react-i18next";+import { cn } from "@/lib/utils";+import type { OptionsGreeks } from "@/lib/options";++type Tone = "positive" | "negative" | "warning" | "neutral";++const TONE_CLS: Record<Tone, string> = {+ positive: "text-success",+ negative: "text-danger",+ warning: "text-warning",+ neutral: "text-foreground",+};++function GreekCard({ label, value, desc, tone }: { label: string; value: string; desc: string; tone: Tone }) {+ return (+ <div className="rounded-xl border border-border/60 bg-card p-4 shadow-sm">+ <div className="text-xs text-muted-foreground">{label}</div>+ <div className={cn("mt-1 truncate text-lg font-semibold tabular-nums", TONE_CLS[tone])}>{value}</div>+ <div className="mt-1 text-xs leading-snug text-muted-foreground">{desc}</div>+ </div>+ );+}++interface Props {+ greeks: OptionsGreeks;+}++export function GreeksCards({ greeks }: Props) {+ const { t } = useTranslation();++ const signTone = (v: number): Tone => (v > 0 ? "positive" : v < 0 ? "negative" : "neutral");++ return (+ <section>+ <div className="mb-2 text-sm font-semibold">{t("options.greeks.title")}</div>+ <div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-5">+ <GreekCard+ label={t("options.greeks.delta")}+ value={greeks.delta.toLocaleString(undefined, { maximumFractionDigits: 2 })}+ desc={t("options.greeks.deltaDesc")}+ tone={signTone(greeks.delta)}+ />+ <GreekCard+ label={t("options.greeks.gamma")}+ value={greeks.gamma.toLocaleString(undefined, { maximumFractionDigits: 4 })}+ desc={t("options.greeks.gammaDesc")}+ tone="neutral"+ />+ <GreekCard+ label={t("options.greeks.theta")}+ value={greeks.theta.toLocaleString(undefined, { maximumFractionDigits: 2 })}+ desc={t("options.greeks.thetaDesc")}+ tone={greeks.theta < 0 ? "warning" : signTone(greeks.theta)}+ />+ <GreekCard+ label={t("options.greeks.vega")}+ value={greeks.vega.toLocaleString(undefined, { maximumFractionDigits: 2 })}+ desc={t("options.greeks.vegaDesc")}+ tone={signTone(greeks.vega)}+ />+ <GreekCard+ label={t("options.greeks.rho")}+ value={greeks.rho.toLocaleString(undefined, { maximumFractionDigits: 2 })}+ desc={t("options.greeks.rhoDesc")}+ tone="neutral"+ />+ </div>+ </section>+ );+}diff --git a/frontend/src/components/options/OptionsChainTable.tsx b/frontend/src/components/options/OptionsChainTable.tsxnew file mode 100644index 000000000..51c26b104--- /dev/null+++ b/frontend/src/components/options/OptionsChainTable.tsx@@ -0,0 +1,270 @@+import { useCallback, useEffect, useMemo, useRef, useState, type FormEvent } from "react";+import { useTranslation } from "react-i18next";+import { Loader2 } from "lucide-react";+import { cn } from "@/lib/utils";+import { api } from "@/lib/api";+import {+ bidAskSpreadPct,+ expirationLabel,+ nearestStrikeIndex,+ type OptionsChainData,+ type OptionsContractRow,+} from "@/lib/options";++const DEFAULT_TICKER = "AAPL";++function fmt(v: number | null, maxDigits = 2): string {+ if (v === null || !Number.isFinite(v)) return "–";+ return v.toLocaleString(undefined, { maximumFractionDigits: maxDigits });+}++function fmtInt(v: number | null): string {+ if (v === null || !Number.isFinite(v)) return "–";+ return Math.round(v).toLocaleString();+}++function fmtIv(v: number | null): string {+ if (v === null || !Number.isFinite(v)) return "–";+ return `${(v * 100).toFixed(1)}%`;+}++function fmtSpread(bid: number | null, ask: number | null): string {+ const pct = bidAskSpreadPct(bid, ask);+ return pct === null ? "–" : `${pct.toFixed(2)}%`;+}++interface WingTableProps {+ title: string;+ rows: OptionsContractRow[];+ atmStrike: number | null;+}++function WingTable({ title, rows, atmStrike }: WingTableProps) {+ const { t } = useTranslation();+ const sorted = useMemo(() => [...rows].sort((a, b) => a.strike - b.strike), [rows]);++ const headers = [+ t("options.chain.strike"),+ t("options.chain.last"),+ t("options.chain.bid"),+ t("options.chain.ask"),+ t("options.chain.spread"),+ t("options.chain.volume"),+ t("options.chain.openInterest"),+ t("options.chain.iv"),+ t("options.chain.itm"),+ ];++ return (+ <div>+ <div className="mb-1.5 text-xs font-semibold text-muted-foreground">{title}</div>+ <div className="overflow-x-auto">+ <table className="w-full text-sm">+ <thead>+ <tr className="text-xs text-muted-foreground">+ {headers.map((h, i) => (+ <th+ key={h}+ className={cn(+ "border-b border-border/60 pb-1.5 pe-3 font-medium whitespace-nowrap",+ i === 0 ? "text-start" : "text-end",+ )}+ >+ {h}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {sorted.map((row) => {+ const isAtm = atmStrike !== null && row.strike === atmStrike;+ return (+ <tr+ key={row.contract_symbol}+ className={cn(+ "border-b border-border/30 transition-colors",+ isAtm ? "bg-primary/10" : "hover:bg-muted/40",+ )}+ >+ <td className="py-1.5 pe-3 text-start font-medium tabular-nums whitespace-nowrap">+ {fmt(row.strike)}+ {isAtm && (+ <span className="ms-1.5 rounded bg-primary/15 px-1 py-0.5 text-[10px] font-medium text-primary">+ {t("options.chain.atm")}+ </span>+ )}+ </td>+ <td className="py-1.5 pe-3 text-end tabular-nums">{fmt(row.last_price)}</td>+ <td className="py-1.5 pe-3 text-end tabular-nums">{fmt(row.bid)}</td>+ <td className="py-1.5 pe-3 text-end tabular-nums">{fmt(row.ask)}</td>+ <td className="py-1.5 pe-3 text-end tabular-nums text-muted-foreground">+ {fmtSpread(row.bid, row.ask)}+ </td>+ <td className="py-1.5 pe-3 text-end tabular-nums">{fmtInt(row.volume)}</td>+ <td className="py-1.5 pe-3 text-end tabular-nums">{fmtInt(row.open_interest)}</td>+ <td className="py-1.5 pe-3 text-end tabular-nums">{fmtIv(row.implied_volatility)}</td>+ <td className="py-1.5 text-end">+ {row.in_the_money && (+ <span className="rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground">+ {t("options.chain.itm")}+ </span>+ )}+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ </div>+ );+}++function SkeletonRows() {+ return (+ <div className="space-y-1.5 py-2">+ {[1, 2, 3, 4, 5, 6].map((i) => (+ <div key={i} className="h-6 rounded bg-muted/50 animate-pulse" />+ ))}+ </div>+ );+}++interface Props {+ /** Entry spot from the builder — anchors the ATM highlight when available. */+ referenceSpot?: number;+}++export function OptionsChainTable({ referenceSpot }: Props) {+ const { t } = useTranslation();+ const [tickerInput, setTickerInput] = useState(DEFAULT_TICKER);+ const [data, setData] = useState<OptionsChainData | null>(null);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const generation = useRef(0);++ const load = useCallback(async (ticker: string, expiration?: number) => {+ const gen = ++generation.current;+ setLoading(true);+ setError(null);+ try {+ const res = await api.getOptionsChain(ticker, expiration);+ if (generation.current !== gen) return;+ if (!res.ok || !res.data) {+ setError(res.error || t("options.chain.errorTitle"));+ setData(null);+ return;+ }+ setData(res.data);+ } catch (e) {+ if (generation.current !== gen) return;+ setError(e instanceof Error ? e.message : t("options.chain.errorTitle"));+ setData(null);+ } finally {+ if (generation.current === gen) setLoading(false);+ }+ }, [t]);++ useEffect(() => {+ void load(DEFAULT_TICKER);+ }, [load]);++ const onSubmit = (e: FormEvent) => {+ e.preventDefault();+ const ticker = tickerInput.trim().toUpperCase();+ if (!ticker) return;+ void load(ticker);+ };++ const atmStrike = useMemo(() => {+ if (!data) return null;+ const rows = data.calls.length > 0 ? data.calls : data.puts;+ if (rows.length === 0) return null;+ const anchor =+ referenceSpot !== undefined && Number.isFinite(referenceSpot) && referenceSpot > 0+ ? referenceSpot+ : [...rows].sort((a, b) => a.strike - b.strike)[Math.floor(rows.length / 2)].strike;+ return rows[nearestStrikeIndex(rows, anchor)].strike;+ }, [data, referenceSpot]);++ return (+ <section className="rounded-xl border border-border/60 bg-card p-4 shadow-sm">+ <div className="mb-3 flex flex-wrap items-center justify-between gap-3">+ <div className="text-sm font-semibold">{t("options.chain.title")}</div>+ <form onSubmit={onSubmit} className="flex flex-wrap items-center gap-2">+ <input+ type="text"+ value={tickerInput}+ onChange={(e) => setTickerInput(e.target.value)}+ placeholder={DEFAULT_TICKER}+ aria-label={t("options.chain.ticker")}+ className="w-24 rounded-md border border-border/60 bg-background px-2 py-1.5 text-sm uppercase outline-none focus:ring-2 focus:ring-primary/40"+ />+ <select+ value={data?.expiration ?? ""}+ onChange={(e) => {+ const exp = e.target.value === "" ? undefined : Number(e.target.value);+ if (data) void load(data.ticker, exp);+ }}+ disabled={!data || loading}+ aria-label={t("options.chain.expiration")}+ className="rounded-md border border-border/60 bg-background px-2 py-1.5 text-sm outline-none focus:ring-2 focus:ring-primary/40 disabled:opacity-50"+ >+ {(data?.expirations ?? []).map((exp) => (+ <option key={exp} value={exp}>+ {expirationLabel(exp)}+ </option>+ ))}+ </select>+ <button+ type="submit"+ disabled={loading}+ className="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground transition-opacity hover:opacity-90 disabled:opacity-50"+ >+ {t("options.chain.load")}+ </button>+ </form>+ </div>++ {error && (+ <div className="mb-3 flex items-center justify-between gap-3 rounded border border-danger/30 bg-danger/5 p-3 text-sm text-danger">+ <span>+ <b>{t("options.chain.errorTitle")}.</b> {error}+ </span>+ <button+ type="button"+ onClick={() => void load(data?.ticker ?? tickerInput.trim().toUpperCase() ?? DEFAULT_TICKER, data?.expiration)}+ className="shrink-0 rounded border border-danger/40 px-2.5 py-1 text-xs font-medium transition-colors hover:bg-danger/10"+ >+ {t("options.chain.retry")}+ </button>+ </div>+ )}++ {loading ? (+ <div aria-label={t("options.chain.loading")}>+ <div className="mb-2 flex items-center gap-2 text-xs text-muted-foreground">+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ {t("options.chain.loading")}+ </div>+ <SkeletonRows />+ </div>+ ) : data ? (+ data.calls.length === 0 && data.puts.length === 0 ? (+ <p className="text-sm text-muted-foreground">{t("options.chain.noData")}</p>+ ) : (+ <div className="flex flex-col gap-5">+ {data.calls.length > 0 && (+ <WingTable title={t("options.chain.calls")} rows={data.calls} atmStrike={atmStrike} />+ )}+ {data.puts.length > 0 && (+ <WingTable title={t("options.chain.puts")} rows={data.puts} atmStrike={atmStrike} />+ )}+ </div>+ )+ ) : !error ? (+ <p className="text-sm text-muted-foreground">{t("options.chain.noData")}</p>+ ) : null}+ </section>+ );+}diff --git a/frontend/src/components/options/StrategyBuilder.tsx b/frontend/src/components/options/StrategyBuilder.tsxnew file mode 100644index 000000000..40297c078--- /dev/null+++ b/frontend/src/components/options/StrategyBuilder.tsx@@ -0,0 +1,257 @@+import { useTranslation } from "react-i18next";+import { Plus, Trash2 } from "lucide-react";+import { cn } from "@/lib/utils";+import {+ buildPayoffRequest,+ roundToNiceStrike,+ STRATEGY_PRESETS,+ type OptionLeg,+ type OptionsLabParams,+} from "@/lib/options";++interface Props {+ legs: OptionLeg[];+ params: OptionsLabParams;+ activePresetId: string | null;+ onApplyPreset: (presetId: string) => void;+ onLegsChange: (legs: OptionLeg[]) => void;+ onParamsChange: (params: OptionsLabParams) => void;+}++const INPUT_CLS =+ "w-full rounded-md border border-border/60 bg-background px-2 py-1.5 text-sm outline-none focus:ring-2 focus:ring-primary/40";++export function StrategyBuilder({+ legs,+ params,+ activePresetId,+ onApplyPreset,+ onLegsChange,+ onParamsChange,+}: Props) {+ const { t } = useTranslation();++ const updateLeg = (index: number, patch: Partial<OptionLeg>) => {+ onLegsChange(legs.map((leg, i) => (i === index ? { ...leg, ...patch } : leg)));+ };++ const removeLeg = (index: number) => {+ onLegsChange(legs.filter((_, i) => i !== index));+ };++ const addLeg = () => {+ onLegsChange([+ ...legs,+ {+ option_type: "call",+ strike: roundToNiceStrike(params.entry_spot) || 100,+ qty: 1,+ },+ ]);+ };++ const setParam = (patch: Partial<OptionsLabParams>) => {+ onParamsChange({ ...params, ...patch });+ };++ const inputsValid = buildPayoffRequest(legs, params) !== null;++ return (+ <section className="rounded-xl border border-border/60 bg-card p-4 shadow-sm">+ <div className="mb-3 text-sm font-semibold">{t("options.builder.title")}</div>++ {/* Presets */}+ <div className="mb-1 text-xs font-medium text-muted-foreground">{t("options.presets.label")}</div>+ <div className="mb-4 flex flex-wrap gap-1.5">+ {STRATEGY_PRESETS.map((preset) => (+ <button+ key={preset.id}+ type="button"+ onClick={() => onApplyPreset(preset.id)}+ className={cn(+ "rounded border px-2.5 py-1 text-xs transition-colors",+ activePresetId === preset.id+ ? "border-primary bg-primary text-primary-foreground"+ : "border-muted-foreground/30 text-muted-foreground hover:border-primary hover:text-foreground",+ )}+ >+ {t(preset.nameKey as never)}+ </button>+ ))}+ </div>++ {/* Legs table */}+ <div className="mb-1 flex items-center justify-between">+ <span className="text-xs font-medium text-muted-foreground">{t("options.builder.legs")}</span>+ <span className="text-[10px] text-muted-foreground/70">{t("options.builder.qtyHint")}</span>+ </div>+ <div className="overflow-x-auto">+ <table className="w-full text-sm">+ <thead>+ <tr className="text-xs text-muted-foreground">+ <th className="pb-1.5 pe-2 font-medium text-start">{t("options.builder.type")}</th>+ <th className="pb-1.5 pe-2 font-medium text-start">{t("options.builder.strike")}</th>+ <th className="pb-1.5 pe-2 font-medium text-start">{t("options.builder.qty")}</th>+ <th className="pb-1.5 pe-2 font-medium text-start">{t("options.builder.premium")}</th>+ <th className="pb-1.5 font-medium" aria-hidden="true" />+ </tr>+ </thead>+ <tbody>+ {legs.map((leg, i) => (+ <tr key={i} className="border-t border-border/40">+ <td className="py-1.5 pe-2">+ <select+ value={leg.option_type}+ onChange={(e) => updateLeg(i, { option_type: e.target.value as OptionLeg["option_type"] })}+ className={cn(INPUT_CLS, "min-w-20")}+ aria-label={`${t("options.builder.type")} ${i + 1}`}+ >+ <option value="call">{t("options.builder.call")}</option>+ <option value="put">{t("options.builder.put")}</option>+ </select>+ </td>+ <td className="py-1.5 pe-2">+ <input+ type="number"+ min={0}+ step="any"+ value={Number.isFinite(leg.strike) ? leg.strike : ""}+ onChange={(e) => updateLeg(i, { strike: parseFloat(e.target.value) })}+ className={cn(INPUT_CLS, "min-w-20 tabular-nums")}+ aria-label={`${t("options.builder.strike")} ${i + 1}`}+ />+ </td>+ <td className="py-1.5 pe-2">+ <input+ type="number"+ step={1}+ value={Number.isFinite(leg.qty) ? leg.qty : ""}+ onChange={(e) => updateLeg(i, { qty: parseInt(e.target.value, 10) })}+ className={cn(INPUT_CLS, "min-w-16 tabular-nums")}+ aria-label={`${t("options.builder.qty")} ${i + 1}`}+ />+ </td>+ <td className="py-1.5 pe-2">+ <input+ type="number"+ min={0}+ step="any"+ placeholder="BS"+ value={leg.premium === undefined ? "" : leg.premium}+ onChange={(e) =>+ updateLeg(i, {+ premium: e.target.value === "" ? undefined : parseFloat(e.target.value),+ })+ }+ className={cn(INPUT_CLS, "min-w-20 tabular-nums")}+ aria-label={`${t("options.builder.premium")} ${i + 1}`}+ title={t("options.builder.premiumHint")}+ />+ </td>+ <td className="py-1.5 text-end">+ <button+ type="button"+ onClick={() => removeLeg(i)}+ disabled={legs.length <= 1}+ className="rounded p-1.5 text-muted-foreground transition-colors hover:bg-danger/10 hover:text-danger disabled:opacity-30"+ aria-label={`${t("options.builder.removeLeg")} ${i + 1}`}+ >+ <Trash2 className="h-3.5 w-3.5" />+ </button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ <div className="mt-2 flex items-center justify-between gap-2">+ <button+ type="button"+ onClick={addLeg}+ className="flex items-center gap-1 rounded-md border border-dashed border-muted-foreground/40 px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:border-primary hover:text-foreground"+ >+ <Plus className="h-3 w-3" />+ {t("options.builder.addLeg")}+ </button>+ <span className="text-[10px] text-muted-foreground/70">{t("options.builder.premiumHint")}</span>+ </div>++ {/* Parameters */}+ <div className="mt-4 mb-2 text-xs font-medium text-muted-foreground">{t("options.builder.parameters")}</div>+ <div className="grid grid-cols-2 gap-3">+ <div className="flex flex-col gap-1">+ <label className="text-[11px] text-muted-foreground">{t("options.builder.entrySpot")}</label>+ <input+ type="number"+ min={0}+ step="any"+ value={Number.isFinite(params.entry_spot) ? params.entry_spot : ""}+ onChange={(e) => setParam({ entry_spot: parseFloat(e.target.value) })}+ className={cn(INPUT_CLS, "tabular-nums")}+ />+ </div>+ <div className="flex flex-col gap-1">+ <label className="text-[11px] text-muted-foreground">{t("options.builder.expiryDays")}</label>+ <input+ type="number"+ min={0}+ step={1}+ value={Number.isFinite(params.expiry_days) ? params.expiry_days : ""}+ onChange={(e) => setParam({ expiry_days: parseFloat(e.target.value) })}+ className={cn(INPUT_CLS, "tabular-nums")}+ />+ </div>+ <div className="flex flex-col gap-1">+ <label className="text-[11px] text-muted-foreground">{t("options.builder.volatility")}</label>+ <input+ type="number"+ min={0}+ step="any"+ value={Number.isFinite(params.volatility_pct) ? params.volatility_pct : ""}+ onChange={(e) => setParam({ volatility_pct: parseFloat(e.target.value) })}+ className={cn(INPUT_CLS, "tabular-nums")}+ />+ </div>+ <div className="flex flex-col gap-1">+ <label className="text-[11px] text-muted-foreground">{t("options.builder.riskFreeRate")}</label>+ <input+ type="number"+ step="any"+ value={Number.isFinite(params.risk_free_rate_pct) ? params.risk_free_rate_pct : ""}+ onChange={(e) => setParam({ risk_free_rate_pct: parseFloat(e.target.value) })}+ className={cn(INPUT_CLS, "tabular-nums")}+ />+ </div>+ <div className="flex flex-col gap-1">+ <label className="text-[11px] text-muted-foreground">{t("options.builder.multiplier")}</label>+ <input+ type="number"+ min={0}+ step="any"+ value={Number.isFinite(params.multiplier) ? params.multiplier : ""}+ onChange={(e) => setParam({ multiplier: parseFloat(e.target.value) })}+ className={cn(INPUT_CLS, "tabular-nums")}+ />+ <span className="text-[10px] text-muted-foreground/70">{t("options.builder.multiplierHint")}</span>+ </div>+ <div className="flex flex-col gap-1">+ <label className="text-[11px] text-muted-foreground">{t("options.builder.commissionRate")}</label>+ <input+ type="number"+ min={0}+ step="any"+ value={Number.isFinite(params.commission_rate_pct) ? params.commission_rate_pct : ""}+ onChange={(e) => setParam({ commission_rate_pct: parseFloat(e.target.value) })}+ className={cn(INPUT_CLS, "tabular-nums")}+ />+ </div>+ </div>++ {!inputsValid && (+ <p className="mt-3 rounded border border-warning/30 bg-warning/5 p-2 text-xs text-warning">+ {t("options.builder.invalidHint")}+ </p>+ )}+ </section>+ );+}diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex fc848e30e..7329fc245 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -11,6 +11,7 @@"alphaZoo": "مكتبة ألفا","settings": "الإعدادات","correlation": "مصفوفة الارتباط",+ "optionsLab": "مختبر الخيارات","sessions": "الجلسات","newChat": "محادثة جديدة","noSessions": "لا توجد محادثات بعد — اضغط + لبدء محادثة",@@ -670,6 +671,112 @@"regimeEnterThreshold": "عتبة الدخول","regimeExitThreshold": "عتبة الخروج"},+ "options": {+ "title": "مختبر الخيارات",+ "subtitle": "منشئ الاستراتيجيات، العائد عند الانتهاء، سيناريوهات السعر × التقلب الضمني، إغريقيات المحفظة، وسلسلة الخيارات الأمريكية الحية.",+ "disclaimer": "للأغراض البحثية فقط. التسعير النظري ونتائج السيناريوهات تقديرات نموذجية وليست نصيحة استثمارية.",+ "errorGeneric": "فشل التحليل",+ "presets": {+ "label": "الاستراتيجيات الجاهزة",+ "longCall": "شراء خيار شراء",+ "longPut": "شراء خيار بيع",+ "bullCallSpread": "فرق خيارات شراء صاعد",+ "bearPutSpread": "فرق خيارات بيع هابط",+ "bullPutSpread": "فرق خيارات بيع صاعد",+ "bearCallSpread": "فرق خيارات شراء هابط",+ "longStraddle": "سترادل طويل",+ "longStrangle": "سترانجل طويل",+ "ironCondor": "الكوندور الحديدي",+ "ironButterfly": "الفراشة الحديدية",+ "callButterfly": "فراشة خيارات الشراء",+ "ratioCallSpread": "فرق نسبي لخيارات الشراء"+ },+ "builder": {+ "title": "منشئ الاستراتيجيات",+ "legs": "الأرجل",+ "type": "النوع",+ "call": "خيار شراء",+ "put": "خيار بيع",+ "strike": "سعر التنفيذ",+ "qty": "الكمية",+ "premium": "العلاوة",+ "premiumHint": "العلاوة الفارغة = التسعير بنموذج Black-Scholes عبر المحرك",+ "qtyHint": "موجب = شراء (طويل)، سالب = بيع (قصير)",+ "addLeg": "إضافة رجل",+ "removeLeg": "حذف رجل",+ "parameters": "المعاملات",+ "entrySpot": "سعر الأصل عند الدخول",+ "expiryDays": "الأيام حتى الانتهاء",+ "volatility": "التقلب (%)",+ "riskFreeRate": "المعدل الخالي من المخاطر (%)",+ "multiplier": "المضاعف",+ "multiplierHint": "100 = عقد الأسهم الأمريكية القياسي",+ "commissionRate": "معدل العمولة (%)",+ "invalidHint": "تحقق من المدخلات: سعر الأصل وأسعار التنفيذ موجبة، الكميات أعداد صحيحة غير صفرية، التقلب موجب.",+ "analyzing": "جارٍ التحليل…"+ },+ "metrics": {+ "entryCost": "تكلفة الدخول",+ "debit": "مدين",+ "credit": "دائن",+ "flat": "متعادل",+ "breakevens": "نقاط التعادل",+ "maxProfit": "أقصى ربح",+ "maxLoss": "أقصى خسارة",+ "unlimited": "غير محدود",+ "none": "لا شيء"+ },+ "payoff": {+ "title": "العائد عند الانتهاء",+ "pnl": "الربح/الخسارة",+ "spot": "سعر الأصل عند الانتهاء",+ "entrySpot": "السعر",+ "breakeven": "نقطة التعادل",+ "noData": "لا توجد بيانات عائد بعد — أنشئ استراتيجية أعلاه."+ },+ "greeks": {+ "title": "إغريقيات المحفظة",+ "delta": "دلتا",+ "deltaDesc": "الانكشاف الاتجاهي مكافئًا بعدد أسهم الأصل الأساسي.",+ "gamma": "غاما",+ "gammaDesc": "مقدار تغيّر دلتا مع كل حركة دولار واحد في الأصل.",+ "theta": "ثيتا",+ "thetaDesc": "التآكل الزمني اليومي بالدولار؛ القيمة السالبة تعني نزيفًا يوميًا في القيمة.",+ "vega": "فيغا",+ "vegaDesc": "الربح/الخسارة بالدولار عند ارتفاع التقلب الضمني 1%.",+ "rho": "رو",+ "rhoDesc": "الربح/الخسارة بالدولار عند ارتفاع أسعار الفائدة 1%."+ },+ "scenario": {+ "title": "مصفوفة سيناريوهات السعر × التقلب الضمني",+ "spotAxis": "سعر الأصل عند الانتهاء",+ "ivAxis": "التقلب الضمني",+ "pnl": "الربح/الخسارة",+ "noData": "لم تُرجع شبكة سيناريوهات."+ },+ "chain": {+ "title": "سلسلة الخيارات الأمريكية",+ "ticker": "الرمز",+ "expiration": "تاريخ الانتهاء",+ "load": "تحميل",+ "loading": "جارٍ تحميل السلسلة…",+ "calls": "خيارات شراء",+ "puts": "خيارات بيع",+ "strike": "سعر التنفيذ",+ "last": "آخر سعر",+ "bid": "عرض الشراء",+ "ask": "طلب البيع",+ "spread": "الفرق%",+ "volume": "الحجم",+ "openInterest": "العقود المفتوحة",+ "iv": "التقلب الضمني%",+ "itm": "داخل المال",+ "atm": "عند السعر",+ "noData": "لم تُرجع عقود لهذا الاختيار.",+ "errorTitle": "سلسلة الخيارات غير متاحة",+ "retry": "إعادة المحاولة"+ }+ },"alphaZoo": {"title": "مكتبة عوامل ألفا","prebuiltAlpha": "{{count}} ألفا كمي مُعدّ مسبقًا عبر 5 مكتبات عوامل",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 50cd27427..7e3aebb43 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -16,6 +16,7 @@"alphaZoo": "Alpha Zoo","settings": "Settings","correlation": "Correlation Matrix",+ "optionsLab": "Options Lab","sessions": "Sessions","newChat": "New Chat","noSessions": "No chats yet — press + to start one",@@ -675,6 +676,112 @@"regimeEnterThreshold": "enter","regimeExitThreshold": "exit"},+ "options": {+ "title": "Options Lab",+ "subtitle": "Strategy builder, expiry payoff, spot x IV scenarios, portfolio Greeks and a live US options chain.",+ "disclaimer": "Research only. Theoretical pricing and scenario outputs are model estimates, not investment advice.",+ "errorGeneric": "Analysis failed",+ "presets": {+ "label": "Presets",+ "longCall": "Long Call",+ "longPut": "Long Put",+ "bullCallSpread": "Bull Call Spread",+ "bearPutSpread": "Bear Put Spread",+ "bullPutSpread": "Bull Put Spread",+ "bearCallSpread": "Bear Call Spread",+ "longStraddle": "Long Straddle",+ "longStrangle": "Long Strangle",+ "ironCondor": "Iron Condor",+ "ironButterfly": "Iron Butterfly",+ "callButterfly": "Call Butterfly",+ "ratioCallSpread": "Ratio Call Spread"+ },+ "builder": {+ "title": "Strategy Builder",+ "legs": "Legs",+ "type": "Type",+ "call": "Call",+ "put": "Put",+ "strike": "Strike",+ "qty": "Qty",+ "premium": "Premium",+ "premiumHint": "Blank premium = Black-Scholes priced by the engine",+ "qtyHint": "Positive = long, negative = short",+ "addLeg": "Add leg",+ "removeLeg": "Remove leg",+ "parameters": "Parameters",+ "entrySpot": "Entry spot",+ "expiryDays": "Days to expiry",+ "volatility": "Volatility (%)",+ "riskFreeRate": "Risk-free rate (%)",+ "multiplier": "Multiplier",+ "multiplierHint": "100 = standard US equity contract",+ "commissionRate": "Commission rate (%)",+ "invalidHint": "Check inputs: positive spot and strikes, non-zero integer quantities, positive volatility.",+ "analyzing": "Analyzing…"+ },+ "metrics": {+ "entryCost": "Entry cost",+ "debit": "Debit",+ "credit": "Credit",+ "flat": "Flat",+ "breakevens": "Breakevens",+ "maxProfit": "Max profit",+ "maxLoss": "Max loss",+ "unlimited": "Unlimited",+ "none": "None"+ },+ "payoff": {+ "title": "Expiry Payoff",+ "pnl": "P&L",+ "spot": "Spot at expiry",+ "entrySpot": "Spot",+ "breakeven": "BE",+ "noData": "No payoff data yet — build a strategy above."+ },+ "greeks": {+ "title": "Portfolio Greeks",+ "delta": "Delta",+ "deltaDesc": "Directional exposure, in equivalent shares of the underlying.",+ "gamma": "Gamma",+ "gammaDesc": "How much delta changes per $1 move in the underlying.",+ "theta": "Theta",+ "thetaDesc": "Daily time decay in dollars. Negative means the position bleeds value each day.",+ "vega": "Vega",+ "vegaDesc": "Dollar P&L for a +1% move in implied volatility.",+ "rho": "Rho",+ "rhoDesc": "Dollar P&L for a +1% move in interest rates."+ },+ "scenario": {+ "title": "Spot x IV Scenario Matrix",+ "spotAxis": "Spot at expiry",+ "ivAxis": "Implied volatility",+ "pnl": "P&L",+ "noData": "No scenario grid returned."+ },+ "chain": {+ "title": "US Options Chain",+ "ticker": "Ticker",+ "expiration": "Expiration",+ "load": "Load",+ "loading": "Loading chain…",+ "calls": "Calls",+ "puts": "Puts",+ "strike": "Strike",+ "last": "Last",+ "bid": "Bid",+ "ask": "Ask",+ "spread": "Spread%",+ "volume": "Volume",+ "openInterest": "OI",+ "iv": "IV%",+ "itm": "ITM",+ "atm": "ATM",+ "noData": "No contracts returned for this selection.",+ "errorTitle": "Options chain unavailable",+ "retry": "Retry"+ }+ },"alphaZoo": {"title": "Alpha Zoo","prebuiltAlpha": "{{count}} pre-built quant alphas across 5 families",diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex 7a66afb36..7f044521b 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -16,6 +16,7 @@"alphaZoo": "Alpha Zoo","settings": "Configuración","correlation": "Matriz de correlación",+ "optionsLab": "Laboratorio de opciones","sessions": "Sesiones","newChat": "Nuevo chat","noSessions": "Aún no hay chats — pulsa + para empezar uno",@@ -675,6 +676,112 @@"regimeEnterThreshold": "entrada","regimeExitThreshold": "salida"},+ "options": {+ "title": "Laboratorio de Opciones",+ "subtitle": "Constructor de estrategias, perfil de vencimiento, escenarios spot × IV, griegas de cartera y cadena de opciones de EE. UU. en vivo.",+ "disclaimer": "Solo para investigación. Los precios teóricos y los escenarios son estimaciones de modelos, no asesoramiento de inversión.",+ "errorGeneric": "Error en el análisis",+ "presets": {+ "label": "Estrategias predefinidas",+ "longCall": "Call comprada",+ "longPut": "Put comprada",+ "bullCallSpread": "Spread alcista de calls",+ "bearPutSpread": "Spread bajista de puts",+ "bullPutSpread": "Spread alcista de puts",+ "bearCallSpread": "Spread bajista de calls",+ "longStraddle": "Straddle comprada",+ "longStrangle": "Strangle comprada",+ "ironCondor": "Cóndor de hierro",+ "ironButterfly": "Mariposa de hierro",+ "callButterfly": "Mariposa de calls",+ "ratioCallSpread": "Spread ratio de calls"+ },+ "builder": {+ "title": "Constructor de estrategias",+ "legs": "Piernas",+ "type": "Tipo",+ "call": "Call",+ "put": "Put",+ "strike": "Strike",+ "qty": "Cantidad",+ "premium": "Prima",+ "premiumHint": "Prima vacía = precio Black-Scholes calculado por el motor",+ "qtyHint": "Positivo = largo, negativo = corto",+ "addLeg": "Añadir pierna",+ "removeLeg": "Eliminar pierna",+ "parameters": "Parámetros",+ "entrySpot": "Spot de entrada",+ "expiryDays": "Días a vencimiento",+ "volatility": "Volatilidad (%)",+ "riskFreeRate": "Tasa libre de riesgo (%)",+ "multiplier": "Multiplicador",+ "multiplierHint": "100 = contrato estándar de acciones de EE. UU.",+ "commissionRate": "Tasa de comisión (%)",+ "invalidHint": "Revisa las entradas: spot y strikes positivos, cantidades enteras distintas de cero, volatilidad positiva.",+ "analyzing": "Analizando…"+ },+ "metrics": {+ "entryCost": "Coste de entrada",+ "debit": "Débito",+ "credit": "Crédito",+ "flat": "Neutro",+ "breakevens": "Puntos de equilibrio",+ "maxProfit": "Beneficio máximo",+ "maxLoss": "Pérdida máxima",+ "unlimited": "Ilimitado",+ "none": "Ninguno"+ },+ "payoff": {+ "title": "Perfil de vencimiento",+ "pnl": "P&G",+ "spot": "Spot a vencimiento",+ "entrySpot": "Spot",+ "breakeven": "Equilibrio",+ "noData": "Aún no hay datos de perfil. Construye una estrategia arriba."+ },+ "greeks": {+ "title": "Griegas de la cartera",+ "delta": "Delta",+ "deltaDesc": "Exposición direccional, en acciones equivalentes del subyacente.",+ "gamma": "Gamma",+ "gammaDesc": "Cuánto cambia delta por cada $1 de movimiento del subyacente.",+ "theta": "Theta",+ "thetaDesc": "Decaimiento temporal diario en dólares. Negativo significa pérdida de valor cada día.",+ "vega": "Vega",+ "vegaDesc": "P&G en dólares ante un +1% de volatilidad implícita.",+ "rho": "Rho",+ "rhoDesc": "P&G en dólares ante un +1% de las tasas de interés."+ },+ "scenario": {+ "title": "Matriz de escenarios spot × IV",+ "spotAxis": "Spot a vencimiento",+ "ivAxis": "Volatilidad implícita",+ "pnl": "P&G",+ "noData": "No se devolvió la cuadrícula de escenarios."+ },+ "chain": {+ "title": "Cadena de opciones de EE. UU.",+ "ticker": "Símbolo",+ "expiration": "Vencimiento",+ "load": "Cargar",+ "loading": "Cargando cadena…",+ "calls": "Calls",+ "puts": "Puts",+ "strike": "Strike",+ "last": "Último",+ "bid": "Bid",+ "ask": "Ask",+ "spread": "Spread%",+ "volume": "Volumen",+ "openInterest": "Interés abierto",+ "iv": "IV%",+ "itm": "ITM",+ "atm": "ATM",+ "noData": "No se devolvieron contratos para esta selección.",+ "errorTitle": "Cadena de opciones no disponible",+ "retry": "Reintentar"+ }+ },"alphaZoo": {"title": "Alpha Zoo","prebuiltAlpha": "{{count}} alphas cuantitativos preconstruidos en 5 familias",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex 410a3415a..70356497b 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -11,6 +11,7 @@"alphaZoo": "アルファ・ライブラリ","settings": "設定","correlation": "相関行列",+ "optionsLab": "オプションラボ","sessions": "セッション","newChat": "新規チャット","noSessions": "チャットはまだありません。+を押して始めましょう",@@ -670,6 +671,112 @@"regimeEnterThreshold": "開始しきい値","regimeExitThreshold": "終了しきい値"},+ "options": {+ "title": "オプションラボ",+ "subtitle": "ストラテジービルダー、満期ペイオフ、原資産価格×IVシナリオ、ポートフォリオ・グリークス、米国オプションチェーン。",+ "disclaimer": "研究目的のみ。理論価格とシナリオ結果はモデルによる推定値であり、投資助言ではありません。",+ "errorGeneric": "分析に失敗しました",+ "presets": {+ "label": "プリセット",+ "longCall": "ロング・コール",+ "longPut": "ロング・プット",+ "bullCallSpread": "ブル・コール・スプレッド",+ "bearPutSpread": "ベア・プット・スプレッド",+ "bullPutSpread": "ブル・プット・スプレッド",+ "bearCallSpread": "ベア・コール・スプレッド",+ "longStraddle": "ロング・ストラドル",+ "longStrangle": "ロング・ストラングル",+ "ironCondor": "アイアン・コンドル",+ "ironButterfly": "アイアン・バタフライ",+ "callButterfly": "コール・バタフライ",+ "ratioCallSpread": "レシオ・コール・スプレッド"+ },+ "builder": {+ "title": "ストラテジービルダー",+ "legs": "レッグ",+ "type": "種類",+ "call": "コール",+ "put": "プット",+ "strike": "権利行使価格",+ "qty": "数量",+ "premium": "プレミアム",+ "premiumHint": "プレミアム空欄 = エンジンがBlack-Scholesで価格設定",+ "qtyHint": "正 = ロング、負 = ショート",+ "addLeg": "レッグを追加",+ "removeLeg": "レッグを削除",+ "parameters": "パラメータ",+ "entrySpot": "エントリー原資産価格",+ "expiryDays": "満期までの日数",+ "volatility": "ボラティリティ(%)",+ "riskFreeRate": "リスクフリー金利(%)",+ "multiplier": "乗数",+ "multiplierHint": "100 = 米国株式標準契約",+ "commissionRate": "手数料率(%)",+ "invalidHint": "入力を確認してください:原資産価格と行使価格は正、数量は非ゼロの整数、ボラティリティは正である必要があります。",+ "analyzing": "分析中…"+ },+ "metrics": {+ "entryCost": "エントリーコスト",+ "debit": "デビット",+ "credit": "クレジット",+ "flat": "フラット",+ "breakevens": "損益分岐点",+ "maxProfit": "最大利益",+ "maxLoss": "最大損失",+ "unlimited": "無制限",+ "none": "なし"+ },+ "payoff": {+ "title": "満期ペイオフ",+ "pnl": "損益",+ "spot": "満期時の原資産価格",+ "entrySpot": "スポット",+ "breakeven": "分岐点",+ "noData": "ペイオフデータはまだありません。上でストラテジーを構築してください。"+ },+ "greeks": {+ "title": "ポートフォリオ・グリークス",+ "delta": "デルタ",+ "deltaDesc": "原資産の相当株数で表した方向性エクスポージャー。",+ "gamma": "ガンマ",+ "gammaDesc": "原資産が1ドル動くときのデルタの変化量。",+ "theta": "シータ",+ "thetaDesc": "1日あたりのタイム・ディケイ(ドル)。負の値は毎日価値が目減りすることを意味します。",+ "vega": "ベガ",+ "vegaDesc": "想定ボラティリティが+1%動いたときの損益(ドル)。",+ "rho": "ロー",+ "rhoDesc": "金利が+1%動いたときの損益(ドル)。"+ },+ "scenario": {+ "title": "原資産価格 × IV シナリオマトリクス",+ "spotAxis": "満期時の原資産価格",+ "ivAxis": "想定ボラティリティ",+ "pnl": "損益",+ "noData": "シナリオグリッドは返されませんでした。"+ },+ "chain": {+ "title": "米国オプションチェーン",+ "ticker": "ティッカー",+ "expiration": "満期日",+ "load": "読み込み",+ "loading": "チェーンを読み込み中…",+ "calls": "コール",+ "puts": "プット",+ "strike": "行使価格",+ "last": "現在値",+ "bid": "ビッド",+ "ask": "アスク",+ "spread": "スプレッド%",+ "volume": "出来高",+ "openInterest": "建玉",+ "iv": "IV%",+ "itm": "ITM",+ "atm": "ATM",+ "noData": "この選択に対するコントラクトは返されませんでした。",+ "errorTitle": "オプションチェーンを利用できません",+ "retry": "再試行"+ }+ },"alphaZoo": {"title": "Alpha ファクターライブラリ","prebuiltAlpha": "5 つの Zoo にまたがる {{count}} 個の事前構築クォント Alpha",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex a5c7ae860..20bba2cd6 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -11,6 +11,7 @@"alphaZoo": "알파 라이브러리","settings": "설정","correlation": "상관 행렬",+ "optionsLab": "옵션 랩","sessions": "세션","newChat": "새 채팅","noSessions": "아직 채팅이 없습니다. +를 눌러 시작하세요",@@ -670,6 +671,112 @@"regimeEnterThreshold": "진입 임계값","regimeExitThreshold": "이탈 임계값"},+ "options": {+ "title": "옵션 랩",+ "subtitle": "전략 빌더, 만기 손익, 현물가 × IV 시나리오, 포트폴리오 그리스, 미국 실시간 옵션 체인.",+ "disclaimer": "연구 목적 전용입니다. 이론 가격과 시나리오 결과는 모델 추정치이며 투자 조언이 아닙니다.",+ "errorGeneric": "분석에 실패했습니다",+ "presets": {+ "label": "프리셋",+ "longCall": "롱 콜",+ "longPut": "롱 풋",+ "bullCallSpread": "불 콜 스프레드",+ "bearPutSpread": "베어 풋 스프레드",+ "bullPutSpread": "불 풋 스프레드",+ "bearCallSpread": "베어 콜 스프레드",+ "longStraddle": "롱 스트래들",+ "longStrangle": "롱 스트랭글",+ "ironCondor": "아이언 콘도르",+ "ironButterfly": "아이언 버터플라이",+ "callButterfly": "콜 버터플라이",+ "ratioCallSpread": "레시오 콜 스프레드"+ },+ "builder": {+ "title": "전략 빌더",+ "legs": "레그",+ "type": "유형",+ "call": "콜",+ "put": "풋",+ "strike": "행사가",+ "qty": "수량",+ "premium": "프리미엄",+ "premiumHint": "프리미엄 비워두면 엔진이 Black-Scholes로 가격 산정",+ "qtyHint": "양수 = 롱, 음수 = 숏",+ "addLeg": "레그 추가",+ "removeLeg": "레그 삭제",+ "parameters": "매개변수",+ "entrySpot": "진입 현물가",+ "expiryDays": "만기까지 일수",+ "volatility": "변동성 (%)",+ "riskFreeRate": "무위험 금리 (%)",+ "multiplier": "승수",+ "multiplierHint": "100 = 미국 주식 표준 계약",+ "commissionRate": "수수료율 (%)",+ "invalidHint": "입력을 확인하세요: 현물가/행사가는 양수, 수량은 0이 아닌 정수, 변동성은 양수여야 합니다.",+ "analyzing": "분석 중…"+ },+ "metrics": {+ "entryCost": "진입 비용",+ "debit": "데빗",+ "credit": "크레딧",+ "flat": "플랫",+ "breakevens": "손익분기점",+ "maxProfit": "최대 이익",+ "maxLoss": "최대 손실",+ "unlimited": "무제한",+ "none": "없음"+ },+ "payoff": {+ "title": "만기 손익",+ "pnl": "손익",+ "spot": "만기 시 현물가",+ "entrySpot": "현물",+ "breakeven": "분기점",+ "noData": "아직 손익 데이터가 없습니다. 위에서 전략을 구성하세요."+ },+ "greeks": {+ "title": "포트폴리오 그리스",+ "delta": "델타",+ "deltaDesc": "기초자산 환산 주식 수로 나타낸 방향성 익스포저.",+ "gamma": "감마",+ "gammaDesc": "기초자산이 1달러 움직일 때 델타의 변화량.",+ "theta": "세타",+ "thetaDesc": "일 단위 시간 가치 감소(달러). 음수면 매일 가치가 줄어듭니다.",+ "vega": "베가",+ "vegaDesc": "내재 변동성이 +1% 변동할 때 손익(달러).",+ "rho": "로",+ "rhoDesc": "금리가 +1% 변동할 때 손익(달러)."+ },+ "scenario": {+ "title": "현물가 × IV 시나리오 행렬",+ "spotAxis": "만기 시 현물가",+ "ivAxis": "내재 변동성",+ "pnl": "손익",+ "noData": "시나리오 그리드가 반환되지 않았습니다."+ },+ "chain": {+ "title": "미국 옵션 체인",+ "ticker": "티커",+ "expiration": "만기일",+ "load": "불러오기",+ "loading": "옵션 체인 로딩 중…",+ "calls": "콜",+ "puts": "풋",+ "strike": "행사가",+ "last": "현재가",+ "bid": "매수호가",+ "ask": "매도호가",+ "spread": "스프레드%",+ "volume": "거래량",+ "openInterest": "미결제약정",+ "iv": "IV%",+ "itm": "ITM",+ "atm": "ATM",+ "noData": "이 선택에 대한 계약이 반환되지 않았습니다.",+ "errorTitle": "옵션 체인을 사용할 수 없습니다",+ "retry": "재시도"+ }+ },"alphaZoo": {"title": "알파 팩터 라이브러리","prebuiltAlpha": "5개 Zoo에 걸친 {{count}}개의 사전 구축 퀀트 Alpha",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex a0cb3d13e..ee88d7b36 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -11,6 +11,7 @@"alphaZoo": "Alpha 因子库","settings": "设置","correlation": "相关性矩阵",+ "optionsLab": "期权实验室","sessions": "会话","newChat": "新建对话","noSessions": "还没有对话——点 + 开始第一个",@@ -670,6 +671,112 @@"regimeEnterThreshold": "进入阈值","regimeExitThreshold": "退出阈值"},+ "options": {+ "title": "期权实验室",+ "subtitle": "策略构建器、到期损益、标的价 × 隐含波动率情景、组合希腊值与美股实时期权链。",+ "disclaimer": "仅供研究参考。理论定价与情景结果为模型估算,不构成投资建议。",+ "errorGeneric": "分析失败",+ "presets": {+ "label": "预设策略",+ "longCall": "买入看涨期权",+ "longPut": "买入看跌期权",+ "bullCallSpread": "牛市看涨价差",+ "bearPutSpread": "熊市看跌价差",+ "bullPutSpread": "牛市看跌价差",+ "bearCallSpread": "熊市看涨价差",+ "longStraddle": "买入跨式组合",+ "longStrangle": "买入宽跨式组合",+ "ironCondor": "铁鹰式组合",+ "ironButterfly": "铁蝴蝶式组合",+ "callButterfly": "看涨蝴蝶式组合",+ "ratioCallSpread": "看涨比率价差"+ },+ "builder": {+ "title": "策略构建器",+ "legs": "期权腿",+ "type": "类型",+ "call": "看涨",+ "put": "看跌",+ "strike": "行权价",+ "qty": "数量",+ "premium": "权利金",+ "premiumHint": "权利金留空 = 由引擎按 Black-Scholes 定价",+ "qtyHint": "正数 = 买入(多头),负数 = 卖出(空头)",+ "addLeg": "添加期权腿",+ "removeLeg": "删除期权腿",+ "parameters": "参数",+ "entrySpot": "入场标的价",+ "expiryDays": "到期天数",+ "volatility": "波动率(%)",+ "riskFreeRate": "无风险利率(%)",+ "multiplier": "合约乘数",+ "multiplierHint": "100 = 美股标准合约",+ "commissionRate": "佣金率(%)",+ "invalidHint": "请检查输入:标的价与行权价需为正数,数量需为非零整数,波动率需为正数。",+ "analyzing": "分析中…"+ },+ "metrics": {+ "entryCost": "入场成本",+ "debit": "支出",+ "credit": "收入",+ "flat": "持平",+ "breakevens": "盈亏平衡点",+ "maxProfit": "最大盈利",+ "maxLoss": "最大亏损",+ "unlimited": "无上限",+ "none": "无"+ },+ "payoff": {+ "title": "到期损益图",+ "pnl": "损益",+ "spot": "到期标的价",+ "entrySpot": "现价",+ "breakeven": "盈亏点",+ "noData": "暂无损益数据——请先在上方构建策略。"+ },+ "greeks": {+ "title": "组合希腊值",+ "delta": "Delta",+ "deltaDesc": "方向性敞口,相当于持有标的资产的股数。",+ "gamma": "Gamma",+ "gammaDesc": "标的资产每变动 1 美元,Delta 的变化量。",+ "theta": "Theta",+ "thetaDesc": "每日时间衰减(美元)。为负表示持仓每天流失价值。",+ "vega": "Vega",+ "vegaDesc": "隐含波动率每上升 1%,损益的变化(美元)。",+ "rho": "Rho",+ "rhoDesc": "利率每上升 1%,损益的变化(美元)。"+ },+ "scenario": {+ "title": "标的价 × 隐含波动率情景矩阵",+ "spotAxis": "到期标的价",+ "ivAxis": "隐含波动率",+ "pnl": "损益",+ "noData": "未返回情景矩阵数据。"+ },+ "chain": {+ "title": "美股期权链",+ "ticker": "代码",+ "expiration": "到期日",+ "load": "加载",+ "loading": "加载期权链…",+ "calls": "看涨期权",+ "puts": "看跌期权",+ "strike": "行权价",+ "last": "最新价",+ "bid": "买价",+ "ask": "卖价",+ "spread": "价差%",+ "volume": "成交量",+ "openInterest": "持仓量",+ "iv": "隐波%",+ "itm": "价内",+ "atm": "平值",+ "noData": "该选择下未返回合约。",+ "errorTitle": "期权链不可用",+ "retry": "重试"+ }+ },"alphaZoo": {"title": "Alpha 因子库","prebuiltAlpha": "{{count}} 个预构建量化 Alpha,覆盖 5 个因子库",diff --git a/frontend/src/lib/__tests__/options.test.ts b/frontend/src/lib/__tests__/options.test.tsnew file mode 100644index 000000000..7ff315e3d--- /dev/null+++ b/frontend/src/lib/__tests__/options.test.ts@@ -0,0 +1,249 @@+import {+ bidAskSpreadPct,+ buildPayoffRequest,+ buildPresetLegs,+ DEFAULT_PARAMS,+ downsampleIndices,+ expirationLabel,+ fractionToPct,+ getPreset,+ ivLabel,+ nearestStrikeIndex,+ niceStrikeStep,+ pctToFraction,+ roundToNiceStrike,+ STRATEGY_PRESETS,+ type OptionLeg,+ type OptionsContractRow,+} from "../options";++describe("strategy preset catalog", () => {+ it("ships at least 10 presets with unique ids and options.presets.* name keys", () => {+ expect(STRATEGY_PRESETS.length).toBeGreaterThanOrEqual(10);+ const ids = STRATEGY_PRESETS.map((p) => p.id);+ expect(new Set(ids).size).toBe(ids.length);+ for (const preset of STRATEGY_PRESETS) {+ expect(preset.nameKey.startsWith("options.presets.")).toBe(true);+ }+ });++ it("long_call builds one long call at the rounded spot strike", () => {+ const legs = buildPresetLegs("long_call", 100)!;+ expect(legs).toHaveLength(1);+ expect(legs[0].option_type).toBe("call");+ expect(legs[0].qty).toBe(1);+ expect(legs[0].strike).toBe(100);+ });++ it("long_put builds one long put", () => {+ const legs = buildPresetLegs("long_put", 100)!;+ expect(legs).toHaveLength(1);+ expect(legs[0].option_type).toBe("put");+ expect(legs[0].qty).toBe(1);+ });++ it("long_straddle buys a call and a put at the same strike", () => {+ const legs = buildPresetLegs("long_straddle", 100)!;+ expect(legs).toHaveLength(2);+ const types = legs.map((l) => l.option_type).sort();+ expect(types).toEqual(["call", "put"]);+ expect(legs[0].strike).toBe(legs[1].strike);+ expect(legs.every((l) => l.qty === 1)).toBe(true);+ });++ it("bull_call_spread longs the lower strike and shorts the higher", () => {+ const legs = buildPresetLegs("bull_call_spread", 100)!;+ expect(legs).toHaveLength(2);+ expect(legs.every((l) => l.option_type === "call")).toBe(true);+ const long = legs.find((l) => l.qty === 1)!;+ const short = legs.find((l) => l.qty === -1)!;+ expect(long.strike).toBeLessThan(short.strike);+ });++ it("iron_condor has four legs, ordered strikes and net-zero quantity", () => {+ const legs = buildPresetLegs("iron_condor", 100)!;+ expect(legs).toHaveLength(4);+ const sorted = [...legs].sort((a, b) => a.strike - b.strike);+ expect(sorted.map((l) => l.strike)).toEqual([90, 95, 105, 110]);+ expect(sorted[0].option_type).toBe("put");+ expect(sorted[0].qty).toBe(1);+ expect(sorted[1].option_type).toBe("put");+ expect(sorted[1].qty).toBe(-1);+ expect(sorted[2].option_type).toBe("call");+ expect(sorted[2].qty).toBe(-1);+ expect(sorted[3].option_type).toBe("call");+ expect(sorted[3].qty).toBe(1);+ expect(legs.reduce((sum, l) => sum + l.qty, 0)).toBe(0);+ });++ it("call_butterfly is +1 / -2 / +1 with the body between the wings", () => {+ const legs = buildPresetLegs("call_butterfly", 100)!;+ expect(legs).toHaveLength(3);+ expect(legs.every((l) => l.option_type === "call")).toBe(true);+ const qtys = [...legs].sort((a, b) => a.strike - b.strike).map((l) => l.qty);+ expect(qtys).toEqual([1, -2, 1]);+ expect(legs.reduce((sum, l) => sum + l.qty, 0)).toBe(0);+ });++ it("ratio_call_spread longs 1 lower strike and shorts 2 higher strikes", () => {+ const legs = buildPresetLegs("ratio_call_spread", 100)!;+ expect(legs).toHaveLength(2);+ const long = legs.find((l) => l.qty === 1)!;+ const short = legs.find((l) => l.qty === -2)!;+ expect(long.strike).toBeLessThan(short.strike);+ });++ it("returns null for unknown presets and invalid spots", () => {+ expect(buildPresetLegs("nope", 100)).toBeNull();+ expect(buildPresetLegs("long_call", 0)).toBeNull();+ expect(buildPresetLegs("long_call", NaN)).toBeNull();+ expect(getPreset("nope")).toBeUndefined();+ });+});++describe("roundToNiceStrike", () => {+ it("rounds to the price-level step grid", () => {+ expect(roundToNiceStrike(100)).toBe(100);+ expect(roundToNiceStrike(227.35)).toBe(225);+ expect(roundToNiceStrike(52)).toBe(52.5);+ expect(roundToNiceStrike(21.4)).toBe(21);+ expect(roundToNiceStrike(3.1)).toBe(3);+ });++ it("never returns a non-positive strike", () => {+ expect(roundToNiceStrike(0.4)).toBeGreaterThan(0);+ expect(roundToNiceStrike(0)).toBe(0);+ expect(roundToNiceStrike(-5)).toBe(0);+ expect(roundToNiceStrike(NaN)).toBe(0);+ });++ it("uses coarser steps for higher prices", () => {+ expect(niceStrikeStep(250)).toBe(5);+ expect(niceStrikeStep(75)).toBe(2.5);+ expect(niceStrikeStep(30)).toBe(1);+ expect(niceStrikeStep(10)).toBe(0.5);+ expect(niceStrikeStep(2)).toBe(0.25);+ });+});++describe("buildPayoffRequest", () => {+ const validLegs: OptionLeg[] = [{ option_type: "call", strike: 100, qty: 1 }];++ it("converts percent inputs to fractions in the request body", () => {+ const req = buildPayoffRequest(validLegs, DEFAULT_PARAMS)!;+ expect(req.entry_spot).toBe(100);+ expect(req.expiry_days).toBe(30);+ expect(req.volatility).toBeCloseTo(0.3);+ expect(req.risk_free_rate).toBeCloseTo(0.05);+ expect(req.commission_rate).toBeCloseTo(0.001);+ expect(req.multiplier).toBe(100);+ expect(req.legs).toHaveLength(1);+ });++ it("omits premium when undefined and keeps it when set", () => {+ const without = buildPayoffRequest(validLegs, DEFAULT_PARAMS)!;+ expect("premium" in without.legs[0]).toBe(false);+ const withPrem = buildPayoffRequest(+ [{ option_type: "put", strike: 95, qty: -1, premium: 2.5 }],+ DEFAULT_PARAMS,+ )!;+ expect(withPrem.legs[0].premium).toBe(2.5);+ });++ it("rejects out-of-contract inputs", () => {+ expect(buildPayoffRequest([], DEFAULT_PARAMS)).toBeNull();+ expect(buildPayoffRequest([{ option_type: "call", strike: -1, qty: 1 }], DEFAULT_PARAMS)).toBeNull();+ expect(buildPayoffRequest([{ option_type: "call", strike: 100, qty: 0 }], DEFAULT_PARAMS)).toBeNull();+ expect(buildPayoffRequest([{ option_type: "call", strike: 100, qty: 1.5 }], DEFAULT_PARAMS)).toBeNull();+ expect(buildPayoffRequest(validLegs, { ...DEFAULT_PARAMS, entry_spot: 0 })).toBeNull();+ expect(buildPayoffRequest(validLegs, { ...DEFAULT_PARAMS, expiry_days: -1 })).toBeNull();+ expect(buildPayoffRequest(validLegs, { ...DEFAULT_PARAMS, volatility_pct: 0 })).toBeNull();+ expect(buildPayoffRequest(validLegs, { ...DEFAULT_PARAMS, multiplier: 0 })).toBeNull();+ expect(buildPayoffRequest(validLegs, { ...DEFAULT_PARAMS, commission_rate_pct: 100 })).toBeNull();+ expect(+ buildPayoffRequest([{ option_type: "call", strike: 100, qty: 1, premium: -2 }], DEFAULT_PARAMS),+ ).toBeNull();+ });+});++describe("percent conversion helpers", () => {+ it("round-trips percents and fractions", () => {+ expect(pctToFraction(30)).toBeCloseTo(0.3);+ expect(pctToFraction(0.1)).toBeCloseTo(0.001);+ expect(fractionToPct(0.05)).toBeCloseTo(5);+ });+});++describe("downsampleIndices", () => {+ it("returns the identity when the grid is already small enough", () => {+ expect(downsampleIndices(10, 61)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);+ });++ it("keeps first and last and stays monotonic on the 121 -> 61 case", () => {+ const idx = downsampleIndices(121, 61);+ expect(idx).toHaveLength(61);+ expect(idx[0]).toBe(0);+ expect(idx[idx.length - 1]).toBe(120);+ for (let i = 1; i < idx.length; i++) {+ expect(idx[i]).toBeGreaterThan(idx[i - 1]);+ }+ });++ it("handles degenerate inputs", () => {+ expect(downsampleIndices(0, 61)).toEqual([]);+ expect(downsampleIndices(5, 1)).toEqual([0, 1, 2, 3, 4]);+ });+});++describe("bidAskSpreadPct", () => {+ it("computes spread percent of mid", () => {+ expect(bidAskSpreadPct(1, 2)).toBeCloseTo(66.6667, 3);+ expect(bidAskSpreadPct(99, 101)).toBeCloseTo(2, 5);+ });++ it("returns null for missing or non-positive mid", () => {+ expect(bidAskSpreadPct(null, 2)).toBeNull();+ expect(bidAskSpreadPct(1, null)).toBeNull();+ expect(bidAskSpreadPct(-1, 1)).toBeNull();+ expect(bidAskSpreadPct(NaN, 1)).toBeNull();+ });+});++describe("nearestStrikeIndex", () => {+ const row = (strike: number): OptionsContractRow => ({+ contract_symbol: `X${strike}`,+ strike,+ last_price: null,+ bid: null,+ ask: null,+ volume: null,+ open_interest: null,+ implied_volatility: null,+ in_the_money: false,+ expiration: 0,+ });++ it("finds the strike closest to the reference spot", () => {+ const rows = [row(90), row(95), row(100), row(105)];+ expect(nearestStrikeIndex(rows, 101)).toBe(2);+ expect(nearestStrikeIndex(rows, 93)).toBe(1);+ });++ it("returns -1 for empty rows or invalid spot", () => {+ expect(nearestStrikeIndex([], 100)).toBe(-1);+ expect(nearestStrikeIndex([row(100)], NaN)).toBe(-1);+ });+});++describe("display formatters", () => {+ it("expirationLabel renders a non-empty locale date", () => {+ const label = expirationLabel(1755216000);+ expect(typeof label).toBe("string");+ expect(label.length).toBeGreaterThan(0);+ });++ it("ivLabel formats IV fractions as percents", () => {+ expect(ivLabel(0.3)).toBe("30%");+ expect(ivLabel(0.255)).toBe("25.5%");+ });+});diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex a55da3219..d5312ac1d 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -1,5 +1,10 @@import i18n from "@/i18n";import { authHeaders, withAuthTicket } from "@/lib/apiAuth";+import type {+ OptionsChainResponse,+ OptionsPayoffRequest,+ OptionsPayoffResponse,+} from "@/lib/options";const BASE = "";@@ -61,7 +66,9 @@ async function errorFromResponse(res: Response): Promise<ApiError> {let detail = `HTTP ${res.status}`;try {const body = await res.json();- detail = body.detail || body.message || detail;+ // Options endpoints report errors under an `error` key+ // ({status:"error", error} / {ok:false, error}) rather than detail/message.+ detail = body.detail || body.message || body.error || detail;} catch { /* ignore */ }if (res.status === 401 || res.status === 403) {detail = getAuthRequiredMessage();@@ -253,6 +260,19 @@ export const api = {alphaCompareStreamUrl: (jobId: string) =>withAuthTicket(`${BASE}/alpha/compare/${encodeURIComponent(jobId)}/stream`),+ // Options Lab+ analyzeOptionsPayoff: (body: OptionsPayoffRequest) =>+ request<OptionsPayoffResponse>("/options/payoff", {+ method: "POST",+ body: JSON.stringify(body),+ }),+ getOptionsChain: (ticker: string, expiration?: number) => {+ const q = new URLSearchParams();+ q.set("ticker", ticker);+ if (expiration !== undefined) q.set("expiration", String(expiration));+ return request<OptionsChainResponse>(`/options/chain?${q.toString()}`);+ },+// Connector runtime channel — privileged surface actions (NOT agent tools).// commit is the ONLY action that writes a mandate; halt trips the kill switch.commitMandate: (body: CommitMandateRequest) =>diff --git a/frontend/src/lib/options.ts b/frontend/src/lib/options.tsnew file mode 100644index 000000000..044e9fd95--- /dev/null+++ b/frontend/src/lib/options.ts@@ -0,0 +1,416 @@+/**+ * Options Lab — API contract types, preset strategy catalog, and pure+ * display-only helpers.+ *+ * All numeric finance math (payoff curves, Black-Scholes pricing, Greeks,+ * scenario grids) is computed by the backend (`POST /options/payoff`).+ * The ONLY client-side math living here is display-only: strike rounding,+ * percent <-> fraction conversion of user input, grid downsampling, and+ * bid/ask spread width.+ */++// ---------------------------------------------------------------------------+// API contract — POST /options/payoff+// ---------------------------------------------------------------------------++export type OptionType = "call" | "put";++/** One option leg. `qty` is a signed integer: positive = long, negative = short. */+export interface OptionLeg {+ option_type: OptionType;+ strike: number;+ qty: number;+ /** Optional per-share premium; when omitted the backend prices via Black-Scholes. */+ premium?: number;+}++export interface OptionsPayoffRequest {+ legs: OptionLeg[];+ entry_spot: number;+ expiry_days: number;+ /** Annual fraction, default 0.05. */+ risk_free_rate?: number;+ /** Annualized IV fraction, default 0.3. */+ volatility?: number;+ /** Contract multiplier, default 1. */+ multiplier?: number;+ /** Fraction in [0, 1), default 0.001. */+ commission_rate?: number;+ spot_min?: number;+ spot_max?: number;+ /** Integer 21-501, default 121. */+ spot_points?: number;+ /** IV scenarios as annualized fractions (max 9). */+ scenario_iv_values?: number[];+}++export interface BreakevenInterval {+ start: number;+ end: number | null;+}++export interface OptionsPayoffSummary {+ net_premium: number;+ entry_commission: number;+ entry_cost: number;+ entry_side: "debit" | "credit" | "flat";+ breakevens: number[];+ breakeven_intervals: BreakevenInterval[];+ max_profit: number | null;+ max_loss: number | null;+ profit_unbounded: boolean;+ loss_unbounded: boolean;+}++export interface OptionsGreeks {+ delta: number;+ gamma: number;+ theta: number;+ vega: number;+ rho: number;+}++export interface ExpiryCurve {+ spot: number[];+ pnl: number[];+}++export interface ScenarioGrid {+ iv_values: number[];+ spot: number[];+ /** One row per iv_values entry, each row aligned with spot. */+ pnl: number[][];+}++export interface OptionsPayoffResponse {+ status: "ok";+ inputs: Record<string, unknown>;+ summary: OptionsPayoffSummary;+ greeks: OptionsGreeks;+ expiry_curve: ExpiryCurve;+ scenario_grid: ScenarioGrid;+ limitations: string[];+}++// ---------------------------------------------------------------------------+// API contract — GET /options/chain+// ---------------------------------------------------------------------------++/** One contract row; any market field may be null (render "–"). */+export interface OptionsContractRow {+ contract_symbol: string;+ strike: number;+ last_price: number | null;+ bid: number | null;+ ask: number | null;+ volume: number | null;+ open_interest: number | null;+ implied_volatility: number | null;+ in_the_money: boolean;+ expiration: number;+}++export interface OptionsChainData {+ ticker: string;+ expiration: number;+ /** Epoch seconds. */+ expirations: number[];+ calls_count: number;+ puts_count: number;+ calls: OptionsContractRow[];+ puts: OptionsContractRow[];+}++export interface OptionsChainResponse {+ ok: boolean;+ market: string;+ source: string;+ data: OptionsChainData;+ /** Present on `{ok: false}` error envelopes (HTTP 400/502 throw as ApiError). */+ error?: string;+}++// ---------------------------------------------------------------------------+// UI parameter model (percent convention)+// ---------------------------------------------------------------------------++/**+ * Builder parameters as the USER types them. ONE convention, kept consistent+ * across the page: volatility, risk-free rate and commission rate are entered+ * as PERCENTS (30 means 30%) and converted to fractions only when the request+ * body is built.+ */+export interface OptionsLabParams {+ entry_spot: number;+ expiry_days: number;+ /** Percent: 30 = 30% annualized IV. Sent as 0.30. */+ volatility_pct: number;+ /** Percent: 5 = 5%. Sent as 0.05. */+ risk_free_rate_pct: number;+ /** Contract multiplier; 100 = standard US equity contract. */+ multiplier: number;+ /** Percent: 0.1 = 0.1%. Sent as 0.001. */+ commission_rate_pct: number;+}++export const DEFAULT_PARAMS: OptionsLabParams = {+ entry_spot: 100,+ expiry_days: 30,+ volatility_pct: 30,+ risk_free_rate_pct: 5,+ multiplier: 100,+ commission_rate_pct: 0.1,+};++export function pctToFraction(pct: number): number {+ return pct / 100;+}++export function fractionToPct(fraction: number): number {+ return fraction * 100;+}++/**+ * Validate inputs against the backend contract and build the request body.+ * Returns null when any input is out of contract bounds (the page then skips+ * the debounced call). Display-only guard — the backend stays authoritative.+ */+export function buildPayoffRequest(+ legs: OptionLeg[],+ p: OptionsLabParams,+): OptionsPayoffRequest | null {+ if (!Number.isFinite(p.entry_spot) || p.entry_spot <= 0) return null;+ if (!Number.isFinite(p.expiry_days) || p.expiry_days < 0) return null;+ if (!Number.isFinite(p.volatility_pct) || p.volatility_pct <= 0) return null;+ if (!Number.isFinite(p.risk_free_rate_pct)) return null;+ if (!Number.isFinite(p.multiplier) || p.multiplier <= 0) return null;+ if (!Number.isFinite(p.commission_rate_pct) || p.commission_rate_pct < 0 || p.commission_rate_pct >= 100) {+ return null;+ }+ if (legs.length === 0) return null;+ for (const leg of legs) {+ if (leg.option_type !== "call" && leg.option_type !== "put") return null;+ if (!Number.isFinite(leg.strike) || leg.strike <= 0) return null;+ if (!Number.isInteger(leg.qty) || leg.qty === 0) return null;+ if (leg.premium !== undefined && (!Number.isFinite(leg.premium) || leg.premium < 0)) return null;+ }+ return {+ legs: legs.map((l) => ({+ option_type: l.option_type,+ strike: l.strike,+ qty: l.qty,+ ...(l.premium !== undefined ? { premium: l.premium } : {}),+ })),+ entry_spot: p.entry_spot,+ expiry_days: p.expiry_days,+ risk_free_rate: pctToFraction(p.risk_free_rate_pct),+ volatility: pctToFraction(p.volatility_pct),+ multiplier: p.multiplier,+ commission_rate: pctToFraction(p.commission_rate_pct),+ };+}++// ---------------------------------------------------------------------------+// Preset strategy catalog+// ---------------------------------------------------------------------------++export interface StrategyPreset {+ id: string;+ /** i18n key of the display name (options.presets.*). */+ nameKey: string;+ /** Generate legs parameterized by the underlying spot S. */+ buildLegs: (spot: number) => OptionLeg[];+}++/** Strike grid step by price level — keeps preset strikes on listed-like increments. */+export function niceStrikeStep(price: number): number {+ if (price >= 200) return 5;+ if (price >= 50) return 2.5;+ if (price >= 20) return 1;+ if (price >= 5) return 0.5;+ return 0.25;+}++/** Round a raw price to a "nice" listed-style strike. Returns 0 for non-positive input. */+export function roundToNiceStrike(price: number): number {+ if (!Number.isFinite(price) || price <= 0) return 0;+ const step = niceStrikeStep(price);+ const rounded = Math.max(step, Math.round(price / step) * step);+ return Number(rounded.toFixed(4));+}++function k(spot: number, factor: number): number {+ return roundToNiceStrike(spot * factor);+}++/**+ * Twelve canonical presets, parameterized by spot S. Strike ratios follow the+ * S x {0.9, 0.95, 1.0, 1.05, 1.1} grid (rounded to nice strikes).+ */+export const STRATEGY_PRESETS: StrategyPreset[] = [+ {+ id: "long_call",+ nameKey: "options.presets.longCall",+ buildLegs: (s) => [{ option_type: "call", strike: k(s, 1), qty: 1 }],+ },+ {+ id: "long_put",+ nameKey: "options.presets.longPut",+ buildLegs: (s) => [{ option_type: "put", strike: k(s, 1), qty: 1 }],+ },+ {+ id: "bull_call_spread",+ nameKey: "options.presets.bullCallSpread",+ buildLegs: (s) => [+ { option_type: "call", strike: k(s, 0.95), qty: 1 },+ { option_type: "call", strike: k(s, 1.05), qty: -1 },+ ],+ },+ {+ id: "bear_put_spread",+ nameKey: "options.presets.bearPutSpread",+ buildLegs: (s) => [+ { option_type: "put", strike: k(s, 1.05), qty: 1 },+ { option_type: "put", strike: k(s, 0.95), qty: -1 },+ ],+ },+ {+ id: "bull_put_spread",+ nameKey: "options.presets.bullPutSpread",+ buildLegs: (s) => [+ { option_type: "put", strike: k(s, 1.05), qty: -1 },+ { option_type: "put", strike: k(s, 0.95), qty: 1 },+ ],+ },+ {+ id: "bear_call_spread",+ nameKey: "options.presets.bearCallSpread",+ buildLegs: (s) => [+ { option_type: "call", strike: k(s, 0.95), qty: -1 },+ { option_type: "call", strike: k(s, 1.05), qty: 1 },+ ],+ },+ {+ id: "long_straddle",+ nameKey: "options.presets.longStraddle",+ buildLegs: (s) => [+ { option_type: "call", strike: k(s, 1), qty: 1 },+ { option_type: "put", strike: k(s, 1), qty: 1 },+ ],+ },+ {+ id: "long_strangle",+ nameKey: "options.presets.longStrangle",+ buildLegs: (s) => [+ { option_type: "call", strike: k(s, 1.05), qty: 1 },+ { option_type: "put", strike: k(s, 0.95), qty: 1 },+ ],+ },+ {+ id: "iron_condor",+ nameKey: "options.presets.ironCondor",+ buildLegs: (s) => [+ { option_type: "put", strike: k(s, 0.9), qty: 1 },+ { option_type: "put", strike: k(s, 0.95), qty: -1 },+ { option_type: "call", strike: k(s, 1.05), qty: -1 },+ { option_type: "call", strike: k(s, 1.1), qty: 1 },+ ],+ },+ {+ id: "iron_butterfly",+ nameKey: "options.presets.ironButterfly",+ buildLegs: (s) => [+ { option_type: "put", strike: k(s, 1), qty: -1 },+ { option_type: "call", strike: k(s, 1), qty: -1 },+ { option_type: "put", strike: k(s, 0.9), qty: 1 },+ { option_type: "call", strike: k(s, 1.1), qty: 1 },+ ],+ },+ {+ id: "call_butterfly",+ nameKey: "options.presets.callButterfly",+ buildLegs: (s) => [+ { option_type: "call", strike: k(s, 0.9), qty: 1 },+ { option_type: "call", strike: k(s, 1), qty: -2 },+ { option_type: "call", strike: k(s, 1.1), qty: 1 },+ ],+ },+ {+ id: "ratio_call_spread",+ nameKey: "options.presets.ratioCallSpread",+ buildLegs: (s) => [+ { option_type: "call", strike: k(s, 1), qty: 1 },+ { option_type: "call", strike: k(s, 1.1), qty: -2 },+ ],+ },+];++export function getPreset(id: string): StrategyPreset | undefined {+ return STRATEGY_PRESETS.find((p) => p.id === id);+}++export function buildPresetLegs(presetId: string, spot: number): OptionLeg[] | null {+ const preset = getPreset(presetId);+ if (!preset || !Number.isFinite(spot) || spot <= 0) return null;+ return preset.buildLegs(spot);+}++// ---------------------------------------------------------------------------+// Display-only helpers (chain table, heatmap downsampling)+// ---------------------------------------------------------------------------++/**+ * Even-stride index selection that ALWAYS keeps the first and last element.+ * Used to downsample the scenario spot grid for heatmap display.+ */+export function downsampleIndices(total: number, maxPoints: number): number[] {+ if (total <= 0) return [];+ if (total <= maxPoints || maxPoints < 2) {+ return Array.from({ length: total }, (_, i) => i);+ }+ const stride = (total - 1) / (maxPoints - 1);+ const indices: number[] = [];+ for (let i = 0; i < maxPoints; i++) {+ indices.push(Math.round(i * stride));+ }+ indices[indices.length - 1] = total - 1;+ return indices;+}++/** Bid/ask spread width as a percent of mid. Null when uncomputable. */+export function bidAskSpreadPct(bid: number | null, ask: number | null): number | null {+ if (bid === null || ask === null || !Number.isFinite(bid) || !Number.isFinite(ask)) return null;+ const mid = (bid + ask) / 2;+ if (mid <= 0) return null;+ return ((ask - bid) / mid) * 100;+}++/** Index of the row whose strike is nearest to the reference spot (-1 when empty). */+export function nearestStrikeIndex(rows: OptionsContractRow[], spot: number): number {+ if (rows.length === 0 || !Number.isFinite(spot)) return -1;+ let best = 0;+ let bestDist = Math.abs(rows[0].strike - spot);+ for (let i = 1; i < rows.length; i++) {+ const dist = Math.abs(rows[i].strike - spot);+ if (dist < bestDist) {+ best = i;+ bestDist = dist;+ }+ }+ return best;+}++/** Locale date label for an epoch-seconds expiration (e.g. "Aug 15, 2026"). */+export function expirationLabel(epochSeconds: number): string {+ return new Date(epochSeconds * 1000).toLocaleDateString(undefined, {+ year: "numeric",+ month: "short",+ day: "numeric",+ });+}++/** Format an IV fraction (0.30) as a percent label ("30%"). */+export function ivLabel(iv: number): string {+ const pct = fractionToPct(iv);+ return `${Number(pct.toFixed(2)).toLocaleString()}%`;+}diff --git a/frontend/src/lib/pnl-colors.ts b/frontend/src/lib/pnl-colors.tsnew file mode 100644index 000000000..85545abf4--- /dev/null+++ b/frontend/src/lib/pnl-colors.ts@@ -0,0 +1,40 @@+/**+ * P&L semantic colors for the Options Lab charts.+ *+ * getChartTheme().upColor/downColor are DIRECTION colors — they flip under the+ * Chinese red-up convention. P&L must read green=profit / red=loss in every+ * locale, so this helper reads the raw --success/--danger design tokens+ * instead (same CSS variables chart-theme parses, but unflipped).+ */++function cssVar(name: string): string {+ return getComputedStyle(document.documentElement).getPropertyValue(name).trim();+}++function hslToHex(hsl: string): string {+ if (!hsl) return "";+ const [h, s, l] = hsl.split(/\s+/).map(parseFloat);+ if (isNaN(h)) return "";+ const a = (s / 100) * Math.min(l / 100, 1 - l / 100);+ const f = (n: number) => {+ const kk = (n + h / 30) % 12;+ const color = l / 100 - a * Math.max(Math.min(kk - 3, 9 - kk, 1), -1);+ return Math.round(255 * color).toString(16).padStart(2, "0");+ };+ return `#${f(0)}${f(8)}${f(4)}`;+}++export interface PnlColors {+ profit: string;+ loss: string;+ neutral: string;+}++export function getPnlColors(): PnlColors {+ const isDark = document.documentElement.classList.contains("dark");+ return {+ profit: hslToHex(cssVar("--success")) || "#22c55e",+ loss: hslToHex(cssVar("--danger")) || "#ef4444",+ neutral: isDark ? "#3a4252" : "#eef0f2",+ };+}diff --git a/frontend/src/pages/OptionsLab.tsx b/frontend/src/pages/OptionsLab.tsxnew file mode 100644index 000000000..c2572233f--- /dev/null+++ b/frontend/src/pages/OptionsLab.tsx@@ -0,0 +1,234 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { CandlestickChart, Loader2 } from "lucide-react";+import { cn } from "@/lib/utils";+import { api } from "@/lib/api";+import {+ buildPayoffRequest,+ buildPresetLegs,+ DEFAULT_PARAMS,+ type OptionLeg,+ type OptionsLabParams,+ type OptionsPayoffRequest,+ type OptionsPayoffResponse,+} from "@/lib/options";+import { StrategyBuilder } from "@/components/options/StrategyBuilder";+import { GreeksCards } from "@/components/options/GreeksCards";+import { OptionsChainTable } from "@/components/options/OptionsChainTable";+import { OptionsPayoffChart } from "@/components/charts/OptionsPayoffChart";+import { OptionsScenarioMatrix } from "@/components/charts/OptionsScenarioMatrix";++const ANALYZE_DEBOUNCE_MS = 500;++function MetricCard({+ label,+ value,+ badge,+ badgeTone = "neutral",+ valueTone = "neutral",+}: {+ label: string;+ value: string;+ badge?: string;+ badgeTone?: "debit" | "credit" | "neutral";+ valueTone?: "positive" | "negative" | "neutral";+}) {+ const badgeCls =+ badgeTone === "debit"+ ? "bg-danger/10 text-danger"+ : badgeTone === "credit"+ ? "bg-success/10 text-success"+ : "bg-muted text-muted-foreground";+ const valueCls =+ valueTone === "positive" ? "text-success" : valueTone === "negative" ? "text-danger" : "";+ return (+ <div className="rounded-xl border border-border/60 bg-card p-4 shadow-sm">+ <div className="flex items-center justify-between gap-2">+ <div className="text-xs text-muted-foreground">{label}</div>+ {badge && (+ <span className={cn("rounded px-1.5 py-0.5 text-[10px] font-medium", badgeCls)}>{badge}</span>+ )}+ </div>+ <div className={cn("mt-1 truncate text-sm font-semibold tabular-nums", valueCls)}>{value}</div>+ </div>+ );+}++export function OptionsLab() {+ const { t } = useTranslation();++ const [params, setParams] = useState<OptionsLabParams>(DEFAULT_PARAMS);+ const [legs, setLegs] = useState<OptionLeg[]>(+ () => buildPresetLegs("long_call", DEFAULT_PARAMS.entry_spot) ?? [],+ );+ const [activePresetId, setActivePresetId] = useState<string | null>("long_call");+ const [result, setResult] = useState<OptionsPayoffResponse | null>(null);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const generation = useRef(0);++ const analyze = useCallback(+ async (req: OptionsPayoffRequest) => {+ const gen = ++generation.current;+ setLoading(true);+ setError(null);+ try {+ const res = await api.analyzeOptionsPayoff(req);+ if (generation.current === gen) setResult(res);+ } catch (e) {+ if (generation.current === gen) {+ setError(e instanceof Error ? e.message : t("options.errorGeneric"));+ }+ } finally {+ if (generation.current === gen) setLoading(false);+ }+ },+ [t],+ );++ useEffect(() => {+ const req = buildPayoffRequest(legs, params);+ if (!req) return;+ const timer = setTimeout(() => void analyze(req), ANALYZE_DEBOUNCE_MS);+ return () => clearTimeout(timer);+ }, [legs, params, analyze]);++ const applyPreset = (presetId: string) => {+ const presetLegs = buildPresetLegs(presetId, params.entry_spot);+ if (!presetLegs) return;+ setActivePresetId(presetId);+ setLegs(presetLegs);+ };++ const handleLegsChange = (next: OptionLeg[]) => {+ setActivePresetId(null);+ setLegs(next);+ };++ const summary = result?.summary ?? null;+ const dash = "–";++ const breakevensText = summary+ ? summary.breakevens.length > 0+ ? summary.breakevens.map((be) => be.toLocaleString()).join(", ")+ : t("options.metrics.none")+ : dash;++ const maxProfitText = summary+ ? summary.profit_unbounded+ ? t("options.metrics.unlimited")+ : summary.max_profit !== null+ ? summary.max_profit.toLocaleString(undefined, { maximumFractionDigits: 2 })+ : t("options.metrics.none")+ : dash;++ const maxLossText = summary+ ? summary.loss_unbounded+ ? t("options.metrics.unlimited")+ : summary.max_loss !== null+ ? summary.max_loss.toLocaleString(undefined, { maximumFractionDigits: 2 })+ : t("options.metrics.none")+ : dash;++ return (+ <div className="flex w-full flex-col gap-4 p-6">+ {/* Header */}+ <div>+ <div className="flex items-center gap-3">+ <CandlestickChart className="h-6 w-6 text-primary" />+ <h1 className="text-2xl font-bold">{t("options.title")}</h1>+ </div>+ <p className="mt-1 text-sm text-muted-foreground">{t("options.subtitle")}</p>+ </div>++ {/* Builder + results */}+ <div className="grid gap-4 xl:grid-cols-3">+ <div className="xl:col-span-1">+ <StrategyBuilder+ legs={legs}+ params={params}+ activePresetId={activePresetId}+ onApplyPreset={applyPreset}+ onLegsChange={handleLegsChange}+ onParamsChange={setParams}+ />+ </div>++ <div className="flex flex-col gap-4 xl:col-span-2">+ {/* Key-metrics strip */}+ <div className={cn("grid grid-cols-2 gap-3 lg:grid-cols-4", loading && "opacity-60")}>+ <MetricCard+ label={t("options.metrics.entryCost")}+ value={+ summary+ ? summary.entry_cost.toLocaleString(undefined, { maximumFractionDigits: 2 })+ : dash+ }+ badge={summary ? t(`options.metrics.${summary.entry_side}`) : undefined}+ badgeTone={+ summary ? (summary.entry_side === "flat" ? "neutral" : summary.entry_side) : "neutral"+ }+ />+ <MetricCard label={t("options.metrics.breakevens")} value={breakevensText} />+ <MetricCard+ label={t("options.metrics.maxProfit")}+ value={maxProfitText}+ valueTone={summary && !summary.profit_unbounded && (summary.max_profit ?? 0) > 0 ? "positive" : "neutral"}+ />+ <MetricCard+ label={t("options.metrics.maxLoss")}+ value={maxLossText}+ valueTone={summary && !summary.loss_unbounded && (summary.max_loss ?? 0) < 0 ? "negative" : "neutral"}+ />+ </div>++ {/* Backend error banner */}+ {error && (+ <div className="rounded border border-danger/30 bg-danger/5 p-3 text-sm text-danger">{error}</div>+ )}++ {/* Payoff diagram */}+ <section className="rounded-xl border border-border/60 bg-card p-4 shadow-sm">+ <div className="mb-2 flex items-center justify-between">+ <div className="text-sm font-semibold">{t("options.payoff.title")}</div>+ {loading && (+ <span className="flex items-center gap-1.5 text-xs text-muted-foreground">+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ {t("options.builder.analyzing")}+ </span>+ )}+ </div>+ <OptionsPayoffChart+ curve={result?.expiry_curve ?? { spot: [], pnl: [] }}+ entrySpot={params.entry_spot}+ breakevens={summary?.breakevens ?? []}+ />+ </section>+ </div>+ </div>++ {/* Portfolio Greeks */}+ {result && <GreeksCards greeks={result.greeks} />}++ {/* Spot x IV scenario matrix */}+ <section className="rounded-xl border border-border/60 bg-card p-4 shadow-sm">+ <div className="mb-2 text-sm font-semibold">{t("options.scenario.title")}</div>+ <OptionsScenarioMatrix+ grid={result?.scenario_grid ?? { iv_values: [], spot: [], pnl: [] }}+ />+ {result && result.limitations.length > 0 && (+ <ul className="mt-2 list-disc ps-5 text-xs text-muted-foreground">+ {result.limitations.map((lim, i) => (+ <li key={i}>{lim}</li>+ ))}+ </ul>+ )}+ </section>++ {/* Live US options chain */}+ <OptionsChainTable referenceSpot={params.entry_spot} />++ <p className="pb-2 text-xs text-muted-foreground">{t("options.disclaimer")}</p>+ </div>+ );+}diff --git a/frontend/src/router.tsx b/frontend/src/router.tsxindex ca163ebab..4ef661878 100644--- a/frontend/src/router.tsx+++ b/frontend/src/router.tsx@@ -28,6 +28,9 @@ const Correlation = lazy(() =>const AlphaZoo = lazy(() =>import("@/pages/AlphaZoo").then((m) => ({ default: m.AlphaZoo })),);+const OptionsLab = lazy(() =>+ import("@/pages/OptionsLab").then((m) => ({ default: m.OptionsLab })),+);function PageLoader() {return (@@ -59,6 +62,7 @@ export const router = createBrowserRouter([{ path: "/runs/:runId", element: wrap(RunDetail) },{ path: "/compare", element: wrap(Compare) },{ path: "/correlation", element: wrap(Correlation) },+ { path: "/options", element: wrap(OptionsLab) },{ path: "/alpha-zoo", element: wrap(AlphaZoo) },{ path: "/alpha-zoo/bench", element: wrap(AlphaZoo) },{ path: "/alpha-zoo/compare", element: wrap(AlphaZoo) },diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex b29420d76..2cbc764d8 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -16,6 +16,7 @@ const PROXY_PATHS = ["/upload","/shadow-reports","/scheduled-runs",+ "/options",];export default defineConfig(({ mode }) => {@@ -47,6 +48,10 @@ export default defineConfig(({ mode }) => {"^/runs/[^/]+/?$": apiProxyWithHtmlFallback,"/runs": apiProxy,"/correlation": apiProxyWithHtmlFallback,+ // /options is both the SPA Options Lab route and an API prefix+ // (/options/payoff, /options/chain) — same dual role as /correlation.+ // Overrides the plain PROXY_PATHS entry above.+ "/options": apiProxyWithHtmlFallback,"^/alpha(?:/|$)": apiProxy,},},