OPEN-SOURCE SCRIPT
Historical Matrix Analyzer [PhenLabs]

📊Historical Matrix Analyzer [PhenLabs]
Version: PineScriptv6
📌Description
The Historical Matrix Analyzer is an advanced probabilistic trading tool that transforms technical analysis into a data-driven decision support system. By creating a comprehensive 56-cell matrix that tracks every combination of RSI states and multi-indicator conditions, this indicator reveals which market patterns have historically led to profitable outcomes and which have not.
At its core, the indicator continuously monitors seven distinct RSI states (ranging from Extreme Oversold to Extreme Overbought) and eight unique indicator combinations (MACD direction, volume levels, and price momentum). For each of these 56 possible market states, the system calculates average forward returns, win rates, and occurrence counts based on your configurable lookback period. The result is a color-coded probability matrix that shows you exactly where you stand in the historical performance landscape.
The standout feature is the Current State Panel, which provides instant clarity on your active market conditions. This panel displays signal strength classifications (from Strong Bullish to Strong Bearish), the average return percentage for similar past occurrences, an estimated win rate using Bayesian smoothing to prevent small-sample distortions, and a confidence level indicator that warns you when insufficient data exists for reliable conclusions.
🚀Points of Innovation
🔧Core Components
🔥Key Features
🎨Visualization


📖Usage Guidelines
RSI Period
MACD Fast Length
MACD Slow Length
MACD Signal Length
Volume MA Period
Statistics Lookback Period
Forward Performance Bars
Color Intensity Sensitivity
Minimum Occurrences for Coloring
Table Position
Show Current State Panel
Info Panel Position
Win Rate Smoothing Strength
✅Best Use Cases
⚠️Limitations
💡What Makes This Unique
🔬How It Works
1. State Classification and Encoding
2. Historical Data Accumulation
3. Forward Return Calculation and Statistics Update
Version: PineScriptv6
📌Description
The Historical Matrix Analyzer is an advanced probabilistic trading tool that transforms technical analysis into a data-driven decision support system. By creating a comprehensive 56-cell matrix that tracks every combination of RSI states and multi-indicator conditions, this indicator reveals which market patterns have historically led to profitable outcomes and which have not.
At its core, the indicator continuously monitors seven distinct RSI states (ranging from Extreme Oversold to Extreme Overbought) and eight unique indicator combinations (MACD direction, volume levels, and price momentum). For each of these 56 possible market states, the system calculates average forward returns, win rates, and occurrence counts based on your configurable lookback period. The result is a color-coded probability matrix that shows you exactly where you stand in the historical performance landscape.
The standout feature is the Current State Panel, which provides instant clarity on your active market conditions. This panel displays signal strength classifications (from Strong Bullish to Strong Bearish), the average return percentage for similar past occurrences, an estimated win rate using Bayesian smoothing to prevent small-sample distortions, and a confidence level indicator that warns you when insufficient data exists for reliable conclusions.
🚀Points of Innovation
- Multi-dimensional state classification combining 7 RSI levels with 8 indicator combinations for 56 unique trackable market conditions
- Bayesian win rate estimation with adjustable smoothing strength to provide stable probability estimates even with limited historical samples
- Real-time active cell highlighting with “NOW” marker that visually connects current market conditions to their historical performance data
- Configurable color intensity sensitivity allowing traders to adjust heat-map responsiveness from conservative to aggressive visual feedback
- Dual-panel display system separating the comprehensive statistics matrix from an easy-to-read current state summary panel
- Intelligent confidence scoring that automatically warns traders when occurrence counts fall below reliable thresholds
🔧Core Components
- RSI State Classification: Segments RSI readings into 7 distinct zones (Extreme Oversold <20, Oversold 20-30, Weak 30-40, Neutral 40-60, Strong 60-70, Overbought 70-80, Extreme Overbought >80) to capture momentum extremes and transitions
- Multi-Indicator Condition Tracking: Simultaneously monitors MACD crossover status (bullish/bearish), volume relative to moving average (high/low), and price direction (rising/falling) creating 8 binary-encoded combinations
- Historical Data Storage Arrays: Maintains rolling lookback windows storing RSI states, indicator states, prices, and bar indices for precise forward-return calculations
- Forward Performance Calculator: Measures price changes over configurable forward bar periods (1-20 bars) from each historical state, accumulating total returns and win counts per matrix cell
- Bayesian Smoothing Engine: Applies statistical prior assumptions (default 50% win rate) weighted by user-defined strength parameter to stabilize estimated win rates when sample sizes are small
- Dynamic Color Mapping System: Converts average returns into color-coded heat map with intensity adjusted by sensitivity parameter and transparency modified by confidence levels
🔥Key Features
- 56-Cell Probability Matrix: Comprehensive grid displaying every possible combination of RSI state and indicator condition, with each cell showing average return percentage, estimated win rate, and occurrence count for complete statistical visibility
- Current State Info Panel: Dedicated display showing your exact position in the matrix with signal strength emoji indicators, numerical statistics, and color-coded confidence warnings for immediate situational awareness
- Customizable Lookback Period: Adjustable historical window from 50 to 500 bars allowing traders to focus on recent market behavior or capture longer-term pattern stability across different market cycles
- Configurable Forward Performance Window: Select target holding periods from 1 to 20 bars ahead to align probability calculations with your trading timeframe, whether day trading or swing trading
- Visual Heat Mapping: Color-coded cells transition from red (bearish historical performance) through gray (neutral) to green (bullish performance) with intensity reflecting statistical significance and occurrence frequency
- Intelligent Data Filtering: Minimum occurrence threshold (1-10) removes unreliable patterns with insufficient historical samples, displaying gray warning colors for low-confidence cells
- Flexible Layout Options: Independent positioning of statistics matrix and info panel to any screen corner, accommodating different chart layouts and personal preferences
- Tooltip Details: Hover over any matrix cell to see full RSI label, complete indicator status description, precise average return, estimated win rate, and total occurrence count
🎨Visualization
- Statistics Matrix Table: A 9-column by 8-row grid with RSI states labeling vertical axis and indicator combinations on horizontal axis, using compact abbreviations (XOverS, OverB, MACD↑, Vol↓, P↑) for space efficiency
- Active Cell Indicator: The current market state cell displays “⦿ NOW ⦿” in yellow text with enhanced color saturation to immediately draw attention to relevant historical performance
- Signal Strength Visualization: Info panel uses emoji indicators (🔥 Strong Bullish, ✅ Bullish, ↗️ Weak Bullish, ➖ Neutral, ↘️ Weak Bearish, ⛔ Bearish, ❄️ Strong Bearish, ⚠️ Insufficient Data) for rapid interpretation
- Histogram Plot: Below the price chart, a green/red histogram displays the current cell’s average return percentage, providing a time-series view of how historical performance changes as market conditions evolve
- Color Intensity Scaling: Cell background transparency and saturation dynamically adjust based on both the magnitude of average returns and the occurrence count, ensuring visual emphasis on reliable patterns
- Confidence Level Display: Info panel bottom row shows “High Confidence” (green), “Medium Confidence” (orange), or “Low Confidence” (red) based on occurrence counts relative to minimum threshold multipliers
📖Usage Guidelines
RSI Period
- Default: 14
- Range: 1 to unlimited
- Description: Controls the lookback period for RSI momentum calculation. Standard 14-period provides widely-recognized overbought/oversold levels. Decrease for faster, more sensitive RSI reactions suitable for scalping. Increase (21, 28) for smoother, longer-term momentum assessment in swing trading. Changes affect how quickly the indicator moves between the 7 RSI state classifications.
MACD Fast Length
- Default: 12
- Range: 1 to unlimited
- Description: Sets the faster exponential moving average for MACD calculation. Standard 12-period setting works well for daily charts and captures short-term momentum shifts. Decreasing creates more responsive MACD crossovers but increases false signals. Increasing smooths out noise but delays signal generation, affecting the bullish/bearish indicator state classification.
MACD Slow Length
- Default: 26
- Range: 1 to unlimited
- Description: Defines the slower exponential moving average for MACD calculation. Traditional 26-period setting balances trend identification with responsiveness. Must be greater than Fast Length. Wider spread between fast and slow increases MACD sensitivity to trend changes, impacting the frequency of indicator state transitions in the matrix.
MACD Signal Length
- Default: 9
- Range: 1 to unlimited
- Description: Smoothing period for the MACD signal line that triggers bullish/bearish state changes. Standard 9-period provides reliable crossover signals. Shorter values create more frequent state changes and earlier signals but with more whipsaws. Longer values produce more confirmed, stable signals but with increased lag in detecting momentum shifts.
Volume MA Period
- Default: 20
- Range: 1 to unlimited
- Description: Lookback period for volume moving average used to classify volume as “high” or “low” in indicator state combinations. 20-period default captures typical monthly trading patterns. Shorter periods (10-15) make volume classification more reactive to recent spikes. Longer periods (30-50) require more sustained volume changes to trigger state classification shifts.
Statistics Lookback Period
- Default: 200
- Range: 50 to 500
- Description: Number of historical bars used to calculate matrix statistics. 200 bars provides substantial data for reliable patterns while remaining responsive to regime changes. Lower values (50-100) emphasize recent market behavior and adapt quickly but may produce volatile statistics. Higher values (300-500) capture long-term patterns with stable statistics but slower adaptation to changing market dynamics.
Forward Performance Bars
- Default: 5
- Range: 1 to 20
- Description: Number of bars ahead used to calculate forward returns from each historical state occurrence. 5-bar default suits intraday to short-term swing trading (5 hours on hourly charts, 1 week on daily charts). Lower values (1-3) target short-term momentum trades. Higher values (10-20) align with position trading and longer-term pattern exploitation.
Color Intensity Sensitivity
- Default: 2.0
- Range: 0.5 to 5.0, step 0.5
- Description: Amplifies or dampens the color intensity response to average return magnitudes in the matrix heat map. 2.0 default provides balanced visual emphasis. Lower values (0.5-1.0) create subtle coloring requiring larger returns for full saturation, useful for volatile instruments. Higher values (3.0-5.0) produce vivid colors from smaller returns, highlighting subtle edges in range-bound markets.
Minimum Occurrences for Coloring
- Default: 3
- Range: 1 to 10
- Description: Required minimum sample size before applying color-coded performance to matrix cells. Cells with fewer occurrences display gray “insufficient data” warning. 3-occurrence default filters out rare patterns. Lower threshold (1-2) shows more data but includes unreliable single-event statistics. Higher thresholds (5-10) ensure only well-established patterns receive visual emphasis.
Table Position
- Default: top_right
- Options: top_left, top_right, bottom_left, bottom_right
- Description: Screen location for the 56-cell statistics matrix table. Position to avoid overlapping critical price action or other indicators on your chart. Consider chart orientation and candlestick density when selecting optimal placement.
Show Current State Panel
- Default: true
- Options: true, false
- Description: Toggle visibility of the dedicated current state information panel. When enabled, displays signal strength, RSI value, indicator status, average return, estimated win rate, and confidence level for active market conditions. Disable to declutter charts when only the matrix table is needed.
Info Panel Position
- Default: bottom_left
- Options: top_left, top_right, bottom_left, bottom_right
- Description: Screen location for the current state information panel (when enabled). Position independently from statistics matrix to optimize chart real estate. Typically placed opposite the matrix table for balanced visual layout.
Win Rate Smoothing Strength
- Default: 5
- Range: 1 to 20
- Description: Controls Bayesian prior weighting for estimated win rate calculations. Acts as virtual sample size assuming 50% win rate baseline. Default 5 provides moderate smoothing preventing extreme win rate estimates from small samples. Lower values (1-3) reduce smoothing effect, allowing win rates to reflect raw data more directly. Higher values (10-20) increase conservatism, pulling win rate estimates toward 50% until substantial evidence accumulates.
✅Best Use Cases
- Pattern-based discretionary trading where you want historical confirmation before entering setups that “look good” based on current technical alignment
- Swing trading with holding periods matching your forward performance bar setting, using high-confidence bullish cells as entry filters
- Risk assessment and position sizing, allocating larger size to trades originating from cells with strong positive average returns and high estimated win rates
- Market regime identification by observing which RSI states and indicator combinations are currently producing the most reliable historical patterns
- Backtesting validation by comparing your manual strategy signals against the historical performance of the corresponding matrix cells
- Educational tool for developing intuition about which technical condition combinations have actually worked versus those that feel right but lack historical evidence
⚠️Limitations
- Historical patterns do not guarantee future performance, especially during unprecedented market events or regime changes not represented in the lookback period
- Small sample sizes (low occurrence counts) produce unreliable statistics despite Bayesian smoothing, requiring caution when acting on low-confidence cells
- Matrix statistics lag behind rapidly changing market conditions, as the lookback period must accumulate new state occurrences before updating performance data
- Forward return calculations use fixed bar periods that may not align with actual trade exit timing, support/resistance levels, or volatility-adjusted profit targets
💡What Makes This Unique
- Multi-Dimensional State Space: Unlike single-indicator tools, simultaneously tracks 56 distinct market condition combinations providing granular pattern resolution unavailable in traditional technical analysis
- Bayesian Statistical Rigor: Implements proper probabilistic smoothing to prevent overconfidence from limited data, a critical feature missing from most pattern recognition tools
- Real-Time Contextual Feedback: The “NOW” marker and dedicated info panel instantly connect current market conditions to their historical performance profile, eliminating guesswork
- Transparent Occurrence Counts: Displays sample sizes directly in each cell, allowing traders to judge statistical reliability themselves rather than hiding data quality issues
- Fully Customizable Analysis Window: Complete control over lookback depth and forward return horizons lets traders align the tool precisely with their trading timeframe and strategy requirements
🔬How It Works
1. State Classification and Encoding
- Each bar’s RSI value is evaluated and assigned to one of 7 discrete states based on threshold levels (0: <20, 1: 20-30, 2: 30-40, 3: 40-60, 4: 60-70, 5: 70-80, 6: >80)
- Simultaneously, three binary conditions are evaluated: MACD line position relative to signal line, current volume relative to its moving average, and current close relative to previous close
- These three binary conditions are combined into a single indicator state integer (0-7) using binary encoding, creating 8 possible indicator combinations
- The RSI state and indicator state are stored together, defining one of 56 possible market condition cells in the matrix
2. Historical Data Accumulation
- As each bar completes, the current state classification, closing price, and bar index are stored in rolling arrays maintained at the size specified by the lookback period
- When the arrays reach capacity, the oldest data point is removed and the newest added, creating a sliding historical window
- This continuous process builds a comprehensive database of past market conditions and their subsequent price movements
3. Forward Return Calculation and Statistics Update
- On each bar, the indicator looks back through the stored historical data to find bars where sufficient forward bars exist to measure outcomes
- For each historical occurrence, the price change from that bar to the bar N periods ahead (where N is the forward performance bars setting) is calculated as a percentage return
- This percentage return is added to the cumulative return total for the specific matrix cell corresponding to that historical bar’s state classification
- Occurrence counts are incremented, and wins are tallied for positive returns, building comprehensive statistics for each of the 56 cells
- The Bayesian smoothing formula combines these raw statistics with prior assumptions (neutral 50% win rate) weighted by the smoothing strength parameter to produce estimated win rates that remain stable even with small samples
💡Note:
The Historical Matrix Analyzer is designed as a decision support tool, not a standalone trading system. Best results come from using it to validate discretionary trade ideas or filter systematic strategy signals. Always combine matrix insights with proper risk management, position sizing rules, and awareness of broader market context. The estimated win rate feature uses Bayesian statistics specifically to prevent false confidence from limited data, but no amount of smoothing can create reliable predictions from fundamentally insufficient sample sizes. Focus on high-confidence cells (green-colored confidence indicators) with occurrence counts well above your minimum threshold for the most actionable insights.
Script open-source
In pieno spirito TradingView, il creatore di questo script lo ha reso open-source, in modo che i trader possano esaminarlo e verificarne la funzionalità. Complimenti all'autore! Sebbene sia possibile utilizzarlo gratuitamente, ricorda che la ripubblicazione del codice è soggetta al nostro Regolamento.
Platform: phenlabs.com
Join our growing community: discord.gg/phenlabs
All content provided by PhenLabs is for informational & educational purposes only. Past performance does not guarantee future results.
Join our growing community: discord.gg/phenlabs
All content provided by PhenLabs is for informational & educational purposes only. Past performance does not guarantee future results.
Declinazione di responsabilità
Le informazioni ed i contenuti pubblicati non costituiscono in alcun modo una sollecitazione ad investire o ad operare nei mercati finanziari. Non sono inoltre fornite o supportate da TradingView. Maggiori dettagli nelle Condizioni d'uso.
Script open-source
In pieno spirito TradingView, il creatore di questo script lo ha reso open-source, in modo che i trader possano esaminarlo e verificarne la funzionalità. Complimenti all'autore! Sebbene sia possibile utilizzarlo gratuitamente, ricorda che la ripubblicazione del codice è soggetta al nostro Regolamento.
Platform: phenlabs.com
Join our growing community: discord.gg/phenlabs
All content provided by PhenLabs is for informational & educational purposes only. Past performance does not guarantee future results.
Join our growing community: discord.gg/phenlabs
All content provided by PhenLabs is for informational & educational purposes only. Past performance does not guarantee future results.
Declinazione di responsabilità
Le informazioni ed i contenuti pubblicati non costituiscono in alcun modo una sollecitazione ad investire o ad operare nei mercati finanziari. Non sono inoltre fornite o supportate da TradingView. Maggiori dettagli nelle Condizioni d'uso.