Fibonacci Entry Bands [AlgoAlpha]OVERVIEW
This script plots Fibonacci Entry Bands, a trend-following and mean-reversion hybrid system built around dynamic volatility-adjusted bands scaled using key Fibonacci levels. It calculates a smoothed basis line and overlays multiple bands at fixed Fibonacci multipliers of either ATR or standard deviation. Depending on the trend direction, specific upper or lower bands become active, offering a clear framework for entry timing, trend identification, and profit-taking zones.
CONCEPTS
The core idea is to use Fibonacci levels—0.618, 1.0, 1.618, and 2.618—as multipliers on a volatility measure to form layered price bands around a trend-following moving average. Trends are defined by whether the basis is rising or falling. The trend determines which side of the bands is emphasized: upper bands for downtrends, lower bands for uptrends. This approach captures both directional bias and extreme price extensions. Take-profit logic is built in via crossovers relative to the outermost bands, scaled by user-selected aggressiveness.
FEATURES
Basis Line – A double EMA smoothing of the source defines trend direction and acts as the central mean.
Volatility Bands – Four levels per side (based on selected ATR or stdev) mark the Fibonacci bands. These become visible only when trend direction matches the side (e.g., only lower bands plot in an uptrend).
Bar Coloring – Bars are shaded with adjustable transparency depending on distance from the basis, with color intensity helping gauge overextension.
Entry Arrows – A trend shift triggers either a long or short signal, with a marker at the outermost band with ▲/▼ signs.
Take-Profit Crosses – If price rejects near the outer band (based on aggressiveness setting), a cross appears marking potential profit-taking.
Bounce Signals – Minor pullbacks that respect the basis line are marked with triangle arrows, hinting at continuation setups.
Customization – Users can toggle bar coloring, signal markers, and select between ATR/stdev as well as take-profit aggressiveness.
Alerts – All major signals, including entries, take-profits, and bounces, are available as alert conditions.
USAGE
To use this tool, load it on your chart, adjust the inputs for volatility method and aggressiveness, and wait for entries to form on trend changes. Use TP crosses and bounce arrows as potential exit or scale-in signals.
Indicatori e strategie
Fibonacci Optimal Entry Zone [OTE] (Zeiierman)█ Overview
Fibonacci Optimal Entry Zone (Zeiierman) is a high-precision market structure tool designed to help traders identify ideal entry zones during trending markets. Built on the principles of Smart Money Concepts (SMC) and Fibonacci retracements, this indicator highlights key areas where price is most likely to react — specifically within the "Golden Zone" (between the 50% and 61.8% retracement).
It tracks structural pivot shifts (CHoCH) and dynamically adjusts Fibonacci levels based on real-time swing tracking. Whether you're trading breakouts, pullbacks, or optimal entries, this tool brings unparalleled clarity to structure-based strategies.
Ideal for traders who rely on confluence, this indicator visually synchronizes swing highs/lows, market structure shifts, Fibonacci retracement levels, and trend alignment — all without clutter or lag.
⚪ The Structural Assumption
Price moves in waves, but key retracements often lead to continuation or reversal — especially when aligned with structure breaks and trend shifts.
The Optimal Entry Zone captures this behavior by anchoring Fibonacci levels between recent swing extremes. The most powerful area — the Golden Zone — marks where institutional re-entry is likely, providing traders with a sniper-like roadmap to structure-based entries.
█ How It Works
⚪ Structure Tracking Engine
At its core, the indicator detects pivots and classifies trend direction:
Structure Period – Determines the depth of pivots used to detect swing highs/lows.
CHoCH – Break of structure logic identifies where the trend shifts or continues, marked visually on the chart.
Bullish & Bearish Modes – Independently toggle uptrend and downtrend detection and styling.
⚪ Fibonacci Engine
Upon each confirmed structural shift, Fibonacci retracement levels are projected between swing extremes:
Custom Levels – Choose which retracements (0.50, 0.618, etc.) are shown.
Real-Time Adjustments – When "Swing Tracker" is enabled, levels and labels update dynamically as price forms new swings.
Example:
If you disable the Swing Tracker, the Golden Level is calculated using the most recent confirmed swing high and low.
If you enable the Swing Tracker, the Golden Level is calculated from the latest swing high or low, making it more adaptive as the trend evolves in real time.
█ How to Use
⚪ Structure-Based Entry
Wait for CHoCH events and use the resulting Fibonacci projection to identify entry points. Enter trades as price taps into the Golden Zone, especially when confluence forms with swing structure or order blocks.
⚪ Real-Time Reaction Tracking
Enable Swing Tracker to keep the tool live — constantly updating zones as price shifts. This is especially useful for scalpers or intraday traders who rely on fresh swing zones.
█ Settings
Structure Period – Number of bars used to define swing pivots. Larger values = stronger structure.
Swing Tracker – Auto-updates fib levels as new highs/lows form.
Show Previous Levels – Keep older fib zones on chart or reset with each structure shift.
-----------------
Disclaimer
The content provided in my scripts, indicators, ideas, algorithms, and systems is for educational and informational purposes only. It does not constitute financial advice, investment recommendations, or a solicitation to buy or sell any financial instruments. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
Dynamic Flow Ribbons [BigBeluga]🔵 OVERVIEW
A dynamic multi-band trend visualization system that adapts to market volatility and reveals trend momentum with layered ribbon channels.
Dynamic Flow Ribbons transforms price action into flowing trend bands that expand and contract with volatility. It not only shows the active directional bias but also visualizes how strong or weak the trend is through layered ribbons, making it easier to assess trend quality and structure.
🔵 CONCEPTS
Uses an adaptive trend detection system built on a volatility envelope derived from an EMA of the average price (HLC3).
Measures volatility using a long-period average of the high-low range, which scales the envelope width dynamically.
Trend direction flips when the average price crosses above or below these envelopes.
Ribbons form around the trend line to show how far price is stretching or compressing relative to the mean.
🔵 FEATURES
Volatility-Based Trend Line:
A thick, color-coded line tracks the current trend with smoother transitions between phases.
Multi-Layered Flow Ribbons:
Up to 10 bands (5 above and 5 below) radiate outward from the upper and lower envelopes, reflecting volatility strength and direction.
Trend Coloring & Transitions:
Ribbons and candles are dynamically colored based on trend direction— green for bullish , orange for bearish . Transparency fades with distance from the core trend band.
Real-Time Responsiveness:
Ribbon structure and trend shifts update in real time, adapting instantly to fast market changes.
🔵 HOW TO USE
Use the color and thickness of the core trend line to follow directional bias.
When ribbons widen symmetrically, it signals strong trend momentum .
Narrowing or overlapping ribbons can suggest consolidation or transition zones .
Combine with breakout systems or volume tools to confirm impulsive or corrective phases .
Adjust the “Length” (factor) input to tune sensitivity—higher values smooth trends more.
🔵 CONCLUSION
Dynamic Flow Ribbons offers a sleek and insightful view into trend strength and structure. By visualizing volatility expansion with directional flow, it becomes a powerful overlay for momentum traders, swing strategists, and trend followers who want to stay ahead of evolving market flows
Multi TF Oscillators Screener [TradingFinder] RSI / ATR / Stoch🔵 Introduction
The oscillator screener is designed to simplify multi-timeframe analysis by allowing traders and analysts to monitor one or multiple symbols across their preferred timeframes—all at the same time. Users can track a single symbol through various timeframes simultaneously or follow multiple symbols in selected intervals. This flexibility makes the tool highly effective for analyzing diverse markets concurrently.
At the core of this screener lie two essential oscillators: RSI (Relative Strength Index) and the Stochastic Oscillator. The RSI measures the speed and magnitude of recent price movements and helps identify overbought or oversold conditions.
It's one of the most reliable indicators for spotting potential reversals. The Stochastic Oscillator, on the other hand, compares the current price to recent highs and lows to detect momentum strength and potential trend shifts. It’s especially effective in identifying divergences and short-term reversal signals.
In addition to these two primary indicators, the screener also displays helpful supplementary data such as the dominant candlestick type (Bullish, Bearish, or Doji), market volatility indicators like ATR and TR, and the four key OHLC prices (Open, High, Low, Close) for each symbol and timeframe. This combination of data gives users a comprehensive technical view and allows for quick, side-by-side comparison of symbols and timeframes.
🔵 How to Use
This tool is built for users who want to view the behavior of a single symbol across several timeframes simultaneously. Instead of jumping between charts, users can quickly grasp the state of a symbol like gold or Bitcoin across the 15-minute, 1-hour, and daily timeframes at a glance. This is particularly useful for traders who rely on multi-timeframe confirmation to strengthen their analysis and decision-making.
The tool also supports simultaneous monitoring of multiple symbols. Users can select and track various assets based on the timeframes that matter most to them. For example, if you’re looking for entry opportunities, the screener allows you to compare setups across several markets side by side—making it easier to choose the most favorable trade. Whether you’re a scalper focused on low timeframes or a swing trader using higher ones, the tool adapts to your workflow.
The screener utilizes the widely-used RSI indicator, which ranges from 0 to 100 and highlights market exhaustion levels. Readings above 70 typically indicate potential pullbacks, while values below 30 may suggest bullish reversals. Viewing RSI across timeframes can reveal meaningful divergences or alignments that improve signal quality.
Another key indicator in the screener is the Stochastic Oscillator, which analyzes the closing price relative to its recent high-low range. When the %K and %D lines converge and cross within the overbought or oversold zones, it often signals a momentum reversal. This oscillator is especially responsive in lower timeframes, making it ideal for spotting quick entries or exits.
Beyond these oscillators, the table includes other valuable data such as candlestick type (bullish, bearish, or doji), volatility measures like ATR and TR, and complete OHLC pricing. This layered approach helps users understand both market momentum and structure at a glance.
Ultimately, this screener allows analysts and traders to gain a full market overview with just one look—empowering faster, more informed, and lower-risk decision-making. It not only saves time but also enhances the precision and clarity of technical analysis.
🔵 Settings
🟣 Display Settings
Table Size : Lets you adjust the table’s visual size with options such as: auto, tiny, small, normal, large, huge.
Table Position : Sets the screen location of the table. Choose from 9 possible positions, combining vertical (top, middle, bottom) and horizontal (left, center, right) alignments.
🟣 Symbol Settings
Each of the 10 symbol slots comes with a full set of customizable parameters :
Enable Symbol : A checkbox to activate or hide each symbol from the table.
Symbol : Define or select the asset (e.g., XAUUSD, BTCUSD, EURUSD, etc.).
Timeframe : Set your desired timeframe for each symbol (e.g., 15, 60, 240, 1D).
RSI Length : Defines the period used in RSI calculation (default is 14).
Stochastic Length : Sets the period for the Stochastic Oscillator.
ATR Length : Sets the length used to calculate the Average True Range, a key volatility metric.
🔵 Conclusion
By combining powerful oscillators like RSI and Stochastic with full customization over symbols and timeframes, this tool provides a fast, flexible solution for technical analysts. Users can instantly monitor one or several assets across multiple timeframes without opening separate charts.
Individual configuration for each symbol, along with the inclusion of key metrics like candlestick type, ATR/TR, and OHLC prices, makes the tool suitable for a wide range of trading styles—from scalping to swing and position trading.
In summary, this screener enables traders to gain a clear, high-level view of various markets in seconds and make quicker, smarter, and lower-risk decisions. It saves time, streamlines analysis, and boosts overall efficiency and confidence in trading strategies.
Math by Thomas - SMC OB + FVG📄 Description
This script is designed for traders following the Smart Money Concepts (SMC) methodology. It automatically detects:
✅ Bullish and Bearish Order Blocks (OBs) based on structural breakouts, displacement, and volume conditions.
✅ Fair Value Gaps (FVGs) using a 3-candle price imbalance model.
🔄 Both OBs and FVGs clean up dynamically when invalidated by price action.
Built with institutional logic, this tool helps identify areas of interest for potential reversals, liquidity grabs, or mitigation plays.
⚙️ How It Works
🔷 Order Blocks (OB)
A Bullish OB is marked after a Break of Structure (BOS) to the upside.
A Bearish OB is marked after BOS to the downside.
Filters like displacement candle and volume spike can be toggled in settings.
Boxes are drawn from the opposing candle in the move, and will disappear once broken or expired.
🟥 Fair Value Gaps (FVG)
FVGs are detected when the middle candle leaves a price imbalance between the first and third candle.
Zones are marked with transparent boxes.
Labels (FVG) appear only once every 20 bars to reduce clutter.
Gaps are removed only after a full candle closes through the zone (conservative logic).
🛠️ User Settings
Choose volume multiplier and ATR period for OB displacement logic.
Set box extension, label transparency, and cleanup behavior.
Full control over colors and midline display.
📈 How to Use
Apply the indicator to any chart (works best on indices, forex, crypto).
Use OBs as points of interest for potential reaction zones or mitigation setups.
Use FVGs to identify imbalances that may attract price.
Watch for confluence between OBs and FVGs for high-probability entries.
📚 Best Practice
Use on 15m–1h timeframe for clean structure.
Align with higher TF bias for direction.
Combine with liquidity sweeps, EQH/EQL, or breaker blocks for refinement.
HOG Liquidity HunterHOG Liquidity Hunter – Pivot‑Based Liquidity Zones
📌 Overview
Plots dynamic support and resistance zones on swing pivots with an ATR‑based buffer. Anchored only when pivots are confirmed, the zones stay close to current price levels—ideal for spotting liquidity runs or traps.
🔧 How It Works
Detects swing highs and lows using ta.pivothigh() / ta.pivotlow() with a user‑defined lookback.
After a pivot is confirmed, calculates BSL/SSL zone = pivot ± (ATR * margin).
Zones update only on confirmed pivots—no repainting on open bars.
⚙️ Inputs
Lookback: bars to confirm pivots (e.g. 10–20).
ATR Margin Multiplier: buffer width (e.g. 1.25).
✅ Benefits
Structure‑focused: Zones align with real swing points.
Responsive yet stable: Tight ATR margin keeps zones precise, only updating on valid pivots.
Clean visuals: Two uncluttered zones—easy to interpret.
🛠 How to Use
Detect near‑zone bounce entries or exits on 4H/1D charts.
Combine with trend or volume indicators for stronger setups.
Use zones to identify potential stop‑run, liquidity re‑tests, or range turns.
⚠️ Notes & Disclaimers
Zones base off historical pivots; may lag until confirmed.
No future-looking data—relying entirely on closing bar confirmation.
Use alongside a complete trading framework; this is not a standalone signal.
RSI Divergence StrategyOverview
The RSI Divergence Strategy Indicator is a trading tool that uses the RSI and divergences created to generate high-probability buy and sell signals.
I have provided the best formula of numbers to use for BTC on a 30 minute timeframe.
You can change where on RSI you enter and exit both long or short trades. This way you can experiment on different tokens using different entry/exit points. Can use on multiple timeframes.
This strategy is designed to open and close long or short trades based on the levels you provide it. You can then check on the RSI where the best levels are for each token you want to trade and amend it as required to generate a profitable strategy.
How It Works
The RSI Divergence Strategy Indicator uses bear and bull divergences in conjuction with a level you have input on the RSI.
RSI for Overbought/Oversold:
• Input variables for entry and exit levels and when the entry levels combine with a bear or bull divergence signal, a trade is alerted.
RSI Divergence:
• Buy and sell signals are confirmed when the RSI creates bearish or bullish divergences and these divergences are in the same area as your levels you input for entry to short or long.
After 7 years of experience and testing I have calculated the exact numbers required and produced a formula to calculate the exact input variables for a 30 minute Bitcoin chart.
Key Features
1️⃣ Divergence Identification – Ensures trades are taken only when a bull or bear divergence has formed.
2️⃣ Overbought/Oversold Input Filtering – Set up your own variables on the RSI for different markets after identifying patterns on the RSI in relation to a bearish or bullish divergence.
3️⃣ Works on any chart – Suitable for all markets and timeframes once you input the correct variables for entry and exit levels.
How to Use
🟢 Basic Trading:
• Use on any timeframe.
• Enter trade only when alert has fired off. Close when it says to exit.
• Change entry and exit levels in the properties of the strategy indicator.
• Make entry and exit levels coincide with bearish or bullish divergences on the RSI.
Check the strategy tester to see backtesting so you know if the indicator is profitable or not for that market and timeframe as each crypto token is different and so is the timeframe you choose.
📢 Webhook Automation:
• Set up TradingView Alerts to auto-execute trades via Webhook-compatible platforms.
Key additions for divergence visualization:
Divergence Arrows:
Bullish divergence: Green label with white 'bull ' text
Bearish divergence: Red label with white 'bear' text
Positioned at the pivot point
Divergence Lines:
Connects consecutive RSI pivot points
Automatically drawn between consecutive pivot points
Enhanced RSI Coloring:
Overbought zone: Red
Oversold zone: Green
Neutral zone: Gray
The visualization helps you instantly spot:
Where divergences are forming on the RSI
The pattern of higher lows (bullish) or lower highs (bearish)
Contextual coloring of RSI relative to standard levels
All divergence markers appear at the correct historical pivot points, making it easy to visually confirm divergence patterns as they develop.
Strategy levels and background zones also shown to help visual look.
Why This Combination?
This indicator is just a simple RSI tool.
It is designed to filter out weak trades and only execute trades that have:
✅ RSI Divergence
✅ Overbought or Oversold Conditions
It does not calculate downtrends or bear markets so care is recommended taking long trades during these times.
Why It’s Worth Using?
📈 Open Source – Free to use and learn from.
📉 Long or Short Term Trading Style – Entry/Exit parameters options are designed for both short or long term trades allowing you to experiment until you find a profitable strategy for that market you want to trade.
📢 Seamless Webhook Automation – Execute trades automatically with TradingView alerts.
💲 Ready to trade smarter?
✅ Add the RSI Divergence Strategy Indicator to your TradingView chart.
Differential-Isaac-Newton
Description of the Differential-Isaac-Newton Indicator (DF-Newton)
This indicator plots custom Fibonacci levels on the chart using configurable multiples and offers various display options to assist with technical analysis.
What does it do?
Calculates and plots Fibonacci levels based on user-defined multiples (default multiple is 20).
Allows switching between long mode (buy) and short mode (sell) to adjust the levels accordingly.
Displays horizontal lines at Fibonacci levels with customizable colors and styles.
Shows labels with different information such as level price, Fibonacci percentage, and difference between levels.
Includes controls to show/hide different elements and customize the appearance.
How to use it?
Main Settings
Multiple of 2 for Fibonacci: Defines the percentage interval used to calculate Fibonacci levels (e.g., 20 creates levels at 0%, 20%, 40%, etc.).
Line Horizontal Offset: Defines the horizontal distance (in bars) of the Fibonacci line to improve visibility.
Short Mode: Enable to calculate levels based on a downward movement (from low to high).
Classic Mode: Changes the line colors to a classic Fibonacci color scheme (blue, green, yellow, orange, red).
Toggle Solid Line: Switches between solid and dotted lines for Fibonacci levels.
Labels
Choose which information to display on the labels next to the lines:
Show Only Level Prices: Displays only the Fibonacci level price.
Show Only Level Percentages: Displays only the Fibonacci percentage level.
Show Difference Values (Δ): Shows the difference between the current and previous level, along with the percentage (which can be hidden).
Hide Percentage in Difference Mode: Hides the percentage when difference mode is enabled.
Hide All Labels: Hides all labels from the chart.
Visual Customization
Label Size: Size of the label text (XS, S, M, L).
Label Horizontal Offset: Horizontal distance of labels relative to the lines.
Background Offset: Adjusts background color offset for better visibility.
Fibonacci Line Color: Color of the Fibonacci lines (when classic mode is off).
Label Text Color: Color of the label text.
Level Interpretation
Fibonacci levels are calculated between the highest high and lowest low of the last 100 candles.
The indicator plots horizontal lines at Fibonacci levels according to the selected multiple.
Line colors help identify important levels (configurable in classic mode).
Labels show the exact level price and Fibonacci percentage, helping with entry, exit, support, and resistance decisions.
Recommendations
Use Short Mode to analyze Fibonacci levels for sell trades.
Use Classic Mode for a traditional color scheme and easier identification.
Adjust Line Horizontal Offset to avoid overlapping current candles.
Combine price and percentage display for easier analysis.
Explore Difference Mode (Δ) to understand gaps between consecutive Fibonacci levels.
Practical Example
If you set the multiple to 20, the indicator will show levels at 0%, 20%, 40%, 60%, 80%, and 100%. Each level will have a horizontal line and a label showing the corresponding price and percentage, or the difference from the previous level, depending on your settings.
MACD Breakout SuperCandlesMACD Breakout SuperCandles
The MACD Breakout SuperCandles indicator is a candle-coloring tool that monitors trend alignment across multiple timeframes using a combination of MACD behavior and simple price structure. It visually reflects market sentiment directly on price candles, helping traders quickly recognize shifting momentum conditions.
How It Works
The script evaluates trend behavior based on:
- Multi-timeframe MACD Analysis: Uses MACD values and signal line relationships to gauge trend direction and strength.
- Price Relative to SMA Zones: Analyzes whether price is positioned above or below the 20-period high and low SMAs on each timeframe.
For each timeframe, the script assigns one of five possible trend statuses:
- SUPERBULL: Strong bullish MACD signal with price above both SMAs.
- Bullish: Bullish MACD crossover with price showing upward bias.
- Basing: MACD flattening or neutralizing near zero with no directional dominance.
- Bearish: Bearish MACD signal without confirmation of stronger trend.
- SUPERBEAR: Strong bearish MACD signal with price below both SMAs.
-Ghost Candles: Candles with basing attributes that can signal directional change or trend strength.
Signal Scoring System
The script compares conditions across four timeframes:
- TF1 (Short)
- TF2 (Medium)
- TF3 (Long)
- MACD at a fixed 10-minute resolution
Each status type is tracked independently. A colored candle is only applied when a status type (e.g., SUPERBULL) reaches the minimum match threshold, defined by the "Min Status Matches for Candle Color" setting. If no status meets the required threshold, the candle is displayed in a neutral "Ghost" color.
Customizable Visuals
The indicator offers full control over candle appearance via grouped settings:
Body Colors
- SUPERBULL Body
- Bullish Body
- Basing Body
- Bearish Body
- SUPERBEAR Body
- Ghost Candle Body (used when no match)
Border & Wick Colors
- SUPERBULL Border/Wick
- Bullish Border/Wick
- Basing Border/Wick
- Bearish Border/Wick
- SUPERBEAR Border/Wick
- Ghost Border/Wick
Colors are grouped by function and can be adjusted independently to match your chart theme or personal preferences.
Settings Overview
- TF1, TF2, TF3: Select short, medium, and long timeframes to monitor trend structure.
- Min Status Matches: Set how many timeframes must agree before a candle status is applied.
- MACD Settings: Customize MACD fast, slow, and signal lengths, and choose MA type (EMA, SMA, WMA).
This tool helps visualize how aligned various timeframe conditions are by embedding sentiment into the candles themselves. It can assist with trend identification, momentum confirmation, or visual filtering for discretionary strategies.
Advanced Market Profile AnalysisChecking if the vpoc, ppoc, and poor high and poor low are any anomolies can be detected with it
Zero-Lag Linear Regression Candles🚀 Zero-Lag Linear Regression Candles
📊 What It Does
The Zero-Lag Linear Regression Candles change traditional candlestick analysis by creating smoothed, predictive candles that eliminate the lag inherent in standard linear regression methods. Instead of waiting for price confirmation, this indicator anticipates market movements using advanced mathematical modeling.
🎯 Key Features
Tri-Layer Super Responsive System
Layer 1: Weighted Linear Regression with exponential decay weighting
Layer 2: Zero-lag correction algorithm that projects future price direction
Layer 3: Adaptive intelligence that adjusts to current market volatility and momentum
Smart Market Adaptation
Automatically adjusts sensitivity based on market volatility (ATR)
Responds to momentum changes in real-time
Filters out market noise while preserving important signals
Customizable
Regression Length: Fine-tune responsiveness (2-50 periods)
Weight Decay Factor: Control how much emphasis to place on recent vs. historical data
Zero-Lag Periods: Adjust the aggressiveness of lag elimination
Adaptive Factor: Set market adaptation strength
🛠️ Usage Instructions
1. Add to Chart: Apply the indicator to any timeframe
2. Configure Settings: Adjust regression length and sensitivity to match your trading style
3. Interpret Signals:
- Green Candles: Bullish linear regression trend
- Red Candles: Bearish linear regression trend
Created by B3AR_Trades
MTF Pivot Fib Speed Resistance FansOverview
This Pine Script indicator, titled "MTF Pivot Fib Speed Resistance Fans", is a multi-timeframe tool that automatically plots Fib Speed Resistance Fan lines based on pivot structures derived from higher timeframes. It mirrors the functionality of TradingView’s built-in “Fib Speed Resistance Fan” drawing tool, but in a dynamic, programmatic way. It uses pivot highs and lows to anchor fan projections, drawing forward-facing trend lines that align with well-known Fibonacci ratios and their extensions.
Pivot Detection Logic
The script identifies pivots by comparing the current bar’s high and low against the highest and lowest prices over a user-defined pivot period. This pivot detection occurs on a higher timeframe of your choice, giving a broader and more strategic view of price structure. The script tracks direction changes in the pivot trend and stores only the most recent few pivots to maintain clean and meaningful fan drawings.
Fan Direction Control
The user can select whether to draw fans for "Buys", "Sells", or "Both". The script only draws fan lines when a new directional move is detected based on the pivot structure and the selected bias. For example, in “Buys” mode, a rising pivot followed by another higher low will trigger upward fan projections.
Fib Speed Resistance Levels
Once two pivots are identified, the script draws multiple fan lines from the first pivot outward, at angles defined by a preset list of Fibonacci levels. These fan lines help visualize speed and strength of a price move.
The script also draws a horizontal line from the pivot for additional confluence at the base level (1.0).
Price Level Plotting
In addition to drawing fan lines, the indicator also plots their price levels on the right-hand price scale. This makes it easier for users to visually reference the projected support and resistance levels without needing to trace the lines manually across the chart.
Mapping to TradingView’s "Fib Speed Resistance Fan"
The expanded set of values used in this script is not arbitrary—they closely align with the default and extended levels available in TradingView's built-in "Fib Speed Resistance Fan" tool.
TradingView’s Fib Fan tool offers several levels by default, including traditional Fibonacci ratios like 0.382, 0.5, 0.618, and 1. However, if you right-click the tool and open its settings, you’ll find additional toggles for levels like 1.618, 2.000, 2.618, and even 4.000. These deeper levels are used to project stronger trend continuations beyond the standard retracement zones.
The inclusion of levels such as 0.25, 0.75, and 1.34 reflects configurations that are available when you manually add or customize levels in TradingView’s fan tool. While 1.34 is not a canonical Fibonacci ratio, it is often found in hybrid Gann/Fib methods and is included in some preset templates in TradingView’s drawing tool for advanced users.
By incorporating these levels directly into the Pine Script, the indicator faithfully reproduces the fan structure users would manually draw using TradingView’s graphical Fib Fan tool—but does so programmatically, dynamically, and with multi-timeframe control. This eliminates manual errors, allows for responsive updating, and adds custom visual tracking via the price scale.
These values are standardized within the context of TradingView's Fib Fan tool and not made up. This script automates what the manual drawing tool achieves, with added precision and flexibility.
Volume Velocity by TenozenA new indicator is here!
Volume Velocity (VV) is designed to help identify whether the market is likely to trend or move sideways. When VV drops below 0, it suggests weak volume momentum, which often leads to choppy or range-bound price action. Conversely, a positive VV typically signals a stronger market drive, potentially indicating trend formation. (Strong reminder! Volume data quality is crucial! I suggest using volume data from futures market!)
VV is calculated using Kalman filter concepts; adapting to the state, covariance, and predictions over time, using matrix-based calculations.
To be honest, it's quite a complex method, and I’m still learning as I go. The current version is based on a translated formula that I personaly modified into Pine Script.
I’d really appreciate any insights or ideas you guys might have! Maybe there’s something I missed or a new approach I could try! Ciao!
Sri_Auto Fibonacci Sri_Auto Fibonacci is an advanced and original implementation of an automatic Fibonacci retracement plotting tool that uses price action pivots and volatility to dynamically draw key Fibonacci levels. Unlike static manual fib drawing, this tool automates the process by reacting to market structure using pivot detection logic and ATR-based deviation confirmation.
📐 What It Does
Detects major high/low pivot swings on a user-selected higher timeframe (default: Daily).
Uses ATR-based deviation threshold to avoid minor or noisy swings.
Automatically plots Fibonacci retracement levels (0, 0.236, 0.382, 0.5, 0.618, 0.786, 1.0).
Displays a dashed line connecting the two pivot points.
Draws horizontal lines and labels at each selected level.
Shows a status label if valid pivots are not yet found.
⚙️ User Inputs
Deviation % Multiplier: Adjusts the sensitivity based on ATR% to ignore small fluctuations.
Pivot Depth: Controls how many bars before/after a point are used to confirm a pivot.
Extend Lines Left/Right: Allows you to keep the levels visible into past/future bars.
Color Customization: Choose custom colors for each level.
Select Which Levels to Show: Toggle levels like 0.382 or 0.786 on/off based on preference.
🧠 How It Works
Pivot Detection
A price is considered a valid high/low pivot if it is the highest/lowest point within a lookback window (depth).
Deviation Filter
To avoid false pivots, the script calculates the % deviation between the new pivot and the last one using ATR/Close. Only when this exceeds a user-defined threshold, the new pivot is accepted.
Fibonacci Calculation
Once a valid new pivot is confirmed, the script draws levels between the latest two swings using the standard Fibonacci ratios.
✅ Key Features
Non-repainting logic for confirmed pivots
Works across all symbols and asset classes
Fully customizable and extendable
Clean, lightweight, and script-efficient
Built with Pine Script v5 standards
Uses request.security() to ensure pivot detection from the selected HTF
No proprietary or obfuscated code
📊 Best Use Cases
Identifying key retracement zones during pullbacks
Confirming support/resistance with fib confluence
Planning entries/exits around dynamic fib areas
Works well in swing trading setups
📌 Important Notes
This tool does not repaint once pivot structure is confirmed.
Designed as a support tool, not a signal generator.
Can be combined with RSI, MACD, volume, or price action for better confirmation.
📜 Disclaimer
This script is developed independently and shared publicly for educational and analytical use only. It is not intended to copy or infringe upon any commercial tool or proprietary indicator. Use at your own discretion. No investment advice is implied.
📧 For feedback or suggestions, feel free to connect through TradingView profile messages.
💡 Happy Trading!
light_logLight Log - A Defensive Programming Library for Pine Script
Overview
The Light Log library transforms Pine Script development by introducing structured logging and defensive programming patterns typically found in enterprise languages like C#. This library addresses a fundamental challenge in Pine Script: the lack of sophisticated error handling and debugging tools that developers expect when building complex trading systems.
At its core, Light Log provides three transformative capabilities that work together to create more reliable and maintainable code. First, it wraps all native Pine Script types in error-aware containers, allowing values to carry validation state alongside their data. Second, it offers a comprehensive logging system with severity levels and conditional rendering. Third, it includes defensive programming utilities that catch errors early and make code self-documenting.
The Philosophy of Errors as Values
Traditional Pine Script error handling relies on runtime errors that halt execution, making it difficult to build resilient systems that can gracefully handle edge cases. Light Log introduces a paradigm shift by treating errors as first-class values that flow through your program alongside regular data.
When you wrap a value using Light Log's type system, you're not just storing data – you're creating a container that can carry both the value and its validation state. For example, when you call myNumber.INT() , you receive an INT object that contains both the integer value and a Log object that can describe any issues with that value. This approach, inspired by functional programming languages, allows errors to propagate through calculations without causing immediate failures.
Consider how this changes error handling in practice. Instead of a calculation failing catastrophically when it encounters invalid input, it can produce a result object that contains both the computed value (which might be na) and a detailed log explaining what went wrong. Subsequent operations can check has_error() to decide whether to proceed or handle the error condition gracefully.
The Typed Wrapper System
Light Log provides typed wrappers for every native Pine Script type: INT, FLOAT, BOOL, STRING, COLOR, LINE, LABEL, BOX, TABLE, CHART_POINT, POLYLINE, and LINEFILL. These wrappers serve multiple purposes beyond simple value storage.
Each wrapper type contains two fields: the value field v holds the actual data, while the error field e contains a Log object that tracks the value's validation state. This dual nature enables powerful programming patterns. You can perform operations on wrapped values and accumulate error information along the way, creating an audit trail of how values were processed.
The wrapper system includes convenient methods for converting between wrapped and unwrapped values. The extension methods like INT() , FLOAT() , etc., make it easy to wrap existing values, while the from_INT() , from_FLOAT() methods extract the underlying values when needed. The has_error() method provides a consistent interface for checking whether any wrapped value has encountered issues during processing.
The Log Object: Your Debugging Companion
The Log object represents the heart of Light Log's debugging capabilities. Unlike simple string concatenation for error messages, the Log object provides a structured approach to building, modifying, and rendering diagnostic information.
Each Log object carries three essential pieces of information: an error type (info, warning, error, or runtime_error), a message string that can be built incrementally, and an active flag that controls conditional rendering. This structure enables sophisticated logging patterns where you can build up detailed diagnostic information throughout your script's execution and decide later whether and how to display it.
The Log object's methods support fluent chaining, allowing you to build complex messages in a readable way. The write() and write_line() methods append text to the log, while new_line() adds formatting. The clear() method resets the log for reuse, and the rendering methods ( render_now() , render_condition() , and the general render() ) control when and how messages appear.
Defensive Programming Made Easy
Light Log's argument validation functions transform how you write defensive code. Instead of cluttering your functions with verbose validation logic, you can use concise, self-documenting calls that make your intentions clear.
The argument_error() function provides strict validation that halts execution when conditions aren't met – perfect for catching programming errors early. For less critical issues, argument_log_warning() and argument_log_error() record problems without stopping execution, while argument_log_info() provides debug visibility into your function's behavior.
These functions follow a consistent pattern: they take a condition to check, the function name, the argument name, and a descriptive message. This consistency makes error messages predictable and helpful, automatically formatting them to show exactly where problems occurred.
Building Modular, Reusable Code
Light Log encourages a modular approach to Pine Script development by providing tools that make functions more self-contained and reliable. When functions validate their inputs and return wrapped values with error information, they become true black boxes that can be safely composed into larger systems.
The void_return() function addresses Pine Script's requirement that all code paths return a value, even in error handling branches. This utility function provides a clean way to satisfy the compiler while making it clear that a particular code path should never execute.
The static log pattern, initialized with init_static_log() , enables module-wide error tracking. You can create a persistent Log object that accumulates information across multiple function calls, building a comprehensive diagnostic report that helps you understand complex behaviors in your indicators and strategies.
Real-World Applications
In practice, Light Log shines when building sophisticated trading systems. Imagine developing a complex indicator that processes multiple data streams, performs statistical calculations, and generates trading signals. With Light Log, each processing stage can validate its inputs, perform calculations, and pass along both results and diagnostic information.
For example, a moving average calculation might check that the period is positive, that sufficient data exists, and that the input series contains valid values. Instead of failing silently or throwing runtime errors, it can return a FLOAT object that contains either the calculated average or a detailed explanation of why the calculation couldn't be performed.
Strategy developers benefit even more from Light Log's capabilities. Complex entry and exit logic often involves multiple conditions that must all be satisfied. With Light Log, each condition check can contribute to a comprehensive log that explains exactly why a trade was or wasn't taken, making strategy debugging and optimization much more straightforward.
Performance Considerations
While Light Log adds a layer of abstraction over raw Pine Script values, its design minimizes performance impact. The wrapper objects are lightweight, containing only two fields. The logging operations only consume resources when actually rendered, and the conditional rendering system ensures that production code can run with logging disabled for maximum performance.
The library follows Pine Script best practices for performance, using appropriate data structures and avoiding unnecessary operations. The var keyword in init_static_log() ensures that persistent logs don't create new objects on every bar, maintaining efficiency even in real-time calculations.
Getting Started
Adopting Light Log in your Pine Script projects is straightforward. Import the library, wrap your critical values, add validation to your functions, and use Log objects to track important events. Start small by adding logging to a single function, then expand as you see the benefits of better error visibility and code organization.
Remember that Light Log is designed to grow with your needs. You can use as much or as little of its functionality as makes sense for your project. Even simple uses, like adding argument validation to key functions, can significantly improve code reliability and debugging ease.
Transform your Pine Script development experience with Light Log – because professional trading systems deserve professional development tools.
Light Log Technical Deep Dive: Advanced Patterns and Architecture
Understanding Errors as Values
The concept of "errors as values" represents a fundamental shift in how we think about error handling in Pine Script. In traditional Pine Script development, errors are events – they happen at a specific moment in time and immediately interrupt program flow. Light Log transforms errors into data – they become information that flows through your program just like any other value.
This transformation has profound implications. When errors are values, they can be stored, passed between functions, accumulated, transformed, and inspected. They become part of your program's data flow rather than exceptions to it. This approach, popularized by languages like Rust with its Result type and Haskell with its Either monad, brings functional programming's elegance to Pine Script.
Consider a practical example. Traditional Pine Script might calculate a momentum indicator like this:
momentum = close - close
If period is invalid or if there isn't enough historical data, this calculation might produce na or cause subtle bugs. With Light Log's approach:
calculate_momentum(src, period)=>
result = src.FLOAT()
if period <= 0
result.e.write("Invalid period: must be positive", true, ErrorType.error)
result.v := na
else if bar_index < period
result.e.write("Insufficient data: need " + str.tostring(period) + " bars", true, ErrorType.warning)
result.v := na
else
result.v := src - src
result.e.write("Momentum calculated successfully", false, ErrorType.info)
result
Now the function returns not just a value but a complete computational result that includes diagnostic information. Calling code can make intelligent decisions based on both the value and its associated metadata.
The Monad Pattern in Pine Script
While Pine Script lacks the type system features to implement true monads, Light Log brings monadic thinking to Pine Script development. The wrapped types (INT, FLOAT, etc.) act as computational contexts that carry both values and metadata through a series of transformations.
The key insight of monadic programming is that you can chain operations while automatically propagating context. In Light Log, this context is the error state. When you have a FLOAT that contains an error, operations on that FLOAT can check the error state and decide whether to proceed or propagate the error.
This pattern enables what functional programmers call "railway-oriented programming" – your code follows a success track when all is well but can switch to an error track when problems occur. Both tracks lead to the same destination (a result with error information), but they take different paths based on the validity of intermediate values.
Composable Error Handling
Light Log's design encourages composition – building complex functionality from simpler, well-tested components. Each component can validate its inputs, perform its calculation, and return a result with appropriate error information. Higher-level functions can then combine these results intelligently.
Consider building a complex trading signal from multiple indicators:
generate_signal(src, fast_period, slow_period, signal_period) =>
log = init_static_log(ErrorType.info)
// Calculate components with error tracking
fast_ma = calculate_ma(src, fast_period)
slow_ma = calculate_ma(src, slow_period)
// Check for errors in components
if fast_ma.has_error()
log.write_line("Fast MA error: " + fast_ma.e.message, true)
if slow_ma.has_error()
log.write_line("Slow MA error: " + slow_ma.e.message, true)
// Proceed with calculation if no errors
signal = 0.0.FLOAT()
if not (fast_ma.has_error() or slow_ma.has_error())
macd_line = fast_ma.v - slow_ma.v
signal_line = calculate_ma(macd_line, signal_period)
if signal_line.has_error()
log.write_line("Signal line error: " + signal_line.e.message, true)
signal.e := log
else
signal.v := macd_line - signal_line.v
log.write("Signal generated successfully")
else
signal.e := log
signal.v := na
signal
This composable approach makes complex calculations more reliable and easier to debug. Each component is responsible for its own validation and error reporting, and the composite function orchestrates these components while maintaining comprehensive error tracking.
The Static Log Pattern
The init_static_log() function introduces a powerful pattern for maintaining state across function calls. In Pine Script, the var keyword creates variables that persist across bars but are initialized only once. Light Log leverages this to create logging objects that can accumulate information throughout a script's execution.
This pattern is particularly valuable for debugging complex strategies where you need to understand behavior across multiple bars. You can create module-level logs that track important events:
// Module-level diagnostic log
diagnostics = init_static_log(ErrorType.info)
// Track strategy decisions across bars
check_entry_conditions() =>
diagnostics.clear() // Start fresh each bar
diagnostics.write_line("Bar " + str.tostring(bar_index) + " analysis:")
if close > sma(close, 20)
diagnostics.write_line("Price above SMA20", false)
else
diagnostics.write_line("Price below SMA20 - no entry", true, ErrorType.warning)
if volume > sma(volume, 20) * 1.5
diagnostics.write_line("Volume surge detected", false)
else
diagnostics.write_line("Normal volume", false)
// Render diagnostics based on verbosity setting
if debug_mode
diagnostics.render_now()
Advanced Validation Patterns
Light Log's argument validation functions enable sophisticated precondition checking that goes beyond simple null checks. You can implement complex validation logic while keeping your code readable:
validate_price_data(open_val, high_val, low_val, close_val) =>
argument_error(na(open_val) or na(high_val) or na(low_val) or na(close_val),
"validate_price_data", "OHLC values", "contain na values")
argument_error(high_val < low_val,
"validate_price_data", "high/low", "high is less than low")
argument_error(close_val > high_val or close_val < low_val,
"validate_price_data", "close", "is outside high/low range")
argument_log_warning(high_val == low_val,
"validate_price_data", "high/low", "are equal (no range)")
This validation function documents its requirements clearly and fails fast with helpful error messages when assumptions are violated. The mix of errors (which halt execution) and warnings (which allow continuation) provides fine-grained control over how strict your validation should be.
Performance Optimization Strategies
While Light Log adds abstraction, careful design minimizes overhead. Understanding Pine Script's execution model helps you use Light Log efficiently.
Pine Script executes once per bar, so operations that seem expensive in traditional programming might have negligible impact. However, when building real-time systems, every optimization matters. Light Log provides several patterns for efficient use:
Lazy Evaluation: Log messages are only built when they'll be rendered. Use conditional logging to avoid string concatenation in production:
if debug_mode
log.write_line("Calculated value: " + str.tostring(complex_calculation))
Selective Wrapping: Not every value needs error tracking. Wrap values at API boundaries and critical calculation points, but use raw values for simple operations:
// Wrap at boundaries
input_price = close.FLOAT()
validated_period = validate_period(input_period).INT()
// Use raw values internally
sum = 0.0
for i = 0 to validated_period.v - 1
sum += close
Error Propagation: When errors occur early, avoid expensive calculations:
process_data(input) =>
validated = validate_input(input)
if validated.has_error()
validated // Return early with error
else
// Expensive processing only if valid
perform_complex_calculation(validated)
Integration Patterns
Light Log integrates smoothly with existing Pine Script code. You can adopt it incrementally, starting with critical functions and expanding coverage as needed.
Boundary Validation: Add Light Log at the boundaries of your system – where user input enters and where final outputs are produced. This catches most errors while minimizing changes to existing code.
Progressive Enhancement: Start by adding argument validation to existing functions. Then wrap return values. Finally, add comprehensive logging. Each step improves reliability without requiring a complete rewrite.
Testing and Debugging: Use Light Log's conditional rendering to create debug modes for your scripts. Production users see clean output while developers get detailed diagnostics:
// User input for debug mode
debug = input.bool(false, "Enable debug logging")
// Conditional diagnostic output
if debug
diagnostics.render_now()
else
diagnostics.render_condition() // Only shows errors/warnings
Future-Proofing Your Code
Light Log's patterns prepare your code for Pine Script's evolution. As Pine Script adds more sophisticated features, code that uses structured error handling and defensive programming will adapt more easily than code that relies on implicit assumptions.
The type wrapper system, in particular, positions your code to take advantage of potential future features or more sophisticated type inference. By thinking in terms of wrapped values and error propagation today, you're building code that will remain maintainable and extensible tomorrow.
Light Log doesn't just make your Pine Script better today – it prepares it for the trading systems you'll need to build tomorrow.
Library "light_log"
A lightweight logging and defensive programming library for Pine Script.
Designed for modular and extensible scripts, this utility provides structured runtime validation,
conditional logging, and reusable `Log` objects for centralized error propagation.
It also introduces a typed wrapping system for all native Pine values (e.g., `INT`, `FLOAT`, `LABEL`),
allowing values to carry errors alongside data. This enables functional-style flows with built-in
validation tracking, error detection (`has_error()`), and fluent chaining.
Inspired by structured logging patterns found in systems like C#, it reduces boilerplate,
enforces argument safety, and encourages clean, maintainable code architecture.
method INT(self, error_type)
Wraps an `int` value into an `INT` struct with an optional log severity.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The raw `int` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: An `INT` object containing the value and a default Log instance.
method FLOAT(self, error_type)
Wraps a `float` value into a `FLOAT` struct with an optional log severity.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : The raw `float` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `FLOAT` object containing the value and a default Log instance.
method BOOL(self, error_type)
Wraps a `bool` value into a `BOOL` struct with an optional log severity.
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
self (bool) : The raw `bool` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `BOOL` object containing the value and a default Log instance.
method STRING(self, error_type)
Wraps a `string` value into a `STRING` struct with an optional log severity.
Namespace types: series string, simple string, input string, const string
Parameters:
self (string) : The raw `string` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `STRING` object containing the value and a default Log instance.
method COLOR(self, error_type)
Wraps a `color` value into a `COLOR` struct with an optional log severity.
Namespace types: series color, simple color, input color, const color
Parameters:
self (color) : The raw `color` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `COLOR` object containing the value and a default Log instance.
method LINE(self, error_type)
Wraps a `line` object into a `LINE` struct with an optional log severity.
Namespace types: series line
Parameters:
self (line) : The raw `line` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `LINE` object containing the value and a default Log instance.
method LABEL(self, error_type)
Wraps a `label` object into a `LABEL` struct with an optional log severity.
Namespace types: series label
Parameters:
self (label) : The raw `label` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `LABEL` object containing the value and a default Log instance.
method BOX(self, error_type)
Wraps a `box` object into a `BOX` struct with an optional log severity.
Namespace types: series box
Parameters:
self (box) : The raw `box` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `BOX` object containing the value and a default Log instance.
method TABLE(self, error_type)
Wraps a `table` object into a `TABLE` struct with an optional log severity.
Namespace types: series table
Parameters:
self (table) : The raw `table` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `TABLE` object containing the value and a default Log instance.
method CHART_POINT(self, error_type)
Wraps a `chart.point` value into a `CHART_POINT` struct with an optional log severity.
Namespace types: chart.point
Parameters:
self (chart.point) : The raw `chart.point` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `CHART_POINT` object containing the value and a default Log instance.
method POLYLINE(self, error_type)
Wraps a `polyline` object into a `POLYLINE` struct with an optional log severity.
Namespace types: series polyline, series polyline, series polyline, series polyline
Parameters:
self (polyline) : The raw `polyline` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `POLYLINE` object containing the value and a default Log instance.
method LINEFILL(self, error_type)
Wraps a `linefill` object into a `LINEFILL` struct with an optional log severity.
Namespace types: series linefill
Parameters:
self (linefill) : The raw `linefill` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `LINEFILL` object containing the value and a default Log instance.
method from_INT(self)
Extracts the integer value from an INT wrapper.
Namespace types: INT
Parameters:
self (INT) : The wrapped INT instance.
Returns: The underlying `int` value.
method from_FLOAT(self)
Extracts the float value from a FLOAT wrapper.
Namespace types: FLOAT
Parameters:
self (FLOAT) : The wrapped FLOAT instance.
Returns: The underlying `float` value.
method from_BOOL(self)
Extracts the boolean value from a BOOL wrapper.
Namespace types: BOOL
Parameters:
self (BOOL) : The wrapped BOOL instance.
Returns: The underlying `bool` value.
method from_STRING(self)
Extracts the string value from a STRING wrapper.
Namespace types: STRING
Parameters:
self (STRING) : The wrapped STRING instance.
Returns: The underlying `string` value.
method from_COLOR(self)
Extracts the color value from a COLOR wrapper.
Namespace types: COLOR
Parameters:
self (COLOR) : The wrapped COLOR instance.
Returns: The underlying `color` value.
method from_LINE(self)
Extracts the line object from a LINE wrapper.
Namespace types: LINE
Parameters:
self (LINE) : The wrapped LINE instance.
Returns: The underlying `line` object.
method from_LABEL(self)
Extracts the label object from a LABEL wrapper.
Namespace types: LABEL
Parameters:
self (LABEL) : The wrapped LABEL instance.
Returns: The underlying `label` object.
method from_BOX(self)
Extracts the box object from a BOX wrapper.
Namespace types: BOX
Parameters:
self (BOX) : The wrapped BOX instance.
Returns: The underlying `box` object.
method from_TABLE(self)
Extracts the table object from a TABLE wrapper.
Namespace types: TABLE
Parameters:
self (TABLE) : The wrapped TABLE instance.
Returns: The underlying `table` object.
method from_CHART_POINT(self)
Extracts the chart.point from a CHART_POINT wrapper.
Namespace types: CHART_POINT
Parameters:
self (CHART_POINT) : The wrapped CHART_POINT instance.
Returns: The underlying `chart.point` value.
method from_POLYLINE(self)
Extracts the polyline object from a POLYLINE wrapper.
Namespace types: POLYLINE
Parameters:
self (POLYLINE) : The wrapped POLYLINE instance.
Returns: The underlying `polyline` object.
method from_LINEFILL(self)
Extracts the linefill object from a LINEFILL wrapper.
Namespace types: LINEFILL
Parameters:
self (LINEFILL) : The wrapped LINEFILL instance.
Returns: The underlying `linefill` object.
method has_error(self)
Returns true if the INT wrapper has an active log entry.
Namespace types: INT
Parameters:
self (INT) : The INT instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the FLOAT wrapper has an active log entry.
Namespace types: FLOAT
Parameters:
self (FLOAT) : The FLOAT instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the BOOL wrapper has an active log entry.
Namespace types: BOOL
Parameters:
self (BOOL) : The BOOL instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the STRING wrapper has an active log entry.
Namespace types: STRING
Parameters:
self (STRING) : The STRING instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the COLOR wrapper has an active log entry.
Namespace types: COLOR
Parameters:
self (COLOR) : The COLOR instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the LINE wrapper has an active log entry.
Namespace types: LINE
Parameters:
self (LINE) : The LINE instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the LABEL wrapper has an active log entry.
Namespace types: LABEL
Parameters:
self (LABEL) : The LABEL instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the BOX wrapper has an active log entry.
Namespace types: BOX
Parameters:
self (BOX) : The BOX instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the TABLE wrapper has an active log entry.
Namespace types: TABLE
Parameters:
self (TABLE) : The TABLE instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the CHART_POINT wrapper has an active log entry.
Namespace types: CHART_POINT
Parameters:
self (CHART_POINT) : The CHART_POINT instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the POLYLINE wrapper has an active log entry.
Namespace types: POLYLINE
Parameters:
self (POLYLINE) : The POLYLINE instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the LINEFILL wrapper has an active log entry.
Namespace types: LINEFILL
Parameters:
self (LINEFILL) : The LINEFILL instance to check.
Returns: True if an error or message is active in the log.
void_return()
Utility function used when a return is syntactically required but functionally unnecessary.
Returns: Nothing. Function never executes its body.
argument_error(condition, function, argument, message)
Throws a runtime error when a condition is met. Used for strict argument validation.
Parameters:
condition (bool) : Boolean expression that triggers the runtime error.
function (string) : Name of the calling function (for formatting).
argument (string) : Name of the problematic argument.
message (string) : Description of the error cause.
Returns: Never returns. Halts execution if the condition is true.
argument_log_info(condition, function, argument, message)
Logs an informational message when a condition is met. Used for optional debug visibility.
Parameters:
condition (bool) : Boolean expression that triggers the log.
function (string) : Name of the calling function.
argument (string) : Argument name being referenced.
message (string) : Informational message to log.
Returns: Nothing. Logs if the condition is true.
argument_log_warning(condition, function, argument, message)
Logs a warning when a condition is met. Non-fatal but highlights potential issues.
Parameters:
condition (bool) : Boolean expression that triggers the warning.
function (string) : Name of the calling function.
argument (string) : Argument name being referenced.
message (string) : Warning message to log.
Returns: Nothing. Logs if the condition is true.
argument_log_error(condition, function, argument, message)
Logs an error message when a condition is met. Does not halt execution.
Parameters:
condition (bool) : Boolean expression that triggers the error log.
function (string) : Name of the calling function.
argument (string) : Argument name being referenced.
message (string) : Error message to log.
Returns: Nothing. Logs if the condition is true.
init_static_log(error_type, message, active)
Initializes a persistent (var) Log object. Ideal for global logging in scripts or modules.
Parameters:
error_type (series ErrorType) : Initial severity level (required).
message (string) : Optional starting message string. Default value of ("").
active (bool) : Whether the log should be flagged active on initialization. Default value of (false).
Returns: A static Log object with the given parameters.
method new_line(self)
Appends a newline character to the Log message. Useful for separating entries during chained writes.
Namespace types: Log
Parameters:
self (Log) : The Log instance to modify.
Returns: The updated Log object with a newline appended.
method write(self, message, flag_active, error_type)
Appends a message to a Log object without a newline. Updates severity and active state if specified.
Namespace types: Log
Parameters:
self (Log) : The Log instance being modified.
message (string) : The text to append to the log.
flag_active (bool) : Whether to activate the log for conditional rendering. Default value of (false).
error_type (series ErrorType) : Optional override for the severity level. Default value of (na).
Returns: The updated Log object.
method write_line(self, message, flag_active, error_type)
Appends a message to a Log object, prefixed with a newline for clarity.
Namespace types: Log
Parameters:
self (Log) : The Log instance being modified.
message (string) : The text to append to the log.
flag_active (bool) : Whether to activate the log for conditional rendering. Default value of (false).
error_type (series ErrorType) : Optional override for the severity level. Default value of (na).
Returns: The updated Log object.
method clear(self, flag_active, error_type)
Clears a Log object’s message and optionally reactivates it. Can also update the error type.
Namespace types: Log
Parameters:
self (Log) : The Log instance being cleared.
flag_active (bool) : Whether to activate the log after clearing. Default value of (false).
error_type (series ErrorType) : Optional new error type to assign. If not provided, the previous type is retained. Default value of (na).
Returns: The cleared Log object.
method render_condition(self, flag_active, error_type)
Conditionally renders the log if it is active. Allows overriding error type and controlling active state afterward.
Namespace types: Log
Parameters:
self (Log) : The Log instance to evaluate and render.
flag_active (bool) : Whether to activate the log after rendering. Default value of (false).
error_type (series ErrorType) : Optional error type override. Useful for contextual formatting just before rendering. Default value of (na).
Returns: The updated Log object.
method render_now(self, flag_active, error_type)
Immediately renders the log regardless of `active` state. Allows overriding error type and active flag.
Namespace types: Log
Parameters:
self (Log) : The Log instance to render.
flag_active (bool) : Whether to activate the log after rendering. Default value of (false).
error_type (series ErrorType) : Optional error type override. Allows dynamic severity adjustment at render time. Default value of (na).
Returns: The updated Log object.
render(self, condition, flag_active, error_type)
Renders the log conditionally or unconditionally. Allows full control over render behavior.
Parameters:
self (Log) : The Log instance to render.
condition (bool) : If true, renders only if the log is active. If false, always renders. Default value of (false).
flag_active (bool) : Whether to activate the log after rendering. Default value of (false).
error_type (series ErrorType) : Optional error type override passed to the render methods. Default value of (na).
Returns: The updated Log object.
Log
A structured object used to store and render logging messages.
Fields:
error_type (series ErrorType) : The severity level of the message (from the ErrorType enum).
message (series string) : The text of the log message.
active (series bool) : Whether the log should trigger rendering when conditionally evaluated.
INT
A wrapped integer type with attached logging for validation or tracing.
Fields:
v (series int) : The underlying `int` value.
e (Log) : Optional log object describing validation status or error context.
FLOAT
A wrapped float type with attached logging for validation or tracing.
Fields:
v (series float) : The underlying `float` value.
e (Log) : Optional log object describing validation status or error context.
BOOL
A wrapped boolean type with attached logging for validation or tracing.
Fields:
v (series bool) : The underlying `bool` value.
e (Log) : Optional log object describing validation status or error context.
STRING
A wrapped string type with attached logging for validation or tracing.
Fields:
v (series string) : The underlying `string` value.
e (Log) : Optional log object describing validation status or error context.
COLOR
A wrapped color type with attached logging for validation or tracing.
Fields:
v (series color) : The underlying `color` value.
e (Log) : Optional log object describing validation status or error context.
LINE
A wrapped line object with attached logging for validation or tracing.
Fields:
v (series line) : The underlying `line` value.
e (Log) : Optional log object describing validation status or error context.
LABEL
A wrapped label object with attached logging for validation or tracing.
Fields:
v (series label) : The underlying `label` value.
e (Log) : Optional log object describing validation status or error context.
BOX
A wrapped box object with attached logging for validation or tracing.
Fields:
v (series box) : The underlying `box` value.
e (Log) : Optional log object describing validation status or error context.
TABLE
A wrapped table object with attached logging for validation or tracing.
Fields:
v (series table) : The underlying `table` value.
e (Log) : Optional log object describing validation status or error context.
CHART_POINT
A wrapped chart point with attached logging for validation or tracing.
Fields:
v (chart.point) : The underlying `chart.point` value.
e (Log) : Optional log object describing validation status or error context.
POLYLINE
A wrapped polyline object with attached logging for validation or tracing.
Fields:
v (series polyline) : The underlying `polyline` value.
e (Log) : Optional log object describing validation status or error context.
LINEFILL
A wrapped linefill object with attached logging for validation or tracing.
Fields:
v (series linefill) : The underlying `linefill` value.
e (Log) : Optional log object describing validation status or error context.
Volatility Quality [Alpha Extract]The Alpha-Extract Volatility Quality (AVQ) Indicator provides traders with deep insights into market volatility by measuring the directional strength of price movements. This sophisticated momentum-based tool helps identify overbought and oversold conditions, offering actionable buy and sell signals based on volatility trends and standard deviation bands.
🔶 CALCULATION
The indicator processes volatility quality data through a series of analytical steps:
Bar Range Calculation: Measures true range (TR) to capture price volatility.
Directional Weighting: Applies directional bias (positive for bullish candles, negative for bearish) to the true range.
VQI Computation: Uses an exponential moving average (EMA) of weighted volatility to derive the Volatility Quality Index (VQI).
vqiRaw = ta.ema(weightedVol, vqiLen)
Smoothing: Applies an additional EMA to smooth the VQI for clearer signals.
Normalization: Optionally normalizes VQI to a -100/+100 scale based on historical highs and lows.
Standard Deviation Bands: Calculates three upper and lower bands using standard deviation multipliers for volatility thresholds.
vqiStdev = ta.stdev(vqiSmoothed, vqiLen)
upperBand1 = vqiSmoothed + (vqiStdev * stdevMultiplier1)
upperBand2 = vqiSmoothed + (vqiStdev * stdevMultiplier2)
upperBand3 = vqiSmoothed + (vqiStdev * stdevMultiplier3)
lowerBand1 = vqiSmoothed - (vqiStdev * stdevMultiplier1)
lowerBand2 = vqiSmoothed - (vqiStdev * stdevMultiplier2)
lowerBand3 = vqiSmoothed - (vqiStdev * stdevMultiplier3)
Signal Generation: Produces overbought/oversold signals when VQI reaches extreme levels (±200 in normalized mode).
Formula:
Bar Range = True Range (TR)
Weighted Volatility = Bar Range × (Close > Open ? 1 : Close < Open ? -1 : 0)
VQI Raw = EMA(Weighted Volatility, VQI Length)
VQI Smoothed = EMA(VQI Raw, Smoothing Length)
VQI Normalized = ((VQI Smoothed - Lowest VQI) / (Highest VQI - Lowest VQI) - 0.5) × 200
Upper Band N = VQI Smoothed + (StdDev(VQI Smoothed, VQI Length) × Multiplier N)
Lower Band N = VQI Smoothed - (StdDev(VQI Smoothed, VQI Length) × Multiplier N)
🔶 DETAILS
Visual Features:
VQI Plot: Displays VQI as a line or histogram (lime for positive, red for negative).
Standard Deviation Bands: Plots three upper and lower bands (teal for upper, grayscale for lower) to indicate volatility thresholds.
Reference Levels: Horizontal lines at 0 (neutral), +100, and -100 (in normalized mode) for context.
Zone Highlighting: Overbought (⋎ above bars) and oversold (⋏ below bars) signals for extreme VQI levels (±200 in normalized mode).
Candle Coloring: Optional candle overlay colored by VQI direction (lime for positive, red for negative).
Interpretation:
VQI ≥ 200 (Normalized): Overbought condition, strong sell signal.
VQI 100–200: High volatility, potential selling opportunity.
VQI 0–100: Neutral bullish momentum.
VQI 0 to -100: Neutral bearish momentum.
VQI -100 to -200: High volatility, strong bearish momentum.
VQI ≤ -200 (Normalized): Oversold condition, strong buy signal.
🔶 EXAMPLES
Overbought Signal Detection: When VQI exceeds 200 (normalized), the indicator flags potential market tops with a red ⋎ symbol.
Example: During strong uptrends, VQI reaching 200 has historically preceded corrections, allowing traders to secure profits.
Oversold Signal Detection: When VQI falls below -200 (normalized), a lime ⋏ symbol highlights potential buying opportunities.
Example: In bearish markets, VQI dropping below -200 has marked reversal points for profitable long entries.
Volatility Trend Tracking: The VQI plot and bands help traders visualize shifts in market momentum.
Example: A rising VQI crossing above zero with widening bands indicates strengthening bullish momentum, guiding traders to hold or enter long positions.
Dynamic Support/Resistance: Standard deviation bands act as dynamic volatility thresholds during price movements.
Example: Price reversals often occur near the third standard deviation bands, providing reliable entry/exit points during volatile periods.
🔶 SETTINGS
Customization Options:
VQI Length: Adjust the EMA period for VQI calculation (default: 14, range: 1–50).
Smoothing Length: Set the EMA period for smoothing (default: 5, range: 1–50).
Standard Deviation Multipliers: Customize multipliers for bands (defaults: 1.0, 2.0, 3.0).
Normalization: Toggle normalization to -100/+100 scale and adjust lookback period (default: 200, min: 50).
Display Style: Switch between line or histogram plot for VQI.
Candle Overlay: Enable/disable VQI-colored candles (lime for positive, red for negative).
The Alpha-Extract Volatility Quality Indicator empowers traders with a robust tool to navigate market volatility. By combining directional price range analysis with smoothed volatility metrics, it identifies overbought and oversold conditions, offering clear buy and sell signals. The customizable standard deviation bands and optional normalization provide precise context for market conditions, enabling traders to make informed decisions across various market cycles.
Market Balance LevelMarket Balance Level (MBL)
This indicator dynamically identifies price consolidation zones (market balance levels) and plots a horizontal line at the average midpoint of the range once a valid breakout occurs. It helps traders visualize key zones where the market was previously in equilibrium and is likely to retest before continuing its trend.
How It Works:
Detects consolidation ranges using consecutive candles within a tight high-low structure.
When a breakout occurs (above or below the range), it plots a line at the average midpoint of the consolidation.
Triangles are drawn on breakouts to visually confirm the breakout direction.
Lines can be customized by color, width, and breakout direction (bullish, bearish, or both).
Recommended Use:
Wait for price to return to the Market Balance Level (MBL). These levels often act as strong support or resistance.
Enter upon engulfment (candle closes strongly in the direction of the breakout), confirming continuation.
Features:
Adjustable consolidation sensitivity and line length.
Option to show/hide bullish or bearish MBLs.
Visual breakout markers (triangles) with alert support.
Optional alert messages for breakout events.
Use this tool to enhance your structure-based or SMC-style trading strategies.
Squeeze Pro Momentum BAR color - KLTDescription:
The Squeeze Pro Momentum indicator is a powerful tool designed to detect volatility compression ("squeeze" zones) and visualize momentum shifts using a refined color-based system. This script blends the well-known concepts of Bollinger Bands and Keltner Channels with an optimized momentum engine that uses dynamic color gradients to reflect trend strength, direction, and volatility.
It’s built for traders who want early warning of potential breakouts and clearer insight into underlying market momentum.
🔍 How It Works:
📉 Squeeze Detection:
This indicator identifies "squeeze" conditions by comparing Bollinger Bands and Keltner Channels:
When Bollinger Bands are inside Keltner Channels → Squeeze is ON
When Bollinger Bands expand outside Keltner Channels → Squeeze is OFF
You’ll see squeeze zones classified as:
Wide
Normal
Narrow
Each represents varying levels of compression and breakout potential.
⚡ Momentum Engine:
Momentum is calculated using linear regression of the price's deviation from a dynamic average of highs, lows, and closes. This gives a more accurate representation of directional pressure in the market.
🧠 Smart Candle Coloring (Optimized):
The momentum color logic is inspired by machine learning principles (no hardcoded thresholds):
EMA smoothing and rate of change (ROC) are used to detect momentum acceleration.
ATR-based filters help remove noise and false signals.
Colors are dynamically assigned based on both direction and trend strength.
🧪 How to Use It:
Look for Squeeze Conditions — especially narrow squeezes, which tend to precede high-momentum breakouts.
Confirm with Momentum Color — strong colors often indicate trend continuation; fading colors may signal exhaustion.
Combine with Price Action — use this tool with support/resistance or patterns for higher probability setups.
Recommended For:
Trend Traders
Breakout Traders
Volatility Strategy Users
Anyone who wants visual clarity on trend strength
📌 Tip: This indicator works great when layered with volume and price action patterns. It is fully non-repainting and supports overlay on price charts.
Engulfing Candles LP v0.12An indicator designed to detect engulfing candles, with customizable tolerance settings. This allows you to adjust for differences in decimal precision across instruments—for example, XAU typically uses 2–3 decimal places, while EURUSD uses five.
The engulfing tolerance setting ensures the indicator works accurately across various markets.
Color coding:
Purple : Engulfing candles that are not at least twice the size of the previous candle.
Red/Green : Engulfing candles that are at least 2x larger than the previous candle (Green for bullish, Red for bearish).
Turtle God IndicatorThe Turtle God indicator displays a turtle icon 🐢 on the most recent candle only, helping traders track current candle behavior at a glance.
✅ Green Turtle above the candle if it’s bullish (close > open)
🔻 Red Turtle below the candle if it’s bearish (close < open)
📌 Only the latest candle is marked — no historical clutter
This tool is useful for:
Live price action observation
Real-time signal overlays
Clean chart setups with dynamic candle feedback
Range Trading Entry Signals (Trend Considered)# Range Market Entry Signal Indicator Guide
## Overview
This indicator is a custom TradingView indicator designed to identify effective entry points in range-bound (sideways) markets. It primarily uses RSI (Relative Strength Index) and visually displays range upper and lower bounds to provide counter-trend trading opportunities.
## Key Features
### 1. Range Identification Function
- **Range Upper/Lower Lines**: Automatically identifies ranges based on the highest and lowest values over a specified period (default 50 periods)
- **70% Line Display**: Shows positions at 30% from the top and bottom of the range, providing more precise entry points
### 2. RSI-Based Signal Generation
- **Buy Signal**: Triggered when RSI reverses after falling below the oversold line (default 30)
- **Sell Signal**: Triggered when RSI reverses after rising above the overbought line (default 80)
### 3. Moving Average Filter (Optional)
- Uses 20-period simple moving average as an auxiliary indicator
- Filtering function that considers trend direction
### 4. Information Display Table
- Current RSI value
- Range upper and lower bound values
- Moving average value
- Supports real-time market condition assessment
## Configuration Parameters
| Parameter | Default Value | Description |
|-----------|---------------|-------------|
| RSI Period | 14 | Period used for RSI calculation |
| RSI Oversold Line | 30 | Threshold for buy signals |
| RSI Overbought Line | 80 | Threshold for sell signals |
| Moving Average Period | 20 | Period for auxiliary moving average |
| Range Detection Period | 50 | Period for calculating range upper/lower bounds |
| Use Moving Average Filter | True | Enable/disable moving average filter |
## Entry Strategies and Usage Examples
### Basic Entry Methods
#### 🟢 Buy Entry
**Conditions**:
- RSI recovers above 31 after falling below 30
- (Optional) Current price is above the 20-period moving average
**Example**:
```
1. Price moves near the range lower bound
2. RSI drops to 28
3. Next candle shows RSI rising to 32 → Buy signal generated
4. Enter near the range lower 70% line
```
#### 🔴 Sell Entry
**Conditions**:
- RSI falls below 79 after rising above 80
- (Optional) Current price is below the 20-period moving average
**Example**:
```
1. Price moves near the range upper bound
2. RSI rises to 82
3. Next candle shows RSI falling to 78 → Sell signal generated
4. Enter near the range upper 70% line
```
### Profit-Taking Strategies
#### Pattern 1: Take Profit at Opposite Range Side
- **Long Positions**: Take profit at range upper bound or upper 70% line
- **Short Positions**: Take profit at range lower bound or lower 70% line
#### Pattern 2: Take Profit on RSI Reversal
- **Long Positions**: When RSI reaches 70-80 levels
- **Short Positions**: When RSI reaches 20-30 levels
#### Pattern 3: Take Profit on Moving Average Cross
- Partial profit-taking when price crosses the moving average in the opposite direction
### Risk Management
#### Stop Loss Placement
- **Long Positions**: Clear break below the range lower bound
- **Short Positions**: Clear break above the range upper bound
#### Position Size Adjustment
- Adjust position size according to range height (upper bound - lower bound)
- Larger positions for narrow ranges, smaller positions for wide ranges
## Optimal Market Conditions
### Suitable Markets
✅ **Range-bound (sideways) markets**
✅ **Markets with moderate volatility**
✅ **Markets with clear support and resistance levels**
### Markets to Avoid
❌ **Strong trending markets**
❌ **Extremely low volatility markets**
❌ **Before and after major economic announcements**
## Practical Usage Tips
### 1. Timeframe Selection
- **Day Trading**: 5-minute to 1-hour charts
- **Swing Trading**: 4-hour to daily charts
### 2. Combination with Other Indicators
- **Bollinger Bands**: Confirm range validity
- **MACD**: Assess trend strength
- **Volume**: Improve signal reliability
### 3. Important Considerations
- Don't rely on a single indicator; use multiple confirmation factors
- Adjust parameters according to changing market conditions
- Backtest historical performance before applying to live trading
## Summary
This indicator is a specialized tool for counter-trend strategies in range-bound markets. By combining RSI reversal signals with range lines, it can help identify efficient entry points. However, the key to success lies in correctly assessing market conditions and using appropriate risk management techniques in conjunction with the indicator.
HTF Candle Display (Evolution FX)HTF Candle Display (Evolution FX)
WHAT IT DOES
This tool overlays a **higher timeframe candle** (like Daily or Weekly) directly on your current lower timeframe chart (like 5m, 15m, 1h). It visually anchors current price action within its broader market context, ideal for traders using multi-timeframe confluence, liquidity mapping, or High-Timeframe-Based decision-making.
KEY FEATURES
Timeframe selection : Choose any higher timeframe (HTF) to display (e.g., D, W, M).
Dynamic candle placement : Position the HTF candle overlay away from price action using distance presets: `Close`, `Near`, `Far`, `Very Far`.
Adjustable thickness : Choose candle body width via `Thin`, `Thick`, or `Thicker` styles.
Fully customisable visuals : Set custom colours for bullish and bearish candles, borders, wicks, and labels.
Highlight box (optional) : Display a semi-transparent box aligned to the HTF candle's real time span.
Label with live countdown : Optionally show a floating label with timeframe info and time remaining in the HTF candle.
Previous candle display : Toggle to show or hide the prior HTF candle for better comparison.
HOW TO USE IT
Select your HTF (e.g., Daily) from the input dropdown.
Use "Distance From Price Action" to shift the visual away from the candles for a cleaner layout.
Adjust "Candle Width" to visually match your preferences.
Optionally toggle:
- "Show Previous Candle"
- "Show Label"
- "Highlight Current Day Price Action Box"
Customise your **colour scheme** to match your charting setup.
Recommended to use on charts like `15m`, `1h`, or `4h` for best visual clarity.
USE CASES
HTF liquidity hunting
Bias framing via daily/weekly structure
Institutional-style trading models
Scalping with macro trend context
Multifractal Forecast [ScorsoneEnterprises]Multifractal Forecast Indicator
The Multifractal Forecast is an indicator designed to model and forecast asset price movements using a multifractal framework. It uses concepts from fractal geometry and stochastic processes, specifically the Multifractal Model of Asset Returns (MMAR) and fractional Brownian motion (fBm), to generate price forecasts based on historical price data. The indicator visualizes potential future price paths as colored lines, providing traders with a probabilistic view of price trends over a specified trading time scale. Below is a detailed breakdown of the indicator’s functionality, inputs, calculations, and visualization.
Overview
Purpose: The indicator forecasts future price movements by simulating multiple price paths based on a multifractal model, which accounts for the complex, non-linear behavior of financial markets.
Key Concepts:
Multifractal Model of Asset Returns (MMAR): Models price movements as a multifractal process, capturing varying degrees of volatility and self-similarity across different time scales.
Fractional Brownian Motion (fBm): A generalization of Brownian motion that incorporates long-range dependence and self-similarity, controlled by the Hurst exponent.
Binomial Cascade: Used to model trading time, introducing heterogeneity in time scales to reflect market activity bursts.
Hurst Exponent: Measures the degree of long-term memory in the price series (persistence, randomness, or mean-reversion).
Rescaled Range (R/S) Analysis: Estimates the Hurst exponent to quantify the fractal nature of the price series.
Inputs
The indicator allows users to customize its behavior through several input parameters, each influencing the multifractal model and forecast generation:
Maximum Lag (max_lag):
Type: Integer
Default: 50
Minimum: 5
Purpose: Determines the maximum lag used in the rescaled range (R/S) analysis to calculate the Hurst exponent. A higher lag increases the sample size for Hurst estimation but may smooth out short-term dynamics.
2 to the n values in the Multifractal Model (n):
Type: Integer
Default: 4
Purpose: Defines the resolution of the multifractal model by setting the size of arrays used in calculations (N = 2^n). For example, n=4 results in N=16 data points. Larger n increases computational complexity and detail but may exceed Pine Script’s array size limits (capped at 100,000).
Multiplier for Binomial Cascade (m):
Type: Float
Default: 0.8
Purpose: Controls the asymmetry in the binomial cascade, which models trading time. The multiplier m (and its complement 2.0 - m) determines how mass is distributed across time scales. Values closer to 1 create more balanced cascades, while values further from 1 introduce more variability.
Length Scale for fBm (L):
Type: Float
Default: 100,000.0
Purpose: Scales the fractional Brownian motion output, affecting the amplitude of simulated price paths. Larger values increase the magnitude of forecasted price movements.
Cumulative Sum (cum):
Type: Integer (0 or 1)
Default: 1
Purpose: Toggles whether the fBm output is cumulatively summed (1=On, 0=Off). When enabled, the fBm series is accumulated to simulate a price path with memory, resembling a random walk with long-range dependence.
Trading Time Scale (T):
Type: Integer
Default: 5
Purpose: Defines the forecast horizon in bars (20 bars into the future). It also scales the binomial cascade’s output to align with the desired trading time frame.
Number of Simulations (num_simulations):
Type: Integer
Default: 5
Minimum: 1
Purpose: Specifies how many forecast paths are simulated and plotted. More simulations provide a broader range of possible price outcomes but increase computational load.
Core Calculations
The indicator combines several mathematical and statistical techniques to generate price forecasts. Below is a step-by-step explanation of its calculations:
Log Returns (lgr):
The indicator calculates log returns as math.log(close / close ) when both the current and previous close prices are positive. This measures the relative price change in a logarithmic scale, which is standard for financial time series analysis to stabilize variance.
Hurst Exponent Estimation (get_hurst_exponent):
Purpose: Estimates the Hurst exponent (H) to quantify the degree of long-term memory in the price series.
Method: Uses rescaled range (R/S) analysis:
For each lag from 2 to max_lag, the function calc_rescaled_range computes the rescaled range:
Calculate the mean of the log returns over the lag period.
Compute the cumulative deviation from the mean.
Find the range (max - min) of the cumulative deviation.
Divide the range by the standard deviation of the log returns to get the rescaled range.
The log of the rescaled range (log(R/S)) is regressed against the log of the lag (log(lag)) using the polyfit_slope function.
The slope of this regression is the Hurst exponent (H).
Interpretation:
H = 0.5: Random walk (no memory, like standard Brownian motion).
H > 0.5: Persistent behavior (trends tend to continue).
H < 0.5: Mean-reverting behavior (price tends to revert to the mean).
Fractional Brownian Motion (get_fbm):
Purpose: Generates a fractional Brownian motion series to model price movements with long-range dependence.
Inputs: n (array size 2^n), H (Hurst exponent), L (length scale), cum (cumulative sum toggle).
Method:
Computes covariance for fBm using the formula: 0.5 * (|i+1|^(2H) - 2 * |i|^(2H) + |i-1|^(2H)).
Uses Hosking’s method (referenced from Columbia University’s implementation) to generate fBm:
Initializes arrays for covariance (cov), intermediate calculations (phi, psi), and output.
Iteratively computes the fBm series by incorporating a random term scaled by the variance (v) and covariance structure.
Applies scaling based on L / N^H to adjust the amplitude.
Optionally applies cumulative summation if cum = 1 to produce a path with memory.
Output: An array of 2^n values representing the fBm series.
Binomial Cascade (get_binomial_cascade):
Purpose: Models trading time (theta) to account for non-uniform market activity (e.g., bursts of volatility).
Inputs: n (array size 2^n), m (multiplier), T (trading time scale).
Method:
Initializes an array of size 2^n with values of 1.0.
Iteratively applies a binomial cascade:
For each block (from 0 to n-1), splits the array into segments.
Randomly assigns a multiplier (m or 2.0 - m) to each segment, redistributing mass.
Normalizes the array by dividing by its sum and scales by T.
Checks for array size limits to prevent Pine Script errors.
Output: An array (theta) representing the trading time, which warps the fBm to reflect market activity.
Interpolation (interpolate_fbm):
Purpose: Maps the fBm series to the trading time scale to produce a forecast.
Method:
Computes the cumulative sum of theta and normalizes it to .
Interpolates the fBm series linearly based on the normalized trading time.
Ensures the output aligns with the trading time scale (T).
Output: An array of interpolated fBm values representing log returns over the forecast horizon.
Price Path Generation:
For each simulation (up to num_simulations):
Generates an fBm series using get_fbm.
Interpolates it with the trading time (theta) using interpolate_fbm.
Converts log returns to price levels:
Starts with the current close price.
For each step i in the forecast horizon (T), computes the price as prev_price * exp(log_return).
Output: An array of price levels for each simulation.
Visualization:
Trigger: Updates every T bars when the bar state is confirmed (barstate.isconfirmed).
Process:
Clears previous lines from line_array.
For each simulation, plots a line from the current bar’s close price to the forecasted price at bar_index + T.
Colors the line using a gradient (color.from_gradient) based on the final forecasted price relative to the minimum and maximum forecasted prices across all simulations (red for lower prices, teal for higher prices).
Output: Multiple colored lines on the chart, each representing a possible price path over the next T bars.
How It Works on the Chart
Initialization: On each bar, the indicator calculates the Hurst exponent (H) using historical log returns and prepares the trading time (theta) using the binomial cascade.
Forecast Generation: Every T bars, it generates num_simulations price paths:
Each path starts at the current close price.
Uses fBm to model log returns, warped by the trading time.
Converts log returns to price levels.
Plotting: Draws lines from the current bar to the forecasted price T bars ahead, with colors indicating relative price levels.
Dynamic Updates: The forecast updates every T bars, replacing old lines with new ones based on the latest price data and calculations.
Key Features
Multifractal Modeling: Captures complex market dynamics by combining fBm (long-range dependence) with a binomial cascade (non-uniform time).
Customizable Parameters: Allows users to adjust the forecast horizon, model resolution, scaling, and number of simulations.
Probabilistic Forecast: Multiple simulations provide a range of possible price outcomes, helping traders assess uncertainty.
Visual Clarity: Gradient-colored lines make it easy to distinguish bullish (teal) and bearish (red) forecasts.
Potential Use Cases
Trend Analysis: Identify potential price trends or reversals based on the direction and spread of forecast lines.
Risk Assessment: Evaluate the range of possible price outcomes to gauge market uncertainty.
Volatility Analysis: The Hurst exponent and binomial cascade provide insights into market persistence and volatility clustering.
Limitations
Computational Intensity: Large values of n or num_simulations may slow down execution or hit Pine Script’s array size limits.
Randomness: The binomial cascade and fBm rely on random terms (math.random), which may lead to variability between runs.
Assumptions: The model assumes log-normal price movements and fractal behavior, which may not always hold in extreme market conditions.
Adjusting Inputs:
Set max_lag based on the desired depth of historical analysis.
Adjust n for model resolution (start with 4–6 to avoid performance issues).
Tune m to control trading time variability (0.5–1.5 is typical).
Set L to scale the forecast amplitude (experiment with values like 10,000–1,000,000).
Choose T based on your trading horizon (20 for short-term, 50 for longer-term for example).
Select num_simulations for the number of forecast paths (5–10 is reasonable for visualization).
Interpret Output:
Teal lines suggest bullish scenarios, red lines suggest bearish scenarios.
A wide spread of lines indicates high uncertainty; convergence suggests a stronger trend.
Monitor Updates: Forecasts update every T bars, so check the chart periodically for new projections.
Chart Examples
This is a daily AMEX:SPY chart with default settings. We see the simulations being done every T bars and they provide a range for us to analyze with a few simulations still in the range.
On this intraday PEPPERSTONE:COCOA chart I modified the Length Scale for fBm, L, parameter to be 1000 from 100000. Adjusting the parameter as you switch between timeframes can give you more contextual simulations.
On BITSTAMP:ETHUSD I modified the L to be 1000000 to have a more contextual set of simulations with crypto's volatile nature.
With L at 100000 we see the range for NASDAQ:TLT is correctly simulated. The recent pop stays within the bounds of the highest simulation. Note this is a cherry picked example to show the power and potential of these simulations.
Technical Notes
Error Handling: The script includes checks for array size limits and division by zero (math.abs(denominator) > 1e-10, v := math.max(v, 1e-10)).
External Reference: The fBm implementation is based on Hosking’s method (www.columbia.edu), ensuring a robust algorithm.
Conclusion
The Multifractal Forecast is a powerful tool for traders seeking to model complex market dynamics using a multifractal framework. By combining fBm, binomial cascades, and Hurst exponent analysis, it generates probabilistic price forecasts that account for long-range dependence and non-uniform market activity. Its customizable inputs and clear visualizations make it suitable for both technical analysis and strategy development, though users should be mindful of its computational demands and parameter sensitivity. For optimal use, experiment with input settings and validate forecasts against other technical indicators or market conditions.