The Middle-High-Low Moving AverageA standard EMA and a Middle-High-Low EMA give a good signal when they cross
"low"に関するスクリプトを検索
ALERT: Passed Yesterday's High/LowThis is just a simple script to show if the current price passed yesterday's high or low price. It will create an alert if so (which can be set up to notify you via email or text).
blog.tradingview.com
Kay_High_LowPrevious High low plotting.
COPIED from Chris Moody's script and adjusted it for my needs.
CD_Average Daily Range Zones- highs and lows of the dayUses daily average ranges of 5 and 10 (most used) as buy (support) and highs (resistance) areas - half ranges used in calculations for a more accurate "forecast" of the H and L . Uses open but not close, so it does not repaint - experimental
Hi-Lo WorldThis script plots the highs/lows from multiple timeframes onto the same chart to help you spot the prevailing long-term, medium-term and short-term trends .
List of timeframes included:
Year
Month
Week
Day
4 Hour
Hour
You can select which timeframes to plot by editing the inputs on the Format Object dialog.
_CM_High_Low_Open_Close_Weekly-IntradayUpdated Indicator - Plots High, Low Open, Close
For Weekly, Daily, 4 Hour, 2 Hour, 1 Hour Current and Previous Sessions Levels.
Updated Adds 4 Hour, 2 Hour, 1 Hour levels for Forex and Intra-Day Traders.
FNGAdataLow“Low prices for FNGA ETF (Dec 2018–May 2025)
The Low prices for FNGA ETF (December 2018 – May 2025) capture the lowest trading price reached during each regular U.S. market session over the entire lifespan of this leveraged exchange-traded note. Initially launched under the ticker FNGU, and later rebranded as FNGA in March 2025 before its eventual redemption, the fund was structured to deliver 3x daily leveraged exposure to the MicroSectors FANG+™ Index. This index concentrated on a small basket of leading technology and tech-enabled growth companies such as Meta (Facebook), Amazon, Apple, Netflix, and Alphabet (Google), along with a few other innovators.
The Low price is particularly important in the study of FNGA because it highlights the intraday downside extremes of a highly volatile, leveraged product. Since FNGA was designed to reset leverage daily, its lows often reflected moments of amplified market stress, when declines in the underlying FANG+™ stocks were multiplied through the 3x leverage structure.
Low volatility Buy w/ TP & SL (Coinrule)The compression of volatility usually leads to expansion. When the breakout comes, it can ignite strong trends. One way to catch a coin trading in an accumulation area is to spot three moving averages with values close to each other. The strategy uses a combination of Moving Averages to spot the best time to buy a coin before its breakout.
Buy Condition
The MA200 is greater than the MA100
The MA50 is greater than the MA100
According to backtesting results, the 1-hour time frame is the best to run this strategy.
Sell Condition
Take Profit: the price increases 8% from the entry price
Stop Loss: the price drops 4% from the entry price
The strategy has a profitability of 40-60% (depending on the market conditions). Having a ratio of two between Take profit and Stop Loss helps keeping the strategy profitable in the long term.
3D Institutional Battlefield [SurgeGuru]Professional Presentation: 3D Institutional Flow Terrain Indicator
Overview
The 3D Institutional Flow Terrain is an advanced trading visualization tool that transforms complex market structure into an intuitive 3D landscape. This indicator synthesizes multiple institutional data points—volume profiles, order blocks, liquidity zones, and voids—into a single comprehensive view, helping you identify high-probability trading opportunities.
Key Features
🎥 Camera & Projection Controls
Yaw & Pitch: Adjust viewing angles (0-90°) for optimal perspective
Scale Controls: Fine-tune X (width), Y (depth), and Z (height) dimensions
Pro Tip: Increase Z-scale to amplify terrain features for better visibility
🌐 Grid & Surface Configuration
Resolution: Adjust X (16-64) and Y (12-48) grid density
Visual Elements: Toggle surface fill, wireframe, and node markers
Optimization: Higher resolution provides more detail but requires more processing power
📊 Data Integration
Lookback Period: 50-500 bars of historical analysis
Multi-Source Data: Combine volume profile, order blocks, liquidity zones, and voids
Weighted Analysis: Each data source contributes proportionally to the terrain height
How to Use the Frontend
💛 Price Line Tracking (Your Primary Focus)
The yellow price line is your most important guide:
Monitor Price Movement: Track how the yellow line interacts with the 3D terrain
Identify Key Levels: Watch for these critical interactions:
Order Blocks (Green/Red Zones):
When yellow price line enters green zones = Bullish order block
When yellow price line enters red zones = Bearish order block
These represent institutional accumulation/distribution areas
Liquidity Voids (Yellow Zones):
When yellow price line enters yellow void areas = Potential acceleration zones
Voids indicate price gaps where minimal trading occurred
Price often moves rapidly through voids toward next liquidity pool
Terrain Reading:
High Terrain Peaks: High volume/interest areas (support/resistance)
Low Terrain Valleys: Low volume areas (potential breakout zones)
Color Coding:
Green terrain = Bullish volume dominance
Red terrain = Bearish volume dominance
Purple = Neutral/transition areas
📈 Volume Profile Integration
POC (Point of Control): Automatically marks highest volume level
Volume Bins: Adjust granularity (10-50 bins)
Height Weight: Control how much volume affects terrain elevation
🏛️ Order Block Detection
Detection Length: 5-50 bar lookback for block identification
Strength Weighting: Recent blocks have greater impact on terrain
Candle Body Option: Use full candles or body-only for block definition
💧 Liquidity Zone Tracking
Multiple Levels: Track 3-10 key liquidity zones
Buy/Sell Side: Different colors for bid/ask liquidity
Strength Decay: Older zones have diminishing terrain impact
🌊 Liquidity Void Identification
Threshold Multiplier: Adjust sensitivity (0.5-2.0)
Height Amplification: Voids create significant terrain depressions
Acceleration Zones: Price typically moves quickly through void areas
Practical Trading Application
Bullish Scenario:
Yellow price line approaches green order block terrain
Price finds support in elevated bullish volume areas
Terrain shows consistent elevation through key levels
Bearish Scenario:
Yellow price line struggles at red order block resistance
Price falls through liquidity voids toward lower terrain
Bearish volume peaks dominate the landscape
Breakout Setup:
Yellow price line consolidates in flat terrain
Minimal resistance (low terrain) in projected direction
Clear path toward distant liquidity zones
Pro Tips
Start Simple: Begin with default settings, then gradually customize
Focus on Yellow Line: Your primary indicator of current price position
Combine Timeframes: Use the same terrain across multiple timeframes for confluence
Volume Confirmation: Ensure terrain peaks align with actual volume spikes
Void Anticipation: When price enters voids, prepare for potential rapid movement
Order Blocks & Voids Architecture
Order Blocks Calculation
Trigger: Price breaks fractal swing points
Bullish OB: When close > swing high → find lowest low in lookback period
Bearish OB: When close < swing low → find highest high in lookback period
Strength: Based on price distance from block extremes
Storage: Global array maintains last 50 blocks with FIFO management
Liquidity Voids Detection
Trigger: Price gaps exceeding ATR threshold
Bull Void: Low - high > (ATR200 × multiplier)
Bear Void: Low - high > (ATR200 × multiplier)
Validation: Close confirms gap direction
Storage: Global array maintains last 30 voids
Key Design Features
Real-time Updates: Calculated every bar, not just on last bar
Global Persistence: Arrays maintain state across executions
FIFO Management: Automatic cleanup of oldest entries
Configurable Sensitivity: Adjustable lookback periods and thresholds
Scientific Testing Framework
Hypothesis Testing
Primary Hypothesis: 3D terrain visualization improves detection of institutional order flow vs traditional 2D charts
Testable Metrics:
Prediction Accuracy: Does terrain structure predict future support/resistance?
Reaction Time: Faster identification of key levels vs conventional methods
False Positive Reduction: Lower rate of failed breakouts/breakdowns
Control Variables
Market Regime: Trending vs ranging conditions
Asset Classes: Forex, equities, cryptocurrencies
Timeframes: M5 to H4 for intraday, D1 for swing
Volume Conditions: High vs low volume environments
Data Collection Protocol
Terrain Features to Quantify:
Slope gradient changes at price inflection points
Volume peak clustering density
Order block terrain elevation vs subsequent price action
Void depth correlation with momentum acceleration
Control Group: Traditional support/resistance + volume profile
Experimental Group: 3D Institutional Flow Terrain
Statistical Measures
Signal-to-Noise Ratio: Terrain features vs random price movements
Lead Time: Terrain formation ahead of price confirmation
Effect Size: Performance difference between groups (Cohen's d)
Statistical Power: Sample size requirements for significance
Validation Methodology
Blind Testing:
Remove price labels from terrain screenshots
Have traders identify key levels from terrain alone
Measure accuracy vs actual price action
Backtesting Framework:
Automated terrain feature extraction
Correlation with future price reversals/breakouts
Monte Carlo simulation for significance testing
Expected Outcomes
If hypothesis valid:
Significant improvement in level prediction accuracy (p < 0.05)
Reduced latency in institutional level identification
Higher risk-reward ratios on terrain-confirmed trades
Research Questions:
Does terrain elevation reliably indicate institutional interest zones?
Are liquidity voids statistically significant momentum predictors?
Does multi-timeframe terrain analysis improve signal quality?
How does terrain persistence correlate with level strength?
LuxAlgo BigBeluga hapharmonic
LibPvotLibrary "LibPvot"
This is a library for advanced technical analysis, specializing
in two core areas: the detection of price-oscillator
divergences and the analysis of market structure. It provides
a back-end engine for signal detection and a toolkit for
indicator plotting.
Key Features:
1. **Complete Divergence Suite (Class A, B, C):** The engine detects
all three major types of divergences, providing a full spectrum of
analytical signals:
- **Regular (A):** For potential trend reversals.
- **Hidden (B):** For potential trend continuations.
- **Exaggerated (C):** For identifying weakness at double tops/bottoms.
2. **Advanced Signal Filtering:** The detection logic uses a
percentage-based price tolerance (`prcTol`). This feature
enables the practical detection of Exaggerated divergences
(which rarely occur at the exact same price) and creates a
"dead zone" to filter insignificant noise from triggering
Regular divergences.
3. **Pivot Synchronization:** A bar tolerance (`barTol`) is used
to reliably match price and oscillator pivots that do not
align perfectly on the same bar, preventing missed signals.
4. **Signal Invalidation Logic:** Features two built-in invalidation
rules:
- An optional `invalidate` parameter automatically terminates
active divergences if the price or the oscillator breaks
the level of the confirming pivot.
- The engine also discards 'half-pivots' (e.g., a price pivot)
if a corresponding oscillator pivot does not appear within
the `barTol` window.
5. **Stateful Plotting Helpers:** Provides helper functions
(`bullDivPos` and `bearDivPos`) that abstract away the
state management issues of visualizing persistent signals.
They generate gap-free, accurately anchored data series
ready to be used in `plotshape` functions, simplifying
indicator-side code.
6. **Rich Data Output:** The core detection functions (`bullDiv`, `bearDiv`)
return a comprehensive 9-field data tuple. This includes the
boolean flags for each divergence type and the precise
coordinates (price, oscillator value, bar index) of both the
starting and the confirming pivots.
7. **Market Structure & Trend Analysis:** Includes a
`marketStructure` function to automatically identify pivot
highs/lows, classify their relationship (HH, LH, LL, HL),
detect structure breaks, and determine the current trend
state (Up, Down, Neutral) based on pivot sequences.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
bullDiv(priceSrc, oscSrc, leftLen, rightLen, depth, barTol, prcTol, persist, invalidate)
Detects bullish divergences (Regular, Hidden, Exaggerated) based on pivot lows.
Parameters:
priceSrc (float) : series float Price series to check for pivots (e.g., `low`).
oscSrc (float) : series float Oscillator series to check for pivots.
leftLen (int) : series int Number of bars to the left of a pivot (default 5).
rightLen (int) : series int Number of bars to the right of a pivot (default 5).
depth (int) : series int Maximum number of stored pivot pairs to check against (default 2).
barTol (int) : series int Maximum bar distance allowed between the price pivot and the oscillator pivot (default 3).
prcTol (float) : series float The percentage tolerance for comparing pivot prices. Used to detect Exaggerated
divergences and filter out market noise (default 0.05%).
persist (bool) : series bool If `true` (default), the divergence flag stays active for the entire duration of the signal.
If `false`, it returns a single-bar pulse on detection.
invalidate (bool) : series bool If `true` (default), terminates an active divergence if price or oscillator break
below the confirming pivot low.
Returns: A tuple containing comprehensive data for a detected bullish divergence.
regBull series bool `true` if a Regular bullish divergence (Class A) is active.
hidBull series bool `true` if a Hidden bullish divergence (Class B) is active.
exgBull series bool `true` if an Exaggerated bullish divergence (Class C) is active.
initPivotPrc series float Price value of the initial (older) pivot low.
initPivotOsz series float Oscillator value of the initial pivot low.
initPivotBar series int Bar index of the initial pivot low.
lastPivotPrc series float Price value of the last (confirming) pivot low.
lastPivotOsz series float Oscillator value of the last pivot low.
lastPivotBar series int Bar index of the last pivot low.
bearDiv(priceSrc, oscSrc, leftLen, rightLen, depth, barTol, prcTol, persist, invalidate)
Detects bearish divergences (Regular, Hidden, Exaggerated) based on pivot highs.
Parameters:
priceSrc (float) : series float Price series to check for pivots (e.g., `high`).
oscSrc (float) : series float Oscillator series to check for pivots.
leftLen (int) : series int Number of bars to the left of a pivot (default 5).
rightLen (int) : series int Number of bars to the right of a pivot (default 5).
depth (int) : series int Maximum number of stored pivot pairs to check against (default 2).
barTol (int) : series int Maximum bar distance allowed between the price pivot and the oscillator pivot (default 3).
prcTol (float) : series float The percentage tolerance for comparing pivot prices. Used to detect Exaggerated
divergences and filter out market noise (default 0.05%).
persist (bool) : series bool If `true` (default), the divergence flag stays active for the entire duration of the signal.
If `false`, it returns a single-bar pulse on detection.
invalidate (bool) : series bool If `true` (default), terminates an active divergence if price or oscillator break
above the confirming pivot high.
Returns: A tuple containing comprehensive data for a detected bearish divergence.
regBear series bool `true` if a Regular bearish divergence (Class A) is active.
hidBear series bool `true` if a Hidden bearish divergence (Class B) is active.
exgBear series bool `true` if an Exaggerated bearish divergence (Class C) is active.
initPivotPrc series float Price value of the initial (older) pivot high.
initPivotOsz series float Oscillator value of the initial pivot high.
initPivotBar series int Bar index of the initial pivot high.
lastPivotPrc series float Price value of the last (confirming) pivot high.
lastPivotOsz series float Oscillator value of the last pivot high.
lastPivotBar series int Bar index of the last pivot high.
bullDivPos(regBull, hidBull, exgBull, rightLen, yPos)
Calculates the plottable data series for bullish divergences. It manages
the complex state of a persistent signal's plotting window to ensure
gap-free and accurately anchored visualization.
Parameters:
regBull (bool) : series bool The regular bullish divergence flag from `bullDiv`.
hidBull (bool) : series bool The hidden bullish divergence flag from `bullDiv`.
exgBull (bool) : series bool The exaggerated bullish divergence flag from `bullDiv`.
rightLen (int) : series int The same `rightLen` value used in `bullDiv` for correct timing.
yPos (float) : series float The series providing the base Y-coordinate for the shapes (e.g., `low`).
Returns: A tuple of three `series float` for plotting bullish divergences.
regBullPosY series float Contains the static anchor Y-value for Regular divergences where a shape should be plotted; `na` otherwise.
hidBullPosY series float Contains the static anchor Y-value for Hidden divergences where a shape should be plotted; `na` otherwise.
exgBullPosY series float Contains the static anchor Y-value for Exaggerated divergences where a shape should be plotted; `na` otherwise.
bearDivPos(regBear, hidBear, exgBear, rightLen, yPos)
Calculates the plottable data series for bearish divergences. It manages
the complex state of a persistent signal's plotting window to ensure
gap-free and accurately anchored visualization.
Parameters:
regBear (bool) : series bool The regular bearish divergence flag from `bearDiv`.
hidBear (bool) : series bool The hidden bearish divergence flag from `bearDiv`.
exgBear (bool) : series bool The exaggerated bearish divergence flag from `bearDiv`.
rightLen (int) : series int The same `rightLen` value used in `bearDiv` for correct timing.
yPos (float) : series float The series providing the base Y-coordinate for the shapes (e.g., `high`).
Returns: A tuple of three `series float` for plotting bearish divergences.
regBearPosY series float Contains the static anchor Y-value for Regular divergences where a shape should be plotted; `na` otherwise.
hidBearPosY series float Contains the static anchor Y-value for Hidden divergences where a shape should be plotted; `na` otherwise.
exgBearPosY series float Contains the static anchor Y-value for Exaggerated divergences where a shape should be plotted; `na` otherwise.
marketStructure(highSrc, lowSrc, leftLen, rightLen, srcTol)
Analyzes the market structure by identifying pivot points, classifying
their sequence (e.g., Higher Highs, Lower Lows), and determining the
prevailing trend state.
Parameters:
highSrc (float) : series float Price series for pivot high detection (e.g., `high`).
lowSrc (float) : series float Price series for pivot low detection (e.g., `low`).
leftLen (int) : series int Number of bars to the left of a pivot (default 5).
rightLen (int) : series int Number of bars to the right of a pivot (default 5).
srcTol (float) : series float Percentage tolerance to consider two pivots as 'equal' (default 0.05%).
Returns: A tuple containing detailed market structure information.
pivType series PivType The type of the most recently formed pivot (e.g., `hh`, `ll`).
lastPivHi series float The price level of the last confirmed pivot high.
lastPivLo series float The price level of the last confirmed pivot low.
lastPiv series float The price level of the last confirmed pivot (either high or low).
pivHiBroken series bool `true` if the price has broken above the last pivot high.
pivLoBroken series bool `true` if the price has broken below the last pivot low.
trendState series TrendState The current trend state (`up`, `down`, or `neutral`).
Advanced Seasonality Pro🎯 HOW TO USE THE ADVANCED SEASONALITY MODEL
📊 UNDERSTANDING THE COMPONENTS
1. MAIN SIGNALS
STRONG BUY (▲): Strong buy signal - Signal > 0.3
WEAK BUY (●): Weak buy signal - Signal 0.1 to 0.3
STRONG SELL (▼): Strong sell signal - Signal < -0.3
WEAK SELL (●): Weak sell signal - Signal -0.1 to -0.3
NEUTRAL: No clear signal
2. INFORMATION TABLE
text
SIGNAL : STRONG BUY ← Most important
MARKET : BULL/BEAR/SIDEWAYS
VOLATILITY : HIGH/LOW/NORMAL
PRICE LEVEL : NEAR RESIST/NEAR SUPPORT/MID-RANGE
RSI : Current RSI value
SIGNAL VALUE: 0.250 ← Signal strength
MONTH : Jan/Feb/... ← Monthly effect
CONFIDENCE : 75% ← Confidence level
🚀 TRADING STRATEGIES
A. FOR BEGINNERS
pinescript
// ONLY TRADE WHEN:
1. SIGNAL = STRONG BUY/STRONG SELL
2. CONFIDENCE > 50%
3. MARKET aligns (Bull market for BUY, Bear market for SELL)
4. Not near resistance (for BUY) or near support (for SELL)
B. FOR EXPERIENCED TRADERS
pinescript
// IDEAL CONDITIONS:
STRONG BUY + BULL MARKET + LOW VOLATILITY + RSI < 60 + NOT NEAR RESISTANCE
STRONG SELL + BEAR MARKET + HIGH VOLATILITY + RSI > 40 + NOT NEAR SUPPORT
⏰ BEST TRADING TIMES
Monthly Patterns:
Strong buys: January, October, December (January Effect, Santa Rally)
Strong sells: September (September Effect)
Caution: March-August (summer low volatility)
Daily/Weekly Patterns:
Week start (Monday): Stronger signals
Week end (Friday): Reduced strength
Month start (1st-5th): Positive bias
Month end (after 25th): Caution advised
📈 PRACTICAL ENTRY STRATEGIES
BUY ORDERS:
pinescript
// WHEN STRONG BUY APPEARS:
1. Wait for price pullback to SMA20 or support
2. Place BUY order with stop loss below recent low
3. Take profit at nearest resistance
4. Minimum risk reward ratio 1:2
SELL ORDERS:
pinescript
// WHEN STRONG SELL APPEARS:
1. Wait for price rally to near resistance
2. Place SELL order with stop loss above recent high
3. Take profit at nearest support
4. Minimum risk reward ratio 1:2
🛡️ RISK MANAGEMENT
Position Sizing:
pinescript
// FORMULA:
Risk per trade = 1-2% of account
Stop loss = 1-2% from entry point
Strong signal → 2% risk
Weak signal → 1% risk
CANCEL Conditions:
pinescript
1. Signal changes from STRONG to WEAK/NEUTRAL
2. RSI enters overbought/oversold zones (>70/<30)
3. Price breaks key levels
4. Sudden volatility spike
🔍 PRACTICAL EXAMPLES
Scenario 1: STRONG BUY
text
SIGNAL: STRONG BUY (0.35)
MARKET: BULL
VOLATILITY: LOW
PRICE LEVEL: MID-RANGE
RSI: 45
MONTH: January
CONFIDENCE: 80%
→ GOOD SIGNAL: Execute BUY order
Scenario 2: WEAK SELL
text
SIGNAL: WEAK SELL (-0.15)
MARKET: SIDEWAYS
VOLATILITY: HIGH
PRICE LEVEL: NEAR SUPPORT
RSI: 35
MONTH: September
CONFIDENCE: 25%
→ WEAK SIGNAL: DO NOT trade
📱 IMPORTANT NOTES
NEVER:
Trade against the signal
Skip stop loss orders
Trade when confidence < 30%
Trade multiple timeframes simultaneously
Let emotions influence decisions
ALWAYS:
Backtest strategy first
Paper trade before using real money
Combine with fundamental analysis
Monitor economic news
Review trades weekly
🎯 CONCLUSION
This model works BEST when:
Combined with other indicators (volume, trend lines)
Used on multiple timeframes
Applied with strict risk management
Patiently waiting for perfect setups
Only trade when at least 3/5 conditions are favorable! 🚀
💡 PRO TIPS
Use on 12H charts for optimal seasonality patterns
Combine with volume confirmation for higher accuracy
Adjust seasonal strength based on market conditions
Monitor economic calendars for news events
Keep trading journal to track performance
🔧 CUSTOMIZATION OPTIONS
You can adjust these parameters in the script:
seasonalStrength: Increase/decrease seasonal influence
usePriceAction: Toggle price action filters
useMarketRegime: Toggle market condition filters
lookbackYears: Adjust historical data period
Remember: No strategy is 100% accurate. Always use proper risk management and never risk more than you can afford to lose!
Volume Weighted LR Standard DeviationThis indicator analyzes market character by decomposing total volatility into three distinct, interpretable components based on a Linear Regression model.
Key Features:
Three-Component Volatility Decomposition: The indicator separates volatility based on the 'Estimate Bar Statistics' option.
Standard Mode (Estimate Bar Statistics = OFF): Calculates volatility based on the selected Source (dies führt hauptsächlich zu 'Trend'- und 'Residual'-Volatilität).
Decomposition Mode (Estimate Bar Statistics = ON): The indicator uses a statistical model ('Estimator') to calculate within-bar volatility. (Assumption: In this mode, the Source input is ignored, and an estimated mean for each bar is used instead). This separates volatility into:
Trend Volatility (Green/Red): Volatility explained by the regression's slope (Momentum).
Residual Volatility (Yellow): Volatility from price oscillating around the regression line (Mean-Reversion).
Within-Bar Volatility (Blue): Volatility from the high-low range of each bar (Noise/Choppiness).
Dual Display Modes: The indicator offers two modes to visualize this decomposition:
Absolute Mode: Displays the total standard deviation as a stacked area chart, partitioned by the variance ratio of the three components.
Normalized Mode: Displays the direct variance ratio (proportion) of each component relative to the total (0-1), ideal for identifying the dominant market character.
Calculation Options:
Normalization: An optional 'Normalize Volatility' setting calculates an Exponential Regression Curve (log-space), making the analysis suitable for growth assets.
Volume Weighting: An option (Volume weighted) applies volume weighting to all regression and volatility calculations.
Multi-Component Pivot Detection: Includes a pivot detector that identifies significant turning points (highs and lows) in both the Total Volatility and the Trend Volatility Ratio. (Note: These pivots are only plotted when 'Plot Mode' is set to 'Absolute').
Note on Confirmation (Lag): Pivot signals are confirmed using a lookback method. A pivot is only plotted after the Pivot Right Bars input has passed, which introduces an inherent lag.
Multi-Timeframe (MTF) Capability:
MTF Volatility Lines: The volatility lines can be calculated on a higher timeframe, with standard options to handle gaps (Fill Gaps) and prevent repainting (Wait for...).
Limitation: The Pivot detection (Calculate Pivots) is disabled if a Higher Timeframe (HTF) is selected.
Integrated Alerts: Includes 9 comprehensive alerts for:
Volatility character changes (e.g., 'Character Change from Noise to Trend').
Dominant character emerging (e.g., 'Bullish Trend Character Emerging').
Total Volatility pivot (High/Low) detection.
Trend Volatility pivot (High/Low) detection.
DISCLAIMER
For Informational/Educational Use Only: This indicator is provided for informational and educational purposes only. It does not constitute financial, investment, or trading advice, nor is it a recommendation to buy or sell any asset.
Use at Your Own Risk: All trading decisions you make based on the information or signals generated by this indicator are made solely at your own risk.
No Guarantee of Performance: Past performance is not an indicator of future results. The author makes no guarantee regarding the accuracy of the signals or future profitability.
No Liability: The author shall not be held liable for any financial losses or damages incurred directly or indirectly from the use of this indicator.
Signals Are Not Recommendations: The alerts and visual signals (e.g., crossovers) generated by this tool are not direct recommendations to buy or sell. They are technical observations for your own analysis and consideration.
Market Structure Pivots TrendThis indicator identifies and visualizes key market structure by plotting confirmed, non-repainting pivot points. It goes beyond simple markers by classifying the pivots, extending dynamic support/resistance lines, and providing a visual representation of the current trend state.
Key Features:
Non-Repainting Pivot Detection:
Uses a standard lookback method (left and right bars) to identify historical pivot points.
Note on Confirmation: Pivots are only confirmed after the Pivot Right Bars input has passed. This is essential for ensuring the signal is non-repainting, but it introduces an inherent lag.
Automatically classifies the sequence of pivots according to Dow Theory: Higher Highs (HH), Higher Lows (HL), Lower Highs (LH), and Lower Lows (LL).
Pivot Classification Filter:
Price Tolerance Filter: A user-defined percentage tolerance filters out insignificant market noise. A pivot is only classified as 'Higher' or 'Lower' if its price exceeds the previous one by more than the set tolerance, leading to more robust signals.
Equal Pivot Detection: The tolerance also enables the detection of Equal Highs (EH) and Equal Lows (EL), highlighting consolidation zones.
Dynamic Support & Resistance Lines:
When enabled, the indicator extends a horizontal line from the most recent confirmed pivot high and low.
These lines update in real-time, providing clear S/R levels.
Lines automatically terminate if the price decisively breaks through them or if a new pivot of the same type is formed.
Trend State Visualization:
A built-in state machine analyzes the sequence of pivots and breaks to determine the current market trend (Uptrend, Downtrend, or Neutral).
Plots a dynamic step-line based on recent highs/lows to visually represent the current trend state.
Full Customization & Alerts:
Display Options: Choose between simple triangles or detailed text labels that show the pivot type, price, and the absolute or relative change from the previous pivot of the same type.
Visual Styling: Full control over colors for all six pivot types (HH, LH, EH, LL, HL, EL) and line styles.
Comprehensive Alerts: Set up alerts for every new pivot formation (e.g., HH, LL), for S/R line breaks, and for changes in the overall trend state (Up, Down, Neutral).
DISCLAIMER
For Informational/Educational Use Only: This indicator is provided for informational and educational purposes only. It does not constitute financial, investment, or trading advice, nor is it a recommendation to buy or sell any asset.
Use at Your Own Risk: All trading decisions you make based on the information or signals generated by this indicator are made solely at your own risk.
No Guarantee of Performance: Past performance is not an indicator of future results. The author makes no guarantee regarding the accuracy of the signals or future profitability.
No Liability: The author shall not be held liable for any financial losses or damages incurred directly or indirectly from the use of this indicator.
Signals Are Not Recommendations: The alerts and visual signals (e.g., crossovers) generated by this tool are not direct recommendations to buy or sell. They are technical observations for your own analysis and consideration.
LibVPrfLibrary "LibVPrf"
This library provides an object-oriented framework for volume
profile analysis in Pine Script®. It is built around the `VProf`
User-Defined Type (UDT), which encapsulates all data, settings,
and statistical metrics for a single profile, enabling stateful
analysis with on-demand calculations.
Key Features:
1. **Object-Oriented Design (UDT):** The library is built around
the `VProf` UDT. This object encapsulates all profile data
and provides methods for its full lifecycle management,
including creation, cloning, clearing, and merging of profiles.
2. **Volume Allocation (`AllotMode`):** Offers two methods for
allocating a bar's volume:
- **Classic:** Assigns the entire bar's volume to the close
price bucket.
- **PDF:** Distributes volume across the bar's range using a
statistical price distribution model from the `LibBrSt` library.
3. **Buy/Sell Volume Splitting (`SplitMode`):** Provides methods
for classifying volume into buying and selling pressure:
- **Classic:** Classifies volume based on the bar's color (Close vs. Open).
- **Dynamic:** A specific model that analyzes candle structure
(body vs. wicks) and a short-term trend factor to
estimate the buy/sell share at each price level.
4. **Statistical Analysis (On-Demand):** Offers a suite of
statistical metrics calculated using a "Lazy Evaluation"
pattern (computed only when requested via `get...` methods):
- **Central Tendency:** Point of Control (POC), VWAP, and Median.
- **Dispersion:** Value Area (VA) and Population Standard Deviation.
- **Shape:** Skewness and Excess Kurtosis.
- **Delta:** Cumulative Volume Delta, including its
historical high/low watermarks.
5. **Structural Analysis:** Includes a parameter-free method
(`getSegments`) to decompose a profile into its fundamental
unimodal segments, allowing for modality detection (e.g.,
identifying bimodal profiles).
6. **Dynamic Profile Management:**
- **Auto-Fitting:** Profiles set to `dynamic = true` will
automatically expand their price range to fit new data.
- **Manipulation:** The resolution, price range, and Value Area
of a dynamic profile can be changed at any time. This
triggers a resampling process that uses a **linear
interpolation model** to re-bucket existing volume.
- **Assumption:** Non-dynamic profiles are fixed and will throw
a `runtime.error` if `addBar` is called with data
outside their initial range.
7. **Bucket-Level Access:** Provides getter methods for direct
iteration and analysis of the raw buy/sell volume and price
boundaries of each individual price bucket.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
create(buckets, rangeUp, rangeLo, dynamic, valueArea, allot, estimator, cdfSteps, split, trendLen)
Construct a new `VProf` object with fixed bucket count & range.
Parameters:
buckets (int) : series int number of price buckets ≥ 1
rangeUp (float) : series float upper price bound (absolute)
rangeLo (float) : series float lower price bound (absolute)
dynamic (bool) : series bool Flag for dynamic adaption of profile ranges
valueArea (int) : series int Percentage of total volume to include in the Value Area (1..100)
allot (series AllotMode) : series AllotMode Allocation mode `classic` or `pdf` (default `classic`)
estimator (series PriceEst enum from AustrianTradingMachine/LibBrSt/1) : series LibBrSt.PriceEst PDF model when `model == PDF`. (deflault = 'uniform')
cdfSteps (int) : series int even #sub-intervals for Simpson rule (default 20)
split (series SplitMode) : series SplitMode Buy/Sell determination (default `classic`)
trendLen (int) : series int Look‑back bars for trend factor (default 3)
Returns: VProf freshly initialised profile
method clone(self)
Create a deep copy of the volume profile.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object to copy
Returns: VProf A new, independent copy of the profile
method clear(self)
Reset all bucket tallies while keeping configuration intact.
Namespace types: VProf
Parameters:
self (VProf) : VProf profile object
Returns: VProf cleared profile (chaining)
method merge(self, srcABuy, srcASell, srcRangeUp, srcRangeLo, srcCvd, srcCvdHi, srcCvdLo)
Merges volume data from a source profile into the current profile.
If resizing is needed, it performs a high-fidelity re-bucketing of existing
volume using a linear interpolation model inferred from neighboring buckets,
preventing aliasing artifacts and ensuring accurate volume preservation.
Namespace types: VProf
Parameters:
self (VProf) : VProf The target profile object to merge into.
srcABuy (array) : array The source profile's buy volume bucket array.
srcASell (array) : array The source profile's sell volume bucket array.
srcRangeUp (float) : series float The upper price bound of the source profile.
srcRangeLo (float) : series float The lower price bound of the source profile.
srcCvd (float) : series float The final Cumulative Volume Delta (CVD) value of the source profile.
srcCvdHi (float) : series float The historical high-water mark of the CVD from the source profile.
srcCvdLo (float) : series float The historical low-water mark of the CVD from the source profile.
Returns: VProf `self` (chaining), now containing the merged data.
method addBar(self, offset)
Add current bar’s volume to the profile (call once per realtime bar).
classic mode: allocates all volume to the close bucket and classifies
by `close >= open`. PDF mode: distributes volume across buckets by the
estimator’s CDF mass. For `split = dynamic`, the buy/sell share per
price is computed via context-driven piecewise s(u).
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
offset (int) : series int To offset the calculated bar
Returns: VProf `self` (method chaining)
method setBuckets(self, buckets)
Sets the number of buckets for the volume profile.
Behavior depends on the `isDynamic` flag.
- If `dynamic = true`: Works on filled profiles by re-bucketing to a new resolution.
- If `dynamic = false`: Only works on empty profiles to prevent accidental changes.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
buckets (int) : series int The new number of buckets
Returns: VProf `self` (chaining)
method setRanges(self, rangeUp, rangeLo)
Sets the price range for the volume profile.
Behavior depends on the `dynamic` flag.
- If `dynamic = true`: Works on filled profiles by re-bucketing existing volume.
- If `dynamic = false`: Only works on empty profiles to prevent accidental changes.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
rangeUp (float) : series float The new upper price bound
rangeLo (float) : series float The new lower price bound
Returns: VProf `self` (chaining)
method setValueArea(self, valueArea)
Set the percentage of volume for the Value Area. If the value
changes, the profile is finalized again.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
valueArea (int) : series int The new Value Area percentage (0..100)
Returns: VProf `self` (chaining)
method getBktBuyVol(self, idx)
Get Buy volume of a bucket.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
idx (int) : series int Bucket index
Returns: series float Buy volume ≥ 0
method getBktSellVol(self, idx)
Get Sell volume of a bucket.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
idx (int) : series int Bucket index
Returns: series float Sell volume ≥ 0
method getBktBnds(self, idx)
Get Bounds of a bucket.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
idx (int) : series int Bucket index
Returns:
up series float The upper price bound of the bucket.
lo series float The lower price bound of the bucket.
method getPoc(self)
Get POC information.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
Returns:
pocIndex series int The index of the Point of Control (POC) bucket.
pocPrice. series float The mid-price of the Point of Control (POC) bucket.
method getVA(self)
Get Value Area (VA) information.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
Returns:
vaUpIndex series int The index of the upper bound bucket of the Value Area.
vaUpPrice series float The upper price bound of the Value Area.
vaLoIndex series int The index of the lower bound bucket of the Value Area.
vaLoPrice series float The lower price bound of the Value Area.
method getMedian(self)
Get the profile's median price and its bucket index. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns:
medianIndex series int The index of the bucket containing the Median.
medianPrice series float The Median price of the profile.
method getVwap(self)
Get the profile's VWAP and its bucket index. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns:
vwapIndex series int The index of the bucket containing the VWAP.
vwapPrice series float The Volume Weighted Average Price of the profile.
method getStdDev(self)
Get the profile's volume-weighted standard deviation. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns: series float The Standard deviation of the profile.
method getSkewness(self)
Get the profile's skewness. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns: series float The Skewness of the profile.
method getKurtosis(self)
Get the profile's excess kurtosis. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns: series float The Kurtosis of the profile.
method getSegments(self)
Get the profile's fundamental unimodal segments. Calculates on-demand if stale.
Uses a parameter-free, pivot-based recursive algorithm.
Namespace types: VProf
Parameters:
self (VProf) : VProf The profile object.
Returns: matrix A 2-column matrix where each row is an pair.
method getCvd(self)
Cumulative Volume Delta (CVD) like metric over all buckets.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns:
cvd series float The final Cumulative Volume Delta (Total Buy Vol - Total Sell Vol).
cvdHi series float The running high-water mark of the CVD as volume was added.
cvdLo series float The running low-water mark of the CVD as volume was added.
VProf
VProf Bucketed Buy/Sell volume profile plus meta information.
Fields:
buckets (series int) : int Number of price buckets (granularity ≥1)
rangeUp (series float) : float Upper price range (absolute)
rangeLo (series float) : float Lower price range (absolute)
dynamic (series bool) : bool Flag for dynamic adaption of profile ranges
valueArea (series int) : int Percentage of total volume to include in the Value Area (1..100)
allot (series AllotMode) : AllotMode Allocation mode `classic` or `pdf`
estimator (series PriceEst enum from AustrianTradingMachine/LibBrSt/1) : LibBrSt.PriceEst Price density model when `model == PDF`
cdfSteps (series int) : int Simpson integration resolution (even ≥2)
split (series SplitMode) : SplitMode Buy/Sell split strategy per bar
trendLen (series int) : int Look‑back length for trend factor (≥1)
maxBkt (series int) : int User-defined number of buckets (unclamped)
aBuy (array) : array Buy volume per bucket
aSell (array) : array Sell volume per bucket
cvd (series float) : float Final Cumulative Volume Delta (Total Buy Vol - Total Sell Vol).
cvdHi (series float) : float Running high-water mark of the CVD as volume was added.
cvdLo (series float) : float Running low-water mark of the CVD as volume was added.
poc (series int) : int Index of max‑volume bucket (POC). Is `na` until calculated.
vaUp (series int) : int Index of upper Value‑Area bound. Is `na` until calculated.
vaLo (series int) : int Index of lower value‑Area bound. Is `na` until calculated.
median (series float) : float Median price of the volume distribution. Is `na` until calculated.
vwap (series float) : float Profile VWAP (Volume Weighted Average Price). Is `na` until calculated.
stdDev (series float) : float Standard Deviation of volume around the VWAP. Is `na` until calculated.
skewness (series float) : float Skewness of the volume distribution. Is `na` until calculated.
kurtosis (series float) : float Excess Kurtosis of the volume distribution. Is `na` until calculated.
segments (matrix) : matrix A 2-column matrix where each row is an pair. Is `na` until calculated.
Scientific Correlation Testing FrameworkScientific Correlation Testing Framework - Comprehensive Guide
Introduction to Correlation Analysis
What is Correlation?
Correlation is a statistical measure that describes the degree to which two assets move in relation to each other. Think of it like measuring how closely two dancers move together on a dance floor.
Perfect Positive Correlation (+1.0): Both dancers move in perfect sync, same direction, same speed
Perfect Negative Correlation (-1.0): Both dancers move in perfect sync but in opposite directions
Zero Correlation (0): The dancers move completely independently of each other
In financial markets, correlation helps us understand relationships between different assets, which is crucial for:
Portfolio diversification
Risk management
Pairs trading strategies
Hedging positions
Market analysis
Why This Script is Special
This script goes beyond simple correlation calculations by providing:
Two different correlation methods (Pearson and Spearman)
Statistical significance testing to ensure results are meaningful
Rolling correlation analysis to track how relationships change over time
Visual representation for easy interpretation
Comprehensive statistics table with detailed metrics
Deep Dive into the Script's Components
1. Input Parameters Explained-
Symbol Selection:
This allows you to select the second asset to compare with the chart's primary asset
Default is Apple (NASDAQ:AAPL), but you can change this to any symbol
Example: If you're viewing a Bitcoin chart, you might set this to "NASDAQ:TSLA" to see if Bitcoin and Tesla are correlated
Correlation Window (60): This is the number of periods used to calculate the main correlation
Larger values (e.g., 100-500) provide more stable, long-term correlation measures
Smaller values (e.g., 10-50) are more responsive to recent price movements
60 is a good balance for most daily charts (about 3 months of trading days)
Rolling Correlation Window (20): A shorter window to detect recent changes in correlation
This helps identify when the relationship between assets is strengthening or weakening
Default of 20 is roughly one month of trading days
Return Type: This determines how price changes are calculated
Simple Returns: (Today's Price - Yesterday's Price) / Yesterday's Price
Easy to understand: "The asset went up 2% today"
Log Returns: Natural logarithm of (Today's Price / Yesterday's Price)
More mathematically elegant for statistical analysis
Better for time-additive properties (returns over multiple periods)
Less sensitive to extreme values.
Confidence Level (95%): This determines how certain we want to be about our results
95% confidence means we accept a 5% chance of being wrong (false positive)
Higher confidence (e.g., 99%) makes the test more strict
Lower confidence (e.g., 90%) makes the test more lenient
95% is the standard in most scientific research
Show Statistical Significance: When enabled, the script will test if the correlation is statistically significant or just due to random chance.
Display options control what you see on the chart:
Show Pearson/Spearman/Rolling Correlation: Toggle each correlation type on/off
Show Scatter Plot: Displays a scatter plot of returns (limited to recent points to avoid performance issues)
Show Statistical Tests: Enables the detailed statistics table
Table Text Size: Adjusts the size of text in the statistics table
2.Functions explained-
calcReturns():
This function calculates price returns based on your selected method:
Log Returns:
Formula: ln(Price_t / Price_t-1)
Example: If a stock goes from $100 to $101, the log return is ln(101/100) = ln(1.01) ≈ 0.00995 or 0.995%
Benefits: More symmetric, time-additive, and better for statistical modeling
Simple Returns:
Formula: (Price_t - Price_t-1) / Price_t-1
Example: If a stock goes from $100 to $101, the simple return is (101-100)/100 = 0.01 or 1%
Benefits: More intuitive and easier to understand
rankArray():
This function calculates the rank of each value in an array, which is used for Spearman correlation:
How ranking works:
The smallest value gets rank 1
The second smallest gets rank 2, and so on
For ties (equal values), they get the average of their ranks
Example: For values
Sorted:
Ranks: (the two 2s tie for ranks 1 and 2, so they both get 1.5)
Why this matters: Spearman correlation uses ranks instead of actual values, making it less sensitive to outliers and non-linear relationships.
pearsonCorr():
This function calculates the Pearson correlation coefficient:
Mathematical Formula:
r = (nΣxy - ΣxΣy) / √
Where x and y are the two variables, and n is the sample size
What it measures:
The strength and direction of the linear relationship between two variables
Values range from -1 (perfect negative linear relationship) to +1 (perfect positive linear relationship)
0 indicates no linear relationship
Example:
If two stocks have a Pearson correlation of 0.8, they have a strong positive linear relationship
When one stock goes up, the other tends to go up in a fairly consistent proportion
spearmanCorr():
This function calculates the Spearman rank correlation:
How it works:
Convert each value in both datasets to its rank
Calculate the Pearson correlation on the ranks instead of the original values
What it measures:
The strength and direction of the monotonic relationship between two variables
A monotonic relationship is one where as one variable increases, the other either consistently increases or decreases
It doesn't require the relationship to be linear
When to use it instead of Pearson:
When the relationship is monotonic but not linear
When there are significant outliers in the data
When the data is ordinal (ranked) rather than interval/ratio
Example:
If two stocks have a Spearman correlation of 0.7, they have a strong positive monotonic relationship
When one stock goes up, the other tends to go up, but not necessarily in a straight-line relationship
tStatistic():
This function calculates the t-statistic for correlation:
Mathematical Formula: t = r × √((n-2)/(1-r²))
Where r is the correlation coefficient and n is the sample size
What it measures:
How many standard errors the correlation is away from zero
Used to test the null hypothesis that the true correlation is zero
Interpretation:
Larger absolute t-values indicate stronger evidence against the null hypothesis
Generally, a t-value greater than 2 (in absolute terms) is considered statistically significant at the 95% confidence level
criticalT() and pValue():
These functions provide approximations for statistical significance testing:
criticalT():
Returns the critical t-value for a given degrees of freedom (df) and significance level
The critical value is the threshold that the t-statistic must exceed to be considered statistically significant
Uses approximations since Pine Script doesn't have built-in statistical distribution functions
pValue():
Estimates the p-value for a given t-statistic and degrees of freedom
The p-value is the probability of observing a correlation as strong as the one calculated, assuming the true correlation is zero
Smaller p-values indicate stronger evidence against the null hypothesis
Standard interpretation:
p < 0.01: Very strong evidence (marked with **)
p < 0.05: Strong evidence (marked with *)
p ≥ 0.05: Weak evidence, not statistically significant
stdev():
This function calculates the standard deviation of a dataset:
Mathematical Formula: σ = √(Σ(x-μ)²/(n-1))
Where x is each value, μ is the mean, and n is the sample size
What it measures:
The amount of variation or dispersion in a set of values
A low standard deviation indicates that the values tend to be close to the mean
A high standard deviation indicates that the values are spread out over a wider range
Why it matters for correlation:
Standard deviation is used in calculating the correlation coefficient
It also provides information about the volatility of each asset's returns
Comparing standard deviations helps understand the relative riskiness of the two assets.
3.Getting Price Data-
price1: The closing price of the primary asset (the chart you're viewing)
price2: The closing price of the secondary asset (the one you selected in the input parameters)
Returns are used instead of raw prices because:
Returns are typically stationary (mean and variance stay constant over time)
Returns normalize for price levels, allowing comparison between assets of different values
Returns represent what investors actually care about: percentage changes in value
4.Information Table-
Creates a table to display statistics
Only shows on the last bar to avoid performance issues
Positioned in the top right of the chart
Has 2 columns and 15 rows
Populating the Table
The script then populates the table with various statistics:
Header Row: "Metric" and "Value"
Sample Information: Sample size and return type
Pearson Correlation: Value, t-statistic, p-value, and significance
Spearman Correlation: Value, t-statistic, p-value, and significance
Rolling Correlation: Current value
Standard Deviations: For both assets
Interpretation: Text description of the correlation strength
The table uses color coding to highlight important information:
Green for significant positive results
Red for significant negative results
Yellow for borderline significance
Color-coded headers for each section
=> Practical Applications and Interpretation
How to Interpret the Results
Correlation Strength
0.0 to 0.3 (or 0.0 to -0.3): Weak or no correlation
The assets move mostly independently of each other
Good for diversification purposes
0.3 to 0.7 (or -0.3 to -0.7): Moderate correlation
The assets show some tendency to move together (or in opposite directions)
May be useful for certain trading strategies but not extremely reliable
0.7 to 1.0 (or -0.7 to -1.0): Strong correlation
The assets show a strong tendency to move together (or in opposite directions)
Can be useful for pairs trading, hedging, or as a market indicator
Statistical Significance
p < 0.01: Very strong evidence that the correlation is real
Marked with ** in the table
Very unlikely to be due to random chance
p < 0.05: Strong evidence that the correlation is real
Marked with * in the table
Unlikely to be due to random chance
p ≥ 0.05: Weak evidence that the correlation is real
Not marked in the table
Could easily be due to random chance
Rolling Correlation
The rolling correlation shows how the relationship between assets changes over time
If the rolling correlation is much different from the long-term correlation, it suggests the relationship is changing
This can indicate:
A shift in market regime
Changing fundamentals of one or both assets
Temporary market dislocations that might present trading opportunities
Trading Applications
1. Portfolio Diversification
Goal: Reduce overall portfolio risk by combining assets that don't move together
Strategy: Look for assets with low or negative correlations
Example: If you hold tech stocks, you might add some utilities or bonds that have low correlation with tech
2. Pairs Trading
Goal: Profit from the relative price movements of two correlated assets
Strategy:
Find two assets with strong historical correlation
When their prices diverge (one goes up while the other goes down)
Buy the underperforming asset and short the outperforming asset
Close the positions when they converge back to their normal relationship
Example: If Coca-Cola and Pepsi are highly correlated but Coca-Cola drops while Pepsi rises, you might buy Coca-Cola and short Pepsi
3. Hedging
Goal: Reduce risk by taking an offsetting position in a negatively correlated asset
Strategy: Find assets that tend to move in opposite directions
Example: If you hold a portfolio of stocks, you might buy some gold or government bonds that tend to rise when stocks fall
4. Market Analysis
Goal: Understand market dynamics and interrelationships
Strategy: Analyze correlations between different sectors or asset classes
Example:
If tech stocks and semiconductor stocks are highly correlated, movements in one might predict movements in the other
If the correlation between stocks and bonds changes, it might signal a shift in market expectations
5. Risk Management
Goal: Understand and manage portfolio risk
Strategy: Monitor correlations to identify when diversification benefits might be breaking down
Example: During market crises, many assets that normally have low correlations can become highly correlated (correlation convergence), reducing diversification benefits
Advanced Interpretation and Caveats
Correlation vs. Causation
Important Note: Correlation does not imply causation
Example: Ice cream sales and drowning incidents are correlated (both increase in summer), but one doesn't cause the other
Implication: Just because two assets move together doesn't mean one causes the other to move
Solution: Look for fundamental economic reasons why assets might be correlated
Non-Stationary Correlations
Problem: Correlations between assets can change over time
Causes:
Changing market conditions
Shifts in monetary policy
Structural changes in the economy
Changes in the underlying businesses
Solution: Use rolling correlations to monitor how relationships change over time
Outliers and Extreme Events
Problem: Extreme market events can distort correlation measurements
Example: During a market crash, many assets may move in the same direction regardless of their normal relationship
Solution:
Use Spearman correlation, which is less sensitive to outliers
Be cautious when interpreting correlations during extreme market conditions
Sample Size Considerations
Problem: Small sample sizes can produce unreliable correlation estimates
Rule of Thumb: Use at least 30 data points for a rough estimate, 60+ for more reliable results
Solution:
Use the default correlation length of 60 or higher
Be skeptical of correlations calculated with small samples
Timeframe Considerations
Problem: Correlations can vary across different timeframes
Example: Two assets might be positively correlated on a daily basis but negatively correlated on a weekly basis
Solution:
Test correlations on multiple timeframes
Use the timeframe that matches your trading horizon
Look-Ahead Bias
Problem: Using information that wouldn't have been available at the time of trading
Example: Calculating correlation using future data
Solution: This script avoids look-ahead bias by using only historical data
Best Practices for Using This Script
1. Appropriate Parameter Selection
Correlation Window:
For short-term trading: 20-50 periods
For medium-term analysis: 50-100 periods
For long-term analysis: 100-500 periods
Rolling Window:
Should be shorter than the main correlation window
Typically 1/3 to 1/2 of the main window
Return Type:
For most applications: Log Returns (better statistical properties)
For simplicity: Simple Returns (easier to interpret)
2. Validation and Testing
Out-of-Sample Testing:
Calculate correlations on one time period
Test if they hold in a different time period
Multiple Timeframes:
Check if correlations are consistent across different timeframes
Economic Rationale:
Ensure there's a logical reason why assets should be correlated
3. Monitoring and Maintenance
Regular Review:
Correlations can change, so review them regularly
Alerts:
Set up alerts for significant correlation changes
Documentation:
Keep notes on why certain assets are correlated and what might change that relationship
4. Integration with Other Analysis
Fundamental Analysis:
Combine correlation analysis with fundamental factors
Technical Analysis:
Use correlation analysis alongside technical indicators
Market Context:
Consider how market conditions might affect correlations
Conclusion
This Scientific Correlation Testing Framework provides a comprehensive tool for analyzing relationships between financial assets. By offering both Pearson and Spearman correlation methods, statistical significance testing, and rolling correlation analysis, it goes beyond simple correlation measures to provide deeper insights.
For beginners, this script might seem complex, but it's built on fundamental statistical concepts that become clearer with use. Start with the default settings and focus on interpreting the main correlation lines and the statistics table. As you become more comfortable, you can adjust the parameters and explore more advanced applications.
Remember that correlation analysis is just one tool in a trader's toolkit. It should be used in conjunction with other forms of analysis and with a clear understanding of its limitations. When used properly, it can provide valuable insights for portfolio construction, risk management, and pair trading strategy development.
v2.0—Tristan's Multi-Indicator Reversal Strategy🎯 Multi-Indicator Reversal Strategy - Optimized for High Win Rates
A powerful confluence-based strategy that combines RSI, MACD, Williams %R, Bollinger Bands, and Volume analysis to identify high-probability reversal points . Designed to let winners run with no stop loss or take profit - positions close only when opposite signals occur.
Also, the 3 hour timeframe works VERY well—just a lot less trades.
📈 Proven Performance
This strategy has been backtested and optimized on multiple blue-chip stocks with 80-90%+ win rates on 1-hour timeframes from Aug 2025 through Oct 2025:
✅ V (Visa) - Payment processor
✅ MSFT (Microsoft) - Large-cap tech
✅ WMT (Walmart) - Retail leader
✅ IWM (Russell 2000 ETF) - Small-cap index
✅ NOW (ServiceNow) - Enterprise software
✅ WM (Waste Management) - Industrial services
These stocks tend to mean-revert at extremes, making them ideal candidates for this reversal-based approach. I only list these as a way to show you the performance of the script. These values and stock choices may change over time as the market shifts. Keep testing!
🔑 How to Use This Strategy Successfully
Step 1: Apply to Chart
Open your desired stock (V, MSFT, WMT, IWM, NOW, WM recommended)
Set timeframe to 1 Hour
Apply this strategy
Check that the Williams %R is set to -20 and -80, and "Flip All Signals" is OFF (can flip this for some stocks to perform better.)
Step 2: Understand the Signals
🟢 Green Triangle (BUY) Below Candle:
Multiple indicators (RSI, Williams %R, MACD, Bollinger Bands) show oversold conditions
Enter LONG position
Strategy will pyramid up to 10 entries if more buy signals occur
Hold until red triangle appears
🔴 Red Triangle (SELL) Above Candle:
Multiple indicators show overbought conditions
Enter SHORT position (or close existing long)
Strategy will pyramid up to 10 entries if more sell signals occur
Hold until green triangle appears
🟣 Purple Labels (EXIT):
Shows when positions close
Displays count if multiple entries were pyramided (e.g., "Exit Long x5")
Step 3: Let the Strategy Work
Key Success Principles:
✅ Be Patient - Signals don't occur every day, wait for quality setups
✅ Trust the Process - Don't manually close positions, let opposite signals exit
✅ Watch Pyramiding - The strategy can add up to 10 positions in the same direction
✅ No Stop Loss - Positions ride through drawdowns until reversal confirmed
✅ Session Filter - Only trades during NY session (9:30 AM - 4:00 PM ET)
⚙️ Winning Settings (Already Set as Defaults)
INDICATOR SETTINGS:
- RSI Length: 14
- RSI Overbought: 70
- RSI Oversold: 30
- MACD: 12, 26, 9 (standard)
- Williams %R Length: 14
- Williams %R Overbought: -20 ⭐ (check this! And adjust to your liking)
- Williams %R Oversold: -80 ⭐ (check this! And adjust to your liking)
- Bollinger Bands: 20, 2.0
- Volume MA: 20 periods
- Volume Multiplier: 1.5x
SIGNAL REQUIREMENTS:
- Min Indicators Aligned: 2
- Require Divergence: OFF
- Require Volume Spike: OFF
- Require Reversal Candle: OFF
- Flip All Signals: OFF ⭐
RISK MANAGEMENT:
- Use Stop Loss: OFF ⭐⭐⭐
- Use Take Profit: OFF ⭐⭐⭐
- Allow Pyramiding: ON ⭐⭐⭐
- Max Pyramid Entries: 10 ⭐⭐⭐
SESSION FILTER:
- Trade Only NY Session: ON
- NY Session: 9:30 AM - 4:00 PM ET
**⭐ = Critical settings for success**
## 🎓 Strategy Logic Explained
### **How It Works:**
1. **Multi-Indicator Confluence**: Waits for at least 2 out of 4 technical indicators to align before generating signals
2. **Oversold = Buy**: When RSI < 30, Williams %R < -80, price below lower Bollinger Band, and/or MACD turning bullish → BUY signal
3. **Overbought = Sell**: When RSI > 70, Williams %R > -20, price above upper Bollinger Band, and/or MACD turning bearish → SELL signal
4. **Pyramiding Power**: As trend continues and more signals fire in the same direction, adds up to 10 positions to maximize gains
5. **Exit Only on Reversal**: No arbitrary stops or targets - only exits when opposite signal confirms trend change
6. **Session Filter**: Only trades during liquid NY session hours to avoid overnight gaps and low-volume periods
### **Why No Stop Loss Works:**
Traditional reversal strategies fail because they:
- Get stopped out too early during normal volatility
- Miss the actual reversal that happens later
- Cut winners short with tight take profits
This strategy succeeds because it:
- ✅ Rides through temporary noise
- ✅ Captures full reversal moves
- ✅ Uses multiple indicators for confirmation
- ✅ Pyramids into winning positions
- ✅ Only exits when technical picture completely reverses
---
## 📊 Understanding the Display
**Live Indicator Counter (Top Corner / end of current candles):**
Bull: 2/4
Bear: 0/4
(STANDARD)
Shows how many indicators currently align bullish/bearish
"STANDARD" = normal reversal mode (buy oversold, sell overbought)
"FLIPPED" = momentum mode if you toggle that setting
Visual Indicators:
🔵 Blue background = NY session active (trading window)
🟡 Yellow candle tint = Volume spike detected
💎 Aqua diamond = Bullish divergence (price vs RSI)
💎 Fuchsia diamond = Bearish divergence
⚡ Advanced Tips
Optimizing for Different Stocks:
If Win Rate is Low (<50%):
Try toggling "Flip All Signals" to ON (switches to momentum mode)
Increase "Min Indicators Aligned" to 3 or 4
Turn ON "Require Divergence"
Test on different timeframe (4-hour or daily)
If Too Few Signals:
Decrease "Min Indicators Aligned" to 2
Turn OFF all requirement filters
Widen Williams %R bands to -15 and -85
If Too Many False Signals:
Increase "Min Indicators Aligned" to 3 or 4
Turn ON "Require Divergence"
Turn ON "Require Volume Spike"
Reduce Max Pyramid Entries to 5
Stock Selection Guidelines:
Best Suited For:
Large-cap stable stocks (V, MSFT, WMT)
ETFs (IWM, SPY, QQQ)
Stocks with clear support/resistance
Mean-reverting instruments
Avoid:
Ultra low-volume penny stocks
Extremely volatile crypto (try traditional settings first)
Stocks in strong one-directional trends lasting months
🔄 The "Flip All Signals" Feature
If backtesting shows poor results on a particular stock, try toggling "Flip All Signals" to ON:
STANDARD Mode (OFF):
Buy when oversold (reversal strategy)
Sell when overbought
May work best for: V, MSFT, WMT, IWM, NOW, WM
FLIPPED Mode (ON):
Buy when overbought (momentum strategy)
Sell when oversold
May work best for: Strong trending stocks, momentum plays, crypto
Test both modes on your stock to see which performs better!
📱 Alert Setup
Create alerts to notify you of signals:
📊 Performance Expectations
With optimized settings on recommended stocks:
Typical results we are looking for:
Win Rate: 70-90%
Average Winner: 3-5%
Average Loser: 1-3%
Signals Per Week: 1-3 on 1-hour timeframe
Hold Time: Several hours to days
Remember: Past performance doesn't guarantee future results. Always use proper risk management.
LibBrStLibrary "LibBrSt"
This is a library for quantitative analysis, designed to estimate
the statistical properties of price movements *within* a single
OHLC bar, without requiring access to tick data. It provides a
suite of estimators based on various statistical and econometric
models, allowing for analysis of intra-bar volatility and
price distribution.
Key Capabilities:
1. **Price Distribution Models (`PriceEst`):** Provides a selection
of estimators that model intra-bar price action as a probability
distribution over the range. This allows for the
calculation of the intra-bar mean (`priceMean`) and standard
deviation (`priceStdDev`) in absolute price units. Models include:
- **Symmetric Models:** `uniform`, `triangular`, `arcsine`,
`betaSym`, and `t4Sym` (Student-t with fat tails).
- **Skewed Models:** `betaSkew` and `t4Skew`, which adjust
their shape based on the Open/Close position.
- **Model Assumptions:** The skewed models rely on specific
internal constants. `betaSkew` uses a fixed concentration
parameter (`BETA_SKEW_CONCENTRATION = 4.0`), and `t4Sym`/`t4Skew`
use a heuristic scaling factor (`T4_SHAPE_FACTOR`)
to map the distribution.
2. **Econometric Log-Return Estimators (`LogEst`):** Includes a set of
econometric estimators for calculating the volatility (`logStdDev`)
and drift (`logMean`) of logarithmic returns within a single bar.
These are unit-less measures. Models include:
- **Parkinson (1980):** A High-Low range estimator.
- **Garman-Klass (1980):** An OHLC-based estimator.
- **Rogers-Satchell (1991):** An OHLC estimator that accounts
for non-zero drift.
3. **Distribution Analysis (PDF/CDF):** Provides functions to work
with the Probability Density Function (`pricePdf`) and
Cumulative Distribution Function (`priceCdf`) of the
chosen price model.
- **Note on `priceCdf`:** This function uses analytical (exact)
calculations for the `uniform`, `triangular`, and `arcsine`
models. For all other models (e.g., `betaSkew`, `t4Skew`),
it uses **numerical integration (Simpson's rule)** as
an approximation of the cumulative probability.
4. **Mathematical Functions:** The library's Beta distribution
models (`betaSym`, `betaSkew`) are supported by an internal
implementation of the natural log-gamma function, which is
based on the Lanczos approximation.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
priceStdDev(estimator, offset)
Estimates **σ̂** (standard deviation) *in price units* for the current
bar, according to the chosen `PriceEst` distribution assumption.
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float σ̂ ≥ 0 ; `na` if undefined (e.g. zero range).
priceMean(estimator, offset)
Estimates **μ̂** (mean price) for the chosen `PriceEst` within the
current bar.
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float μ̂ in price units.
pricePdf(estimator, price, offset)
Probability-density under the chosen `PriceEst` model.
**Returns 0** when `p` is outside the current bar’s .
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
price (float) : series float Price level to evaluate.
offset (int) : series int To offset the calculated bar
Returns: series float Density value.
priceCdf(estimator, upper, lower, steps, offset)
Cumulative probability **between** `upper` and `lower` under
the chosen `PriceEst` model. Outside-bar regions contribute zero.
Uses a fast, analytical calculation for Uniform, Triangular, and
Arcsine distributions, and defaults to numerical integration
(Simpson's rule) for more complex models.
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
upper (float) : series float Upper Integration Boundary.
lower (float) : series float Lower Integration Boundary.
steps (int) : series int # of sub-intervals for numerical integration (if used).
offset (int) : series int To offset the calculated bar.
Returns: series float Probability mass ∈ .
logStdDev(estimator, offset)
Estimates **σ̂** (standard deviation) of *log-returns* for the current bar.
Parameters:
estimator (series LogEst) : series LogEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float σ̂ (unit-less); `na` if undefined.
logMean(estimator, offset)
Estimates μ̂ (mean log-return / drift) for the chosen `LogEst`.
The returned value is consistent with the assumptions of the
selected volatility estimator.
Parameters:
estimator (series LogEst) : series LogEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float μ̂ (unit-less log-return).
LibWghtLibrary "LibWght"
This is a library of mathematical and statistical functions
designed for quantitative analysis in Pine Script. Its core
principle is the integration of a custom weighting series
(e.g., volume) into a wide array of standard technical
analysis calculations.
Key Capabilities:
1. **Universal Weighting:** All exported functions accept a `weight`
parameter. This allows standard calculations (like moving
averages, RSI, and standard deviation) to be influenced by an
external data series, such as volume or tick count.
2. **Weighted Averages and Indicators:** Includes a comprehensive
collection of weighted functions:
- **Moving Averages:** `wSma`, `wEma`, `wWma`, `wRma` (Wilder's),
`wHma` (Hull), and `wLSma` (Least Squares / Linear Regression).
- **Oscillators & Ranges:** `wRsi`, `wAtr` (Average True Range),
`wTr` (True Range), and `wR` (High-Low Range).
3. **Volatility Decomposition:** Provides functions to decompose
total variance into distinct components for market analysis.
- **Two-Way Decomposition (`wTotVar`):** Separates variance into
**between-bar** (directional) and **within-bar** (noise)
components.
- **Three-Way Decomposition (`wLRTotVar`):** Decomposes variance
relative to a linear regression into **Trend** (explained by
the LR slope), **Residual** (mean-reversion around the
LR line), and **Within-Bar** (noise) components.
- **Local Volatility (`wLRLocTotStdDev`):** Measures the total
"noise" (within-bar + residual) around the trend line.
4. **Weighted Statistics and Regression:** Provides a robust
function for Weighted Linear Regression (`wLinReg`) and a
full suite of related statistical measures:
- **Between-Bar Stats:** `wBtwVar`, `wBtwStdDev`, `wBtwStdErr`.
- **Residual Stats:** `wResVar`, `wResStdDev`, `wResStdErr`.
5. **Fallback Mechanism:** All functions are designed for reliability.
If the total weight over the lookback period is zero (e.g., in
a no-volume period), the algorithms automatically fall back to
their unweighted, uniform-weight equivalents (e.g., `wSma`
becomes a standard `ta.sma`), preventing errors and ensuring
continuous calculation.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
wSma(source, weight, length)
Weighted Simple Moving Average (linear kernel).
Parameters:
source (float) : series float Data to average.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 1.
Returns: series float Linear-kernel weighted mean; falls back to
the arithmetic mean if Σweight = 0.
wEma(source, weight, length)
Weighted EMA (exponential kernel).
Parameters:
source (float) : series float Data to average.
weight (float) : series float Weight series.
length (simple int) : simple int Look-back length ≥ 1.
Returns: series float Exponential-kernel weighted mean; falls
back to classic EMA if Σweight = 0.
wWma(source, weight, length)
Weighted WMA (linear kernel).
Parameters:
source (float) : series float Data to average.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 1.
Returns: series float Linear-kernel weighted mean; falls back to
classic WMA if Σweight = 0.
wRma(source, weight, length)
Weighted RMA (Wilder kernel, α = 1/len).
Parameters:
source (float) : series float Data to average.
weight (float) : series float Weight series.
length (simple int) : simple int Look-back length ≥ 1.
Returns: series float Wilder-kernel weighted mean; falls back to
classic RMA if Σweight = 0.
wHma(source, weight, length)
Weighted HMA (linear kernel).
Parameters:
source (float) : series float Data to average.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 1.
Returns: series float Linear-kernel weighted mean; falls back to
classic HMA if Σweight = 0.
wRsi(source, weight, length)
Weighted Relative Strength Index.
Parameters:
source (float) : series float Price series.
weight (float) : series float Weight series.
length (simple int) : simple int Look-back length ≥ 1.
Returns: series float Weighted RSI; uniform if Σw = 0.
wAtr(tr, weight, length)
Weighted ATR (Average True Range).
Implemented as WRMA on *true range*.
Parameters:
tr (float) : series float True Range series.
weight (float) : series float Weight series.
length (simple int) : simple int Look-back length ≥ 1.
Returns: series float Weighted ATR; uniform weights if Σw = 0.
wTr(tr, weight, length)
Weighted True Range over a window.
Parameters:
tr (float) : series float True Range series.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 1.
Returns: series float Weighted mean of TR; uniform if Σw = 0.
wR(r, weight, length)
Weighted High-Low Range over a window.
Parameters:
r (float) : series float High-Low per bar.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 1.
Returns: series float Weighted mean of range; uniform if Σw = 0.
wBtwVar(source, weight, length, biased)
Weighted Between Variance (biased/unbiased).
Parameters:
source (float) : series float Data series.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population (biased); false → sample.
Returns:
variance series float The calculated between-bar variance (σ²btw), either biased or unbiased.
sumW series float The sum of weights over the lookback period (Σw).
sumW2 series float The sum of squared weights over the lookback period (Σw²).
wBtwStdDev(source, weight, length, biased)
Weighted Between Standard Deviation.
Parameters:
source (float) : series float Data series.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population (biased); false → sample.
Returns: series float σbtw uniform if Σw = 0.
wBtwStdErr(source, weight, length, biased)
Weighted Between Standard Error.
Parameters:
source (float) : series float Data series.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population (biased); false → sample.
Returns: series float √(σ²btw / N_eff) uniform if Σw = 0.
wTotVar(mu, sigma, weight, length, biased)
Weighted Total Variance (= between-group + within-group).
Useful when each bar represents an aggregate with its own
mean* and pre-estimated σ (e.g., second-level ranges inside a
1-minute bar). Assumes the *weight* series applies to both the
group means and their σ estimates.
Parameters:
mu (float) : series float Group means (e.g., HL2 of 1-second bars).
sigma (float) : series float Pre-estimated σ of each group (same basis).
weight (float) : series float Weight series (volume, ticks, …).
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population (biased); false → sample.
Returns:
varBtw series float The between-bar variance component (σ²btw).
varWtn series float The within-bar variance component (σ²wtn).
sumW series float The sum of weights over the lookback period (Σw).
sumW2 series float The sum of squared weights over the lookback period (Σw²).
wTotStdDev(mu, sigma, weight, length, biased)
Weighted Total Standard Deviation.
Parameters:
mu (float) : series float Group means (e.g., HL2 of 1-second bars).
sigma (float) : series float Pre-estimated σ of each group (same basis).
weight (float) : series float Weight series (volume, ticks, …).
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population (biased); false → sample.
Returns: series float σtot.
wTotStdErr(mu, sigma, weight, length, biased)
Weighted Total Standard Error.
SE = √( total variance / N_eff ) with the same effective sample
size logic as `wster()`.
Parameters:
mu (float) : series float Group means (e.g., HL2 of 1-second bars).
sigma (float) : series float Pre-estimated σ of each group (same basis).
weight (float) : series float Weight series (volume, ticks, …).
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population (biased); false → sample.
Returns: series float √(σ²tot / N_eff).
wLinReg(source, weight, length)
Weighted Linear Regression.
Parameters:
source (float) : series float Data series.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 2.
Returns:
mid series float The estimated value of the regression line at the most recent bar.
slope series float The slope of the regression line.
intercept series float The intercept of the regression line.
wResVar(source, weight, midLine, slope, length, biased)
Weighted Residual Variance.
linear regression – optionally biased (population) or
unbiased (sample).
Parameters:
source (float) : series float Data series.
weight (float) : series float Weighting series (volume, etc.).
midLine (float) : series float Regression value at the last bar.
slope (float) : series float Slope per bar.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population variance (σ²_P), denominator ≈ N_eff.
false → sample variance (σ²_S), denominator ≈ N_eff - 2.
(Adjusts for 2 degrees of freedom lost to the regression).
Returns:
variance series float The calculated residual variance (σ²res), either biased or unbiased.
sumW series float The sum of weights over the lookback period (Σw).
sumW2 series float The sum of squared weights over the lookback period (Σw²).
wResStdDev(source, weight, midLine, slope, length, biased)
Weighted Residual Standard Deviation.
Parameters:
source (float) : series float Data series.
weight (float) : series float Weight series.
midLine (float) : series float Regression value at the last bar.
slope (float) : series float Slope per bar.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population (biased); false → sample.
Returns: series float σres; uniform if Σw = 0.
wResStdErr(source, weight, midLine, slope, length, biased)
Weighted Residual Standard Error.
Parameters:
source (float) : series float Data series.
weight (float) : series float Weight series.
midLine (float) : series float Regression value at the last bar.
slope (float) : series float Slope per bar.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population (biased); false → sample.
Returns: series float √(σ²res / N_eff); uniform if Σw = 0.
wLRTotVar(mu, sigma, weight, midLine, slope, length, biased)
Weighted Linear-Regression Total Variance **around the
window’s weighted mean μ**.
σ²_tot = E_w ⟶ *within-group variance*
+ Var_w ⟶ *residual variance*
+ Var_w ⟶ *trend variance*
where each bar i in the look-back window contributes
m_i = *mean* (e.g. 1-sec HL2)
σ_i = *sigma* (pre-estimated intrabar σ)
w_i = *weight* (volume, ticks, …)
ŷ_i = b₀ + b₁·x (value of the weighted LR line)
r_i = m_i − ŷ_i (orthogonal residual)
Parameters:
mu (float) : series float Per-bar mean m_i.
sigma (float) : series float Pre-estimated σ_i of each bar.
weight (float) : series float Weight series w_i (≥ 0).
midLine (float) : series float Regression value at the latest bar (ŷₙ₋₁).
slope (float) : series float Slope b₁ of the regression line.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population; false → sample.
Returns:
varRes series float The residual variance component (σ²res).
varWtn series float The within-bar variance component (σ²wtn).
varTrd series float The trend variance component (σ²trd), explained by the linear regression.
sumW series float The sum of weights over the lookback period (Σw).
sumW2 series float The sum of squared weights over the lookback period (Σw²).
wLRTotStdDev(mu, sigma, weight, midLine, slope, length, biased)
Weighted Linear-Regression Total Standard Deviation.
Parameters:
mu (float) : series float Per-bar mean m_i.
sigma (float) : series float Pre-estimated σ_i of each bar.
weight (float) : series float Weight series w_i (≥ 0).
midLine (float) : series float Regression value at the latest bar (ŷₙ₋₁).
slope (float) : series float Slope b₁ of the regression line.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population; false → sample.
Returns: series float √(σ²tot).
wLRTotStdErr(mu, sigma, weight, midLine, slope, length, biased)
Weighted Linear-Regression Total Standard Error.
SE = √( σ²_tot / N_eff ) with N_eff = Σw² / Σw² (like in wster()).
Parameters:
mu (float) : series float Per-bar mean m_i.
sigma (float) : series float Pre-estimated σ_i of each bar.
weight (float) : series float Weight series w_i (≥ 0).
midLine (float) : series float Regression value at the latest bar (ŷₙ₋₁).
slope (float) : series float Slope b₁ of the regression line.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population; false → sample.
Returns: series float √((σ²res, σ²wtn, σ²trd) / N_eff).
wLRLocTotStdDev(mu, sigma, weight, midLine, slope, length, biased)
Weighted Linear-Regression Local Total Standard Deviation.
Measures the total "noise" (within-bar + residual) around the trend.
Parameters:
mu (float) : series float Per-bar mean m_i.
sigma (float) : series float Pre-estimated σ_i of each bar.
weight (float) : series float Weight series w_i (≥ 0).
midLine (float) : series float Regression value at the latest bar (ŷₙ₋₁).
slope (float) : series float Slope b₁ of the regression line.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population; false → sample.
Returns: series float √(σ²wtn + σ²res).
wLRLocTotStdErr(mu, sigma, weight, midLine, slope, length, biased)
Weighted Linear-Regression Local Total Standard Error.
Parameters:
mu (float) : series float Per-bar mean m_i.
sigma (float) : series float Pre-estimated σ_i of each bar.
weight (float) : series float Weight series w_i (≥ 0).
midLine (float) : series float Regression value at the latest bar (ŷₙ₋₁).
slope (float) : series float Slope b₁ of the regression line.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population; false → sample.
Returns: series float √((σ²wtn + σ²res) / N_eff).
wLSma(source, weight, length)
Weighted Least Square Moving Average.
Parameters:
source (float) : series float Data series.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 2.
Returns: series float Least square weighted mean. Falls back
to unweighted regression if Σw = 0.





















