Shifted Buy PressureDifferentiated Buy Pressure Indicator Documentation
Overview: The Differentiated Buy Pressure indicator is a custom Pine Script™ indicator designed to measure and visualize buy and sell pressure in the market. It calculates buy pressure based on a combination of volume, range, and gap, and provides a differentiated buy pressure which is shifted by 90°, offering predictive insights.
Inputs:
Window Size: The window size for average calculation (default: 20).
Show Overlay: Option to show the price overlay (default: false).
Overlay Boost Factor: Boosting factor for overlaying the price (default: 0.01).
Calculations:
Relative Range: Calculated as (high - low) / close.
Average Range: Simple moving average of the relative range over the specified window.
Average Volume: Simple moving average of the volume over the specified window.
Relative Gap: Calculated as open / close .
Average Gap: Simple moving average of the relative gap over the specified window.
Buy Pressure: Calculated using the formula: buy_pressure = -math.log(relative_range / avg_range * volume / avg_volume * relative_gap / avg_gap)
Differentiated Buy Pressure: Calculated as the difference between the current and previous buy pressure: diff_buy_pressure = buy_pressure - buy_pressure
Plots:
Zero Line: A horizontal line at zero for reference.
Buy Pressure: Plotted in blue, representing the calculated buy pressure.
Differentiated Buy Pressure: Plotted in red, representing the differentiated buy pressure.
Overlay: Optionally plots the price overlay boosted by the differentiated buy pressure.
Labels:
Labels are created to display the buy pressure and differentiated buy pressure values on the chart.
Usage: This indicator helps traders visualize the buy and sell pressure in the market. Positive values indicate buy pressure, while negative values indicate sell pressure. The differentiated buy pressure, shifted by 90°, provides predictive insights into future market movements.
This documentation provides a comprehensive overview of the Differentiated Buy Pressure indicator, explaining its purpose, inputs, calculations, and usage.
Indicators and strategies
KAI QUANTUM Candles Analysis - Yearly BreakdownThe "KAI QUANTUM Analysis – Yearly Breakdown" indicator offers a comprehensive, year-by-year examination of candlestick behavior, enabling traders and analysts to gauge market dynamics over extended periods. Key features include:
Yearly Aggregation:
The indicator groups candlestick data by year, providing a clear snapshot of market behavior for each period.
Dual-Color Analysis:
It categorizes candles as bullish (green) or bearish (red) and computes statistics separately for each, allowing you to assess both upward and downward market trends.
Average Body Size & Candle Count:
For each year, the indicator calculates the average body size of green and red candles and tracks the total number of each, helping you understand overall market volatility and momentum.
Top 10 Candle Analysis:
It identifies the ten largest candles (by body size) in each year and computes their average size, offering insight into the most significant market moves during that period.
Largest Candle Metrics:
The indicator determines the absolute size of the largest green and red candles in each year.
Percentage Move Calculation:
In addition to absolute values, it computes the largest move as a percentage of the open price for both green and red candles. This allows you to see not only which year experienced the biggest moves but also how those moves compare relative to the opening price.
Clear Tabular Display:
All the computed statistics are organized in an on-chart table, making it easy to compare yearly trends at a glance.
Ideal for daily and higher timeframes, this indicator is a valuable tool for long-term market analysis, enabling you to identify trends, assess volatility, and make informed trading decisions based on historical market behavior.
KAI QUANTUM Candles Analysis - Yearly BreakdownThis indicator analyzes candlestick data on a year-by-year basis to provide insights into market dynamics. For each year, it computes key statistics for both bullish (green) and bearish (red) candles:
Average Body Size: Calculates the average body size for all green and red candles.
Candle Count: Tracks the total number of green and red candles.
Top 10 Average: Determines the average body size of the top 10 largest candles for each color.
Largest Candle: Identifies the single largest candle (by body size) for both green and red candles.
All these statistics are displayed in a table at the bottom right of the chart, making it easy to compare the performance and behavior of candles across different years. The indicator is designed for daily and higher timeframes, offering a valuable tool for long-term market analysis, trend identification, and assessing market volatility and momentum over time.
Enhanced ATR vs EMA(ATR) - Volatility Environmentcompares ATR data with 10EMA data, once ATR line is above EMA then there's high volatility and if EMA is above then volatility is low.
Trading Sessions with EMAs Trading Sessions with EMAs created by -binod
this is a trading indicator. It includes all sessions such as the Tokyo session, the Asian session, and the New York session, it also has four EMAs included.
moving average strategy.How It Works:
Weekly 50 VWMA Filter:
The strategy checks if the current price is above the weekly 50 VWMA.
If not, no trades or signals are generated.
Entry:
A long position is opened when:
The price is above the weekly 50 VWMA.
Two consecutive candles close above the 200 WVMA on the current timeframe.
The second candle's close is above the HLCC4 of the first candle.
Exit:
The long position is closed when:
The daily close price is below the daily 200 WVMA.
Next Entry:
After the position is closed, the strategy waits for the next valid buy signal (if the price remains above the weekly 50 VWMA).
Jerusalem Session Weekday MarkingJerusalem Session Weekday Marking
This indicator applies a background color to each trading day based on the Jerusalem time zone (Asia/Jerusalem). It's a simple, no-frills tool for traders operating in markets that follow a Sunday-Thursday business week.
How It Works:
Monday to Thursday → Red background (Regular trading days)
Friday to Sunday → Green background (Weekend/non-standard trading days)
Background coloring applies to the entire day (not just session hours).
Why Use This?
Designed for traders focusing on Middle Eastern, Israeli, and Forex markets.
Helps differentiate trading days at a glance in a market where Friday-Saturday weekends are standard.
Works automatically with Jerusalem timezone, no manual adjustments needed.
🚀 Simple, effective, and useful for traders who care about local trading schedules. 🚀
Low Volume Liquidity Void DetectorHow It Works:
The script calculates an average volume over a user-defined lookback period.
It identifies low-volume bars where volume is below a percentage of the average.
It checks if the price is near significant highs/lows within that period, indicating a possible liquidity void.
If the price enters these voids, it triggers long or short signals with alerts.
Internals Elite NASDAQInternals Elite NASDAQ Indicator: Overview and Functionality
Overview:
The Internals Elite NASDAQ indicator is a market breadth tool designed for **NASDAQ market internals analysis**. It provides traders with a **table-based visualization** of various key market metrics that help gauge overall market strength, sentiment, and momentum.
Key Features and What It Does:
The indicator fetches and displays **real-time market internals** by monitoring various breadth indicators, price action, and macroeconomic influences. It presents this data in a **color-coded table overlay** that updates dynamically to reflect changes in market sentiment.
---
Market Internals Monitored:
1. TICK Index (TICKQ)
- Measures short-term market sentiment by tracking the number of advancing vs. declining stocks at a given moment.
- Green: Strong positive sentiment (above threshold).
- Red: Weak sentiment (below threshold).
2. Advance-Decline Line (ADDQ) & Moving Average Sentiment
- Tracks the net difference between advancing and declining stocks on the NASDAQ.
- EMA-Based Trend Signal:
- Uses a 10-period EMA to smooth ADDQ values and identify trends.
- Rising EMA suggests broad market strength (bullish momentum).
- Falling EMA** indicates market weakness** (bearish pressure).
- Directional Arrow System:
- 📈 Rising → Market internals improving (bullish).
- 📉 Falling → Weakening breadth (bearish).
3. VIX (Volatility Index) & EMA Sentiment
- Measures market volatility and risk sentiment.
- EMA-Based VIX Trend Analysis:
- Uses a 10-period EMA to track VIX momentum.
- Falling VIX EMA → Market stability & bullish sentiment.
- Rising VIX EMA → Increased fear & bearish conditions.
- Color-Coded Risk Levels:
- Green: Low VIX (market confidence).
- Orange: Neutral/transition phase.
- Red: High VIX (risk-off environment).
4. VWAP Deviation (% Above VWAP)
- Indicates how many stocks are trading above or below the VWAP (Volume Weighted Average Price).
- Used for tracking institutional activity and potential market reversals.
5. M7 VWAP (Mega-Cap 7 VWAP)
- Tracks VWAP levels for AAPL, MSFT, GOOGL, AMZN, META, NVDA, TSLA.
- Indicates whether **major tech stocks** are supporting or dragging the market.
6. Dollar Index (DXY)
- Measures the strength of the U.S. Dollar relative to other currencies.
- Impacts NASDAQ stocks as a weaker dollar tends to benefit tech stocks.
7. US 10-Year Treasury Yield (US10Y)
- Tracks interest rate trends, which influence market liquidity and risk appetite.
8. Bitcoin Price (BTCUSD)
- Cryptocurrency correlation tracking; used as a speculative risk indicator.
9. QQQ Price & Change (%)
- The performance of the *ASDAQ-100 ETF (QQQ) for broader index trend confirmation.
10. Current Ticker Price Change (%)
- Shows the **percentage change** of the selected stock relative to its previous close.
---
### How It Helps Traders:
✅ Identifies Trend Strength → Using EMA-based ADDQ & VIX signals for sentiment confirmation.
✅ Detects Market Turning Points → Through TICKQ, VWAP deviation, and M7 VWAP.
✅ Tracks Institutional Activity→ Watching whether mega-cap tech stocks are supporting the market.
✅ Measures Risk Appetite → By integrating VIX, DXY, US10Y, and BTC into the analysis.
✅ Provides Macro Confirmation → Understanding if external factors (like bond yields) are impacting NASDAQ moves.
---
Final Summary:
The Internals Elite NASDAQ is a market internals dashboard that consolidates essential breadth, volatility, macro, and risk indicators into a single view. By incorporating EMA-based trend tracking for ADDQ and VIX, the indicator helps traders confirm bullish or bearish sentiment shifts and make data-driven trading decisions.
Would you like any additional refinements? 🚀
Day of Week Performance█ OVERVIEW
The Day of Week Performance indicator is designed to visualise and compare the cumulative percentage change for each day of the week. This indicator explores one of the many calendar based anomalies in financial markets.
In financial analysis, a calendar based anomaly refers to recurring patterns or tendencies associated with specific time periods, such as days of the week. By calculating the cumulative percentage change for each day (Monday through Friday) and displaying the results both graphically and in a summary table, this indicator helps identify whether certain days consistently outperform others.
█ FEATURES
Customisable time window via Time Settings.
Calculates cumulative percentage change for each day (Monday to Friday) separately.
Option to use Sunday instead of Friday for CFDs and Futures analysis.
Distinct visual representation for each day using unique colours.
Customisable table settings including position and font size.
Built-in error checks to ensure the indicator is applied on a Daily timeframe.
█ HOW TO USE
Add the indicator to a chart set to a Daily timeframe.
Select your desired Start Time and End Time in the Time Settings.
Toggle the performance table on or off in the Table Settings.
Adjust the table’s location and font size as needed.
Use the "Use Sunday instead of Friday" option if your market requires it.
View the cumulative performance plotted in distinct colours.
Colour Scheme:
Monday: Blue
Tuesday: Red
Wednesday: Green
Thursday: Orange
Friday: Purple
Simple EMA Crossover Strategy
Calculates the 35-period and 100-period EMAs.
Detects when the EMA 35 crosses above (crossover_up) or below (crossover_down) the EMA 100.
Plots both EMAs on the chart for visual reference.
Implements the strategy logic:
Enters a long position when EMA 35 crosses above EMA 100.
Exits the long position when EMA 35 crosses below EMA 100.
Plots buy (green triangle) and sell (red triangle) signals on the chart.
backtest 2 years 1 hour timeframe (194% proffit max drawdown 30%)
Bitcoin Trend & Momentum Indicator🚀 Bitcoin Trend & Momentum Indicator 🚀
This indicator is designed to help traders identify long-term trends and momentum shifts in Bitcoin's price movements. By utilizing a 120-day Simple Moving Average (SMA), it highlights whether the market is in a bullish or bearish phase.
Key Features:
✅ Long-Term Trend Detection – Helps distinguish between bullish and bearish phases using SMA(120).
✅ Clear Buy & Sell Signals – Marks BUY when price crosses above SMA and SELL when it crosses below.
✅ Background Highlights – Green for uptrends, red for downtrends.
✅ Simple & Effective – Suitable for both beginners and experienced traders.
This indicator does not provide financial advice. Always use it alongside other analysis tools.
AdvancedLines (FiboBands) - PaSKaL
Overview :
AdvancedLines (FiboBands) - PaSKaL is an advanced technical analysis tool designed to automate the plotting of key Fibonacci retracement levels based on the highest high and lowest low over a customizable period. This indicator helps traders identify critical price zones such as support, resistance, and potential trend reversal or continuation points.
By using AdvancedLines (FiboBands) - PaSKaL , traders can easily spot key areas where the price is likely to reverse or consolidate, or where the trend may continue. It is particularly useful for trend-following, scalping, and range-trading strategies.
Key Features:
Automatic Fibonacci Level Calculation :
- The indicator automatically calculates and plots key Fibonacci levels (0.236, 0.382, 0.5, 0.618, and 0.764), which are crucial for identifying potential support and resistance levels in the market.
Adjustable Parameters :
- Bands Length: You can adjust the bands_length setting to change the number of bars used for calculating the highest high and lowest low. This gives flexibility for using the indicator on different timeframes and trading styles.
- Visibility: The Fibonacci levels, as well as the midline (0.5 Fibonacci level), can be shown or hidden based on your preference.
- Color Customization: You can change the color of each Fibonacci level and background fills to suit your chart preferences.
Fibonacci Levels
- The main Fibonacci levels plotted are:
- 0.236 – Minor support/resistance level
- 0.382 – Moderate retracement level
- 0.5 – Midpoint retracement, often used as a key level
- 0.618 – Golden ratio, considered one of the most important Fibonacci levels
- 0.764 – Strong reversal level, often indicating a continuation or change in trend
Background Fill
- The indicator allows you to fill the background between the Fibonacci levels and the bands with customizable colors. This makes it easier to visually highlight key zones on the chart.
How the Indicator Works:
AdvancedLines (FiboBands) - PaSKaL calculates the range (difference between the highest high and the lowest low) over a user-defined number of bars (e.g., 300). Fibonacci levels are derived from this range, helping traders identify potential price reversal points.
Mathematical Basis :
Fibonacci retracement levels are based on the Fibonacci sequence, where each number is the sum of the previous two (0, 1, 1, 2, 3, 5, 8, 13, etc.). The ratios derived from this sequence (such as 0.618 and 0.382) have been widely observed in nature, market cycles, and price movements. These ratios are used to forecast potential price retracements or continuation points after a major price move.
Fibonacci Levels Calculation :
Identify the Range: The highest high and the lowest low over the defined period are calculated.
Apply Fibonacci Ratios: Fibonacci ratios (0.236, 0.382, 0.5, 0.618, and 0.764) are applied to this range to calculate the corresponding price levels.
Plot the Levels: The indicator automatically plots these levels on your chart.
Customizing Fibonacci Levels & Colors:
The "AdvancedLines (FiboBands) - PaSKaL" indicator offers various customization options for Fibonacci levels, colors, and visibility:
Fibonacci Level Ratios:
- You can customize the Fibonacci level ratios through the following inputs:
- Fibo Level 1: 0.764
- Fibo Level 2: 0.618
- Fibo Level 3: 0.5
- Fibo Level 4: 0.382
- Fibo Level 5: 0.236
- These levels determine key areas where price may reverse or pause. You can adjust these ratios based on your trading preferences.
Fibonacci Level Colors:
- Each Fibonacci level can be assigned a different color to make it more distinguishable on your chart:
- Fibo Level 1 Color (default: Yellow)
- Fibo Level 2 Color (default: Orange)
- Fibo Level 3 Color (default: Green)
- Fibo Level 4 Color (default: Red)
- Fibo Level 5 Color (default: Blue)
- You can change these colors to fit your visual preferences or to align with your existing chart themes.
Visibility of Fibonacci Levels:
- You can choose whether to display each Fibonacci level using the following visibility inputs:
- Show Fibo Level 1 (0.764): Display or hide this level.
- Show Fibo Level 2 (0.618): Display or hide this level.
- Show Fibo Level 3 (0.5): Display or hide this level.
- Show Fibo Level 4 (0.382): Display or hide this level.
- Show Fibo Level 5 (0.236): Display or hide this level.
- This allows you to customize the indicator according to the specific Fibonacci levels that are most relevant to your trading strategy.
Background Fill Color
- The background between the Fibonacci levels and price bands can be filled with customizable colors:
- Fill Color for Upper Band & Fibo Level 1: This color will fill the area between the upper band and Fibonacci Level 1.
- Fill Color for Lower Band & Fibo Level 5: This color will fill the area between the lower band and Fibonacci Level 5.
- Adjusting these colors helps highlight critical zones where price may reverse or consolidate.
How to Use AdvancedLines (FiboBands) - PaSKaL in Trading :
Range Trading :
Range traders typically buy at support and sell at resistance. Fibonacci levels provide excellent support and resistance zones in a ranging market.
Example: If price reaches the 0.618 level in an uptrend, it may reverse, providing an opportunity to sell.
Conversely, if price drops to the 0.382 level, a bounce might occur, and traders can buy, anticipating the market will stay within the range.
Trend-following Trading :
For trend-following traders, Fibonacci levels act as potential entry points during a retracement. After a strong trend, price often retraces to one of the Fibonacci levels before continuing in the direction of the trend.
Example: In a bullish trend, when price retraces to the 0.382 level, it could be a signal to buy, as the price might resume its upward movement after the correction.
In a bearish trend, retracements to levels like 0.618 or 0.764 could provide optimal opportunities for shorting as the price resumes its downward movement.
Scalping :
Scalpers focus on short-term price movements. Fibonacci levels can help identify precise entry and exit points for quick trades.
Example: If price is fluctuating in a narrow range, a scalper can enter a buy trade at 0.236 and exit at the next Fibonacci level, such as 0.382 or 0.5, capturing small but consistent profits.
Stop-Loss and Take-Profit Levels :
Fibonacci levels can also help in setting stop-loss and take-profit levels.
Example: In a bullish trend, you can set a stop-loss just below the 0.236 level and a take-profit at 0.618.
In a bearish trend, set the stop-loss just above the 0.382 level and the take-profit at 0.764.
Identifying Reversals and Continuations :
Reversals: When price reaches a Fibonacci level and reverses direction, it may indicate the end of a price move.
Trend Continuation: If price bounces off a Fibonacci level and continues in the same direction, this may signal that the trend is still intact.
Conclusion :
AdvancedLines (FiboBands) - PaSKaL is an essential tool for any trader who uses Fibonacci retracements in their trading strategy. By automatically plotting key Fibonacci levels, this indicator helps traders quickly identify support and resistance zones, forecast potential reversals, and make more informed trading decisions.
For Trend-following Traders: Use Fibonacci levels to find optimal entry points after a price retracement.
For Range Traders: Identify key levels where price is likely to reverse or bounce within a range.
For Scalpers: Pinpoint small price movements and take advantage of quick profits by entering and exiting trades at precise Fibonacci levels.
By incorporating AdvancedLines (FiboBands) - PaSKaL into your trading setup, you will gain a deeper understanding of price action, improve your decision-making process, and enhance your overall trading performance.
Custom BOS/CHoCH, Order Blocks, FVG by OPB TRADESIdentify break of structube, change of character (Potential trend reversal) and fair value gaps
Triple EMA Crossover v.13 EMA Crossover
This script, Triple EMA Crossover v.1, is a technical indicator designed for trading analysis. It calculates and plots three Exponential Moving Averages (EMAs) with customizable lengths and colors. The script highlights crossover events between the 13-period and 21-period EMAs, changing the EMA colors dynamically to green on a bullish crossover and red on a bearish crossover.
Key features include:
Crossover Signals: Identifies buy (bullish) and sell (bearish) signals when the 13 EMA crosses above or below the 21 EMA while the 8 EMA confirms the trend direction.
Dynamic Coloring & Glow Effect: EMAs change colors based on trend direction, with a shaded area between them for better visualization.
Arrow Markers: Displays arrows at crossover points, with an option to enable or disable them.
VWAP Integration: Option to display the Volume-Weighted Average Price (VWAP) for additional trend analysis.
Alerts: Generates alerts for bullish and bearish crossover signals.
This script helps traders visually identify trend shifts and potential trade opportunities efficiently.
Relative Strength Index colored above/below midpointThis indicator enhances the standard Relative Strength Index (RSI) by incorporating dynamic color changes, moving average smoothing, Bollinger Bands, and divergence detection. It visually highlights overbought and oversold conditions while offering customizable smoothing options to refine RSI signals. Additionally, it detects potential bullish and bearish divergences by analyzing price action relative to RSI movements, helping traders spot potential trend reversals. The indicator also provides real-time alerts when divergences are detected, making it a valuable tool for identifying shifts in market momentum.
Rajesh Raju nifty options SMA/RSIThis indicator is designed for Nifty Index Options trading on a 5-minute timeframe. It uses a combination of the Simple Moving Average (SMA) and Relative Strength Index (RSI) to identify potential buy and sell signals.
How It Works:
A BUY signal is triggered when the price crosses above the SMA and RSI is below the overbought level.
A SELL signal is generated when the price crosses below the SMA and RSI is above the oversold level.
The SMA line is displayed in pink (purple in Pine Script) to track trend direction.
Alerts are included to notify users of trade signals in real time.
This indicator helps traders make informed decisions by identifying trend reversals and momentum shifts
Bollinger Band Breakout ScannerBollinger Bands Behavior:
The bands were previously squeezed (narrow range), indicating low volatility.
The last few candles show a breakout above the upper Bollinger Band with increasing volume, signaling a strong bullish move.
Breakout Confirmation:
A green candle has closed above the upper Bollinger Band.
Volume is also rising, which adds strength to the breakout.
A potential uptrend may follow if the breakout sustains.
MACD Scalping Strategy (30m & 1m)Long/short scalping strategy
use the 30m MACD to understand trend and 1m MACD crosses to scalp long/short
RR Nifty Index Options Strategy This is a 5-minute trading strategy designed for Nifty Index Options, utilizing a combination of the Simple Moving Average (SMA) and the Relative Strength Index (RSI) to identify trade opportunities.
How It Works
Entry Conditions:
A BUY signal is generated when the price crosses above the SMA, and RSI is below the overbought level.
A SELL signal is triggered when the price crosses below the SMA, and RSI is above the oversold level.
Exit Conditions:
Positions are closed automatically if the price hits either:
Target Profit (1% gain from entry price)
Stop Loss (0.5% loss from entry price)
Custom Length Moving AverageThe Custom Length Moving Average is a dynamic indicator that allows traders to plot a moving average with an adjustable length based on their preferred number of days. Users can choose between Simple Moving Average (SMA), Exponential Moving Average (EMA), or Weighted Moving Average (WMA) to match their trading strategy. The script automatically calculates the moving average length by factoring in the chart’s timeframe and trading session duration, ensuring precision and adaptability. This makes it an ideal tool for traders looking for a flexible moving average that adjusts to different market conditions and timeframes.
Price Volume Trend Oscillator AlertsA simple smoothed PVT oscillator with adjustable high and low thresholds and an exponential average thrown in.
Gives entry and exit signals when PVT (orange) crosses EMA (blue) or PVT crosses midline for the more cautious.
Look for divergences for beetter results.
Alerts for everything; threshold crosses, ema crosses and midline crosses.
Experimenting with settings might improve (or worsen) results!
Never rely on one indicator.
Good luck!
Ultimate RSI Strategy### Overview
This Pine Script is a **TradingView strategy** that implements the "Ultimate RSI" indicator as originally designed by LuxAlgo. The script calculates an augmented version of the Relative Strength Index (RSI) and then uses its behavior to generate long and short trading signals. In addition to computing the indicator values, the script visually plots the Ultimate RSI, its smoothed signal line, and constant lines representing overbought, midline, and oversold levels. It also uses color-filled areas to highlight when the indicator is in overbought or oversold regions.
---
### Key Components
1. **Strategy Declaration and Settings**
- **Version:** The script is written in Pine Script version 6.
- **Strategy Settings:**
- Declared using the `strategy()` function.
- Parameters include an initial capital of $10,000, a percentage-of-equity position sizing (default 10% per trade), and other currency-related settings.
- `overlay=false` indicates that the indicator is displayed in a separate pane (as it is an oscillator).
2. **User Inputs**
- **RSI Parameters:**
- `length`: The period over which the indicator calculates the highest and lowest values (default 14).
- `src`: The data source (typically the closing price).
- `smoType1`: The smoothing method for the RSI calculation. Options include EMA, SMA, RMA, and TMA.
- **Signal Line Parameters:**
- `smooth`: The smoothing period for the signal line (default 14).
- `smoType2`: The smoothing method used for the signal line.
- **Visual Customizations:**
- Colors for the main Ultimate RSI line (`arsiCss`), signal line (`signalCss`), overbought and oversold levels, and the filled areas (`obAreaCss` and `osAreaCss`).
- Overbought (`obValue`, default 80) and oversold (`osValue`, default 20) levels.
- An option (`autoCss`) to automatically adjust the RSI color based on chart settings.
3. **Calculation of the Ultimate RSI**
- **Highs and Lows:**
- The script calculates the highest and lowest prices over the defined period (`length`).
- **Difference Calculation:**
- It computes a difference value (`diff`) based on whether the high or low changes compared to the previous bar, or simply the price change.
- **Smoothing:**
- Two moving averages are applied:
- One to the raw difference (numerator) and one to the absolute difference (denominator), using the chosen smoothing method (`smoType1`).
- The Ultimate RSI value is then derived by scaling the ratio of these smoothed values into a 0–100 range (with 50 as the midline).
- **Signal Line:**
- A second smoothing (using the chosen method `smoType2` and period `smooth`) is applied to the Ultimate RSI to form a signal line.
4. **Trading Logic and Entry/Exit Conditions**
- **Long Entry Condition:**
- A long (buy) signal is generated when the Ultimate RSI crosses above its signal line *and* the Ultimate RSI is below the midline (50). This suggests a recovery from an oversold condition.
- **Short Entry Condition:**
- A short (sell) signal is generated when the Ultimate RSI crosses below its signal line *and* the Ultimate RSI is above the midline. This indicates a potential decline from an overbought condition.
- **Position Management:**
- Before entering a new trade, the script closes any existing position in the opposite direction. For example, if a short signal occurs while a long position is open, the long position is closed.
5. **Plotting and Visual Elements**
- **Indicator and Signal Line:**
- The Ultimate RSI and its signal line are plotted as lines in the indicator pane.
- **Constant Lines:**
- Instead of using `hline`, constant lines are plotted for the overbought, midline, and oversold levels. This allows them to be used with the `fill()` function.
- **Filled Areas:**
- The area between the Ultimate RSI plot and the overbought level is filled with a specified color when the indicator is above the overbought threshold.
- Similarly, the area between the oversold level and the Ultimate RSI plot is filled when the indicator is below the oversold threshold.
- These fills help visually emphasize extreme conditions on the indicator.
---
### Summary
- **Purpose:** The script combines an augmented RSI calculation with a simple trend-following strategy.
- **Signal Generation:** It uses crossovers between the Ultimate RSI and its smoothed signal line to determine entry points, with filters to avoid taking trades when the RSI is near its midline.
- **Visualization:** Clear plots and color-coded areas allow traders to quickly identify when the market may be overbought or oversold.
- **Strategy Behavior:** Designed for both long and short trading, the strategy actively manages positions by closing opposing trades when a reversal signal is generated.
This description should give you a comprehensive understanding of the script’s structure, functionality, and how it can be used within TradingView to both visualize the Ultimate RSI indicator and to backtest a simple trading strategy based on its signals.