COLOUR CODED ULTIMATE OSCILLATOR WITH LEVELS (70/50/30)Just added 70/30/50 levels to @LazyBear 's "Color Coded UO" script.
Happy Trading!
Cerca negli script per "美元汇率30天走势"
[STRATEGY]EMA 30/60 Cross Strategystrategy based on EMA 30/60 cross
works best on 4hr timeframes & high-midcaps
5 Moving Average Exponential 7-15-30-50-2005 Moving Average Exponential. Crypto EMA. 7 is a fast support or resistance, 15 confirmation support or resistance. 30 Important support and resistance. 50 institutional support or resistance. 200 general trend, support and resistance.
6 SMA's (fit to BTC) 9,20,30,50,128,200 (exponential optional)I've been using these for a while trading Bitcoin and I've found them to be the most useful to me. I replaced the 7 you may have seen in the first set with the 9 as I'm seeing it tested across many time frames quite frequently. The least used of the six is the 30 period, but it does have some influence I've found on the large time frames, mainly the weekly.
6 Simple Moving Averages 9,20,30,50,128,200 (bitcoin tested)I've condensed my SMAs down to these 6 and have found them to be most useful for Bitcoin, which is what I trade the most. They all have played their roll in acting as support and resistance and making decisions with the 30 period probably the least relevant, but relevant nonetheless. There is the option to change to exponential if desired.
EvaMacD for 30 linesEva Chart calculate IIR Filter with Multiple MACD Histogram and estimate the cycle.
This oscillator can find the most powerful frequency. This use 30 MACD histogram lines tuned for filter.
Simple Moving Averages (7, 30, 50, 100, 200)7, 30, 50, 100, 200 simple moving averages, bundled in one indicator (for users who are using the free TradingView service and can only load limited number of indicators at any given time).
You can turn each moving average on or off at will and change the colors.
Guppy MMA 3, 5, 8, 10, 12, 15 and 30, 35, 40, 45, 50, 60Guppy Multiple Moving Average
Short Term EMA 3, 5, 8, 10, 12, 15
Long Term EMA 30, 35, 40, 45, 50, 60
Use for SFTS Class
Ultimate Oscillator with 70/30/50 LinesUltimate Oscillator with 70/30/50 lines and a background.
Read how to use it here:
stockcharts.com
Enjoy :)
Mark 30m High/Low on 1m30 MIN HIGHS AND LOWS
Marked on the one minute chart.
High is marked with a green line.
Low is marked with a red line.
MTF EMA Pane with Diagnostics30 sec chart, 1 min EMA goes flat, I buy, 1 min EMA stays inside the group, I stay in the trade.
Not financial advice. I am working on an Algo killer, stay tuned. I am dedicating the rest of my life, as short as it my be, to beating the Men behind the Algo's. Buy me some coffee.
Send USDT thru ETH or Base to BYDFi 0x20391e32afd61dc9e1ec027651391b56ceade4e0
Join BYDFi
Referral Link: Spin for a possible $100
partner.bydfi.com
Deposit: USDT via;
ETH (ERC20) 0x20391e32afd61dc9e1ec027651391b56ceade4e0
Tron (TRC20)
TUs5u2YxtQrQfRwYK2CsMmSDGvND6Uopdj
BNB/Base (BEP20)
0x20391e32afd61dc9e1ec027651391b56ceade4e0
Solana
696LAngiQBbdk4m6k1ZBiKZrFtjTJo6dxCnVXMEePQea
30s OR ProjectionsThis script gets the opening range for NQ,ES, and YM. It then created deviations based on this range as targets to take profit from. You may also use the deviations to enter into trades looking for the other side of the range. You have the ability to shade areas of the range.
7:30 AM ET Bar HighlighterHow it works
Step Explanation
1️⃣ hour(time, targetTZ) and minute(time, targetTZ) convert each bar’s opening time to America/New_York and check for 7 : 25.
2️⃣ When both match, isTargetBar becomes true.
3️⃣ bgcolor() paints that candle red, and plotshape() draws the white dot just above it.
Adjustable Color Changing WMA by Slope Degree30 weighted moving average that changes colors based upon degree of slope. Consider it a green light for buying/selling pullbacks to the wma. You can adjust the colors and the threshold for the degree of slope.
30 Day Moving AverageThis indicator offers a longer time frame view compared to the 9 day moving average. This can give a better indication over longer term market moves.
Quarterly Cycle Theory with DST time AdjustedThe Quarterly Theory removes ambiguity, as it gives specific time-based reference points to look for when entering trades. Before being able to apply this theory to trading, one must first understand that time is fractal:
Yearly Quarters = 4 quarters of three months each.
Monthly Quarters = 4 quarters of one week each.
Weekly Quarters = 4 quarters of one day each (Monday - Thursday). Friday has its own specific function.
Daily Quarters = 4 quarters of 6 hours each = 4 trading sessions of a trading day.
Sessions Quarters = 4 quarters of 90 minutes each.
90 Minute Quarters = 4 quarters of 22.5 minutes each.
Yearly Cycle: Analogously to financial quarters, the year is divided in four sections of three months each:
Q1 - January, February, March.
Q2 - April, May, June (True Open, April Open).
Q3 - July, August, September.
Q4 - October, November, December.
S&P 500 E-mini Futures (daily candles) — Monthly Cycle.
Monthly Cycle: Considering that we have four weeks in a month, we start the cycle on the first month’s Monday (regardless of the calendar Day):
Q1 - Week 1: first Monday of the month.
Q2 - Week 2: second Monday of the month (True Open, Daily Candle Open Price).
Q3 - Week 3: third Monday of the month.
Q4 - Week 4: fourth Monday of the month.
S&P 500 E-mini Futures (4 hour candles) — Weekly Cycle.
Weekly Cycle: Daye determined that although the trading week is composed by 5 trading days, we should ignore Friday, and the small portion of Sunday’s price action:
Q1 - Monday.
Q2 - Tuesday (True Open, Daily Candle Open Price).
Q3 - Wednesday.
Q4 - Thursday.
S&P 500 E-mini Futures (1 hour candles) — Daily Cycle.
Daily Cycle: The Day can be broken down into 6 hour quarters. These times roughly define the sessions of the trading day, reinforcing the theory’s validity:
Q1 - 18:00 - 00:00 Asia.
Q2 - 00:00 - 06:00 London (True Open).
Q3 - 06:00 - 12:00 NY AM.
Q4 - 12:00 - 18:00 NY PM.
S&P 500 E-mini Futures (15 minute candles) — 6 Hour Cycle.
6 Hour Quarters or 90 Minute Cycle / Sessions divided into four sections of 90 minutes each (EST/EDT):
Asian Session
Q1 - 18:00 - 19:30
Q2 - 19:30 - 21:00 (True Open)
Q3 - 21:00 - 22:30
Q4 - 22:30 - 00:00
London Session
Q1 - 00:00 - 01:30
Q2 - 01:30 - 03:00 (True Open)
Q3 - 03:00 - 04:30
Q4 - 04:30 - 06:00
NY AM Session
Q1 - 06:00 - 07:30
Q2 - 07:30 - 09:00 (True Open)
Q3 - 09:00 - 10:30
Q4 - 10:30 - 12:00
NY PM Session
Q1 - 12:00 - 13:30
Q2 - 13:30 - 15:00 (True Open)
Q3 - 15:00 - 16:30
Q4 - 16:30 - 18:00
S&P 500 E-mini Futures (5 minute candles) — 90 Minute Cycle.
Micro Cycles: Dividing the 90 Minute Cycle yields 22.5 Minute Quarters, also known as Micro Sessions or Micro Quarters:
Asian Session
Q1/1 18:00:00 - 18:22:30
Q2 18:22:30 - 18:45:00
Q3 18:45:00 - 19:07:30
Q4 19:07:30 - 19:30:00
Q2/1 19:30:00 - 19:52:30 (True Session Open)
Q2/2 19:52:30 - 20:15:00
Q2/3 20:15:00 - 20:37:30
Q2/4 20:37:30 - 21:00:00
Q3/1 21:00:00 - 21:23:30
etc. 21:23:30 - 21:45:00
London Session
00:00:00 - 00:22:30 (True Daily Open)
00:22:30 - 00:45:00
00:45:00 - 01:07:30
01:07:30 - 01:30:00
01:30:00 - 01:52:30 (True Session Open)
01:52:30 - 02:15:00
02:15:00 - 02:37:30
02:37:30 - 03:00:00
03:00:00 - 03:22:30
03:22:30 - 03:45:00
03:45:00 - 04:07:30
04:07:30 - 04:30:00
04:30:00 - 04:52:30
04:52:30 - 05:15:00
05:15:00 - 05:37:30
05:37:30 - 06:00:00
New York AM Session
06:00:00 - 06:22:30
06:22:30 - 06:45:00
06:45:00 - 07:07:30
07:07:30 - 07:30:00
07:30:00 - 07:52:30 (True Session Open)
07:52:30 - 08:15:00
08:15:00 - 08:37:30
08:37:30 - 09:00:00
09:00:00 - 09:22:30
09:22:30 - 09:45:00
09:45:00 - 10:07:30
10:07:30 - 10:30:00
10:30:00 - 10:52:30
10:52:30 - 11:15:00
11:15:00 - 11:37:30
11:37:30 - 12:00:00
New York PM Session
12:00:00 - 12:22:30
12:22:30 - 12:45:00
12:45:00 - 13:07:30
13:07:30 - 13:30:00
13:30:00 - 13:52:30 (True Session Open)
13:52:30 - 14:15:00
14:15:00 - 14:37:30
14:37:30 - 15:00:00
15:00:00 - 15:22:30
15:22:30 - 15:45:00
15:45:00 - 15:37:30
15:37:30 - 16:00:00
16:00:00 - 16:22:30
16:22:30 - 16:45:00
16:45:00 - 17:07:30
17:07:30 - 18:00:00
S&P 500 E-mini Futures (30 second candles) — 22.5 Minute Cycle.
PnL Bubble [%] | Fractalyst1. What's the indicator purpose?
The PnL Bubble indicator transforms your strategy's trade PnL percentages into an interactive bubble chart with professional-grade statistics and performance analytics. It helps traders quickly assess system profitability, understand win/loss distribution patterns, identify outliers, and make data-driven strategy improvements.
How does it work?
Think of this indicator as a visual report card for your trading performance. Here's what it does:
What You See
Colorful Bubbles: Each bubble represents one of your trades
Blue/Cyan bubbles = Winning trades (you made money)
Red bubbles = Losing trades (you lost money)
Bigger bubbles = Bigger wins or losses
Smaller bubbles = Smaller wins or losses
How It Organizes Your Trades:
Like a Photo Album: Instead of showing all your trades at once (which would be messy), it shows them in "pages" of 500 trades each:
Page 1: Your first 500 trades
Page 2: Trades 501-1000
Page 3: Trades 1001-1500, etc.
What the Numbers Tell You:
Average Win: How much money you typically make on winning trades
Average Loss: How much money you typically lose on losing trades
Expected Value (EV): Whether your trading system makes money over time
Positive EV = Your system is profitable long-term
Negative EV = Your system loses money long-term
Payoff Ratio (R): How your average win compares to your average loss
R > 1 = Your wins are bigger than your losses
R < 1 = Your losses are bigger than your wins
Why This Matters:
At a Glance: You can instantly see if you're a profitable trader or not
Pattern Recognition: Spot if you have more big wins than big losses
Performance Tracking: Watch how your trading improves over time
Realistic Expectations: Understand what "average" performance looks like for your system
The Cool Visual Effects:
Animation: The bubbles glow and shimmer to make the chart more engaging
Highlighting: Your biggest wins and losses get extra attention with special effects
Tooltips: hover any bubble to see details about that specific trade.
What are the underlying calculations?
The indicator processes trade PnL data using a dual-matrix architecture for optimal performance:
Dual-Matrix System:
• Display Matrix (display_matrix): Bounded to 500 trades for rendering performance
• Statistics Matrix (stats_matrix): Unbounded storage for complete statistical accuracy
Trade Classification & Aggregation:
// Separate wins, losses, and break-even trades
if val > 0.0
pos_sum += val // Sum winning trades
pos_count += 1 // Count winning trades
else if val < 0.0
neg_sum += val // Sum losing trades
neg_count += 1 // Count losing trades
else
zero_count += 1 // Count break-even trades
Statistical Averages:
avg_win = pos_count > 0 ? pos_sum / pos_count : na
avg_loss = neg_count > 0 ? math.abs(neg_sum) / neg_count : na
Win/Loss Rates:
total_obs = pos_count + neg_count + zero_count
win_rate = pos_count / total_obs
loss_rate = neg_count / total_obs
Expected Value (EV):
ev_value = (avg_win × win_rate) - (avg_loss × loss_rate)
Payoff Ratio (R):
R = avg_win ÷ |avg_loss|
Contribution Analysis:
ev_pos_contrib = avg_win × win_rate // Positive EV contribution
ev_neg_contrib = avg_loss × loss_rate // Negative EV contribution
How to integrate with any trading strategy?
Equity Change Tracking Method:
//@version=6
strategy("Your Strategy with Equity Change Export", overlay=true)
float prev_trade_equity = na
float equity_change_pct = na
if barstate.isconfirmed and na(prev_trade_equity)
prev_trade_equity := strategy.equity
trade_just_closed = strategy.closedtrades != strategy.closedtrades
if trade_just_closed and not na(prev_trade_equity)
current_equity = strategy.equity
equity_change_pct := ((current_equity - prev_trade_equity) / prev_trade_equity) * 100
prev_trade_equity := current_equity
else
equity_change_pct := na
plot(equity_change_pct, "Equity Change %", display=display.data_window)
Integration Steps:
1. Add equity tracking code to your strategy
2. Load both strategy and PnL Bubble indicator on the same chart
3. In bubble indicator settings, select your strategy's equity tracking output as data source
4. Configure visualization preferences (colors, effects, page navigation)
How does the pagination system work?
The indicator uses an intelligent pagination system to handle large trade datasets efficiently:
Page Organization:
• Page 1: Trades 1-500 (most recent)
• Page 2: Trades 501-1000
• Page 3: Trades 1001-1500
• Page N: Trades to
Example: With 1,500 trades total (3 pages available):
• User selects Page 1: Shows trades 1-500
• User selects Page 4: Automatically falls back to Page 3 (trades 1001-1500)
5. Understanding the Visual Elements
Bubble Visualization:
• Color Coding: Cyan/blue gradients for wins, red gradients for losses
• Size Mapping: Bubble size proportional to trade magnitude (larger = bigger P&L)
• Priority Rendering: Largest trades displayed first to ensure visibility
• Gradient Effects: Color intensity increases with trade magnitude within each category
Interactive Tooltips:
Each bubble displays quantitative trade information:
tooltip_text = outcome + " | PnL: " + pnl_str +
"\nDate: " + date_str + " " + time_str +
"\nTrade #" + str.tostring(trade_number) + " (Page " + str.tostring(active_page) + ")" +
"\nRank: " + str.tostring(rank) + " of " + str.tostring(n_display_rows) +
"\nPercentile: " + str.tostring(percentile, "#.#") + "%" +
"\nMagnitude: " + str.tostring(magnitude_pct, "#.#") + "%"
Example Tooltip:
Win | PnL: +2.45%
Date: 2024.03.15 14:30
Trade #1,247 (Page 3)
Rank: 5 of 347
Percentile: 98.6%
Magnitude: 85.2%
Reference Lines & Statistics:
• Average Win Line: Horizontal reference showing typical winning trade size
• Average Loss Line: Horizontal reference showing typical losing trade size
• Zero Line: Threshold separating wins from losses
• Statistical Labels: EV, R-Ratio, and contribution analysis displayed on chart
What do the statistical metrics mean?
Expected Value (EV):
Represents the mathematical expectation per trade in percentage terms
EV = (Average Win × Win Rate) - (Average Loss × Loss Rate)
Interpretation:
• EV > 0: Profitable system with positive mathematical expectation
• EV = 0: Break-even system, profitability depends on execution
• EV < 0: Unprofitable system with negative mathematical expectation
Example: EV = +0.34% means you expect +0.34% profit per trade on average
Payoff Ratio (R):
Quantifies the risk-reward relationship of your trading system
R = Average Win ÷ |Average Loss|
Interpretation:
• R > 1.0: Wins are larger than losses on average (favorable risk-reward)
• R = 1.0: Wins and losses are equal in magnitude
• R < 1.0: Losses are larger than wins on average (unfavorable risk-reward)
Example: R = 1.5 means your average win is 50% larger than your average loss
Contribution Analysis (Σ):
Breaks down the components of expected value
Positive Contribution (Σ+) = Average Win × Win Rate
Negative Contribution (Σ-) = Average Loss × Loss Rate
Purpose:
• Shows how much wins contribute to overall expectancy
• Shows how much losses detract from overall expectancy
• Net EV = Σ+ - Σ- (Expected Value per trade)
Example: Σ+: 1.23% means wins contribute +1.23% to expectancy
Example: Σ-: -0.89% means losses drag expectancy by -0.89%
Win/Loss Rates:
Win Rate = Count(Wins) ÷ Total Trades
Loss Rate = Count(Losses) ÷ Total Trades
Shows the probability of winning vs losing trades
Higher win rates don't guarantee profitability if average losses exceed average wins
7. Demo Mode & Synthetic Data Generation
When using built-in sources (close, open, etc.), the indicator generates realistic demo trades for testing:
if isBuiltInSource(source_data)
// Generate random trade outcomes with realistic distribution
u_sign = prand(float(time), float(bar_index))
if u_sign < 0.5
v_push := -1.0 // Loss trade
else
// Skewed distribution favoring smaller wins (realistic)
u_mag = prand(float(time) + 9876.543, float(bar_index) + 321.0)
k = 8.0 // Skewness factor
t = math.pow(u_mag, k)
v_push := 2.5 + t * 8.0 // Win trade
Demo Characteristics:
• Realistic win/loss distribution mimicking actual trading patterns
• Skewed distribution favoring smaller wins over large wins
• Deterministic randomness for consistent demo results
• Includes jitter effects to prevent visual overlap
8. Performance Limitations & Optimizations
Display Constraints:
points_count = 500 // Maximum 500 dots per page for optimal performance
Pine Script v6 Limits:
• Label Count: Maximum 500 labels per indicator
• Line Count: Maximum 100 lines per indicator
• Box Count: Maximum 50 boxes per indicator
• Matrix Size: Efficient memory management with dual-matrix system
Optimization Strategies:
• Pagination System: Handle unlimited trades through 500-trade pages
• Priority Rendering: Largest trades displayed first for maximum visibility
• Dual-Matrix Architecture: Separate display (bounded) from statistics (unbounded)
• Smart Fallback: Automatic page clamping prevents empty displays
Impact & Workarounds:
• Visual Limitation: Only 500 trades visible per page
• Statistical Accuracy: Complete dataset used for all calculations
• Navigation: Use page input to browse through entire trade history
• Performance: Smooth operation even with thousands of trades
9. Statistical Accuracy Guarantees
Data Integrity:
• Complete Dataset: Statistics matrix stores ALL trades without limit
• Proper Aggregation: Separate tracking of wins, losses, and break-even trades
• Mathematical Precision: Pine Script v6's enhanced floating-point calculations
• Dual-Matrix System: Display limitations don't affect statistical accuracy
Calculation Validation:
// Verified formulas match standard trading mathematics
avg_win = pos_sum / pos_count // Standard average calculation
win_rate = pos_count / total_obs // Standard probability calculation
ev_value = (avg_win * win_rate) - (avg_loss * loss_rate) // Standard EV formula
Accuracy Features:
• Mathematical Correctness: Formulas follow established trading statistics
• Data Preservation: Complete dataset maintained for all calculations
• Precision Handling: Proper rounding and boundary condition management
• Real-Time Updates: Statistics recalculated on every new trade
10. Advanced Technical Features
Real-Time Animation Engine:
// Shimmer effects with sine wave modulation
offset = math.sin(shimmer_t + phase) * amp
// Dynamic transparency with organic flicker
new_transp = math.min(flicker_limit, math.max(-flicker_limit, cur_transp + dir * flicker_step))
• Sine Wave Shimmer: Dynamic glowing effects on bubbles
• Organic Flicker: Random transparency variations for natural feel
• Extreme Value Highlighting: Special visual treatment for outliers
• Smooth Animations: Tick-based updates for fluid motion
Magnitude-Based Priority Rendering:
// Sort trades by magnitude for optimal visual hierarchy
sort_indices_by_magnitude(values_mat)
• Largest First: Most important trades always visible
• Intelligent Sorting: Custom bubble sort algorithm for trade prioritization
• Performance Optimized: Efficient sorting for real-time updates
• Visual Hierarchy: Ensures critical trades never get hidden
Professional Tooltip System:
• Quantitative Data: Pure numerical information without interpretative language
• Contextual Ranking: Shows trade position within page dataset
• Percentile Analysis: Performance ranking as percentage
• Magnitude Scaling: Relative size compared to page maximum
• Professional Format: Clean, data-focused presentation
11. Quick Start Guide
Step 1: Add Indicator
• Search for "PnL Bubble | Fractalyst" in TradingView indicators
• Add to your chart (works on any timeframe)
Step 2: Configure Data Source
• Demo Mode: Leave source as "close" to see synthetic trading data
• Strategy Mode: Select your strategy's PnL% output as data source
Step 3: Customize Visualization
• Colors: Set positive (cyan), negative (red), and neutral colors
• Page Navigation: Use "Trade Page" input to browse trade history
• Visual Effects: Built-in shimmer and animation effects are enabled by default
Step 4: Analyze Performance
• Study bubble patterns for win/loss distribution
• Review statistical metrics: EV, R-Ratio, Win Rate
• Use tooltips for detailed trade analysis
• Navigate pages to explore full trade history
Step 5: Optimize Strategy
• Identify outlier trades (largest bubbles)
• Analyze risk-reward profile through R-Ratio
• Monitor Expected Value for system profitability
• Use contribution analysis to understand win/loss impact
12. Why Choose PnL Bubble Indicator?
Unique Advantages:
• Advanced Pagination: Handle unlimited trades with smart fallback system
• Dual-Matrix Architecture: Perfect balance of performance and accuracy
• Professional Statistics: Institution-grade metrics with complete data integrity
• Real-Time Animation: Dynamic visual effects for engaging analysis
• Quantitative Tooltips: Pure numerical data without subjective interpretations
• Priority Rendering: Intelligent magnitude-based display ensures critical trades are always visible
Technical Excellence:
• Built with Pine Script v6 for maximum performance and modern features
• Optimized algorithms for smooth operation with large datasets
• Complete statistical accuracy despite display optimizations
• Professional-grade calculations matching institutional trading analytics
Practical Benefits:
• Instantly identify system profitability through visual patterns
• Spot outlier trades and risk management issues
• Understand true risk-reward profile of your strategies
• Make data-driven decisions for strategy optimization
• Professional presentation suitable for performance reporting
Disclaimer & Risk Considerations:
Important: Historical performance metrics, including positive Expected Value (EV), do not guarantee future trading success. Statistical measures are derived from finite sample data and subject to inherent limitations:
• Sample Bias: Historical data may not represent future market conditions or regime changes
• Ergodicity Assumption: Markets are non-stationary; past statistical relationships may break down
• Survivorship Bias: Strategies showing positive historical EV may fail during different market cycles
• Parameter Instability: Optimal parameters identified in backtesting often degrade in forward testing
• Transaction Cost Evolution: Slippage, spreads, and commission structures change over time
• Behavioral Factors: Live trading introduces psychological elements absent in backtesting
• Black Swan Events: Extreme market events can invalidate statistical assumptions instantaneously
Support and Resistance levels from Options DataINTRODUCTION
This script is designed to visualize key support and resistance levels derived from options data on TradingView charts. It overlays lines, labels, and boxes to highlight levels such as Put Walls (gamma support), Call Walls (gamma resistance), Gamma Flip points, Vanna levels, and more.
These levels are intended to help traders identify potential areas of price magnetism, reversal, or breakout based on options market dynamics. All calculations and visualizations are based on user-provided data pasted into the input field, as Pine Script cannot directly fetch external options data due to platform limitations (explained below).
For convenience, my website allows users to interact with a bot that will generate the string for up to 30 tickers at once getting nearly real-time data on demand (data is cached for 15min). With the output string pasted into this indicator, it's a bliss to shuffle through your portfolio and see those levels for each ticker.
The script is open-source under TradingView's terms, allowing users to study, modify, and improve it. It draws inspiration from common options-derived metrics like gamma exposure and vanna, which are widely discussed in financial literature. No external code is copied without rights; all logic is original or based on standard mathematical formulas.
How the Options Levels Are Calculated
The levels displayed by this script are not computed within Pine Script itself—instead, they rely on pre-calculated values provided by the user (via a pasted data string). These values are derived from options chain data fetched from financial APIs (e.g., using libraries like yfinance in Python). Here's a step-by-step overview of how these levels are generally calculated externally before being input into the script:
Fetching Options Data:
Historical and current options chain data for a ticker (e.g., strikes, open interest, volume, implied volatility, expirations) is retrieved for near-term expirations (e.g., up to 90 days).
Current stock price is obtained from recent history.
Gamma Support (Put Wall) and Resistance (Call Wall):
Gamma Calculation: For each option, gamma (the rate of change of delta) is computed using the Black-Scholes formula:
gamma = N'(d1) / (S * sigma * sqrt(T))
where S is the stock price, K is the strike, T is time to expiration (in years), sigma is implied volatility, r is the risk-free rate (e.g., 0.0445), and N'(d1) is the normal probability density function.
Weighted gamma is multiplied by open interest and aggregated by strike.
The Put Wall is the strike below the current price with the highest weighted gamma from puts (acting as support).
The Call Wall is the strike above the current price with the highest weighted gamma from calls (acting as resistance).
Short-term versions focus on strikes closer to the money (e.g., within 10-15% of the price).
Gamma Flip Level:
Net dealer gamma exposure (GEX) is calculated across all strikes:
GEX = sum (gamma * OI * 100 * S^2 * sign * decay)
where sign is +1 for calls/-1 for puts, and decay is 1 / sqrt(T).
The flip point is the price where net GEX changes sign (from positive to negative or vice versa), interpolated between strikes.
Vanna Levels:
Vanna (sensitivity of delta to volatility) is calculated:
vanna = -N'(d1) * d2 / sigma
where d2 = d1 - sigma * sqrt(T).
Weighted by open interest, the highest positive and negative vanna strikes are identified.
Other Levels:
S1/R1: Significant strikes with high combined open interest and volume (80% OI + 20% volume), below/above price for support/resistance.
Implied Move: ATM implied volatility scaled by S * sigma * sqrt(d/365) (e.g., for 7 days).
Call/Put Ratio: Total call contracts divided by put contracts (OI + volume).
IV Percentage: Average ATM implied volatility.
Options Activity Level: Average contracts per unique strike, binned into levels (0-4).
Stop Loss: Dynamically set below the lowest support (e.g., Put Wall, Gamma Flip), adjusted by IV (tighter in low IV).
Fib Target: 1.618 extension from Put Wall to Call Wall range.
Previous day levels are stored for comparison (e.g., to detect Call Wall movement >2.5% for alerts).
Effect as Support and Resistance in Technical Trading
Options levels like gamma walls influence price action due to market maker hedging:
Put Wall (Gamma Support): High put gamma below price creates a "magnet" effect—market makers buy stock as price falls, providing support. Traders might look for bounces here as entry points for longs.
Call Wall (Gamma Resistance): High call gamma above price leads to selling pressure from hedging, acting as resistance. Rejections here could signal trims, sells or even shorts.
Gamma Flip: Where gamma exposure flips sign, often a volatility pivot—crossing it can accelerate moves (bullish above, bearish below).
Vanna Levels: Positive/negative vanna indicate volatility sensitivity; crosses may signal regime shifts.
Implied Move: Shows expected range; prices outside suggest overextension.
S1/R1 and Fib Target: Volume/OI clusters act as classic S/R; Fib extensions project upside targets post-breakout.
In trading, these are not guarantees—combine with TA (e.g., volume, trends). High activity levels imply stronger effects; low CP ratio suggests bearish sentiment. Alerts trigger on proximities/crosses for awareness, not advice.
Limitations of the TradingView Platform for Data Pulling
TradingView's Pine Script is sandboxed for security and performance:
No direct internet access or API calls (e.g., can't fetch yfinance data in-script).
Limited to chart data/symbol info; no real-time options chains.
Inputs are static per load; updates require manual pasting.
Caching isn't persistent across sessions.
This prevents dynamic data pulling, ensuring scripts remain lightweight but requiring external tools for fresh data.
Creative Solution for On-Demand Data Pulling
To overcome these limitations, users can use external tools or scripts (e.g., Python-based) to fetch and compute levels on demand. The tool processes tickers, generates a formatted string (e.g., "TICKER:level1,level2,...;TIMESTAMP:unix;"), and users paste it into the script's input. This keeps data fresh without violating platform rules, as computation happens off-platform. For example, run a local script to query APIs and output the string—adaptable for any ticker.
Script Functionality Breakdown
Inputs: Custom data string (parsed for levels/timestamp); toggles for short-term/previous/Vanna/stop loss; style options (colors, transparency).
Parsing: Extracts levels for the chart symbol; gets timestamp for "updated ago" display.
Drawing: Lines/labels for levels; boxes for gamma zones/implied move; clears old elements on updates.
Info Panel: Top-right summary with metrics (CP ratio, IV, distances, activity); emojis for quick status.
Alerts: Conditions for proximities, crosses, bounces (e.g., 0.5% bounce from Put Wall).
Performance: Uses vars for persistence; efficient for real-time.
This script is educational—test thoroughly. Not financial advice; past performance isn't indicative of future results. Feedback welcome via TradingView comments.