OPEN-SOURCE SCRIPT

SPX Iron Fly Session Tracker

69
Overview

This indicator provides visual tracking for iron fly option structures designed for SPX 0-day-to-expiration (0DTE) intraday trading. It implements a two-phase position management system that adapts to different market conditions throughout the trading day.

This is a visualization and tracking tool only. It does not execute trades, access real options data, or calculate actual profit and loss. All displayed positions are theoretical representations based on underlying price movement.

Strategy Goal and Context

The Core Objective:
The strategy aims to have SPX price expire within your iron fly positions at end of day. When price expires inside a fly's profit zone (between the wings), that position captures maximum premium. The challenge is that price moves throughout the day, so static positioning rarely succeeds.

The Solution: Active Management
Rather than setting positions and hoping price cooperates, this approach continuously manages and repositions flies to keep price centered within your profit zones. As SPX drifts during the trading session, you add new flies at current price levels and close flies that price has moved away from.

The Goal: Multiple Profitable Expirations
By session end, you want as many flies as possible to have price expire within their center zones. This requires:
  • Adding new flies as price moves away from existing positions
  • Closing flies when price crosses beyond their optimal range
  • Building layered coverage in the afternoon to increase probability of capture
  • Adapting wing widths to time of day and volatility


The Reality: Capital and Time Intensive
This is not a passive strategy. Successful implementation requires:
  • Substantial capital (each fly requires margin, multiple flies compound this)
  • Active monitoring throughout trading sessions
  • Quick decision-making as positions trigger
  • Multiple position adjustments per session
  • Disciplined adherence to management rules


How This Indicator Helps:

For backtesting:
  • Use replay mode to study how positions would have managed on historical sessions
  • Test different parameter combinations to find optimal settings
  • Observe position behavior during various market conditions
  • Understand timing and frequency of position adds and closes
  • Validate whether your capital can support the required position count


For live session support:
  • Real-time visual tracking shows current position coverage
  • Alerts notify you immediately when new positions should be added
  • Position closure alerts help you manage exits promptly
  • Reference strike tracking shows where you're measuring movement from
  • History table provides audit trail of all position activity


The indicator handles the complex tracking and rule application, allowing you to focus on execution and risk management.

Key Use Cases

1. Replay Mode - Backtest and Study
Use TradingView's replay feature to validate the strategy on historical sessions:
  • Step through past SPX sessions bar-by-bar
  • See exactly when positions would have opened and closed
  • Count how many flies would have expired profitably
  • Analyze different parameter settings on the same historical data
  • Study position behavior during trending vs ranging conditions
  • Calculate approximate capital requirements for your setup
  • Refine your parameters before risking real capital


2. Live Session Alerts
Set up real-time notifications for active trading sessions:
  • Get alerted immediately when new positions trigger
  • Receive notifications when positions close
  • Alerts include strike level, wing width, and closure reason
  • Works on mobile, desktop, email, or webhook
  • Never miss a position signal during active trading
  • Maintain awareness even when away from screens briefly


3. Fully Customizable Parameters
Adapt every aspect to your risk tolerance and capital:
  • Adjust trigger distances for more or fewer position adds
  • Modify wing widths for different volatility environments
  • Change session timing to match your trading schedule
  • Set maximum concurrent positions to your capital limits
  • Fine-tune spacing to match available strike increments


Iron Fly Structure

An iron fly is a neutral options strategy with four legs:
- Short 1 ATM Call
- Short 1 ATM Put
- Long 1 OTM Call (upper wing protection)
- Long 1 OTM Put (lower wing protection)

The structure creates a defined risk zone. Maximum profit occurs when price expires at the center strike. Loss increases as price moves toward the wings (breakeven points). Maximum loss is defined and occurs beyond the wings.

Expiration Goal:
You want SPX to close inside the fly's wings. If SPX expires at the strike, you capture maximum premium. If SPX expires between the strike and either wing, you still profit (reduced). If SPX expires beyond the wings, you realize a loss (but it's defined and limited by the wings).

Two-Phase Management System

The indicator tracks positions across two distinct trading phases with different management rules:

Phase 1: TWO_GLASS - Morning Session (Default 10am-1pm ET)

Conservative positioning with active repositioning:
- Trigger new positions when price moves 7.5 points from reference strike (configurable)
- Maintain maximum 2 concurrent positions (configurable)
- 10-point spacing between position strikes (configurable)
- 40-point wing width (configurable)
- Exit rule: When two positions are active and price crosses to one strike level, close the OTHER position

This phase uses a "follow the price" approach. You're not trying to stack multiple positions yet - you're maintaining one or two flies centered on wherever price currently is. As price drifts, you add a new fly at the current level and close the old one when price moves too far away.

Phase 2: THREE_GLASS - Afternoon Session (Default 1pm-4pm ET)

Accumulation mode with layered coverage:
- Trigger new positions every 2.5 points of price movement (configurable)
- Maintain maximum 6 concurrent positions (configurable)
- 5-point spacing between strikes (configurable)
- 20-point wings early, reducing to 10 points after 3pm (configurable)
- Exit rule: Positions only close when price reaches wing extremes

This phase builds a stacked profit zone. Instead of swapping positions, you accumulate multiple flies as price moves. The goal is to have several flies active at expiration, creating a wider net to capture price. Tighter spacing and more frequent triggers create this layered coverage.

Why Two Different Phases?

Morning (Phase 1):
Earlier in the day, price has more time to move substantially. Maintaining many concurrent positions is riskier because price could trend and hit multiple wings. The strategy uses selective positioning with wider wings and active replacement.

Afternoon (Phase 2):
Closer to expiration, price movements typically compress. Time for large moves decreases. The strategy shifts to accumulation, building a net of positions to increase probability that final expiration price falls within at least one (ideally several) of your flies. Tighter wings and more positions become appropriate.

Exit Mechanisms

Strike Cross Exit (Phase 1 Only)
When two positions are active, if price moves to or beyond one position's strike level, the OTHER position closes. This keeps your coverage centered on current price action rather than maintaining positions price has moved away from.

Example: Flies at 5900 and 5910 are open. Price moves to 5910. The fly at 5900 closes because price has moved to the 5910 level. You're now positioned at current price (5910) rather than maintaining coverage at old price (5900).

Wing Extreme Exit (Both Phases)
Any position closes immediately when price touches its upper or lower wing boundary. This represents the breakeven/maximum loss point, so the position is closed to prevent further deterioration.

Dynamic Wing Adjustment

Wing widths automatically adjust based on time of day:
- Phase 1 (Morning): 40 points (customizable)
- Phase 2 Early (1pm-3pm): 20 points (customizable)
- Phase 2 Late (3pm-4pm): 10 points (customizable)

This progressive tightening reflects decreasing price movement potential as expiration approaches. Wider wings earlier provide more protection when price could move substantially. Tighter wings later allow more precise positioning when price movements typically compress.

All values are fully adjustable to match your risk parameters and observed market volatility.

Customization Guide

Every parameter can be modified to suit your trading style, risk tolerance, and capital:

Session Timing
- TWO_GLASS Start Hour: When Phase 1 begins (default: 10am ET)
- THREE_GLASS Start Hour: When Phase 2 begins (default: 1pm ET)
- Wing Width Change Hour: When wings tighten (default: 3pm ET)
- Session End Hour: When tracking stops (default: 4pm ET)

Phase 1 Parameters (Fully Adjustable)
- Trigger Distance: How far price must move from reference strike to add new position (default: 7.5, range: 0.1+)
- Fly Spacing: Distance between position strikes (default: 10, range: 1.0+)
- Wing Width: Distance from strike to wings (default: 40, range: 5.0+)
- Max Flies: Maximum concurrent positions (default: 2, range: 1-10)

Phase 2 Early Parameters (Fully Adjustable)
- Trigger Distance: Movement needed to add new position (default: 2.5, range: 0.1+)
- Fly Spacing: Distance between strikes (default: 5, range: 1.0+)
- Wing Width: Strike to wing distance (default: 20, range: 5.0+)
- Max Flies: Maximum concurrent positions (default: 6, range: 1-20)

Phase 2 Late Parameters
- Wing Width: Reduced width after 3pm (default: 10, range: 5.0+)

General Settings
- Strike Rounding: Round strikes to nearest multiple (default: 5.0, range: 1.0+)
- Bars Before Check: Bars to wait before allowing closure (default: 2, prevents premature exits)

Display Options
- Show History Table: Toggle detailed position log (default: on)
- History Table Rows: Number of positions displayed (default: 15, range: 5-30)

Alert Settings
- Enable Alerts: Toggle notifications for opens/closes (default: on)

How to Use

For Backtesting in Replay Mode:
  • Select a historical SPX trading session
  • Apply indicator to 1-5 minute timeframe
  • Configure your preferred parameters
  • Activate TradingView's replay feature
  • Play through the session (step-by-step or continuous)
  • Observe when positions open (green boxes appear)
  • Watch position closures (boxes turn gray)
  • Count how many flies would have expired with price inside (green at session end)
  • Note total number of position adds throughout session
  • Calculate approximate capital needed (positions × margin per fly)
  • Test different parameter combinations on same historical data
  • Study position behavior during trending vs ranging sessions


For Live Trading Sessions:
  • Apply indicator to SPX on 1-5 minute timeframe
  • Configure parameters based on your backtest results
  • Create alerts for "Iron Fly Opened" and "Iron Fly Closed"
  • Set alert frequency to "Once Per Bar Close"
  • Choose notification method (popup, mobile app, email, webhook)
  • Monitor the status table (top-right) for current session and reference strike
  • Review history table (bottom-right) for position log with timestamps
  • When alert triggers, use visual cues to manually place actual option orders
  • Execute position adds and closes as indicated by the tracker


Visual Interpretation:
  • Green boxes = Active positions (theoretical profit zones)
  • White lines (Phase 1) / Aqua lines (Phase 2) = Strike levels
  • Red/Blue dotted lines = Wing boundaries (breakeven/risk limits)
  • Gray boxes = Closed positions (historical reference)
  • Current SPX price line = Shows where price is relative to positions
  • Top-right table = Current session status, reference strike, open/closed counts
  • Bottom-right table = Complete position history with open/close timestamps


Alert System Details

The indicator generates detailed alert messages for position management:

Position Opened:
- Strike level where fly should be placed
- Wing width (±points from strike)
- Session phase (Phase 1 or Phase 2)
- Alert format example: "Iron Fly OPENED | Strike: 5900 | Wings: ±40 | Session: TWO_GLASS"

Position Closed:
- Strike level of fly being closed
- Closure reason (strike cross, wing extreme, etc.)
- Session phase
- Alert format example: "Iron Fly CLOSED | Strike: 5900 | Reason: Price crossed to lower fly | Session: TWO_GLASS"

Configure alerts once before market open, then receive automatic notifications as positions trigger throughout the trading session.

Parameter Optimization Suggestions

For Higher Volatility Environments:
- Increase trigger distances (e.g., Phase 1: 10-15 points, Phase 2: 3-5 points)
- Widen wing widths (e.g., Phase 1: 50-60 points, Phase 2: 25-30 points early, 15-20 late)
- Increase strike spacing to reduce position frequency

For Lower Volatility Environments:
- Decrease trigger distances (e.g., Phase 1: 5-7 points, Phase 2: 1.5-2 points)
- Tighten wing widths (e.g., Phase 1: 30-35 points, Phase 2: 15-18 points early, 8-10 late)
- Reduce strike spacing for more granular coverage

For Conservative Risk Management:
- Reduce maximum concurrent positions (Phase 1: 1, Phase 2: 3-4)
- Widen wing widths for more breathing room
- Increase bars before check to avoid whipsaws
- Use wider trigger distances to reduce position frequency

For Aggressive Positioning:
- Increase maximum concurrent positions (Phase 2: 8-10)
- Tighten trigger distances for more frequent adds
- Reduce bars before check for faster responses
- Use tighter spacing to create denser coverage

Capital Considerations:
Remember that each fly requires margin. If Phase 2 allows 6 concurrent flies and each requires $10,000 margin, you need $60,000 in available capital just for position requirements, plus additional cushion for adverse movement.

Use replay mode to count maximum concurrent positions that would have occurred on historical sessions with your parameters, then calculate total capital needed.

Practical Application

This tool provides visual guidance and management support. To implement the strategy:

  • Backtest thoroughly in replay mode first
  • Validate capital requirements for your parameter settings
  • Confirm you can actively monitor positions during trading hours
  • Use displayed positions as reference for manual order placement
  • Match indicator parameters to your actual option contracts
  • Account for real-world factors: commissions, slippage, bid-ask spreads, option availability
  • Implement proper position sizing based on available capital
  • Set up alerts before market open to catch all signals
  • Execute actual trades manually in your brokerage platform
  • Track actual results versus indicator expectations


Important Limitations

  • Theoretical tracking only - not an automated trading system
  • No access to real option prices, Greeks, or implied volatility
  • No profit/loss calculations or risk metrics
  • Does not account for time decay (theta), delta, gamma, vega changes
  • Assumes continuous price action - gaps or halts not handled
  • Designed for 0DTE SPX options - not suitable for other timeframes or instruments
  • Assumes option availability at all strike levels - may not reflect reality
  • Does not model actual option bid/ask spreads or liquidity
  • Assumes instant execution at desired strikes - slippage not considered
  • Historical replay shows theoretical behavior only - actual market conditions may differ
  • Does not adjust for changing implied volatility throughout session
  • Position count and timing may not match what's executable in real markets


Capital and Time Requirements

This strategy is resource-intensive:

Capital Requirements:
  • Each iron fly requires margin (varies by broker and strike width)
  • Multiple concurrent positions multiply capital needs
  • Example: 6 flies at $10,000 each = $60,000 minimum
  • Additional cushion needed for adverse movement
  • Pattern Day Trader rules may apply (requires $25,000 minimum)


Time Requirements:
  • Active monitoring during trading hours (typically 10am-4pm ET)
  • Quick response to position add/close signals
  • Multiple position adjustments per session possible
  • Cannot be passive or set-and-forget
  • Requires ability to place orders promptly when alerted


Use replay mode to understand the commitment level before attempting live implementation.

Risk Considerations

Iron fly trading involves substantial risk. This indicator provides visualization and management support only - it does not constitute financial advice or trading recommendations.

Options trading can result in total loss of capital. The indicator's theoretical positions do not reflect actual trading results. Backtest analysis and historical visualization do not guarantee similar future outcomes. Multiple concurrent positions multiply both profit potential and loss risk.

Always conduct independent research, understand all risks, validate capital requirements, and never trade with funds you cannot afford to lose. Consider starting with paper trading to validate execution capability before risking real capital.

Technical Notes

The indicator uses price-based triggers only. It does not:
  • Connect to options data feeds
  • Calculate theoretical option values or Greeks
  • Execute trades automatically
  • Provide specific trading signals or recommendations
  • Account for option-specific factors (implied volatility, time decay, bid/ask spreads)


All displayed information represents theoretical position placement based solely on underlying SPX price movement and user-configured parameters. The tool helps visualize the management framework but requires the trader to handle all actual execution and risk management decisions.

This is an educational and analytical tool for understanding iron fly position management concepts. It requires active interpretation, backtesting validation, and manual implementation by the user.

כתב ויתור

המידע והפרסומים אינם מיועדים להיות, ואינם מהווים, ייעוץ או המלצה פיננסית, השקעתית, מסחרית או מכל סוג אחר המסופקת או מאושרת על ידי TradingView. קרא עוד ב־תנאי השימוש.