Directional Market Efficiency [QuantAlgo]🟢 Overview
The Directional Market Efficiency indicator is an advanced trend analysis tool that measures how efficiently price moves in a given direction relative to the total price movement over a specified period. Unlike traditional momentum oscillators that only measure price change magnitude, this indicator combines efficiency measurement with directional bias to provide a comprehensive view of market behavior ranging from -1 (perfectly efficient downward movement) to +1 (perfectly efficient upward movement).
The indicator transforms the classic Efficiency Ratio concept by incorporating directional bias, creating a normalized oscillator that simultaneously reveals trend strength, direction, and market regime (trending vs. ranging). This dual-purpose functionality helps traders and investors identify high-probability trend continuation opportunities while filtering out choppy, inefficient price movements that often lead to false signals and whipsaws.
🟢 How It Works
The indicator employs a sophisticated two-step calculation process that first measures pure efficiency, then applies directional weighting to create the final signal. The efficiency calculation compares the absolute net price change over a lookback period to the sum of all individual bar-to-bar price movements during that same period. This ratio reveals how much of the total price movement contributed to actual progress in a specific direction.
The directional component applies the mathematical sign of the net price change (positive for upward movement, negative for downward movement) to the efficiency ratio, creating values between -1 and +1. The resulting Directional Efficiency is then smoothed using an Exponential Moving Average to reduce noise while maintaining responsiveness. Additionally, the system incorporates a configurable threshold level that distinguishes between trending markets (high efficiency) and ranging markets (low efficiency), enabling regime-based analysis and strategy adaptation.
🟢 How to Use
1. Signal Interpretation and Market Regime Analysis
Positive Territory (Above Zero): Indicates efficient upward price movement with bullish directional bias and favorable conditions for long positions
Negative Territory (Below Zero): Signals efficient downward price movement with bearish directional bias and favorable conditions for short positions
High Absolute Values (±0.4 to ±1.0): Represent highly efficient trending conditions with strong directional conviction and reduced noise
Low Absolute Values (±0.1 to ±0.3): Suggest ranging or consolidating markets with inefficient price movement and increased whipsaw risk
Zero Line Crosses: Mark critical directional shifts and provide primary entry/exit signals for trend-following strategies
2. Threshold-Based Market Regime Classification
Above Threshold (Trending Markets): When efficiency exceeds the threshold level, markets are classified as trending, favoring momentum strategies
Below Threshold (Ranging Markets): When efficiency falls below the threshold, markets are classified as ranging, favoring mean reversion approaches
3. Preset Configurations for Different Trading Styles
Default
Universally applicable configuration optimized for medium-term analysis across multiple timeframes and asset classes, providing balanced sensitivity and noise filtering.
Scalping
Highly responsive setup for ultra-short-term trades with increased sensitivity to quick efficiency changes. Best suited for 1-15 minute charts and rapid-fire trading approaches.
Swing Trading
Designed for multi-day position holding with enhanced noise filtering and focus on sustained efficiency trends. Optimal for 1-4 hour and daily timeframe analysis.
🟢 Pro Tips for Trading and Investing
→ Trend Continuation Filter: Enter long positions when Directional Efficiency crosses above zero in trending markets (above threshold) and short positions when crossing below zero, ensuring alignment with efficient price movement.
→ Range Trading Optimization: In ranging markets (below threshold), take profits on extreme readings and enter mean reversion trades when efficiency approaches zero from either direction.
→ Multi-Timeframe Confluence: Combine higher timeframe trend direction with lower timeframe efficiency signals for optimal entry timing.
→ Risk Management Enhancement: Reduce position sizes or avoid new entries when efficiency readings are weak (near zero), as these conditions indicate higher probability of choppy, unpredictable price movement.
→ Signal Strength Assessment: Prioritize trades with high absolute efficiency values (±0.4 or higher) as these represent the most reliable directional moves with reduced likelihood of immediate reversal.
→ Regime Transition Trading: Watch for efficiency threshold breaks combined with directional changes as these often mark significant trend initiation or termination points requiring strategic position adjustments.
→ Alert Integration: Utilize the built-in alert system for real time notifications of zero-line crosses, threshold breaks, and regime changes to maintain constant market awareness without continuous chart monitoring.
Statistics
Session Volatility Dashboard█ Session Volatility Dashboard: HOW IT WORKS
This tool is built on transparent, statistically-grounded principles to ensure reliability and build user trust.
Session Logic: The script accurately identifies session periods based on user-defined start and end times in conjunction with the selected UTC offset. This ensures the session boxes and data are correctly aligned regardless of your local timezone or daylight saving changes.
Volatility Calculation: The core of the volatility engine is a comparison of current and historical price action. The script calculates a rolling Average True Range (ATR) over a user-defined lookback period (e.g., the last 20 sessions). It then compares the current session's ATR to this historical baseline to generate a simple percentage. For example, a reading of "135%" indicates the current session is 35% more volatile than the recent average, while "80%" indicates a contraction in volatility.
Dashboard Population : The script leverages TradingView's table object to construct the dashboard. This powerful feature allows the data to be displayed in a fixed position on the screen (e.g., top-right corner). Unlike plotted text, this table does not scroll with the chart's price history, ensuring that the most critical, up-to-date information is always available at a glance.
█ ACTIONABLE INTELLIGENCE: TRADING STRATEGIES & USE CASES
Translate data into action with these practical trading concepts.
Strategy 1: The Breakout Trade: Identify a session with low, coiling volatility (e.g., a Volatility reading below 75%)—often the Asian session. Mark the session high and low plotted by the indicator. These levels become prime targets for a potential breakout trade during the high-volume, high-volatility open of the subsequent London session.
Strategy 2 : The Mean Reversion (Fade) Trade: In a session with extremely high volatility (e.g., >150% of average), watch for price to rapidly extend to a new session high or low and then print a clear reversal candlestick pattern (like a pin bar or engulfing candle). This can signal momentum exhaustion and a high-probability opportunity to "fade" the move back toward the session midpoint.
Strategy 3 : The Trend Continuation: During a clear trending day, use the session midpoint as a dynamic area of value. Look for price to pull back to the midpoint during the London or New York session. If the session's Bias in the dashboard remains aligned with the higher-timeframe trend, this can present a quality entry to rejoin the established momentum.
█ COMPLETE CUSTOMIZATION: SETTINGS
Session Times: Independently set the start and end times for Asia, London, and New York sessions.
Timezone: Select your preferred UTC offset to align all sessions correctly.
Volatility Lookback: Define the number of past sessions to use for calculating the average volatility baseline (default is 20).
Dashboard Settings: Choose the on-screen position of the table, text size, and colors.
Visual Elements: Toggle on/off session background colors, high/low lines, and midpoint lines. Customize all colors.
Alerts: Enable/disable and customize alerts for session high/low breaks and volatility threshold crossings.
AnnualizedReturnCalculatorLibrary "AnnualizedReturnCalculator"
TODO: add library description here
calculateAnnualizedReturn(isStartTime, enableLog)
Parameters:
isStartTime (bool) : 开始时间的BOOL值变量(用于标记策略开始时间)
enableLog (bool) : 是否输出日志
Returns:
返回持仓基准年化收益率、资金基准年化收益率、总收益、平均资金占用
Max Drawdown (Asset-Based Lookback)Max Drawdown (Long-Term Trading)
🟦 Majors BTC, ETH, BNB, LTC 180 – 365
Captures full correction cycles and recovery patterns (6–12 months).
🟩 Altcoins SOL, ADA, DOT, LINK, AVAX 90 – 180
Alts move faster than majors; 3–6 months catches most large swings.
🟥 Meme coins DOGE, SHIB, PEPE, FLOKI 60 – 120
Volatile with quick trend reversals; 2–4 months captures parabolic runs + drawdowns.
📅 Chart Timeframe:
Use Daily (1D) timeframe for all these.
For extra macro insight, try Weekly (1W) with 52 bars (≈ 1 year).
Compare multiple assets using the same period to assess relative risk.
If you're building a long-term portfolio, combine this with:
200-day SMA or EMA for trend context.
Sharpe Ratio or Sortino Ratio if you're looking for risk-adjusted return metrics.
ETH-BCH Strategy-V0 (Powered by BCH)ETH-BCH Strategy – Cross-Asset Divergence-Based Momentum Strategy
(Optimized for 2H ETHUSDT)
________________________________________
Strategy Overview
This strategy aims to identify long trade opportunities based on cross-asset divergence among Ethereum (ETH) and Bitcoin Cash (BCH). By integrating momentum filters, volatility bands, volume signals, and timing logic, it captures medium-term price swings while maintaining strict risk controls.
________________________________________
📌 Strategy Logic Overview
Entry Conditions:
• Cross-Asset Momentum:
Enter when BCH outperforms ETH over the last bar.
• Volume Filter:
BCH trading volume must exceed 135% of its 20-period average, indicating genuine market interest.
• Volatility Filter:
ETH price should be below 110% of the lower Bollinger Band boundary (20 periods, 2 standard deviations), signaling oversold conditions.
• RSI & MACD Confirmation:
ETH RSI < 70 (not overbought) and BCH MACD line above its signal line (supporting upward trend).
• Optional Entry Boosters:
Entry signal is reinforced if ETH has fallen more than -20% in the past 48 hours or -25% in the past 72 hours.
• Timing Constraint:
Entry only allowed after at least 1 bar has passed since the last sell.
Exit Conditions:
• Take Profit:
Exit when ETH price rises 30% above the entry price.
• Trailing Stop Loss:
Exit if ETH price drops 6% from the highest point reached after entry.
• Cross-Asset Reversal:
Exit triggered when BTC outperforms BCH by a threshold calculated as ETH short-term/long-term volume ratio × 2.5.
• Timing Constraint:
Exit only allowed after 12 bars have passed since the last buy.
________________________________________
📊 Indicators Used
Category Indicators
Volatility Bollinger Bands (20 periods, 2σ) on ETH close
Momentum RSI(14) on ETH, MACD(12,26,9) on BCH
Volume BCH volume compared to 20-period SMA (threshold at 1.35×)
Divergence Percentage change comparison between ETH, BCH, and BTC closes (1-bar interval)
Volatility Ratio ETH volume short-term vs long-term average to modulate exit threshold
________________________________________
⚙️ Strategy Settings (Backtest)
Setting Value
Chart Symbol ETHUSDT
Timeframe 2 Hours
Position Size 10% of equity (default), also tested at 100% for comparison
Initial Capital $10,000
Commission 0.1%
Slippage 3 points
________________________________________
📈 Performance Summary (Backtested Jan 2023 – Jul 2025, ETHUSDT 2H)
Metric 10% Position Size (Default) 100% Position Size (Aggressive)
Net Profit 30.91% 1064.80%
Max Drawdown(MDD) 1.94% 19.38%
Profit Factor 5.1 4.6
Win Rate 61.54% (40/65) 61.54% (40/65)
Total Trades 65 65
• The 10% position sizing delivers strong risk-adjusted returns with low drawdown, suitable for conservative or institutional traders.
• The 100% sizing highlights the full alpha potential but with significantly higher drawdown risk.
• Both maintain consistent win rate and profit factor, evidencing robustness.
________________________________________
💡 Additional Notes and Usage Suggestions
• The strategy combines cross-asset signals with volatility and momentum validations to reduce false entries.
• Enforces cooldown periods between trades to avoid overtrading.
• Uses 2-hour candles for main logic and 5-minute data for more precise entry and exit pricing.
• Well-suited for traders who prioritize timing over blind holding and want to harness the interplay between ETH, BCH, and BTC.
• Can be integrated into diversified portfolios or as part of rotational trading systems.
• Ideal for advanced users looking to enhance ETH exposure with dynamic timing signals.
________________________________________
⚠️ Disclaimer
This strategy is intended for educational and research purposes only. All performance figures are based on historical backtests and do not guarantee future results. Trading involves risk; use appropriate risk management.
Korea M2 Liquidity Index💡 Korea M2 Liquidity Index
- This indicator visualizes Korea's M2 liquidity trends, designed to help both domestic and global investors easily understand the overall money supply situation in the Korean economy.
- In particular, by comparing it with the KOSPI index, investors can assess the equity market level relative to liquidity, allowing for a more precise valuation analysis to determine whether the Korean stock market is overvalued or undervalued.
✅ What is M2?
- M2 is a broad measure of money supply, which includes cash, demand deposits, savings deposits, and certain financial products.
- It serves as a crucial macroeconomic indicator that reflects the overall liquidity and capital supply in the Korean economy.
💰 KRW and USD display options
- KRW basis: Displays the total M2 amount in Korean won (in trillion units).
- USD basis: Converts the total M2 amount into US dollars using the KRW/USD exchange rate(KRW/USD) making it useful for global investors or those analyzing in USD terms.
📊 Display style and interpretation
- Users can freely choose to display Korea’s M2 and liquidity index and turn them on or off as needed.
- The index is simplified and displayed in trillion won units, allowing for an intuitive view of long-term trends and structural changes.
- The Offset (days) feature enables temporal adjustments, making it easier to compare this indicator with other economic or financial data series.
🌏 Example use cases
- Domestic policy analysis: Analyze the correlation between Bank of Korea's monetary policy changes (base rates, liquidity injections, etc.) and M2 growth.
- FX and global capital flow analysis: Understand the relationship between KRW/USD exchange rate fluctuations and changes in domestic liquidity.
- Leading indicator for asset markets: Use it as a forward-looking signal for stock, real estate, and bond markets.
- Comparison with KOSPI index: Identify gaps between liquidity and market levels to support strategic investment decisions and evaluate market capitalization levels more precisely.
copyright @invest_hedgeway
============================================================
💡 Korea M2 Liquidity Index
- 이 지표는 대한민국의 M2 유동성 흐름을 시각화하여, 국내 및 글로벌 투자자들이 한국 경제의 자금 공급 상태를 한눈에 파악할 수 있도록 설계되었습니다.
- 특히 코스피 지수와 비교 분석함으로써 유동성 대비 주가지수 수준을 평가하고, 한국 증시의 상대적 고평가·저평가 여부를 판단해 보다 정교한 밸류에이션 분석에 활용할 수 있습니다.
✅ M2란?
- M2는 광의통화 지표로, 현금 + 요구불 예금 + 저축성 예금 + 금융상품(일부) 등을 포함하는 총 유동성을 의미합니다. 이는 한국 경제의 자금 공급 상태를 나타내는 중요한 거시경제 지표로 활용됩니다.
💰 KRW 및 USD 표시 선택
- KRW(원화) 기준: 한국 원화 기준으로 M2 총액(조 단위)을 나타냅니다.
- USD 기준: M2 총액을 환율(KRW/USD) 기준으로 달러화 환산 후 표시하여, 글로벌 투자자나 달러화 기준 평가 시 활용 가능합니다.
📊 표시 방식과 해석
- 사용자는 한국의 M2와 유동성지수를 자유롭게 선택해 원하는 방식으로 켜거나 끌 수 있습니다.
- 지표는 조원(Trillion won) 단위로 단순화해 표시되며, 장기 흐름과 추세 변화를 시각적으로 확인할 수 있습니다.
- Offset (days) 기능을 통해 시리즈를 시차 조정할 수 있어, 다른 경제 지표와의 비교 분석에 유용합니다.
🌏 활용 예시
- 국내 정책 분석: 한국은행의 통화정책 변화(기준금리, 유동성 공급 등)와 M2 증가율 간 상관성 분석.
- 환율 및 글로벌 자금 흐름 분석: 원/달러 환율 변동과 유동성 간 상관관계 파악.
- 주식, 부동산, 채권 등 자산시장 선행 지표로서 활용.
- 코스피 지수와의 비교 분석: 시장 유동성과 지수의 괴리를 파악하여 전략적 투자 판단과 시가총액 수준에 대한 평가에 활용.
copyright @invest_hedgeway
PCR tableOverview
This indicator displays a multi-period table of forward-looking price projections. It combines normalized directional momentum (Positive Change Ratio, PCR) with volatility (ATR) and presents a forecast for upcoming time intervals, adjusted for your local UTC offset.
Concepts & Calculations
Positive Change Ratio (PCR):
((total positive change)/(total change)-0.5)*2, producing a value between –100 and +100.
Synthetic ATR: Calculates average true range over the same lookbacks to capture volatility.
PCR × ATR: Forms a volatility-weighted directional forecast, indicating expected move magnitude.
Future Price Projection: Adds PCR × ATR value to current close to estimate future price at each lookahead interval.
Table Layout
There are 12 forecast horizons—1× to 12× the chart timeframe (e.g., minutes, hours, days). Each row displays:
1. Future Time: Timestamp of each projection (adjustable via UTC offset)
2. PCR: Directional bias per period (–1 to +1)
3. PCR × ATR: E xpected move magnitude
4. Future Price: Close + (PCR × ATR)
High and low PCR×ATR rows are highlighted green for minimum value in the price forecast (buy signal) or red for maximum value in the price forecast (sell signal).
How to Use
1. Set UTC offset to your time zone for accurate future timestamps.
2. View PCR to assess bullish (positive) or bearish (negative) momentum.
3. Use PCR × ATR to estimate move strength and direction.
4. Reference Future Price for potential levels over upcoming intervals, and for buy and sell signals.
Limitations & Disclaimers
* This model uses linear extrapolation based on recent price behavior. It does not guarantee future prices.
* It uses only current bar data and no lookahead logic—compliant with Pine Script rules.
* Designed for analytical insight, not as an automated signal or trade executor.
* Best used on standard bar/candle charts (avoid non-standard types like Heikin‑Ashi or Renko).
Daily Gain/Loss Statistics by Day of WeekDaily Gain/Loss Statistics by Day of Week
Overview
This Pine Script indicator analyzes historical price data to provide comprehensive day-of-week performance statistics, helping traders identify patterns and optimize their trading strategies based on which days historically perform better or worse.
Key Features
📊 Day-of-Week Analysis
7-day breakdown showing Monday through Sunday statistics
Average Gain % - Average percentage gains on winning days for each day of the week
Average Loss % - Average percentage losses on losing days (displayed with minus sign)
Median High % - Typical percentage move from open to daily high
Median Low % - Typical percentage move from open to daily low
🎯 Visual Performance Indicators
🚀 Rocket symbol - Marks the best performing day (highest average gains)
🔻 Red triangle down - Marks the worst performing day (lowest average gains)
Current day highlighting - Today's row highlighted in yellow (#ffdd444b)
⚡ Real-Time Session Tracking
Current Session row - Shows today's performance percentage in real-time
Color-coded gains/losses - Green for positive, red for negative
🎨 Professional Themes
⚙️ Customization Options
Date range selection - Choose specific time periods for analysis
Table positioning - 9 different screen positions
Table sizing - 6 size options from tiny to huge
Timeframe protection - Works only on 1D timeframe with user-friendly warnings
How It Works
Data Collection - Analyzes daily OHLC data within your selected date range
Day Classification - Categorizes each trading day by day of the week
Statistical Calculation - Computes averages and medians for each day type
Performance Ranking - Identifies best and worst performing days
Real-Time Display - Shows current session performance vs historical patterns
Trading Applications
Entry/Exit Timing - Identify optimal days for opening/closing positions
Risk Management - Avoid trading on historically poor-performing days
Strategy Optimization - Align trading strategies with day-of-week patterns
Market Timing - Understand weekly market cycles and seasonality
This indicator transforms raw price data into actionable intelligence, helping traders make more informed decisions based on proven historical day-of-week performance patterns.
8 AM & 9 AM NY Candle HighlighterThis indicator helps me to know when the 9am NY candle has closed above or below the previous candle.
DOGE 15MIN**Warm Reminder:** This strategy is intended solely for exploratory research and experimentation to evaluate the effectiveness of various signals. Drawing inspiration from patterns observed on the DOGE cryptocurrency 15-minute chart, it provides a tailored framework to identify potential trading opportunities. For optimal results, it is currently recommended exclusively for DOGE 15min charts. Remember, trading involves inherent risks, and past performance is not indicative of future results. We are dedicated to ongoing optimizations and refinements to enhance its robustness across broader applications—stay tuned for updates!
#### **A. Long Entry Signals**
These conditions trigger a long position entry, provided the strategy has no existing position (position_size == 0) and is not blocked. Signals can be enabled/disabled via input toggles (e.g., enable_vix).
- **VIX Reversal (vix_long)**: VIX signal shifts from high to low volatility (non-high volatility), with RSI between 30-50.
- **RSI Oversold (rsi_long)**: RSI crosses above 30.
- **CVD Bullish (cvd_long)**: CVD is rising.
- **Price RSI Bullish (prsi_long)**: Price RSI crosses above 30 or a long signal is triggered.
- **RangeEMA Bullish (rema_long)**: Candlestick is above POC, with KAMA trend flipping upward.
- **ZVWAP Oversold (zvwap_long)**: ZVWAP enters the oversold zone.
- **KAMA + Volume Bullish (kama_long)**: KAMA trend flips upward, candlestick is above POC, volume is rising, and the candle is bullish (green).
- **Volume Burst Bullish (vol_burst_long)**: Volume RSI crosses below threshold (default 70), open > close (bearish/red candle), triggered within the last two candles. **Special: Ignores all blocks** (bypasses not_long, Pivot, OI, RSI/ADX extreme filters).
#### **B. Short Entry Signals**
Similar to long entries: requires no existing position and no blocks.
- **RSI Overbought (rsi_short)**: RSI crosses below 70.
- **CVD Bearish (cvd_short)**: CVD is declining.
- **Price RSI Bearish (prsi_short)**: Price RSI crosses below 70 or a short signal is triggered.
- **RangeEMA Bearish (rema_short)**: Candlestick is below POC, with KAMA trend flipping downward.
- **ZVWAP Overbought (zvwap_short)**: ZVWAP enters the overbought zone.
- **KAMA + Volume Bearish (kama_short)**: KAMA trend flips downward, candlestick is below POC, volume is declining, and the candle is bearish (red).
- **Chop Bearish (chop_short)**: Chop crosses below 38.2, with RSI > 50.
- **Volume Burst Bearish (vol_burst_short)**: Volume RSI crosses below threshold (default 70), RSI > 70, and close > open (bullish/green candle), triggered within the last two candles. **Special: Ignores all blocks** (bypasses not_short, Pivot, OI, RSI/ADX extreme filters).
#### **C. Long Entry Blocks/Filters**
These conditions block long entries unless the signal ignores blocks (e.g., Volume Burst).
- **Base Prohibition (not_long)**: Volume is declining, or ADX is bearish (di_bear), or VIX is in high volatility (vix_flag), or RSI < 30.
- **Pivot Filter**: Recent Pivot is in a disadvantaged position.
- **OI Filter**: OI is declining.
- **RSI/ADX Extreme Filter**: RSI > 70 or ADX is bullish (di_bull).
- **Other**: Strategy already has a position (position_size != 0), or extreme volatility (is_extreme, though disabled in code).
#### **D. Short Entry Blocks/Filters**
Similar to long blocks.
- **Base Prohibition (not_short)**: Volume is rising, or (Chop < 38.2 and RSI > 50), or ADX is bullish (di_bull), or RSI > 70.
- **Pivot Filter**: Recent Pivot is in a disadvantaged position.
- **OI Filter**: OI is rising.
- **RSI/ADX Extreme Filter**: RSI < 30 or ADX is bearish (di_bear).
- **Other**: Existing position, or extreme volatility.
#### **E. Long Exit Signals**
Triggers closing of long positions, based on states (e.g., super_long, weak_long, only_kama).
- **KAMA Bearish Flip (exist_long)**: KAMA trend flips downward, or KAMA is downward with a short signal.
- **VIX Signal**: VIX shifts from low to high volatility, with RSI < 50.
- **Reversal Signal**: Short signal present and KAMA is downward.
- **Weak Trend Stop-Loss (weak_stop_long)**: In weak_long state, candlestick near POC, and close crosses below POC.
- **Weak KAMA Stop-Loss (weak_kama_long)**: In weak_long state, candlestick far from POC, and KAMA trend reverses.
- **Global Exit (exist_all)**: Volume RSI crosses below threshold (vol_under), or KAMA exit (kama_exit_long), or weak stop-loss, etc.
- **Special**: If in strong_long_hold (only_kama and KAMA remains bullish), ignore certain exit signals to hold the position.
#### **F. Short Exit Signals**
Similar to long exits.
- **KAMA Bullish Flip (exist_short)**: KAMA trend flips upward, or KAMA is upward with a long signal.
- **Reversal Signal**: Long signal present and KAMA is upward.
- **Weak Trend Stop-Loss (weak_stop_short)**: In weak_short state, candlestick near POC, and close crosses above short_state.current_max.
- **Weak KAMA Stop-Loss (weak_kama_short)**: In weak_short state, candlestick far from POC, and KAMA flips upward.
- **Global Exit (exist_all)**: Same as above.
Orthogonal Projections to Latent Structures (O-PLS)Version 0.1
Orthogonal Projections to Latent Structures (O-PLS) Indicator for TradingView
This indicator, named "Orthogonal Projections to Latent Structures (O-PLS)", is designed to help traders understand the relevance or predictive power of various market variables on the future close price of the asset it's applied to. Unlike standard correlation coefficients that show a simple linear relationship, O-PLS aims to separate variables into "predictive" (relevant to Y) and "orthogonal" (irrelevant noise) components. This Pine Script indicator provides a simplified proxy of the relevance score derived from O-PLS principles.
Purpose of the Indicator
The primary purpose of this indicator is to identify which technical factors (such as price, volume, and other indicators) have the strongest relationship with the future price movement of the current trading instrument. By providing a "relevance score" for each input variable, it helps traders focus on the most influential data points, potentially leading to more informed trading decisions.
Inputs
The indicator offers the following user-definable inputs:
* **Lookback Period:** This integer input (default: 100, min: 10, max: 500) determines the number of past bars used to calculate the relevance scores for each variable. A longer lookback period considers more historical data, which can lead to smoother, less reactive scores but might miss recent shifts in variable importance.
* **External Asset Symbol:** This symbol input (default: `BINANCE:BTCUSDT`) allows you to specify an external asset (e.g., `BINANCE:ETHUSDT`, `NASDAQ:TSLA`) whose close price will be included in the analysis as an additional variable. This is useful for cross-market analysis to see how other assets influence the current chart.
* **Plot Visibility Checkboxes (e.g., "Plot: Open Price Relevance", "Plot: Volume Relevance", etc.):** These boolean checkboxes allow you to toggle the visibility of individual relevance score plots on the chart, helping to declutter the display and focus on specific variables.
Outputs
The indicator provides two main types of output:
Relevance Score Plots: These are lines plotted in a separate pane below the main price chart. Each line corresponds to a specific market variable (Open Price, Close Price, High Price, Low Price, Volume, various RSIs, SMAs, MFI, and the External Asset Close). The value of each line represents the calculated "relevance score" for that variable, typically scaled between 0 and 10. A higher score indicates a stronger predictive relationship with the future close price.
Sorted Relevance Table : A table displayed in the top-right corner of the chart provides a clear, sorted list of all analyzed variables and their corresponding relevance scores. The table is sorted in descending order of relevance, making it easy to identify the most influential factors at a glance. Each variable name in the table is colored according to its plot color, and the external asset's name is dynamically displayed without the "BINANCE:" prefix.
How to Use the Indicator
1. **Add to Chart:** Apply the "Orthogonal Projections to Latent Structures (O-PLS)" indicator to your desired trading chart (e.g., ETH/USDT).
2. **Adjust Inputs:**
* **Lookback Period:** Experiment with different lookback periods to see how the relevance scores change. A shorter period might highlight recent correlations, while a longer one might show more fundamental relationships.
* **External Asset Symbol:** If you trade BTC/USDT, you might add ETH/USDT or SPX as an external asset to see its influence.
3. **Analyze Relevance Scores:**
* **Plots:** Observe the individual relevance score plots over time. Are certain variables consistently high? Do scores change before significant price moves?
* **Table:** Refer to the sorted table on the latest confirmed bar to quickly identify the top-ranked variables.
4. **Incorporate into Strategy:** Use the insights from the relevance scores to:
* Prioritize certain indicators or price actions in your trading strategy. For example, if "Volume" has a high relevance score, it suggests volume confirmation is critical for future price moves.
* Understand the influence of inter-market relationships (via the External Asset Close).
How the Indicator Works
The indicator works by performing the following steps on each bar:
1. **Data Fetching:** It gathers historical data for various price components (open, high, low, close), volume, and calculated technical indicators (SMA, RSI, MFI) for the specified `lookback` period. It also fetches the close price of an `External Asset Symbol` .
2. **Standardization (Z-scoring):** All collected raw data series are standardized by converting them into Z-scores. This involves subtracting the mean of each series and dividing by its standard deviation . Standardization is crucial because it brings all variables to a common scale, preventing variables with larger absolute values from disproportionately influencing the correlation calculations.
3. **Correlation Calculation (Proxy for O-PLS Relevance):** The indicator then calculates a simplified form of correlation between each standardized input variable and the standardized future close price (Y variable) . This correlation is a proxy for the relevance that O-PLS would identify. A high absolute correlation indicates a strong linear relationship.
4. **Relevance Scaling:** The calculated correlation values are then scaled to a range of 0 to 10 to provide an easily interpretable "relevance score" .
5. **Output Display:** The relevance scores are presented both as time-series plots (allowing observation of changes over time) and in a real-time sorted table (for quick identification of top factors on the current bar) .
How it Differs from Full O-PLS
This indicator provides a *simplified proxy* of O-PLS principles rather than a full, mathematically rigorous O-PLS model. Here's why and how it differs:
* **Dimensionality Reduction:** A full O-PLS model would involve complex matrix factorization techniques to decompose the independent variables (X) into components that are predictive of Y and components that are orthogonal (unrelated) to Y but still describe X's variance. Pine Script's array capabilities and computational limits make direct implementation of these matrix operations challenging.
* **Orthogonal Components:** A true O-PLS model explicitly identifies and removes orthogonal components (noise) from the X data that are unrelated to Y. This indicator, in its simplified form, primarily focuses on the direct correlation (relevance) between each X variable and Y after standardization, without explicitly modeling and separating these orthogonal variations.
* **Predictive Model:** A full O-PLS model is ultimately a predictive model that can be used for regression (predicting Y). This indicator, however, focuses solely on **identifying the relevance/correlation of inputs to Y**, rather than building a predictive model for Y itself. It's more of an analytical tool for feature importance than a direct prediction engine.
* **Computational Intensity:** Full O-PLS involves Singular Value Decomposition (SVD) or Partial Least Squares (PLS) algorithms, which are computationally intensive. The indicator uses simpler statistical measures (mean, standard deviation, and direct correlation calculation over a lookback window) that are feasible within Pine Script's execution limits.
In essence, this Pine Script indicator serves as a practical tool for gaining insights into variable relevance, inspired by the spirit of O-PLS, but adapted for the constraints and common use cases of a TradingView environment.
Polaris Trend All-in-One📘 Polaris Trend Indicator: Trading Rules & Strategy
Guide
The Polaris Trend Indicator is designed to simplify trading decisions by identifying key entry
and exit signals without the need for excessive technical analysis. This system combines the
Polaris Trend with the Polaris Golden Wave and Market Bias tools to give you confidence
across multiple timeframes.
This guide outlines clear trading rules for two use cases:
● Swing Trading
● Long-Term Investing and Holding
⚡ Swing Trading Strategy
Swing trading can be challenging when the market direction is unclear. The Polaris Trend helps
traders stay on the right side of momentum with straightforward visual signals. This approach is
best used on the Daily or Weekly chart.
✅ Entry Criteria (Bullish Trades)
● A solid green column appears above the zero line.
● A green upward arrow confirms bullish momentum.
● Enter your trade immediately when the green column first appears.
● Hold the trade until a red column appears, signaling a shift in momentum.
🚫 Exit Criteria (Bullish Trades)
● The first appearance of a red column after a green run.
● Multiple green columns followed by a red column.
● Do not enter trades mid-trend; always enter on the first green flip.
***Recommended Swing Strategy
● When a new daily green column appears but the weekly columns are still red, stay
nimble. Enter your position when the Polaris Trend Indicator turns green and displays an
upward-pointing arrow.
● If the price pulls back to a higher low but a red daily column forms, sell 50% of your
position and move your stop loss to your original entry. Then, wait for the next daily
green column and arrow to reappear, this is your signal to reenter the 50% you exited.
● If the price continues to rise and the weekly columns also turn green, shift your focus
to the weekly chart. Ignore daily signals and hold the trade until the weekly column
turns red, which will be your cue to exit. The weekly green column is your confirmation of
a stronger uptrend and a potential longer hold.
🔻 Entry Criteria (Bearish Trades)
● A solid red column appears below the zero line.
● A red downward arrow confirms bearish momentum.
● Enter your short trade immediately when the red column first appears.
● Hold until a green column appears, indicating momentum has shifted.
🔁 Exit Criteria (Bearish Trades)
● The first green column that follows a red sequence.
● Same rule applies: enter only on the initial flip, not mid-trend.
Note: The first color flip is the most reliable entry point. Avoid entering positions
deep into a trend, wait for the clear signal from Polaris.
🧭 Long-Term Investing Strategy
This approach combines the Polaris Golden Wave, Polaris Trend, and Market Bias to help
long-term investors buy at deep value levels and scale into positions over time.
📉 Ideal Entry: Golden Zone + Polaris Trend Signal
● Use the Golden Wave to identify the monthly 0.618–0.826 retracement zone
(significant discount levels).
● When price enters the Golden Zone and the Polaris Trend shows a green column on
the Daily or Weekly, this is your optimal entry point.
● If the trend turns red inside the zone, consider trimming positions and re-entering on the
next bullish signal.
If price drops below the Golden Zone, the stock becomes even more undervalued,
wait for the next green Polaris Trend signal to enter.
💰 Secondary Entry: Market Bias Rebounds
● If you miss the Golden Zone entry or are dollar-cost averaging:
○ Use the Market Bias on a Weekly timeframe.
○ Wait for price to retrace into the Market Bias band after moving higher.
○ Look for a red Polaris Trend column, then wait for price to enter the Market
Bias band and once it enters, wait for Polaris Trend signal to flip back to green
for your entry. If the trend turns red inside the zone, consider trimming positions
and re-entering on the next bullish signal.
Think of the Market Bias like a lake and price like a skipping stone—you want to
buy when the stone comes down and touches the surface.
📊 Indicator Explanations
🔶 Golden Wave (Monthly Fibonacci Retracement Zones)
● Highlights key monthly retracement zones (0.618 to 0.826).
● Helps identify deep-value entries on longer timeframes.
● Visible across all chart timeframes for consistent macro reference.
🔴 Market Bias (Smoothed Heikin-Ashi Trend Filter)
● Measures trend direction and strength using smoothed Heikin-Ashi candles and
oscillation logic.
● Customizable smoothing, oscillator period, and timeframe inputs.
● Option to display trend signals in a separate pane with dynamic coloring.
This combined approach empowers traders to make high-quality decisions with clarity and
discipline. Whether you're entering short-term swings or building long-term positions, the
Polaris Trend system guides you with timely, data-driven signals.
Eliora Gold 1min (Heikin Ashi)Eliora -focused trading strategy designed for anything on the 1-minute timeframe using Heikin Ashi candles. This mode combines advanced market logic with structured risk management to deliver smooth, disciplined trade execution.
Key Features:
✅ Trend Confirmation – Aligns with dominant market direction for higher accuracy.
✅ ATR-Based Volatility Filter – Avoids high-risk conditions and chaotic price action.
✅ Candle Strength Logic – Filters weak setups, focusing on strong momentum.
✅ Balanced Risk/Reward – Calculates stop-loss and take-profit dynamically for consistent results.
✅ Cooldown & Overtrade Protection – Limits frequency to maintain trade quality.
This version of Eliora is built for scalpers and intraday traders seeking high-probability entries with graceful exits.
UniversalPositionCalculatorV5🚀 Universal Position Calculator v5 (with Margin-Check) 🚀
Stop using calculators and complicated Excel sheets! 🤯 With the Universal Position Calculator v5, you have the ultimate tool right on your TradingView chart to manage your position size perfectly. Whether it's Forex, Gold, or Indices – this indicator does all the work for you!
✨ What does this indicator do? ✨
This indicator is your personal risk manager. It calculates the exact lot size for your next trade based on your capital, your desired risk, and your leverage. The best part? It immediately checks if your trade is even possible with your margin and warns you if you're about to over-leverage your account! 🚦
🌟 Key Features at a Glance 🌟
Automatic Lot Calculation: Just enter your risk in percent, and the indicator calculates the perfect lot size.
Margin Check: Instantly detects if your desired position size is limited by your margin and adjusts it. No more margin calls due to oversized positions!
For All Asset Classes: Works perfectly for Forex pairs (e.g., EURUSD) and other assets like commodities (XAUUSD) or indices (GER30). 💹
Currency Conversion: Automatically converts between your account currency and the asset's currency. It doesn't matter if you trade in EUR, USD, CHF, or JPY. 💱
Interactive Lines: Simply drag and drop the Entry and Stop Loss lines directly on the chart to plan your trade. 🎯
Clear Info Panel: All important information (lot size, required margin, risk in €/$/...) is displayed cleanly and clearly on your chart.
🛠️ How to Use: It's This Easy! 🛠️
The setup is a piece of cake and done in two simple steps.
Step 1: Configure Your Setup
Go to the indicator settings and fill out the "1. Setup" section:
Asset Type: Choose Forex for currency pairs or Other for everything else (e.g., Gold, Oil, Indices).
Account Currency: Enter the currency of your trading account (e.g., USD).
Account Capital: Enter your current account capital.
Risk in % per Trade: How much of your capital do you want to risk per trade? (e.g., 1.0 for 1%).
Leverage: Enter your account's leverage (e.g., 30 for 30:1).
Contract Size for 'Other': IMPORTANT! Only for the Other type. For Gold (XAUUSD), this is often 100; for the DAX (GER30), it's often 1 or 25. Check your broker's specifications for this!
Step 2: Plan Your Trade
Now for the fun part in the "2. Trade Control" section:
Entry Line (Blue Line): Click on the blue line and drag it to your desired entry level. You can also enter the value manually in the settings.
Stop Loss Line (Red Line): Click on the red line and drag it to your stop-loss level.
Step 3: Read the Results
As soon as you've set your Entry and Stop Loss, the Info Panel in the top-right corner will instantly show you the results:
Correct Lot Size: This is the lot size you need to enter with your broker for this trade.
⚠️ Heads up: If it says "Lot Size (Margin Limited!)" in orange, it means your desired risk was too high for your leverage. The indicator has automatically reduced the lot size to the maximum possible to avoid a margin call.
Required Margin: This is how much capital will be blocked on your account as a security deposit (margin) for this trade.
Risk in : The exact amount of money you will lose if your stop loss is triggered.
With this tool, you can make disciplined and mathematically sound trading decisions. Good luck and Happy Trading! 📈💰
LiliALHUNTERSystem_v2📚 **Library: LiliALHUNTERSystem_v2**
This library provides a powerful target management system for Pine Script developers.
It includes advanced calculators for EMA, RMA, and Supertrend, and introduces a central `createTargets()` function to dynamically render target lines and labels based on long/short trade logic.
🛠️ **Main Features:**
– Dynamic horizontal & vertical target lines
– Dual target configuration (Target 1 & Target 2)
– Directional logic via `isLong1`, `isLong2`
– Integrated Supertrend validation
– Visual dashboard and label display
– Works seamlessly with custom indicators
🎯 **Purpose:**
The `LiliALHUNTERSystem_v2` Library enables Pine coders to manage and visualize targets consistently across all trading strategies and indicators. It simplifies target logic while maintaining visual clarity and modular usage.
⚠️ **Disclaimer:**
This script is intended for educational and analytical purposes only. It does not constitute financial advice.
Library "LiliALHUNTERSystem_v2"
ema_calc(len, source)
Parameters:
len (simple int)
source (float)
rma_calc(len, source)
Parameters:
len (simple int)
source (float)
supertrend_calc(length, factor)
Parameters:
length (simple int)
factor (float)
createTargets(config, state, source1A, source1B, source2A, source2B)
Parameters:
config (TargetConfig)
state (TargetState)
source1A (float)
source1B (float)
source2A (float)
source2B (float)
showDashboard(state, dashLoc, textSize)
Parameters:
state (TargetState)
dashLoc (string)
textSize (string)
TargetConfig
Fields:
enableTarget1 (series bool)
enableTarget2 (series bool)
isLong1 (series bool)
isLong2 (series bool)
target1Condition (series string)
target2Condition (series string)
target1Color (series color)
target2Color (series color)
target1Style (series string)
target2Style (series string)
distTarget1 (series float)
distTarget2 (series float)
distOptions1 (series string)
distOptions2 (series string)
showLabels (series bool)
showDash (series bool)
TargetState
Fields:
target1LineV (series line)
target1LineH (series line)
target2LineV (series line)
target2LineH (series line)
target1Lbl (series label)
target2Lbl (series label)
target1Active (series bool)
target2Active (series bool)
target1Value (series float)
target2Value (series float)
countTargets1 (series int)
countTgReached1 (series int)
countTargets2 (series int)
countTgReached2 (series int)
order flow buy/sell and profundity OrderBook Buy/Sell Flow & Polarity Indicator
This powerful indicator provides a detailed look into the market's internal dynamics by visualizing Order Flow (Tape/Time & Sales) and Price Polarity directly on your chart, all within a clean, customizable table. Understand real-time buying and selling pressure and gain insights into who's in control of the candle.
Key Features:
Real-time Order Flow (Tape/Time & Sales): Tracks individual "ticks" (price and volume updates) within the current bar, allowing you to see the immediate impact of buy and sell orders.
Dynamic Table Display: All data is presented in an intuitive, customizable table that can be positioned anywhere on your chart.
Aggregated Buy/Sell Volume: Clearly distinguishes between volume driven by buying (price moving up on a tick) and selling (price moving down on a tick).
"Rocket" Order Detection: Highlights unusually large buy or sell orders based on configurable thresholds (in BTC Millions for major cryptos, and Thousands/Millions for others), helping you spot significant institutional or whale activity.
Candle Polarity Section: A dedicated area in the table that shows the percentage of buying vs. selling volume for the entire current candle. The central cell dynamically blends between bullish (green) and bearish (red) colors, visually representing the dominant polarity.
Customizable Aesthetics: Full control over table colors, text colors, font sizes, and individual label colors to match your chart's theme.
Lightweight & Efficient: Designed to run smoothly without significant impact on your chart's performance.
Why Use This Indicator?
Most indicators only show you the result of price action. The "OrderBook Buy/Sell Flow & Polarity" indicator goes deeper, showing you the cause behind the price movement. By understanding the immediate order flow and the underlying buy/sell pressure within each candle, you can:
Identify accumulation or distribution: Spot when smart money might be entering or exiting positions.
Confirm breakouts/breakdowns: See if there's genuine volume behind price moves.
Gauge market sentiment in real-time: Quickly assess who is more aggressive – buyers or sellers.
Improve entry and exit points: Make more informed decisions based on live market activity.
Settings & Customization:
The indicator comes with a comprehensive set of input options, allowing you to fine-tune its appearance and functionality:
Table Position: Choose from various chart locations (Top/Middle/Bottom, Left/Center/Right).
Window Size (Order Flow): Adjust how many recent order flow "ticks" are displayed.
Colors: Personalize all table, text, and label colors.
Rocket Thresholds: Define the volume levels for "rocket" order detection based on asset type.
Polarity Section Toggle: Enable or disable the real-time candle polarity display.
Note: This indicator provides insights based on available real-time tick data from TradingView. While it simulates aspects of order book and tape reading, it is important to remember that direct access to full exchange Level 2 data is not available on TradingView.
Disclaimer: This indicator is for informational purposes only and should not be considered financial advice. Trading involves risk, and past performance is not indicative of future results.
[Teyo69] T1 ATR Standard Deviation Breakout Bands🧭 OVERVIEW
T1 ATR Standard Deviation Breakout Bands is a breakout tool designed to detect volatility-driven price expansion beyond statistically significant zones. It calculates real-time ATR-based standard deviation bands, dynamically tracking breakout conditions with adjustable smoothing. With flexible moving average types and the Kijun-sen as the default baseline, this indicator is built for traders who want to avoid fakeouts and only engage when volatility confirms conviction.
✨ FEATURES
Utilizes ATR standard deviation for real-time volatility band calculations
Supports multiple moving average types (EMA, SMA, WMA, etc.) including Kijun-sen by default
Adjustable ATR multiplier to fine-tune breakout sensitivity
Fully configurable length inputs and MA source types
Identifies long opportunities when price closes above the upper band
Identifies short opportunities when price closes below the lower band
Ideal for trend continuation, momentum breakouts, and volatility-based filtering
🎯 HOW TO USE
Apply the indicator on your preferred timeframe (works best on trending conditions).
Set your baseline MA to match your system (default: Kijun-sen).
Adjust the ATR period and multiplier to balance sensitivity vs. noise.
Go long when the close breaks above the upper standard deviation band.
Go short when the close breaks below the lower standard deviation band.
Use Markers signals to highlight breakout moments.
Can also be used to identify if price is ranging when it is in the gray area of the indicator
⚙️ CONFIGURATION
Length: Period for the moving average and ATR
MA Type: Choose from EMA, SMA, WMA, or Kijun-sen
ATR Multiplier: Controls how wide the breakout bands are
Source: Price type used for calculations (default: close)
⚠️ LIMITATIONS
Standard deviation assumes price is statistically normal — not always true during news spikes
Band expansion does not guarantee follow-through — use in conjunction with volume or trend filters
💡 ADVANCED TIPS
Combine with a trend filter (e.g., 200 EMA) to trade only in the direction of the dominant trend
Use wider ATR multipliers on lower timeframes to reduce noise
Pair with oscillators (e.g., RSI, MACD) for breakout + momentum confluence setups
For scalping, reduce the length but widen the multiplier slightly
📓 NOTES
The standard deviation of ATR is used to capture how volatile volatility itself is. This reveals when the market is entering statistically significant price expansion.
Why this matters: Standard deviation is a core statistical tool for understanding distribution outliers. When price exceeds the upper band, it is outside normal volatility expectations — signaling potential breakout strength.
This indicator applies breakout theory to volatility, not just price action, offering a unique edge over classic Bollinger or Keltner bands.
ZScore Plot with Ranked TableVersion 0.1
ZScore Plot with Ranked Table — Overview
This indicator visualizes the rolling ZScores of up to 10 crypto assets, giving traders a normalized view of log return deviations over time. It's designed for volatility analysis, anomaly detection, and clustering of asset behavior.
🎯 Purpose
• Show how each asset's performance deviates from its historical mean
• Identify potential overbought/oversold conditions across assets
• Provide a ranked leaderboard to compare asset behavior instantly
⚙️ Inputs
• Lookback: Number of bars to calculate mean and standard deviation
• Asset 1–10: Choose up to 10 symbols (e.g. BTCUSDT, ETHUSDT)
📈 Outputs
• ZScore Lines: Each asset plotted on a normalized scale (mean = 0, SD = 1)
• End-of-Line Labels: Asset names displayed at latest bar
• Leaderboard Table: Ranked list (top-right) showing:
◦ Asset name (color-matched)
◦ Final ZScore (rounded to 3 decimals)
🧠 Use Cases
• Quantitative traders seeking cross-asset momentum snapshots
• Signal engineers tracking volatility clusters
• Risk managers monitoring outliers and systemic shifts
Z-Score Multi-Model ClusteringA price/volume clustering framework combining three market behavior models into a single indicator. Designed to help identify emerging trend strength, turning points, and volatility-driven entries or exits.
🔍 How It Works
This indicator classifies market states by comparing normalized price/volume behavior (via Z-Score) to different types of statistical or geometric "cluster centers." You can choose from three clustering approaches:
🧠 Clustering Models
1. Percentile (Z+CVD) – Trend Momentum Bias
Uses volume Z-Score + Cumulative Volume Delta (CVD).
Detects institutional pressure by clustering volume surges with directional delta.
Best for: Breakouts, momentum trades, volume-led reversals.
Cluster Colors:
🔹 Green triangle = Strong bullish confluence
🔻 Red triangle = Bearish divergence (bull trap risk)
⚪ Gray = Neutral/low conviction
2. Euclidean (Z+Slope) – Swing Mean-Reversion
Measures the angle of recent Z-score slope and compares it to directional cluster centers.
Helps detect early directional shifts or exhaustion.
Best for: Swing entries, pullback setups, exit timing
3. Hilbert Phase – Turn Detection via Signal Phase
Applies Hilbert Transform to the Z-Score, measuring the phase difference between trend and oscillator components.
Ideal for anticipating turns or detecting cyclical inflection points.
Useful for: Scalping, top/bottom spotting, volatility fades
✅ Features
Auto-updating cluster logic based on current data
Tooltips and clean user interface
Optional cluster bar coloring (can be toggled off)
Signal-only plotting keeps candlesticks readable
Clear entry/exit logic with triangle markers
Supports trend, swing, and oscillation-based systems
🛠️ Suggested Use Cases
Combine with VWAP, Session High/Low, or Liquidity Zones to confirm entry conditions.
Use Cluster 2 (strong bullish) on pullbacks to trend structure for add-on entries.
Use Cluster 1 in strong trends to watch for potential traps or exits.
Toggle models based on your strategy: e.g., Hilbert for scalping, Percentile for macro trend breaks.
🧪 Best Timeframes
Works across all markets and timeframes
For Percentile (Z+CVD), use intraday TF with 1m–5m CVD source
Hilbert and Euclidean preferred on 5m–1h for accurate slope/phase signals
⚠️ Notes
Clusters do not generate trade signals alone; use them in context with structure, VWAP, or trend filters.
Marker signals are filtered with a magnitude threshold to reduce noise.
Multi-Crypto Principal Component AnalysisVersion 0.2
## 📌 Multi-Crypto Principal Component Analysis (PCA) — Indicator Summary
### 🎯 Purpose
This indicator identifies **cryptocurrency assets that are behaving differently** from the rest of the market, using a simplified approach inspired by Principal Component Analysis (PCA). It’s designed to help traders spot **cross-market divergences**, detect outliers, and improve asset selection and correlation-based strategies.
### ⚙️ How It Works
The indicator analyzes the **log returns** of up to 7 user-defined assets over a configurable lookback period (default: 100 bars). It computes the **z-score** (standardized deviation) for each asset’s return series and compares it against the average behavior of the group.
If an asset’s behavior deviates significantly (beyond a threshold of 1.5 standard deviations), it’s flagged as an **outlier**.
- Each outlier is plotted as a **colored dot horizontally spaced** above the price bar
- Up to **3 dots per bar** are shown for visual clarity
This PCA-style detection works in real time, directly on the chart, and gives you a quick overview of which assets are breaking correlation.
### 🔧 Inputs
- 🕒 **Lookback Period**: Number of bars to analyze (default: 100)
- 🔢 **Assets 1–7**: Choose any 7 crypto symbols from any exchange
- 🎨 **Colors**: Predefined per asset (e.g. BTCUSDT = red, ETHUSDT = yellow)
- 📈 **Threshold**: Internal (1.5 std dev); adjustable in code if needed
### 📊 Outputs
- 🟢 Dots above candles representing assets that are acting as outliers
- 🧠 Real-time clustering insight based on statistical deviation
- 🧭 Spatially spaced dots to avoid visual overlap when multiple outliers appear
### ⚠️ Limitations
- This is a **PCA-inspired approximation**, not true matrix-based PCA
- It does **not compute principal components or eigenvectors**
- Sensitivity may vary with asset volatility or sparse trading data
- Real PCA requires external tools like Python or R for full dimensional analysis
This tool is ideal for traders who want real-time crypto correlation insights without needing external data science platforms. It’s lightweight, fast, and highly visual — and gives you a powerful lens into market dislocations across multiple assets.
M2 Global G13 Liquidity (Custom & Shift, US DXY Adj.)🌎 M2 Global G13 Liquidity index (Custom & Shift, US DXY Adj.)
💡 Indicator Overview
The M2 Global G13 Liquidity indicator combines the M2 liquidity of 13 major countries, allowing users to selectively include or exclude each country to visualize global capital flows and potential investment liquidity at a glance.
Each country's M2 data is converted to USD using real-time exchange rates, and the US M2 is further adjusted using the Dollar Index (DXY) to reflect the impact of dollar strength or weakness on US liquidity.
✅ What is M2?
M2 is a broad measure of money supply that includes cash, demand deposits, savings deposits, and certain financial products.
It represents a country's overall liquidity and capital supply and is often interpreted as "dry powder" ready to be deployed into various assets such as equities, real estate, and bonds.
Therefore, M2 serves as a crucial benchmark for assessing a country's potential investment capacity that can flow into markets at any time.
💰 Exchange Rate & Dollar Index Adjustment
- All country M2 data is converted from local currencies to USD.
- The US M2 is further adjusted using the Dollar Index (DXY) to better reflect its real global power:
- DXY > 100 → Liquidity contraction (strong dollar effect)
- DXY < 100 → Liquidity expansion (weak dollar effect)
🗺️ Country Selection Options
- Default selection: United States
- Major selections: China, Eurozone, Japan, United Kingdom (core G5 economies)
- Additional selections: Switzerland, Canada, India, Russia, Brazil, South Korea, Mexico, South Africa
- Users can freely add or remove countries to customize the indicator to match their analytical needs.
📈 Example Use Cases
- Monitor global capital flows: Track worldwide liquidity trends and detect potential market risk signals.
- Analyze exchange rate and monetary policy trends: Compare dollar strength with major central bank policies.
- Benchmark against equity indices: Evaluate correlations with MSCI World, KOSPI, NASDAQ, etc.
- Valuation analysis: Compare overall liquidity levels to equity index prices or market capitalization to assess relative valuation and identify potential overvaluation or undervaluation.
- Crisis response strategy: Identify liquidity contraction during global credit crises or deleveraging phases.
==================================================
🌎 M2 글로벌 G13 유동성 지수 (Custom & Shift, US DXY Adj.)
💡 지표 소개
M2 Global G13 Liquidity 지표는 세계 13개 주요국의 M2 유동성을 선택적으로 결합하여, 글로벌 자금 흐름과 잠재 투자 자금을 한눈에 시각화할 수 있도록 설계된 종합 유동성 지표입니다.
국가별 M2 데이터를 환율과 결합해 달러 기준으로 표준화하며, 특히 미국 M2는 달러지수(DXY)로 보정하여 달러 강약에 따른 파급력을 반영합니다.
✅ M2란?
M2는 광의 통화지표로, 현금 + 요구불 예금 + 저축성 예금 + 일부 금융상품을 포함합니다.
이는 한 국가의 유동성 수준과 자금 공급 상태를 나타내는 핵심 거시경제 지표이며, **주식·부동산·채권 등 다양한 자산에 투자될 준비가 된 '대기자금'**으로도 해석됩니다.
따라서 M2는 투자시장으로 언제든지 흘러들어갈 수 있는 잠재적 투자 역량을 평가할 때 중요한 기준입니다.
💰 환율 및 달러지수 보정
- 모든 국가 M2는 자국 통화에서 **달러(USD)**로 환산됩니다.
- 특히 미국 M2는 달러 가치의 글로벌 실질 파워를 평가하기 위해 DXY 보정을 적용합니다.
- DXY > 100 → 유동성 축소 (강달러 효과)
- DXY < 100 → 유동성 확대 (약달러 효과)
🗺️ 국가별 선택 옵션
- 기본 선택: 미국
- 주요 선택: 중국, 유로존, 일본, 영국 (주요 G5)
- 추가 선택: 스위스, 캐나다, 인도, 러시아, 브라질, 한국, 멕시코, 남아공
- 사용자는 각 국가를 자유롭게 더하거나 빼면서 커스터마이즈할 수 있습니다.
📈 활용 예시
- 글로벌 자금 흐름 모니터링: 전세계 유동성 추세 및 시장 리스크 신호 분석
- 환율/금리 정책 분석: 달러 강약과 주요국 정책 변화 비교
- 주가지수 벤치마크 비교: MSCI World, 코스피, 나스닥 등과 상관관계 확인
- 밸류에이션 분석: 전체 유동성 수준을 주가지수나 시가총액과 비교하여, 시장의 상대적 고평가·저평가 여부를 평가
- 위기 대응 전략: 글로벌 신용위기·자금 긴축 국면 대비
3D Surface Modeling [PhenLabs]📊 3D Surface Modeling
Version: PineScript™ v6
📌 Description
The 3D Surface Modeling indicator revolutionizes technical analysis by generating three-dimensional visualizations of multiple technical indicators across various timeframes. This advanced analytical tool processes and renders complex indicator data through a sophisticated matrix-based calculation system, creating an intuitive 3D surface representation of market dynamics.
The indicator employs array-based computations to simultaneously analyze multiple instances of selected technical indicators, mapping their behavior patterns across different temporal dimensions. This unique approach enables traders to identify complex market patterns and relationships that may be invisible in traditional 2D charts.
🚀 Points of Innovation
Matrix-Based Computation Engine: Processes up to 500 concurrent indicator calculations in real-time
Dynamic 3D Rendering System: Creates depth perception through sophisticated line arrays and color gradients
Multi-Indicator Integration: Seamlessly combines VWAP, Hurst, RSI, Stochastic, CCI, MFI, and Fractal Dimension analyses
Adaptive Scaling Algorithm: Automatically adjusts visualization parameters based on indicator type and market conditions
🔧 Core Components
Indicator Processing Module: Handles real-time calculation of multiple technical indicators using array-based mathematics
3D Visualization Engine: Converts indicator data into three-dimensional surfaces using line arrays and color mapping
Dynamic Scaling System: Implements custom normalization algorithms for different indicator types
Color Gradient Generator: Creates depth perception through programmatic color transitions
🔥 Key Features
Multi-Indicator Support: Comprehensive analysis across seven different technical indicators
Customizable Visualization: User-defined color schemes and line width parameters
Real-time Processing: Continuous calculation and rendering of 3D surfaces
Cross-Timeframe Analysis: Simultaneous visualization of indicator behavior across multiple periods
🎨 Visualization
Surface Plot: Three-dimensional representation using up to 500 lines with dynamic color gradients
Depth Indicators: Color intensity variations showing indicator value magnitude
Pattern Recognition: Visual identification of market structures across multiple timeframes
📖 Usage Guidelines
Indicator Selection
Type: VWAP, Hurst, RSI, Stochastic, CCI, MFI, Fractal Dimension
Default: VWAP
Starting Length: Minimum 5 periods
Default: 10
Step Size: Interval between calculations
Range: 1-10
Visualization Parameters
Color Scheme: Green, Red, Blue options
Line Width: 1-5 pixels
Surface Resolution: Up to 500 lines
✅ Best Use Cases
Multi-timeframe market analysis
Pattern recognition across different technical indicators
Trend strength assessment through 3D visualization
Market behavior study across multiple periods
⚠️ Limitations
High computational resource requirements
Maximum 500 line restriction
Requires substantial historical data
Complex visualization learning curve
🔬 How It Works
1. Data Processing:
Calculates selected indicator values across multiple timeframes
Stores results in multi-dimensional arrays
Applies custom scaling algorithms
2. Visualization Generation:
Creates line arrays for 3D surface representation
Applies color gradients based on value magnitude
Renders real-time updates to surface plot
3. Display Integration:
Synchronizes with chart timeframe
Updates surface plot dynamically
Maintains visual consistency across updates
🌟 Credits:
Inspired by LonesomeTheBlue (modified for multiple indicator types with scaling fixes and additional unique mappings)
💡 Note:
Optimal performance requires sufficient computing resources and historical data. Users should start with default settings and gradually adjust parameters based on their analysis requirements and system capabilities.
Average Daily % Change by Weekday📊 Average Daily % Change by Weekday
This script calculates and displays the average daily percentage change for each weekday (Monday through Sunday) based on historical price data. It helps traders analyze which days tend to be bullish or bearish over a selected backtest date range.
✅ Features:
Customizable date range (From Year/Month/Day to To Year/Month/Day)
Calculates average % change for each weekday (Mon–Sun)
Supports assets that trade 7 days (e.g., crypto)
Color-coded outputs (green = positive, red = negative)
Final results shown as a table in the bottom-right corner
Works only on the 1D timeframe (daily)
🧠 How it works:
For each day within the selected date range:
The script calculates the % change as: (Close - Open) / Open * 100
Then, it groups the data by weekday and averages the values
This gives you insight into how each day of the week behaves historically for the current asset.
⚠️ Notes:
This script only works on daily (1D) timeframes.
For most accurate results, use it on assets with long trading history (e.g., BTCUSD).
Designed for educational and statistical analysis purposes.
NQ Hourly Standard Deviation ZonesNQ Hourly Standard Deviation ZonesDescriptionThe NQ Hourly Standard Deviation Zones indicator is designed for traders analyzing the NASDAQ 100 futures (NQ) on an hourly timeframe. It plots dynamic support and resistance zones based on historical standard deviation (SD) levels calculated from the hourly open price. These zones represent the expected price range for each hour of the trading day, offering insights into potential price targets, reversals, or breakout levels. The indicator is highly customizable, allowing users to adjust the data period, display settings, and visual preferences to suit their trading style.The indicator calculates and displays:
• 0.5 SD Zones: Representing the price levels one-half standard deviation above and below the hourly open.
• 1.0 SD Zones: Representing the price levels one standard deviation above and below the hourly open.
• Hourly Open Line: A reference line marking the hourly open price.
These zones are derived from pre-calculated standard deviation data for the high and low price movements relative to the hourly open, segmented by each hour of the day (0–23). Users can select from multiple historical data periods (3 months to 17+ years) to align the zones with their preferred lookback period, accommodating both short-term and long-term trading strategies.Key Features
• Customizable Data Periods: Choose from 3 months, 6 months, 9 months, 1 year, 2 years, 3 years, 4 years, 5 years, 10 years, 15 years, or 17+ years of historical data to calculate standard deviation zones.
• RTH Filter: Option to display zones only during Regular Trading Hours (RTH, 9:00–15:59, America/New_York timezone) for traders focusing on the main trading session.
• Visual Customization:
• Toggle visibility of 0.5 SD and 1.0 SD labels.
• Customize line styles (Solid, Dotted, Dashed) and colors for 0.5 SD and 1.0 SD lines.
• Enable or disable shaded fills between the 0.5 SD and 1.0 SD zones, with customizable fill color.
• Timezone Support: Aligns with user-specified timezone (default: America/New_York) for accurate hourly calculations.
• Dynamic Updates: Zones are redrawn at the start of each new hourly bar, ensuring real-time relevance.
How It WorksThe indicator uses pre-computed standard deviation values for price movements (high and low) from the hourly open, based on the selected data period. For each hour of the day:
• High Zones: The +0.5 SD and +1.0 SD levels are plotted above the hourly open price.
• Low Zones: The -0.5 SD and -1.0 SD levels are plotted below the hourly open price.
• Hourly Open: A dotted line marks the open price for reference.
• Fills: Optional shaded areas between the 0.5 SD and 1.0 SD zones highlight the expected price range.
• Labels: Optional labels display "+0.5 σ," "-0.5 σ," "+1.0 σ," "-1.0 σ," and "h.o" (hourly open) at the end of each hourly bar for clarity.
The zones are plotted as horizontal lines spanning the duration of the hour, with fills and labels updated dynamically as new hourly bars form. The indicator clears previous lines and labels at the start of each new hour to maintain a clean chart.Usage
• Intraday Trading: Use the 0.5 SD and 1.0 SD zones as dynamic support and resistance levels for identifying potential entry/exit points, reversals, or breakout opportunities.
• Range Trading: The zones help visualize the expected price range for each hour, aiding in range-bound strategies.
• Risk Management: The 1.0 SD zones represent statistically significant levels, useful for setting stop-loss or take-profit levels.
• Session Filtering: Enable the "Show RTH Only" option to focus on high-liquidity hours, ideal for day traders.
• Historical Analysis: Select different data periods to analyze how price behavior varies over short-term (e.g., 3 months) versus long-term (e.g., 17+ years) market conditions.
Settings
• Settings:
• Show RTH Only (9:00–15:59): Toggle to display zones only during Regular Trading Hours (default: true).
• Timezone: Select the timezone for accurate hourly alignment (default: America/New_York).
• Select Data Period: Choose the historical data period for standard deviation calculations (options: 3 Months, 6 Months, 9 Months, 1 Year, 2 Years, 3 Years, 4 Years, 5 Years, 10 Years, 15 Years, 17+ Years; default: 17+ Years).
• Visuals:
• Show Fill: Toggle shaded areas between 0.5 SD and 1.0 SD zones (default: true).
• Fill Color: Customize the color and transparency of the fill (default: light gray, 90% transparency).
• 0.5 SD Line: Set the color (default: gray, 50% transparency) and style (Solid, Dotted, Dashed; default: Dashed) for 0.5 SD lines.
• 1.0 SD Line: Set the color (default: gray, 0% transparency) and style (Solid, Dotted, Dashed; default: Solid) for 1.0 SD lines.
• Show 0.5 SD Labels: Toggle visibility of 0.5 SD labels (default: true) and set their text color (default: gray).
• Show 1.0 SD Labels: Toggle visibility of 1.0 SD labels (default: true) and set their text color (default: gray).
Notes
• The indicator is optimized for the NASDAQ 100 futures (NQ) on an hourly timeframe. Ensure the chart is set to a compatible timeframe (e.g., 1-hour) for accurate results.
• Standard deviation values are pre-calculated and stored for each hour of the day, based on historical data. They are not dynamically recalculated from live data, ensuring consistent performance.
• The indicator uses up to 500 lines and labels to comply with TradingView’s rendering limits, ensuring smooth operation even on extended charts.
• For best results, use on liquid instruments like NQ futures, and consider combining with other technical indicators for confirmation.
Example Use CaseA trader focusing on NQ day trading can enable "Show RTH Only" and select a 3-month data period to plot zones for the 9:00–15:59 session. During the 10:00 AM hour, if the price approaches the +1.0 SD zone, the trader might anticipate resistance and consider a short position, using the -1.0 SD zone as a potential target. Conversely, a break above the +1.0 SD zone could signal a breakout, prompting a long position.Limitations
• The indicator relies on pre-computed standard deviation values, which may not reflect real-time market volatility.
• It is designed specifically for hourly charts and may not function correctly on other timeframes.
• The RTH filter assumes a standard trading session (9:00–15:59); custom session times are not supported.
AuthorThis indicator is designed for traders seeking a statistical approach to intraday price analysis, leveraging historical volatility patterns to inform trading decisions.