Abstraction Layer Architecture

Options Strategy Finder

A unified abstraction layer that aggregates options data from Interactive Brokers, TradingView, and other sources to find optimal strategies while persisting analysis for historical tracking.

🔗

Multi-Source Aggregation

Pull data from IB, TradingView, Yahoo - use the best source available with automatic fallback

💾

Persistent Storage

Store chains in Redis, IV history in TimescaleDB, track strategy performance over time

🤖

AI Integration

Query via Claude Code with natural language - "Find me a bull call spread on NVDA for March"

Automated Analysis

No more clicking through TWS - automate searches and get alerts when opportunities appear

System Architecture

Abstraction layer over existing tools with persistent storage

Claude CodeMCP Tools
Open WebUIChat Interface
Trading DashboardWeb App
HTTP / REST / MCP
Options Search API (FastAPI) optionsearch-api.ai-servicers.com
Internal
Strategy Engine Generator, Calculator, Ranker
Data Aggregator Provider Router + Normalizer
Provider Interface
Data Providers (Priority Order)
Interactive Brokers Primary - Port 4004
TradingView Enrichment - Port 8000
Yahoo Finance Fallback - yfinance
Cache + Persist
Persistence Layer
Redis Tiered Cache (5s/5m/24h)
PostgreSQL + TimescaleDB Single Instance

Your Existing Data Sources

Leverage the tools you already pay for

📊

Interactive Brokers

PRIMARY
  • Real-time options chains with Greeks
  • Accurate bid/ask spreads
  • Volume and open interest
  • Option Strategy Lab reference
  • Paper trading execution (future)
📈

TradingView

ENRICHMENT
  • IV Rank and IV Percentile
  • Technical indicators (RSI, MACD)
  • Buy/Sell/Neutral recommendations
  • Historical volatility data
  • Already integrated via existing API
🏦

Fidelity

REFERENCE
  • Active Trader Pro strategy ideas
  • Strategy Screener reference
  • Research and analysis
  • Manual verification source
  • Future API integration possible
🌐

Yahoo Finance

FALLBACK
  • Free delayed options data
  • Basic chain information
  • Used when IB unavailable
  • yfinance Python library
  • Good for testing/development

Example Flow: Multi-Source Analysis

How data flows through the abstraction layer

Scenario

You ask Claude: "Find me the best options strategy for NVDA to hit $155 by March. I want defined risk."

1

MCP Request Received

Claude Code invokes the search_strategies MCP tool

Tool: search_strategies
Symbol: NVDA
Target: $155 (+10%)
Timeline: ~90 days (March expiry)
Constraint: defined_risk: true
2

Check Redis Cache

Look for recently cached chain data

Key: chains:NVDA:2025-03-21
Result: MISS (cache expired)
Action: Fetch from providers
Redis
3

Fetch from Interactive Brokers

Primary provider returns full options chain

# ib_insync fetches via IB Gateway
Expiration: 2025-03-21
Calls: 45 contracts
Puts: 45 contracts
Greeks: Delta, Gamma, Theta, Vega
Liquidity: Volume, Open Interest, Spread
Interactive Brokers
4

Enrich with TradingView

Add technical analysis and IV metrics

# TradingView API enrichment
IV Rank: 62 (above average)
IV Percentile: 71
RSI (14): 54.2
MACD Signal: BULLISH
Recommendation: BUY
TradingView
5

Cache & Persist

Store for reuse and historical tracking

# Hot cache for repeated queries
Redis: chains:NVDA:2025-03-21 TTL: 60s

# Historical tracking
TimescaleDB: iv_history (symbol, iv_rank, timestamp)
Redis TimescaleDB
6

Generate & Score Strategies

Filter for defined risk, calculate metrics, rank by target alignment

# Strategy engine processing
Filter: defined_risk=true → Spreads only
Generated: 312 vertical spreads
Calculated: P&L at $155, PoP, Greeks
Ranked: Top 20 by score
7

Return Enriched Results

Claude presents the top strategies with full context

Data Persistence

Tiered caching + unified database

⚡ Redis - Fast Data 5-10s TTL

Quotes and Greeks change rapidly - short cache prevents stale execution data

quotes:{symbol} greeks:{symbol}:{strike}

⚡ Redis - Slow Data 5m TTL

IV metrics and technicals change slowly - longer cache OK

iv:{symbol} technicals:{symbol}

⚡ Redis - Static Data 24h TTL

Contract specs and strike lists rarely change

contracts:{symbol} strikes:{symbol}:{exp}

🗄 PostgreSQL + TimescaleDB Permanent

Single instance with TimescaleDB extension - hypertables for time-series, regular tables for config

iv_history (hypertable) price_history (hypertable) watchlist, alerts (tables)

Example Result

Multi-source enriched strategy recommendation

#1
Bull Call Spread
NVDA Mar 21 '25 140/155 Call Spread
91.2
SCORE
BUY 1x NVDA Mar 140 Call @ $18.50
SELL 1x NVDA Mar 155 Call @ $9.20
$930
Net Debit
$570
Max Profit
$930
Max Loss
$149.30
Breakeven
58%
Prob. of Profit
$570
P&L @ $155
📈 TradingView Enrichment: IV Rank 62 | RSI 54.2 | Signal: BUY

Data Sources Used

IB Chain, Greeks, Prices
TV IV Rank, RSI, Signal
Redis Cached 45s ago

Critical Components (Peer Reviewed)

Validated by Gemini, Claude, and Codex

Corporate Actions

CRITICAL
  • Splits/dividends destroy strategies overnight
  • Monitor IB corporate actions feed
  • Auto-invalidate affected cached chains
  • Alert on positions with pending actions
🛡

Circuit Breakers

RELIABILITY
  • Track provider health status
  • Fail fast on repeated errors
  • Auto-fallback to next provider
  • IB: 5 failures, TradingView: 3 failures
🔒

Cache Stampede Protection

PERFORMANCE
  • Single-flight pattern for cache misses
  • Only one caller fetches on expiry
  • Prevents thundering herd to IB API
  • Async refresh-ahead for hot keys
🎯

Strategy Scoring

ACCURACY
  • Don't rank purely on ROI
  • Weight by Probability of Profit
  • Penalize wide bid/ask spreads
  • Penalize high gamma (management overhead)
🏷

Data Provenance

SAFETY
  • Tag all data with source + timestamp
  • IB = real-time, TradingView = ~15m delayed
  • Never mix delayed IV with real-time quotes
  • Cache version for schema invalidation
📊

Observability

OPS
  • Structured logging with provider labels
  • Metrics: latency, errors, cache hit ratio
  • Trace provider calls for debugging
  • Queue depth monitoring

Strategy Scoring Formula

score = (
    # Expected value weighted by probability
    (max_profit × prob_of_profit) - (max_loss × (1 - prob_of_profit))

    # Penalize illiquid options
    × liquidity_factor  # 0-1, based on bid/ask spread

    # Penalize high-maintenance strategies
    - gamma_penalty  # High gamma = constant adjustment
)

Why not just ROI? A 500% return with 5% probability is worse than 50% return with 60% probability.

⚠ American Options Warning

py_vollib calculates European options. US equity options are American style. Flag strategies where early exercise matters (deep ITM puts, calls before dividends).

⚠ TradingView Fragility

tradingview-ta is unofficial and brittle. Plan for breakage. Free tier is ~15m delayed. Always have fallback strategy.

Position Sizing & Quality Filters

Risk management and option quality parameters

💰

Position Sizing

RISK MGMT
  • max_allocation - Max buying power to use ($)
  • max_risk - Max acceptable loss ($)
  • allow_multiple_contracts - Scale up position
  • max_contracts - Contract limit (default: 10)
🔍

Liquidity Filters

QUALITY
  • min_open_interest - Min OI (default: 100)
  • max_bid_ask_spread_pct - Max spread % (5%)
  • min_volume - Daily volume floor
📅

Time Filters

EXPIRY
  • min_days_to_expiry - No weeklies (14+)
  • max_days_to_expiry - Cap for LEAPs
  • exclude_earnings - Skip earnings dates
🎯

Greeks Filters

TARGETING
  • delta_range - Target delta [0.2, 0.4]
  • min_probability_of_profit - PoP floor (50%)
  • max_gamma - Limit adjustment need

Position Sizing Example

// Request: max_allocation=$5000, max_risk=$2000, allow_multiple=true

Bull Call Spread: NVDA 140/155 @ $9.30/contract
  max_loss_per_contract: $930
  max_contracts_by_risk: floor($2000 / $930) = 2 contracts
  max_contracts_by_capital: floor($5000 / $930) = 5 contracts
  recommended: 2 contracts (limited by max_risk)

Result:
  total_cost: $1,860
  max_loss: $1,860 (within $2000 limit)
  max_profit: $1,140 (2 × $570)

Defined vs Undefined Risk: For spreads, max_loss = debit paid. For naked options, max_loss is calculated from margin requirements.

Complete API Request

{
  "symbol": "AAPL",
  "current_price": 195.50,
  "target_prices": [205.28, 215.05],
  "timeline_days": 90,
  "allowed_strategies": ["vertical_spread", "covered_call"],

  // Position Sizing
  "max_allocation": 5000,
  "max_risk": 2000,
  "allow_multiple_contracts": true,
  "max_contracts": 10,

  // Quality Filters
  "min_probability_of_profit": 0.50,
  "min_open_interest": 100,
  "max_bid_ask_spread_pct": 5.0,
  "min_days_to_expiry": 14,
  "exclude_earnings": true,
  "delta_range": [0.20, 0.40],

  // Data & Storage
  "data_sources": ["ib", "tradingview"],
  "persist_results": true
}