OPEN-SOURCE SCRIPT
Aktualisiert SPX Iron Fly Session Tracker

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:
The Reality: Capital and Time Intensive
This is not a passive strategy. Successful implementation requires:
How This Indicator Helps:
For backtesting:
For live session support:
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:
2. Live Session Alerts
Set up real-time notifications for active trading sessions:
3. Fully Customizable Parameters
Adapt every aspect to your risk tolerance and capital:
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:
For Live Trading Sessions:
Visual Interpretation:
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:
Important Limitations
Capital and Time Requirements
This strategy is resource-intensive:
Capital Requirements:
Time Requirements:
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:
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.
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.
Versionshinweise
b]Recent Updates - P&L Tracking SystemVersion 2.0 - January 2026
This update adds comprehensive P&L tracking capabilities to document your actual trading results directly within the indicator. After executing iron fly positions in your brokerage account, you can now input your actual fill prices to calculate exact profitability.
What's New
Real Fill Price Tracking - Enter actual credit received when opening each fly, record actual debit paid when closing each fly, track different contract quantities per position, calculates gross P&L before commissions and net P&L after commissions.
Integrated P&L Display - The history table now includes three additional columns: Cont (number of contracts traded), Enter (credit received per contract when opening), and Exit (debit paid per contract when closing).
Session Totals - At the bottom of the history table you'll see Brutto P&L (total gross profit/loss before commissions) and Netto P&L (total net profit/loss after commissions), color-coded with green for profit and red for loss.
Commission Support - Configurable open and close commission rates with default TastyTrade structure of $7.05 open and $7.05 close, adjustable for expired positions, with per-contract calculation for accurate multi-contract tracking.
How It Works
After your trading session, open indicator settings and scroll to P&L Tracking sections (organized in groups of 5 flies). For each fly you traded, enter the number of contracts, credit received when opening per contract, and debit paid when closing per contract (or 0 if expired worthless). The table automatically calculates and displays Brutto and Netto P&L.
Example Calculation:
Fly #2 with 3 contracts, Enter Credit $1.35, Exit Debit $0.50, Commissions $7.05 + $7.05 = $14.10
Brutto P&L: ($1.35 - $0.50) × $100 × 3 = $255.00
Netto P&L: $255.00 - ($14.10 × 3) = $212.70
Why This Matters
Previously, the indicator showed theoretical position management only. Now you can document actual performance for each trading session, track which sessions were profitable versus unprofitable, compare theoretical signals against actual execution results, identify slippage between indicator triggers and real fills, maintain a detailed trading journal within TradingView, and calculate exact session P&L including all commission costs.
P&L tracking is completely optional. The indicator continues to function normally for visualization and alerting even if no P&L data is entered. All P&L inputs are hidden from the status bar to keep the interface clean.
Versionshinweise
OverviewThis indicator tracks iron butterfly positions on SPX with fully dynamic parameters that adapt to real-time market conditions. Version 3 introduces DMI-based regime classification - the system now reads market conditions and automatically adjusts wing widths, position spacing, and exit timing.
The core philosophy: accumulate premium in range-bound markets, exit automatically when trends develop.
What's New in v3
- DMI-Based Regime Classification - Uses Directional Movement Index to detect trending vs range-bound conditions
- Dynamic Parameter Scaling - Wing width, spacing, and triggers adjust based on ATR and market regime
- Regime-Based Exits - Positions close automatically when market conditions deteriorate
- Reduced Max Flies - Default of 3 flies for better capital efficiency (~$10k accounts)
- False Trigger Protection - Prevents spurious fly creation when regime improves
How It Works
Market Regime Classification
The system monitors DI+ and DI- spread to classify market conditions:
- SAFE (DI Spread < 15) - Range-bound market. Ideal for iron flies. Accumulate positions.
- CAUTION (DI Spread 15-25) - Mild trend developing. Wider wings, close SAFE-born flies.
- WARNING (DI Spread 25-30) - Trend strengthening. Close ALL positions.
- NO_ENTRY (DI Spread > 30) - Strong trend. Stay flat, no new entries.
Dynamic Parameters
All parameters scale with ATR to adapt to current volatility:
- Wing Width = ATR × 5 (SAFE) or ATR × 7 (CAUTION)
- Spacing = ATR × 1.5 (SAFE) or ATR × 2.0 (CAUTION)
- Trigger = ATR × 1.0 (SAFE) or ATR × 1.5 (CAUTION)
Opening New Flies
New flies open when ALL conditions are met:
- Session is active (default 10am-4pm ET)
- Regime allows entries (SAFE or CAUTION)
- Open flies < Max (default 3)
- Price moved >= trigger distance from nearest fly
Closing Flies
Flies close based on these triggers:
- Regime → CAUTION: Close flies born in SAFE (under-protected)
- Regime → WARNING: Close ALL flies (trend developing)
- Regime → NO_ENTRY: Close ALL flies (strong trend)
- Wing Extreme: Price hits upper or lower wing (max loss point)
- Session End: All flies expire at session close
Close Reasons
- REG↓ - SAFE fly closed when regime worsened to CAUTION
- WARN - All flies closed when regime reached WARNING
- NOENT - All flies closed when regime reached NO_ENTRY
- W-UP / W-DN - Price hit wing extreme
- EXP - Session ended, fly expired
Key Settings
DMI Filter
DI Spread thresholds define regime boundaries. Default: Safe (15), Caution (25), No Entry (30)
Wing Width
Multipliers control wing distance. Default: Safe (5.0×), Caution (7.0×). Bounded by min/max.
Spacing & Trigger
Control fly placement. Default spacing: 1.5× (Safe), 2.0× (Caution). Trigger: 1.0× (Safe), 1.5× (Caution).
Position Limits
Max Concurrent Flies: 3 (recommended for ~$10k accounts with dynamic spacing)
P&L Tracking
Manual entry fields allow tracking actual trade performance:
- Enter contracts traded for each fly
- Enter credit received when opening
- Enter debit paid when closing (0 if expired worthless)
- Commission settings for accurate net P&L
Example Session
- 10:00 - Regime SAFE (DI=10), open Fly #0 at 5965
- 10:25 - Price moves +6pts, trigger exceeded, open Fly #1 at 5970
- 10:50 - Price moves +5pts, open Fly #2 at 5975 (max reached)
- 11:30 - Price oscillates, 3 flies collecting premium
- 12:00 - DI spread rises to 17, regime → CAUTION
- 12:00 - Fly #0 closes (born in SAFE), Flies #1-2 stay open
- 13:15 - DI spread rises to 26, regime → WARNING
- 13:15 - ALL remaining flies close, position flat
Visual Elements
- Boxes - Show fly range from lower to upper wing
- Lines - Solid white = strike, dotted = wings
- Labels - Display strike and wing prices
- Background - Green (SAFE), Yellow (CAUTION), Orange (WARNING), Red (NO_ENTRY)
- Colors - Border color indicates regime when fly was opened
Alerts
Simple text alerts for:
- Fly opened (includes strike, wings, regime, ATR, DI spread)
- Fly closed (includes strike, close reason, regime at open)
Limitations
- DMI is a lagging indicator - regime changes occur after trends begin
- Designed for SPX 5-minute charts
- Pine Script state resets on chart refresh - fly history is rebuilt from current day only
- P&L tracking requires manual entry of trade data
Disclaimer
This indicator is for educational and informational purposes only. It does not constitute financial advice. Options trading involves substantial risk of loss. Past performance does not guarantee future results. Always paper trade before risking real capital and never risk more than you can afford to lose.
```
Versionshinweise
ron Fly Strategy - Dynamic Edition v3.4A dynamic iron butterfly tracking indicator for SPX 0DTE options that adapts to real-time market conditions using DMI (Directional Movement Index) regime classification.
What's New in v3.4
Late Session Scaling
After 3 PM ET (configurable), all parameters reduce by 50% (configurable). Near expiration, long wings cost almost nothing — tighter structures optimize risk/reward while reducing max loss exposure.
Wing Minimum Floor
Wing width minimum (default ±10 points) is now an absolute floor that never scales. Ensures adequate protection even in low-volatility late sessions.
Position Re-establishment
When nearest open fly is more than 2× spacing away from current price, the system opens a new fly at current price. Prevents "stranded fly" scenario where old positions block new entries.
Regime Entry Refinement
Only SAFE and CAUTION regimes allow new entries. WARNING and NO_ENTRY block all entries for trend protection. Automatic re-entry when regime improves from WARNING/NO_ENTRY back to tradeable conditions.
How It Works
Market Regime Classification
SAFE (DI Spread < 15): Range-bound market, ideal for iron flies
CAUTION (DI Spread 15-25): Mild trend, uses wider wings for protection
WARNING (DI Spread 25-30): Trend developing, closes all positions
NO_ENTRY (DI Spread > 30): Strong trend, stays flat
Dynamic Parameters
All parameters scale with ATR to adapt to current volatility:
Wing width: Protection distance from center strike
Spacing: Distance between adjacent flies
Trigger: Price movement required to open new fly
Regime-Based Exits
Positions close automatically when market conditions deteriorate, protecting capital before trends fully develop.
Visual Guide
Green border: SAFE regime fly
Yellow border: CAUTION regime fly
Aqua border: Late session fly (after 3 PM ET)
Background color: Current market regime
White line: Center strike (short straddle)
Dotted lines: Wing strikes (long options)
Settings
Session Timing
Session Start/End Hour (ET)
Late Session Start Hour (default: 3 PM)
Late Session Scaling (default: 50%)
DMI Filter
DI Spread thresholds for each regime
DMI Length and ADX Smoothing
Wing Width
Multipliers for SAFE and CAUTION regimes
Minimum and maximum bounds
Spacing & Trigger
Multipliers for each regime
Minimum bounds
Position Management
Max concurrent flies (recommended: 2-3)
Regime-based closing toggle
P&L Tracking
Manual entry fields for tracking actual trade performance:
Contracts per fly
Entry credit received
Exit debit paid
Commission settings
Recommended Use
Apply to SPX or ES futures on 1-5 minute timeframe
Monitor regime changes throughout the session
Use suggested strikes for actual trade entries
Track performance with built-in P&L fields
Risk Disclaimer
This indicator is for educational purposes only. Iron butterflies carry significant risk — max loss equals wing width minus premium received. Past performance does not guarantee future results. Always manage position size appropriately.
Changelog
v3.4
Added late session scaling (50% parameter reduction after 3 PM ET)
Fixed wing minimum to never scale below absolute floor
Added position re-establishment when flies too far from price
Refined regime entries (only SAFE/CAUTION allow new positions)
Added automatic re-entry after regime improvement
Added "Late" column to history table
Added session status to info panel
Aqua visual distinction for late session flies
v3.0
Complete rewrite with DMI-based regime classification
Dynamic ATR-scaled parameters
Regime-based automatic closing
Enhanced visual feedback
P&L tracking system
Open-source Skript
Ganz im Sinne von TradingView hat dieser Autor sein/ihr Script als Open-Source veröffentlicht. Auf diese Weise können nun auch andere Trader das Script rezensieren und die Funktionalität überprüfen. Vielen Dank an den Autor! Sie können das Script kostenlos verwenden, aber eine Wiederveröffentlichung des Codes unterliegt unseren Hausregeln.
Haftungsausschluss
Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.
Open-source Skript
Ganz im Sinne von TradingView hat dieser Autor sein/ihr Script als Open-Source veröffentlicht. Auf diese Weise können nun auch andere Trader das Script rezensieren und die Funktionalität überprüfen. Vielen Dank an den Autor! Sie können das Script kostenlos verwenden, aber eine Wiederveröffentlichung des Codes unterliegt unseren Hausregeln.
Haftungsausschluss
Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.