File size: 13,432 Bytes
8587686 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 | """Options Scanner MCP server.
Exposes the options_scanner engine as MCP tools: universe scanning,
per-symbol strategy building, chain summaries, and position/roll checks.
Run (stdio transport, what Claude Desktop / Hermes expect):
python mcp_server.py
Data provider is auto-selected from the environment:
TRADIER_API_KEY real-time, full greeks/OI
ALPACA_KEY_ID+SECRET real-time IEX (thin quotes, no OI)
POLYGON_API_KEY real-time snapshot
(none set) Yahoo Finance, ~15-min delayed
This server reads market data and computes structures. It never places
orders.
"""
import json
from dataclasses import asdict
# SDK compatibility: current main is mcp.server.mcpserver.MCPServer; the
# released 1.x package still exposes the same decorator API as FastMCP.
try:
from mcp.server.mcpserver import MCPServer
except ImportError: # pragma: no cover - released SDK
from mcp.server.fastmcp import FastMCP as MCPServer
from options_scanner.config import RiskParams, LARGE_CAPS, HIGH_IV_CANDIDATES, LIQUID_ETFS
from options_scanner.data import get_provider
from options_scanner.strategies import ALL_BUILDERS
from options_scanner.risk import passes_liquidity, passes_defined_risk, risk_report, score
from options_scanner.rolling import Position, check, DEFAULT_ROLL_RULES
from options_scanner.universe import auto_universe
from options_scanner.scan import scan_symbol as engine_scan_symbol
mcp = MCPServer("options-scanner")
STRATEGY_FAMILIES = {
"vertical": "Bull/Bear credit and debit spreads",
"calendar": "Same-strike call/put calendars",
"diagonal": "Offset-strike diagonals (long theta)",
"butterfly": "Long call butterfly + iron butterfly",
"iron_condor": "Iron condor (credit, defined risk)",
"ratio_backspread": "1x2 call ratio backspread",
"jade_lizard": "Short put + call spread credit combo",
"double_diagonal": "Short strangle with long back-month wings",
"short_straddle": "Naked straddle (blocked unless allow_undefined_risk)",
"short_strangle": "Naked strangle (blocked unless allow_undefined_risk)",
}
def _params(account_size=25000.0, risk_pct=5.0, allow_undefined_risk=False,
min_oi=100, max_rel_spread=0.25, credit_short_delta=0.30,
condor_short_delta=0.20, min_dte=5, max_dte=45) -> RiskParams:
return RiskParams(
account_size=account_size, max_buying_power_pct=risk_pct,
allow_undefined_risk=allow_undefined_risk, min_oi=min_oi,
max_rel_spread=max_rel_spread, credit_short_delta=credit_short_delta,
condor_short_delta=condor_short_delta, min_dte=min_dte, max_dte=max_dte,
)
def _candidates_json(symbol, cands):
return {"symbol": symbol, "count": len(cands),
"candidates": [{"strategy": c.name, "view": c.view,
"legs": [l.label() for l, _ in c.legs],
"credit_debit_usd": round(c.net_credit * 100, 2),
"risk": risk_report(c),
"score": c.score, "notes": c.notes,
"reasons": c.reasons} for c in cands]}
# ---------- impl functions (plain Python, unit-testable) ----------
def impl_scan_universe(symbols=None, provider=None, max_expiries=5,
account_size=25000.0, risk_pct=5.0,
allow_undefined_risk=False, top_n=15):
params = _params(account_size, risk_pct, allow_undefined_risk)
prov = get_provider(provider)
universe = ([s.strip().upper() for s in symbols.split(",") if s.strip()]
if symbols else auto_universe())
rows, errors = [], []
for sym in universe:
try:
_, cands, err = engine_scan_symbol(prov, sym, params, max_expiries)
if err:
errors.append({"symbol": sym, "error": err})
continue
rows.extend({"symbol": sym, "strategy": c.name, "view": c.view,
"credit_debit_usd": round(c.net_credit * 100, 2),
"max_profit_usd": round(c.max_profit * 100, 2),
"max_loss_usd": round(c.max_loss * 100, 2),
"pop_pct": round(c.pop * 100, 1), "score": c.score,
"legs": " ; ".join(l.label() for l, _ in c.legs),
"breakevens": ",".join(str(b) for b in c.breakevens),
"notes": c.notes}
for c in cands)
except Exception as e:
errors.append({"symbol": sym, "error": str(e)[:200]})
rows.sort(key=lambda r: r["score"], reverse=True)
return {"provider": prov.name, "scanned": len(universe) - len(errors),
"universe_size": len(universe), "candidates_found": len(rows),
"top": rows[:top_n], "errors": errors}
def impl_scan_symbol(symbol, provider=None, max_expiries=5,
account_size=25000.0, risk_pct=5.0,
allow_undefined_risk=False):
params = _params(account_size, risk_pct, allow_undefined_risk)
prov = get_provider(provider)
params.max_candidates_per_symbol = 999 # return everything, caller filters
_, cands, err = engine_scan_symbol(prov, symbol.strip().upper(), params, max_expiries)
return _candidates_json(symbol.strip().upper(), cands) if not err else {"error": err}
def impl_build_strategy(symbol, strategy, provider=None, account_size=25000.0,
risk_pct=5.0, allow_undefined_risk=False):
"""Build one named structure family on a symbol. `strategy` matches the
family keys from list_strategies (e.g. iron_condor, jade_lizard)."""
params = _params(account_size, risk_pct, allow_undefined_risk)
params.max_candidates_per_symbol = 999
prov = get_provider(provider)
sym = symbol.strip().upper()
_, cands, err = engine_scan_symbol(prov, sym, params, 5)
if err:
return {"error": err}
key = strategy.strip().lower().replace("-", "_").replace(" ", "_")
needle = STRATEGY_FAMILIES.get(key)
if needle is None:
return {"error": f"unknown strategy '{strategy}'. Use list_strategies."}
# match by family keywords in the candidate name
aliases = {"vertical": "Spread", "calendar": "Calendar",
"diagonal": "Diagonal", "butterfly": "Butterfly",
"iron_condor": "Iron Condor", "ratio_backspread": "Backspread",
"jade_lizard": "Jade Lizard", "double_diagonal": "Double Diagonal",
"short_straddle": "Straddle", "short_strangle": "Strangle"}
want = aliases[key]
hits = [c for c in cands if want.lower() in c.name.lower()]
if not hits:
return {"symbol": sym, "count": 0,
"note": f"no {needle} built for {sym} — usually a wing/strike "
f"missing from the provider feed (the builder refuses to "
f"fake strikes), or a liquidity/earnings gate rejection.",
"families_that_did_build": sorted({c.name for c in cands})}
return _candidates_json(sym, hits[:4])
def impl_chain_summary(symbol, provider=None, max_expiries=6):
prov = get_provider(provider)
chain = prov.get_chain(symbol.strip().upper(), max_expiries=max_expiries)
exps = chain.expirations()
return {"symbol": chain.symbol, "provider": prov.name, "spot": round(chain.spot, 2),
"iv30_pct": round(chain.iv30 * 100, 1),
"next_earnings": chain.next_earnings or None,
"expirations": exps[:max_expiries],
"quote_count": len(chain.quotes),
"front_liquidity": round(chain.liquidity_score(exps[0]), 1) if exps else 0.0}
def impl_check_position(position, symbol, provider=None,
profit_target_pct=0.50, stop_loss_mult=2.0,
roll_dte=21, tested_delta=0.40):
"""position: list of legs [{kind:'C'|'P', strike, expiry:'YYYY-MM-DD',
side:+1|-1, qty}], plus entry_credit (per share, >0 credit) and
entry_date. Returns close/roll/hold recommendations."""
prov = get_provider(provider)
chain = prov.get_chain(symbol.strip().upper(), max_expiries=6)
pos = Position(symbol=symbol.strip().upper(),
structure=str(position.get("structure", "custom")),
legs=[(l["kind"], float(l["strike"]), l["expiry"],
int(l["side"]), int(l.get("qty", 1)))
for l in position["legs"]],
entry_credit=float(position.get("entry_credit", 0.0)),
entry_date=str(position.get("entry_date", "")))
rules = dict(DEFAULT_ROLL_RULES, profit_target_pct=profit_target_pct,
stop_loss_mult=stop_loss_mult, roll_dte=roll_dte,
tested_delta=tested_delta)
actions = check(pos, chain, rules)
return {"symbol": pos.symbol, "spot": round(chain.spot, 2),
"dte_left": min(chain.get(k, e, kk).dte
for kk, k, e, s, q in pos.legs
if chain.get(k, e, kk)),
"actions": [{"action": a.action, "reason": a.reason,
"urgency": a.urgency,
"proposed_legs": [list(x) for x in a.proposed_legs]}
for a in actions]}
def impl_list_strategies():
return {"families": STRATEGY_FAMILIES,
"defaults": {"credit_short_delta": 0.30, "condor_short_delta": 0.20,
"spread_width_usd": 10.0, "min_oi": 100,
"max_rel_spread": 0.25, "risk_pct_default": 5.0,
"roll_rules": DEFAULT_ROLL_RULES}}
def impl_list_watchlists():
return {"large_caps": LARGE_CAPS, "high_iv": HIGH_IV_CANDIDATES,
"sector_etfs": LIQUID_ETFS,
"auto_universe_size": len(auto_universe())}
# ---------- MCP tool registration ----------
@mcp.tool()
def scan_universe(symbols: str = "", provider: str = "", max_expiries: int = 5,
account_size: float = 25000.0, risk_pct: float = 5.0,
allow_undefined_risk: bool = False, top_n: int = 15) -> dict:
"""Run the multi-strategy scanner. Empty `symbols` = auto universe
(large caps + high-IV names + ETFs). Returns ranked candidates with
credit/debit, max profit/loss, POP, breakevens and legs. `provider`:
'' (auto) | tradier | alpaca | polygon | yfinance."""
return impl_scan_universe(symbols or None, provider or None, max_expiries,
account_size, risk_pct, allow_undefined_risk, top_n)
@mcp.tool()
def scan_symbol(symbol: str, provider: str = "", max_expiries: int = 5,
account_size: float = 25000.0, risk_pct: float = 5.0,
allow_undefined_risk: bool = False) -> dict:
"""Build every eligible strategy on one ticker, with full risk reports:
max profit/loss, POP, breakevens, per-leg labels and gate reasons."""
return impl_scan_symbol(symbol, provider or None, max_expiries,
account_size, risk_pct, allow_undefined_risk)
@mcp.tool()
def build_strategy(symbol: str, strategy: str, provider: str = "",
account_size: float = 25000.0, risk_pct: float = 5.0,
allow_undefined_risk: bool = False) -> dict:
"""Build a specific structure family on a symbol: vertical, calendar,
diagonal, butterfly, iron_condor, ratio_backspread, jade_lizard,
double_diagonal, short_straddle, short_strangle. Returns matching
candidates with legs and risk. See list_strategies for details."""
return impl_build_strategy(symbol, strategy, provider or None,
account_size, risk_pct, allow_undefined_risk)
@mcp.tool()
def chain_summary(symbol: str, provider: str = "", max_expiries: int = 6) -> dict:
"""Quick chain read on a ticker: spot, 30-day ATM IV, front expiry
liquidity score, next earnings date, quote count."""
return impl_chain_summary(symbol, provider or None, max_expiries)
@mcp.tool()
def check_position(position: dict, symbol: str, provider: str = "",
profit_target_pct: float = 0.50, stop_loss_mult: float = 2.0,
roll_dte: int = 21, tested_delta: float = 0.40) -> dict:
"""Position management with rolling mechanics. Pass the open position as
{"structure": "...", "entry_credit": 3.2, "entry_date": "2026-10-01",
"legs": [{"kind": "P", "strike": 279.0, "expiry": "2026-11-02",
"side": -1, "qty": 1}, ...]} (entry_credit per share, >0 =
credit received). Returns close/take-profit/roll-out/roll-down/roll-up
recommendations per the given rules."""
return impl_check_position(position, symbol, provider or None,
profit_target_pct, stop_loss_mult,
roll_dte, tested_delta)
@mcp.tool()
def list_strategies() -> dict:
"""All supported strategy families and the engine's default risk
parameters and roll rules."""
return impl_list_strategies()
@mcp.tool()
def list_watchlists() -> dict:
"""The built-in watchlist pools (large caps, high-IV names, sector ETFs)
and the auto universe size."""
return impl_list_watchlists()
if __name__ == "__main__":
import sys
if "--http" in sys.argv: # remote clients: http://127.0.0.1:8000/mcp
mcp.run(transport="streamable-http")
else:
mcp.run()
|