OPEN-SOURCE SCRIPT
Market State Router [Permutation + Eigenstructure]

MSR-PX is an experimental quantitative market-regime and systemic-pressure framework designed to classify the environment surrounding price rather than operate as a conventional buy/sell oscillator.
Instead of asking only whether price is rising or falling, MSR-PX evaluates several dimensions of market behavior:
The result is a rule-based Market State Router that classifies conditions as Trend, Breakout, Mean Reversion, Event/Systemic Risk, No Trade, or Loading Data.
🧠 CORE ENGINE 1 — LOCAL PERMUTATION STRUCTURE
MSR-PX measures local price-order dynamics using normalized permutation entropy.
Default configuration:
Permutation entropy examines the ordering of consecutive price observations rather than simply measuring return magnitude.
Lower entropy indicates that a smaller subset of ordinal patterns is dominating recent behavior, suggesting greater local structure.
Higher entropy indicates that ordinal patterns are being expressed more uniformly, suggesting increasing disorder.
MSR-PX ranks this structural measurement against its recent historical baseline so the router can evaluate structure relative to the market's own recent behavior.
⚡ CORE ENGINE 2 — DIRECTIONAL EFFICIENCY
Directional efficiency compares:
Absolute net displacement
against
Total bar-to-bar travel
over the selected lookback.
This helps separate two environments that may have similar volatility but very different internal behavior:
Higher efficiency supports directional Trend and Breakout states.
Lower efficiency supports rotational and Mean Reversion interpretations.
🌐 CORE ENGINE 3 — CROSS-ASSET EIGENSTRUCTURE
MSR-PX builds a rolling 5 × 5 cross-asset correlation system from synchronized observations of:
The benchmark symbols are configurable.
The cross-asset network updates only from synchronized observations, helping avoid partially populated correlation samples when benchmark data is unavailable.
MSR-PX then analyzes the matrix's eigenvalue spectrum to estimate how concentrated market behavior has become around a common factor.
Diagnostics include:
When the dominant eigenvalue becomes increasingly concentrated while spectral entropy contracts, the network is behaving more like a coordinated system and less like a collection of independent markets.
🌀 CORE ENGINE 4 — SYSTEMIC ABSORPTION
Systemic Absorption is an MSR-PX composite measure of cross-asset common-factor concentration.
It incorporates:
The resulting measurement is designed to distinguish between:
The term Absorption here does not refer to traditional order-flow or liquidity absorption.
It specifically represents MSR-PX's estimate of systemic cross-asset concentration relative to its own historical baseline.
🎯 CORE ENGINE 5 — TARGET-ATTRIBUTED FACTOR DIRECTION
A strong systemic factor does not imply that every asset is responding to that factor in the same direction.
MSR-PX therefore adjusts the dominant factor impulse using the charted asset's loading magnitude and loading sign on the dominant eigenvector.
Conceptually:
Factor Impulse × Target Loading Strength × Target Loading Direction
This allows the router to distinguish between:
This target attribution is used when evaluating directional alignment and systemic conflict.
🚦 THE MARKET STATE ROUTER
The individual engines feed a priority-based classification system.
The router does not simply select whichever condition produces the largest number. Certain environments intentionally take precedence over normal directional states.
1. EVENT / SYSTEMIC RISK
The highest-priority state.
Event/Systemic Risk requires elevated systemic concentration together with either:
This state is intended to identify environments where broader cross-asset forces may be dominating normal local relationships.
When active, the router readout emphasizes reduced aggression rather than attempting to predict a specific directional trade.
2. BREAKOUT LONG / BREAKOUT SHORT
Breakout requires a stronger combination of:
Breakout represents the router's strongest coordinated directional state.
3. TREND LONG / TREND SHORT
Trend states identify directional environments characterized by:
Trend does not require the same degree of systemic impulse as Breakout.
4. MEAN REVERSION
Mean Reversion is favored when the environment shows a combination of:
This describes an environment where rotational interpretation may be more appropriate than directional continuation.
5. NO TRADE / LOADING DATA
No Trade means the router does not find sufficient evidence for one of the primary states.
Loading Data appears while the historical buffers required for permutation structure, synchronized correlation, eigenstructure, and percentile calculations are still populating.
These are intentional router outputs rather than errors.
📊 HOW TO READ MSR-PX
TREND LONG / SHORT
Local structure and directional efficiency support continuation in the routed direction.
BREAKOUT LONG / SHORT
Local direction and systemic participation are strongly coordinated.
This is the router's strongest directional participation regime.
MEAN REVERSION
Directional efficiency is weak, structure is disordered, and systemic coupling is limited.
The environment is behaving more rotationally than directionally.
EVENT / SYSTEMIC RISK
Cross-asset concentration is elevated and systemic impulse or local/systemic conflict has become unusually strong.
Normal local relationships may be less reliable during this state.
NO TRADE
Conditions are mixed, ambiguous, or insufficient for a stronger classification.
📈 STATE SCORE
MSR-PX includes an internal State Score summarizing the strength of evidence supporting the active regime.
This score is not a calibrated probability.
For example:
An 86% State Score does not mean there is an 86% probability that a trade will succeed.
It should be interpreted only as an internal regime-strength measurement derived from the router's component conditions.
🧪 FORWARD VALIDATION LOGGER
MSR-PX includes a built-in forward transition logger for research purposes.
The logger tracks whether detected systemic fragility conditions subsequently transition into an Event / Systemic Risk state within a configurable forward horizon.
It records information including:
This logger is a forward transition diagnostic.
It is not presented as a complete trading backtest, statistical significance test, or proof of predictive profitability.
⏱️ TIMEFRAME GUIDANCE
MSR-PX is designed primarily for intraday market-state analysis.
5 minutes is the recommended starting timeframe for the default configuration because it provides a practical balance between responsiveness and cross-asset regime stability.
No timeframe should be interpreted as universally or statistically optimal.
Regime behavior should be evaluated independently for the market, session, and trading horizon being studied.
🌍 SESSION AND BENCHMARK CONSIDERATIONS
The default network uses U.S.-centric equity, rates, dollar, and volatility benchmarks.
When MSR-PX is applied to:
users should consider both the trading schedules and economic relevance of the selected benchmark symbols.
Because the eigenstructure engine depends on synchronized observations, benchmark selection and session availability matter.
🔬 WHAT MSR-PX IS — AND IS NOT
MSR-PX is a market-state research and contextual framework.
It is not:
The state thresholds are currently rule-based rather than statistically learned.
The purpose of the project is to explore whether combining local ordinal structure, directional efficiency, cross-asset eigenstructure, systemic concentration, and target-specific factor attribution can provide useful context about the current market environment.
🔓 OPEN-SOURCE PHILOSOPHY
MSR-PX is published open source so the methodology can be inspected, challenged, modified, and independently tested.
The research question is whether combining:
provides useful market-state information beyond what any one component provides independently.
Users are encouraged to inspect the implementation, test different markets and timeframes, experiment with alternative benchmark networks, and evaluate the router's behavior independently.
⚠️ LIMITATIONS
Important limitations include:
DISCLAIMER
This indicator is provided for educational, analytical, and research purposes only.
Nothing presented by MSR-PX constitutes financial, investment, or trading advice.
Users are responsible for independently evaluating the methodology and determining whether information produced by the indicator is appropriate for their own research or decision-making.
Instead of asking only whether price is rising or falling, MSR-PX evaluates several dimensions of market behavior:
- Is local price action ordered or disordered?
- Is movement directionally efficient or rotational?
- Are major cross-asset markets becoming systemically coordinated?
- Is the charted asset participating in the dominant market factor?
- Are local and systemic forces aligned or in conflict?
- Which market-state interpretation is most consistent with the current environment?
The result is a rule-based Market State Router that classifies conditions as Trend, Breakout, Mean Reversion, Event/Systemic Risk, No Trade, or Loading Data.
🧠 CORE ENGINE 1 — LOCAL PERMUTATION STRUCTURE
MSR-PX measures local price-order dynamics using normalized permutation entropy.
Default configuration:
- Embedding dimension: 4
- Ordinal patterns: 24
- Permutation lookback: 250 bars
Permutation entropy examines the ordering of consecutive price observations rather than simply measuring return magnitude.
Lower entropy indicates that a smaller subset of ordinal patterns is dominating recent behavior, suggesting greater local structure.
Higher entropy indicates that ordinal patterns are being expressed more uniformly, suggesting increasing disorder.
MSR-PX ranks this structural measurement against its recent historical baseline so the router can evaluate structure relative to the market's own recent behavior.
⚡ CORE ENGINE 2 — DIRECTIONAL EFFICIENCY
Directional efficiency compares:
Absolute net displacement
against
Total bar-to-bar travel
over the selected lookback.
This helps separate two environments that may have similar volatility but very different internal behavior:
- Price traveling efficiently in one direction
- Price covering substantial distance while repeatedly reversing and rotating
Higher efficiency supports directional Trend and Breakout states.
Lower efficiency supports rotational and Mean Reversion interpretations.
🌐 CORE ENGINE 3 — CROSS-ASSET EIGENSTRUCTURE
MSR-PX builds a rolling 5 × 5 cross-asset correlation system from synchronized observations of:
- The charted asset
- SPY — U.S. equity risk
- TLT — long-duration Treasury exposure
- DXY — U.S. dollar
- VIX — implied equity volatility
The benchmark symbols are configurable.
The cross-asset network updates only from synchronized observations, helping avoid partially populated correlation samples when benchmark data is unavailable.
MSR-PX then analyzes the matrix's eigenvalue spectrum to estimate how concentrated market behavior has become around a common factor.
Diagnostics include:
- Dominant eigenvalue share
- Spectral entropy
- Common-factor concentration
- Target loading on the dominant eigenvector
When the dominant eigenvalue becomes increasingly concentrated while spectral entropy contracts, the network is behaving more like a coordinated system and less like a collection of independent markets.
🌀 CORE ENGINE 4 — SYSTEMIC ABSORPTION
Systemic Absorption is an MSR-PX composite measure of cross-asset common-factor concentration.
It incorporates:
- Dominant eigenvalue concentration
- Inverse spectral entropy
- Historical percentile normalization
The resulting measurement is designed to distinguish between:
- Decoupled environments, where local price behavior dominates
- Systemically coupled environments, where a shared cross-asset factor is exerting greater control
The term Absorption here does not refer to traditional order-flow or liquidity absorption.
It specifically represents MSR-PX's estimate of systemic cross-asset concentration relative to its own historical baseline.
🎯 CORE ENGINE 5 — TARGET-ATTRIBUTED FACTOR DIRECTION
A strong systemic factor does not imply that every asset is responding to that factor in the same direction.
MSR-PX therefore adjusts the dominant factor impulse using the charted asset's loading magnitude and loading sign on the dominant eigenvector.
Conceptually:
Factor Impulse × Target Loading Strength × Target Loading Direction
This allows the router to distinguish between:
- A systemic factor becoming active
- The charted asset participating in that factor
- The charted asset responding inversely to that factor
- Local price action conflicting with the target-attributed systemic direction
This target attribution is used when evaluating directional alignment and systemic conflict.
🚦 THE MARKET STATE ROUTER
The individual engines feed a priority-based classification system.
The router does not simply select whichever condition produces the largest number. Certain environments intentionally take precedence over normal directional states.
1. EVENT / SYSTEMIC RISK
The highest-priority state.
Event/Systemic Risk requires elevated systemic concentration together with either:
- A sufficiently strong systemic factor impulse
- Meaningful conflict between local price direction and the target-attributed dominant factor
This state is intended to identify environments where broader cross-asset forces may be dominating normal local relationships.
When active, the router readout emphasizes reduced aggression rather than attempting to predict a specific directional trade.
2. BREAKOUT LONG / BREAKOUT SHORT
Breakout requires a stronger combination of:
- Ordered local structure
- Sufficient directional efficiency
- Systemic participation
- Strong directional impulse
- Agreement between local and target-attributed factor direction
Breakout represents the router's strongest coordinated directional state.
3. TREND LONG / TREND SHORT
Trend states identify directional environments characterized by:
- Ordered structure
- Sufficient directional efficiency
- Active local directional impulse
- Directional consistency with systemic forces when systemic concentration is elevated
Trend does not require the same degree of systemic impulse as Breakout.
4. MEAN REVERSION
Mean Reversion is favored when the environment shows a combination of:
- Disordered local structure
- Weak or decoupled systemic absorption
- Low directional efficiency
This describes an environment where rotational interpretation may be more appropriate than directional continuation.
5. NO TRADE / LOADING DATA
No Trade means the router does not find sufficient evidence for one of the primary states.
Loading Data appears while the historical buffers required for permutation structure, synchronized correlation, eigenstructure, and percentile calculations are still populating.
These are intentional router outputs rather than errors.
📊 HOW TO READ MSR-PX
TREND LONG / SHORT
Local structure and directional efficiency support continuation in the routed direction.
BREAKOUT LONG / SHORT
Local direction and systemic participation are strongly coordinated.
This is the router's strongest directional participation regime.
MEAN REVERSION
Directional efficiency is weak, structure is disordered, and systemic coupling is limited.
The environment is behaving more rotationally than directionally.
EVENT / SYSTEMIC RISK
Cross-asset concentration is elevated and systemic impulse or local/systemic conflict has become unusually strong.
Normal local relationships may be less reliable during this state.
NO TRADE
Conditions are mixed, ambiguous, or insufficient for a stronger classification.
📈 STATE SCORE
MSR-PX includes an internal State Score summarizing the strength of evidence supporting the active regime.
This score is not a calibrated probability.
For example:
An 86% State Score does not mean there is an 86% probability that a trade will succeed.
It should be interpreted only as an internal regime-strength measurement derived from the router's component conditions.
🧪 FORWARD VALIDATION LOGGER
MSR-PX includes a built-in forward transition logger for research purposes.
The logger tracks whether detected systemic fragility conditions subsequently transition into an Event / Systemic Risk state within a configurable forward horizon.
It records information including:
- Total fragility transitions
- Warnings that reached Event/Systemic Risk
- Warnings that expired without transition
- Transition rate
- Average transition time
- Age of the currently pending observation
This logger is a forward transition diagnostic.
It is not presented as a complete trading backtest, statistical significance test, or proof of predictive profitability.
⏱️ TIMEFRAME GUIDANCE
MSR-PX is designed primarily for intraday market-state analysis.
5 minutes is the recommended starting timeframe for the default configuration because it provides a practical balance between responsiveness and cross-asset regime stability.
- 1 minute: Faster regime transitions and earlier sensitivity to changing conditions, with greater exposure to short-term noise.
- 5 minutes: Recommended default for active intraday regime analysis.
- 15 minutes: Slower and smoother regime context for traders who prefer less frequent state changes.
No timeframe should be interpreted as universally or statistically optimal.
Regime behavior should be evaluated independently for the market, session, and trading horizon being studied.
🌍 SESSION AND BENCHMARK CONSIDERATIONS
The default network uses U.S.-centric equity, rates, dollar, and volatility benchmarks.
When MSR-PX is applied to:
- Futures
- Cryptocurrency
- Overnight sessions
- International markets
- Assets trading outside U.S. cash-equity hours
users should consider both the trading schedules and economic relevance of the selected benchmark symbols.
Because the eigenstructure engine depends on synchronized observations, benchmark selection and session availability matter.
🔬 WHAT MSR-PX IS — AND IS NOT
MSR-PX is a market-state research and contextual framework.
It is not:
- A standalone buy/sell system
- A guaranteed market predictor
- A calibrated probability model
- A replacement for risk management
- A claim of statistically optimal thresholds
The state thresholds are currently rule-based rather than statistically learned.
The purpose of the project is to explore whether combining local ordinal structure, directional efficiency, cross-asset eigenstructure, systemic concentration, and target-specific factor attribution can provide useful context about the current market environment.
🔓 OPEN-SOURCE PHILOSOPHY
MSR-PX is published open source so the methodology can be inspected, challenged, modified, and independently tested.
The research question is whether combining:
- Permutation Structure
- Directional Efficiency
- Cross-Asset Eigenstructure
- Systemic Concentration
- Target-Specific Factor Attribution
provides useful market-state information beyond what any one component provides independently.
Users are encouraged to inspect the implementation, test different markets and timeframes, experiment with alternative benchmark networks, and evaluate the router's behavior independently.
⚠️ LIMITATIONS
Important limitations include:
- State thresholds are rule-based and are not claimed to be universally optimal.
- Correlation and eigenstructure measurements are backward-looking.
- Cross-asset relationships can change through time.
- Different trading sessions can produce uneven benchmark availability.
- Shorter timeframes can produce noisier regime transitions.
- State Score is an internal strength score, not a statistical probability.
- Historical behavior does not guarantee future behavior.
- Regime classification does not itself constitute a trading signal.
DISCLAIMER
This indicator is provided for educational, analytical, and research purposes only.
Nothing presented by MSR-PX constitutes financial, investment, or trading advice.
Users are responsible for independently evaluating the methodology and determining whether information produced by the indicator is appropriate for their own research or decision-making.
オープンソーススクリプト
TradingViewの精神に則り、このスクリプトの作者はコードをオープンソースとして公開してくれました。トレーダーが内容を確認・検証できるようにという配慮です。作者に拍手を送りましょう!無料で利用できますが、コードの再公開はハウスルールに従う必要があります。
免責事項
これらの情報および投稿は、TradingViewが提供または承認する金融、投資、取引、またはその他の種類の助言もしくは推奨であることを意図したものではなく、またこれらに該当するものでもありません。詳細は利用規約をご覧ください。
オープンソーススクリプト
TradingViewの精神に則り、このスクリプトの作者はコードをオープンソースとして公開してくれました。トレーダーが内容を確認・検証できるようにという配慮です。作者に拍手を送りましょう!無料で利用できますが、コードの再公開はハウスルールに従う必要があります。
免責事項
これらの情報および投稿は、TradingViewが提供または承認する金融、投資、取引、またはその他の種類の助言もしくは推奨であることを意図したものではなく、またこれらに該当するものでもありません。詳細は利用規約をご覧ください。