System Guide
Complete reference for every file, function, and workflow in the IBKR Options Income System.
Weekly Workflow
Monday 09:35 ET → GitHub Actions triggers main.py monday
→ market_intel.py computes composite score (almanac + macro + technical + LLM + human)
→ strategy.py selects SPX strikes and builds recommendation
→ docs/data/trade_state.json updated and pushed to GitHub
→ ibkr-options-income.pages.dev auto-updates (Cloudflare, ~60 seconds)
→ alerts.py sends Telegram message to Professor Dr. Tan's phone
→ Professor Dr. Tan reviews on website and clicks APPROVE
→ executor.py connects to IBKR TWS and places the order
→ Telegram confirmation: trade filled, premium received
Daily 15:45 ET → risk_manager.py checks 50% profit target or stop loss
Thursday 15:45 ET → All positions force-closed, week P&L recorded
Python Files
Central configuration file. Every trading parameter lives here — nothing is hardcoded elsewhere.
To change strategy behavior (number of spreads, strike distance, profit targets), edit only this file.
- IBKR_HOST / PORT / ACCOUNTConnection settings for TWS API (port 7496 live, 7497 paper)
- NUM_SPREADS = 10Moderate risk profile — 10 bull put spreads per week
- SPREAD_WIDTH = 1010-point wide spread (e.g. 7350/7340 puts)
- TARGET_DELTA = 0.05Sell put at ~5 delta = approximately 5% out of the money
- PROFIT_TARGET_PCT = 0.50Close position when 50% of premium is captured
- MAX_LOSS_PCT = 2.00Stop loss trigger at 200% of premium received
- VIX_MAX = 25Skip all trades if VIX above 25 — too dangerous to sell premium
- MIN_BULLISH_SCORE = 55Minimum composite intel score to proceed with trade
The intelligence layer — connects CP3405 market prediction agents to trading decisions.
Computes a composite score (0–100) from five sources. Score above 55 = proceed, below 45 = skip, below 35 = hard veto.
- get_almanac_score()Seasonal bias from monthly SPX historical patterns + day-of-week adjustment
- get_macro_score()Fed stance, yields, credit spreads → risk-on / risk-off environment
- get_technical_score()SPX price vs key moving averages → trend strength signal
- get_llm_synthesis_score()Aggregates ChatGPT / Gemini / DeepSeek weekly predictions from CP3405
- get_human_score()Professor Dr. Tan's manual override — read from trade_state.json via website
- get_composite_score()Weighted average of all five scores → final BULLISH / NEUTRAL / BEARISH bias
- get_vix()Fetches live VIX level via yfinance for volatility gate check
Bull put spread construction logic. Takes market intel composite score and current SPX price,
selects optimal strikes, checks all trade gates, and builds the weekly recommendation object.
- get_next_friday()Calculates upcoming Friday for weekly expiry selection
- should_trade(intel)Gate check — returns (proceed: bool, reason: str) based on score and VIX
- calculate_strikes(spx_price, score)Intel-adjusted OTM distance: 4% (high conviction), 5% (standard), 6% (cautious)
- build_recommendation(spx_price)Assembles full trade recommendation dict saved to trade_state.json
Enforces all risk rules. Never risks more than 3% of account per week.
Monitors open positions daily and triggers closes when profit targets or stop losses are hit.
- check_portfolio_risk(positions)Ensures total weekly risk stays within $10,000 hard limit
- should_close_position(position)Evaluates 50% profit, 200% stop loss, Thursday forced close
- calculate_position_size(capital, score)Scales spreads down when intel conviction is low (marginal score = half size)
IBKR TWS API integration. Connects to Trader Workstation on port 7496 and places the spread order.
Requires TWS running with API enabled. Will NOT execute without Professor Dr. Tan's approval flag set.
- IBKRApp classEWrapper + EClient subclass handling connection, order status, error callbacks
- make_spx_put_contract(strike, expiry)Builds IBKR Contract object for SPX put option on CBOE
- make_combo_order(action, qty, price)Builds limit order for spread legs
- place_bull_put_spread(recommendation)Master execution function — checks approval, connects to TWS, places order
Telegram notification system. Every significant trade event sends a formatted message to
Professor Dr. Tan's phone. Credentials stored as GitHub Secrets — never in code.
- alert_recommendation_ready(rec)Sent Monday morning — trade details + link to approve on website
- alert_trade_executed(execution)Sent after IBKR confirms fill — shows actual strike, premium, total credit
- alert_profit_target(position, pnl)Sent when 50% profit target hit mid-week
- alert_stop_loss(position, pnl)Sent if position moves against us — roll or close signal
- alert_thursday_close(n, pnl)Sent Thursday EOD — weekly P&L summary
Master controller. Entry point for all GitHub Actions workflows and manual runs.
Orchestrates the full pipeline by calling the other modules in sequence.
- run_monday_open()Generates weekly recommendation, saves to JSON, sends Telegram alert
- run_daily_check()Checks all open positions against profit/loss targets, closes if triggered
- run_execute()Processes approval flag → calls executor.py → confirms fill via Telegram
- load_state() / save_state()Read/write trade_state.json — single source of truth for all system state
Data & Configuration Files
Single source of truth for all live system state. Updated by GitHub Actions after every run.
The website reads this file to display the dashboard. Professor Dr. Tan's approval is also
written here, which triggers execution on the next Actions run.
- recommendationCurrent week's trade details, approved flag, executed flag, intel scores
- open_positionsArray of active trades with entry price, current value, max risk
- trade_logHistorical record of every completed trade with P&L
- total_pnl / win_rateCumulative performance statistics shown on dashboard KPIs
GitHub Actions workflow. Runs automatically every Monday at 09:35 ET (14:35 UTC).
Can also be triggered manually via workflow_dispatch for testing. Calls main.py monday.
GitHub Actions workflow. Runs Monday–Friday at 15:45 ET (20:45 UTC) to check profit targets.
Thursday run includes forced close of all open positions. Calls main.py check.
Website Files (docs/ folder → ibkr-options-income.pages.dev)
Trading Command Center dashboard. Reads trade_state.json and renders live KPIs,
this week's recommendation, market intelligence bars, open positions, and trade log.
Approve button sets approved flag and triggers execution workflow.
This system's resume prompt for Claude. Paste the prompt into any new Claude chat session
to instantly restore full context — strategy, architecture, pending items, and credentials reference.
This page. Complete file-by-file reference for the entire system.
Pending Setup Items
1
Set up Telegram bot — get TELEGRAM_BOT_TOKEN from @BotFather and TELEGRAM_CHAT_ID from getUpdates API PENDING
2
Enable IBKR TWS API — TWS → Edit → Global Configuration → API → Settings → Enable ActiveX and Socket Clients → Port 7496 PENDING
3
Add GitHub Secrets — repo Settings → Secrets → TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID PENDING
4
Wire approval button — update trade_state.json via GitHub API when Professor Dr. Tan clicks Approve PENDING
5
Live SPX price feed — replace placeholder in strategy.py with live IBKR market data call PENDING
6
First paper trade test — run main.py monday manually to validate full pipeline end-to-end PENDING
7
Cloudflare Pages connected to GitHub repo — auto-deploys from /docs folder ✅ DONE
8
All Python modules built and pushed to GitHub ✅ DONE
9
GitHub Actions schedules configured (Monday + Daily) ✅ DONE