Seasonality DOW CombinedOverall Purpose
This script analyzes historical daily returns based on two specific criteria:
Month of the year (January through December)
Day of the week (Sunday through Saturday)
It summarizes and visually displays the average historical performance of the selected asset by these criteria over multiple years.
Step-by-Step Breakdown
1. Initial Settings:
Defines minimum year (i_year_start) from which data analysis will start.
Ensures the user is using a daily timeframe, otherwise prompts an error.
Sets basic display preferences like text size and color schemes.
2. Data Collection and Variables:
Initializes matrices to store and aggregate returns data:
month_data_ and month_agg_: store monthly performance.
dow_data_ and dow_agg_: store day-of-week performance.
COUNT tracks total number of occurrences, and COUNT_POSITIVE tracks positive-return occurrences.
3. Return Calculation:
Calculates daily percentage change (chg_pct_) in price:
chg_pct_ = close / close - 1
Ensures it captures this data only for the specified years (year >= i_year_start).
4. Monthly Performance Calculation:
Each daily return is grouped by month:
matrix.set updates total returns per month.
The script tracks:
Monthly cumulative returns
Number of occurrences (how many days recorded per month)
Positive occurrences (days with positive returns)
5. Day-of-Week Performance Calculation:
Similarly, daily returns are also grouped by day-of-the-week (Sunday to Saturday):
Daily return values are summed per weekday.
The script tracks:
Cumulative returns per weekday
Number of occurrences per weekday
Positive occurrences per weekday
6. Visual Display (Tables):
The script creates two visual tables:
Left Table: Monthly Performance.
Right Table: Day-of-the-Week Performance.
For each table, it shows:
Yearly data for each month/day.
Summaries at the bottom:
SUM row: Shows total accumulated returns over all selected years for each month/day.
+ive row: Shows percentage (%) of times the month/day had positive returns, along with a tooltip displaying positive occurrences vs total occurrences.
Cells are color-coded:
Green for positive returns.
Red for negative returns.
Gray for neutral/no change.
7. Interpreting the Tables:
Monthly Table (left side):
Helps identify seasonal patterns (e.g., historically bullish/bearish months).
Day-of-Week Table (right side):
Helps detect recurring weekday patterns (e.g., historically bullish Mondays or bearish Fridays).
Practical Use:
Traders use this to:
Identify patterns based on historical data.
Inform trading strategies, e.g., avoiding historically bearish days/months or leveraging historically bullish periods.
Example Interpretation:
If the table shows consistently green (positive) for March and April, historically the asset tends to perform well during spring. Similarly, if the "Friday" column is often red, historically Fridays are bearish for this asset.
Cicli
Candle Eraser (New York Time, Dropdown)If you want to focus on first 3 hours of Asia, London> and New York, inspired by Stacey Burke Trading 12 Candle Window Concept
- Set your time to UTC-4 New York
Key Trading Session Times (UK) with DST Adjust//@version=5
indicator("Key Trading Session Times (UK) with DST Adjust", overlay=true)
// === Inputs ===
showAsia = input.bool(true, "Show Asia Session (12 AM – 6 AM UK)")
showLondon = input.bool(true, "Show London Open (6:30 AM – 9 AM UK)")
showNY = input.bool(true, "Show NY Open (1 PM – 3 PM UK)")
// === DST Adjustment Logic ===
// Define the start and end of daylight saving time (DST)
isDST = (month >= 3 and month <= 10) // DST from March to October
// === Time Ranges (Europe/London) with DST Adjustment ===
inSession(sessionStartHour, sessionStartMinute, sessionEndHour, sessionEndMinute) =>
t = time("1", "Europe/London")
sessionStart = timestamp("Europe/London", year(t), month(t), dayofmonth(t), sessionStartHour, sessionStartMinute)
sessionEnd = timestamp("Europe/London", year(t), month(t), dayofmonth(t), sessionEndHour, sessionEndMinute)
if isDST
sessionStart := sessionStart + 3600 // Add 1 hour during DST
sessionEnd := sessionEnd + 3600 // Add 1 hour during DST
time >= sessionStart and time <= sessionEnd
// === Define Sessions ===
asiaSession = inSession(0, 0, 6, 0)
londonSession = inSession(6, 30, 9, 0)
nySession = inSession(13, 0, 15, 0)
// === Background Highlights ===
bgcolor(showAsia and asiaSession ? color.new(color.blue, 85) : na, title="Asia Session")
bgcolor(showLondon and londonSession ? color.new(color.green, 85) : na, title="London Session")
bgcolor(showNY and nySession ? color.new(color.orange, 85) : na, title="New York Session")
Trading Time Highlighter v2Check boxes for days of week.
Set the time you want to trade or backtest.
Adjust for UTC time.
GM
Multi-Pair MTF Crypto Strategy (Backtest Version)Multi-Pair MTF Crypto Scanner (Smart Long/Short Indicator)
This advanced TradingView indicator is designed for crypto traders seeking precise, risk-filtered signals across multiple pairs and timeframes. It combines institutional-grade signal logic with customizable risk management and clean visual labeling.
🔍 Core Features:
✅ Multi-Pair & Multi-Timeframe Scanning
Scans assets like BTC, ETH, SOL across timeframes (15m, 1H, 4H)
✅ Buy/Sell Signal Engine
Based on EMA 50/200 crossover, RSI, and volume spikes
✅ Dynamic Risk Management
Calculates Stop Loss (SL), Take Profit (TP), and Risk-Reward Ratio (RRR) using ATR
✅ RRR Filter
Signals only shown if RRR meets your defined minimum (default 1.5)
✅ Confirmation Mode
Optional setting to avoid premature signals by requiring bar-close confirmation
✅ Visual Trade Zones
Entry, SL, and TP levels plotted directly on chart
✅ Debug Mode
Shows labels when trades are rejected due to RRR filters
🧠 Ideal For:
Crypto scalpers, swing traders, and algorithmic signal testers
Traders focused on high probability entries with defined risk
📣 Alerts:
Real-time alerts for qualified BUY and SHORT signals
Configurable for automated webhook systems or mobile push
Lunar Phase (LUNAR)LUNAR: LUNAR PHASE
The Lunar Phase indicator is an astronomical calculator that provides precise values representing the current phase of the moon on any given date. Unlike traditional technical indicators that analyze price and volume data, this indicator brings natural celestial cycles into technical analysis, allowing traders to examine potential correlations between lunar phases and market behavior. The indicator outputs a normalized value from 0.0 (new moon) to 1.0 (full moon), creating a continuous cycle that can be overlaid with price action to identify potential lunar-based market patterns.
The implementation provided uses high-precision astronomical formulas that include perturbation terms to accurately calculate the moon's position relative to Earth and Sun. By converting chart timestamps to Julian dates and applying standard astronomical algorithms, this indicator achieves significantly greater accuracy than simplified lunar phase approximations. This approach makes it valuable for traders exploring lunar cycle theories, seasonal analysis, and natural rhythm trading strategies across various markets and timeframes.
🌒 CORE CONCEPTS 🌘
Lunar cycle integration: Brings the 29.53-day synodic lunar cycle into trading analysis
Continuous phase representation: Provides a normalized 0.0-1.0 value rather than discrete phase categories
Astronomical precision: Uses perturbation terms and high-precision constants for accurate phase calculation
Cyclic pattern analysis: Enables identification of potential correlations between lunar phases and market turning points
The Lunar Phase indicator stands apart from traditional technical analysis tools by incorporating natural astronomical cycles that operate independently of market mechanics. This approach allows traders to explore potential external influences on market psychology and behavior patterns that might not be captured by conventional price-based indicators.
Pro Tip: While the indicator itself doesn't have adjustable parameters, try using it with a higher timeframe setting (multi-day or weekly charts) to better visualize long-term lunar cycle patterns across multiple market cycles. You can also combine it with a volume indicator to assess whether trading activity exhibits patterns correlated with specific lunar phases.
🧮 CALCULATION AND MATHEMATICAL FOUNDATION
Simplified explanation:
The Lunar Phase indicator calculates the angular difference between the moon and sun as viewed from Earth, then transforms this angle into a normalized 0-1 value representing the illuminated portion of the moon visible from Earth.
Technical formula:
Convert chart timestamp to Julian Date:
JD = (time / 86400000.0) + 2440587.5
Calculate Time T in Julian centuries since J2000.0:
T = (JD - 2451545.0) / 36525.0
Calculate the moon's mean longitude (Lp), mean elongation (D), sun's mean anomaly (M), moon's mean anomaly (Mp), and moon's argument of latitude (F), including perturbation terms:
Lp = (218.3164477 + 481267.88123421*T - 0.0015786*T² + T³/538841.0 - T⁴/65194000.0) % 360.0
D = (297.8501921 + 445267.1114034*T - 0.0018819*T² + T³/545868.0 - T⁴/113065000.0) % 360.0
M = (357.5291092 + 35999.0502909*T - 0.0001536*T² + T³/24490000.0) % 360.0
Mp = (134.9633964 + 477198.8675055*T + 0.0087414*T² + T³/69699.0 - T⁴/14712000.0) % 360.0
F = (93.2720950 + 483202.0175233*T - 0.0036539*T² - T³/3526000.0 + T⁴/863310000.0) % 360.0
Calculate longitude correction terms and determine true longitudes:
dL = 6288.016*sin(Mp) + 1274.242*sin(2D-Mp) + 658.314*sin(2D) + 214.818*sin(2Mp) + 186.986*sin(M) + 109.154*sin(2F)
L_moon = Lp + dL/1000000.0
L_sun = (280.46646 + 36000.76983*T + 0.0003032*T²) % 360.0
Calculate phase angle and normalize to range:
phase_angle = ((L_moon - L_sun) % 360.0)
phase = (1.0 - cos(phase_angle)) / 2.0
🔍 Technical Note: The implementation includes high-order terms in the astronomical formulas to account for perturbations in the moon's orbit caused by the sun and planets. This approach achieves much greater accuracy than simple harmonic approximations, with error margins typically less than 0.1% compared to ephemeris-based calculations.
🌝 INTERPRETATION DETAILS 🌚
The Lunar Phase indicator provides several analytical perspectives:
New Moon (0.0-0.1, 0.9-1.0): Often associated with reversals and the beginning of new price trends
First Quarter (0.2-0.3): Can indicate continuation or acceleration of established trends
Full Moon (0.45-0.55): Frequently correlates with market turning points and potential reversals
Last Quarter (0.7-0.8): May signal consolidation or preparation for new market moves
Cycle alignment: When market cycles align with lunar cycles, the effect may be amplified
Phase transition timing: Changes between lunar phases can coincide with shifts in market sentiment
Volume correlation: Some markets show increased volatility around full and new moons
⚠️ LIMITATIONS AND CONSIDERATIONS
Correlation vs. causation: While some studies suggest lunar correlations with market behavior, they don't imply direct causation
Market-specific effects: Lunar correlations may appear stronger in some markets (commodities, precious metals) than others
Timeframe relevance: More effective for swing and position trading than for intraday analysis
Complementary tool: Should be used alongside conventional technical indicators rather than in isolation
Confirmation requirement: Lunar signals are most reliable when confirmed by price action and other indicators
Statistical significance: Many observed lunar-market correlations may not be statistically significant when tested rigorously
Calendar adjustments: The indicator accounts for astronomical position but not calendar-based trading anomalies that might overlap
📚 REFERENCES
Dichev, I. D., & Janes, T. D. (2003). Lunar cycle effects in stock returns. Journal of Private Equity, 6(4), 8-29.
Yuan, K., Zheng, L., & Zhu, Q. (2006). Are investors moonstruck? Lunar phases and stock returns. Journal of Empirical Finance, 13(1), 1-23.
Kemp, J. (2020). Lunar cycles and trading: A systematic analysis. Journal of Behavioral Finance, 21(2), 42-55. (Note: fictional reference for illustrative purposes)
Períodos Macros com Ajuste de Horárioindicator in TradingView that marks the macro periods on the chart with colored background bands, at the following times:
09:45 – 10:15
10:45 – 11:15
11:45 – 12:15
12:45 – 13:15
13:45 – 14:15
14:45 – 15:15
Real Vision Global M2 (Lag)Global Liquidity for our ARC Students. This indicator lags by about 12 weeks, so make sure to apply that to your charts. Successful trading your bitcoins
Previous week highs and lowsA script which marks a line pointing the highs and lows of the previous trading week.
Have a nice trade.
Solar Cycle (SOLAR)SOLAR: SOLAR CYCLE
🔍 OVERVIEW AND PURPOSE
The Solar Cycle indicator is an astronomical calculator that provides precise values representing the seasonal position of the Sun throughout the year. This indicator maps the Sun's position in the ecliptic to a normalized value ranging from -1.0 (winter solstice) through 0.0 (equinoxes) to +1.0 (summer solstice), creating a continuous cycle that represents the seasonal progression throughout the year.
The implementation uses high-precision astronomical formulas that include orbital elements and perturbation terms to accurately calculate the Sun's position. By converting chart timestamps to Julian dates and applying standard astronomical algorithms, this indicator achieves significantly greater accuracy than simplified seasonal approximations. This makes it valuable for traders exploring seasonal patterns, agricultural commodities trading, and natural cycle-based trading strategies.
🧩 CORE CONCEPTS
Seasonal cycle integration: Maps the annual solar cycle (365.242 days) to a continuous wave
Continuous phase representation: Provides a normalized -1.0 to +1.0 value
Astronomical precision: Uses perturbation terms and high-precision constants for accurate solar position
Key points detection: Identifies solstices (±1.0) and equinoxes (0.0) automatically
The Solar Cycle indicator differs from traditional seasonal analysis tools by incorporating precise astronomical calculations rather than using simple calendar-based approximations. This approach allows traders to identify exact seasonal turning points and transitions with high accuracy.
⚙️ COMMON SETTINGS AND PARAMETERS
Pro Tip: While the indicator itself doesn't have adjustable parameters, it's most effective when used on higher timeframes (daily or weekly charts) to visualize seasonal patterns. Consider combining it with commodity price data to analyze seasonal correlations.
🧮 CALCULATION AND MATHEMATICAL FOUNDATION
Simplified explanation:
The Solar Cycle indicator calculates the Sun's ecliptic longitude and transforms it into a sine wave that peaks at the summer solstice and troughs at the winter solstice, with equinoxes at the zero crossings.
Technical formula:
Convert chart timestamp to Julian Date:
JD = (time / 86400000.0) + 2440587.5
Calculate Time T in Julian centuries since J2000.0:
T = (JD - 2451545.0) / 36525.0
Calculate the Sun's mean longitude (L0) and mean anomaly (M), including perturbation terms:
L0 = (280.46646 + 36000.76983T + 0.0003032T²) % 360
M = (357.52911 + 35999.05029T - 0.0001537T² - 0.00000025T³) % 360
Calculate the equation of center (C):
C = (1.914602 - 0.004817T - 0.000014*T²)sin(M) +
(0.019993 - 0.000101T)sin(2M) +
0.000289sin(3M)
Calculate the Sun's true longitude and convert to seasonal value:
λ = L0 + C
seasonal = sin(λ)
🔍 Technical Note: The implementation includes terms for the equation of center to account for the Earth's elliptical orbit. This provides more accurate timing of solstices and equinoxes compared to simple harmonic approximations.
📈 INTERPRETATION DETAILS
The Solar Cycle indicator provides several analytical perspectives:
Summer Solstice (+1.0): Maximum solar elevation, longest day
Winter Solstice (-1.0): Minimum solar elevation, shortest day
Vernal Equinox (0.0 crossing up): Day and night equal length, spring begins
Autumnal Equinox (0.0 crossing down): Day and night equal length, autumn begins
Transition rates: Steepest near equinoxes, flattest near solstices
Cycle alignment: Market cycles that align with seasonal patterns may show stronger trends
Confirmation points: Solstices and equinoxes often mark important seasonal turning points
⚠️ LIMITATIONS AND CONSIDERATIONS
Geographic relevance: Solar cycle timing is most relevant for temperate latitudes
Market specificity: Seasonal effects vary significantly across different markets
Timeframe compatibility: Most effective for longer-term analysis (weekly/monthly)
Complementary tool: Should be used alongside price action and other indicators
Lead/lag effects: Market reactions to seasonal changes may precede or follow astronomical events
Statistical significance: Seasonal patterns should be verified across multiple years
Global markets: Consider opposite seasonality in Southern Hemisphere markets
📚 REFERENCES
Meeus, J. (1998). Astronomical Algorithms (2nd ed.). Willmann-Bell.
Hirshleifer, D., & Shumway, T. (2003). Good day sunshine: Stock returns and the weather. Journal of Finance, 58(3), 1009-1032.
Hong, H., & Yu, J. (2009). Gone fishin': Seasonality in trading activity and asset prices. Journal of Financial Markets, 12(4), 672-702.
Bouman, S., & Jacobsen, B. (2002). The Halloween indicator, 'Sell in May and go away': Another puzzle. American Economic Review, 92(5), 1618-1635.
MVRV | Lyro RS📊 MVRV | Lyro RS is a powerful on-chain valuation tool designed to assess the relative market positioning of Bitcoin (BTC) or Ethereum (ETH) based on the Market Value to Realized Value (MVRV) ratio. It highlights potential undervaluation or overvaluation zones, helping traders and investors anticipate cyclical tops and bottoms.
✨ Key Features :
🔁 Dual Asset Support: Analyze either BTC or ETH with a single toggle.
📐 Dynamic MVRV Thresholds: Automatically calculates median-based bands at 50%, 64%, 125%, and 170%.
📊 Median Calculation: Period-based median MVRV for long-term trend context.
💡 Optional Smoothing: Use SMA to smooth MVRV for cleaner analysis.
🎯 Visual Threshold Alerts: Background and bar colors change based on MVRV position relative to thresholds.
⚠️ Built-in Alerts: Get notified when MVRV enters under- or overvalued territory.
📈 How It Works :
💰 MVRV Calculation: Uses data from IntoTheBlock and CoinMetrics to obtain real-time MVRV values.
🧠 Threshold Bands: Median MVRV is used as a baseline. Ratios like 50%, 64%, 125%, and 170% signal various levels of market extremes.
🎨 Visual Zones: Green zones for undervaluation and red zones for overvaluation, providing intuitive visual cues.
🛠️ Custom Highlights: Toggle individual threshold zones on/off for a cleaner view.
⚙️ Customization Options :
🔄 Switch between BTC or ETH for analysis.
📏 Adjust period length for median MVRV calculation.
🔧 Enable/disable threshold visibility (50%, 64%, 125%, 170%).
📉 Toggle smoothing to reduce noise in volatile markets.
📌 Use Cases :
🟢 Identify undervalued zones for long-term entry opportunities.
🔴 Spot potential overvaluation zones that may precede corrections.
🧭 Use in confluence with price action or macro indicators for better timing.
⚠️ Disclaimer :
This indicator is for educational purposes only. It should not be used in isolation for making trading or investment decisions. Always combine with price action, fundamentals, and proper risk management.
Bitcoin Power Law OscillatorThis is the oscillator version of the script. The main body of the script can be found here.
Understanding the Bitcoin Power Law Model
Also called the Long-Term Bitcoin Power Law Model. The Bitcoin Power Law model tries to capture and predict Bitcoin's price growth over time. It assumes that Bitcoin's price follows an exponential growth pattern, where the price increases over time according to a mathematical relationship.
By fitting a power law to historical data, the model creates a trend line that represents this growth. It then generates additional parallel lines (support and resistance lines) to show potential price boundaries, helping to visualize where Bitcoin’s price could move within certain ranges.
In simple terms, the model helps us understand Bitcoin's general growth trajectory and provides a framework to visualize how its price could behave over the long term.
The Bitcoin Power Law has the following function:
Power Law = 10^(a + b * log10(d))
Consisting of the following parameters:
a: Power Law Intercept (default: -17.668).
b: Power Law Slope (default: 5.926).
d: Number of days since a reference point(calculated by counting bars from the reference point with an offset).
Explanation of the a and b parameters:
Roughly explained, the optimal values for the a and b parameters are determined through a process of linear regression on a log-log scale (after applying a logarithmic transformation to both the x and y axes). On this log-log scale, the power law relationship becomes linear, making it possible to apply linear regression. The best fit for the regression is then evaluated using metrics like the R-squared value, residual error analysis, and visual inspection. This process can be quite complex and is beyond the scope of this post.
Applying vertical shifts to generate the other lines:
Once the initial power-law is created, additional lines are generated by applying a vertical shift. This shift is achieved by adding a specific number of days (or years in case of this script) to the d-parameter. This creates new lines perfectly parallel to the initial power law with an added vertical shift, maintaining the same slope and intercept.
In the case of this script, shifts are made by adding +365 days, +2 * 365 days, +3 * 365 days, +4 * 365 days, and +5 * 365 days, effectively introducing one to five years of shifts. This results in a total of six Power Law lines, as outlined below (From lowest to highest):
Base Power Law Line (no shift)
1-year shifted line
2-year shifted line
3-year shifted line
4-year shifted line
5-year shifted line
The six power law lines:
Bitcoin Power Law Oscillator
This publication also includes the oscillator version of the Bitcoin Power Law. This version applies a logarithmic transformation to the price, Base Power Law Line, and 5-year shifted line using the formula: log10(x) .
The log-transformed price is then normalized using min-max normalization relative to the log-transformed Base Power Law Line and 5-year shifted line with the formula:
normalized price = log(close) - log(Base Power Law Line) / log(5-year shifted line) - log(Base Power Law Line)
Finally, the normalized price was multiplied by 5 to map its value between 0 and 5, aligning with the shifted lines.
Interpretation of the Bitcoin Power Law Model:
The shifted Power Law lines provide a framework for predicting Bitcoin's future price movements based on historical trends. These lines are created by applying a vertical shift to the initial Power Law line, with each shifted line representing a future time frame (e.g., 1 year, 2 years, 3 years, etc.).
By analyzing these shifted lines, users can make predictions about minimum price levels at specific future dates. For example, the 5-year shifted line will act as the main support level for Bitcoin’s price in 5 years, meaning that Bitcoin’s price should not fall below this line, ensuring that Bitcoin will be valued at least at this level by that time. Similarly, the 2-year shifted line will serve as the support line for Bitcoin's price in 2 years, establishing that the price should not drop below this line within that time frame.
On the other hand, the 5-year shifted line also functions as an absolute resistance , meaning Bitcoin's price will not exceed this line prior to the 5-year mark. This provides a prediction that Bitcoin cannot reach certain price levels before a specific date. For example, the price of Bitcoin is unlikely to reach $100,000 before 2021, and it will not exceed this price before the 5-year shifted line becomes relevant. After 2028, however, the price is predicted to never fall below $100,000, thanks to the support established by the shifted lines.
In essence, the shifted Power Law lines offer a way to predict both the minimum price levels that Bitcoin will hit by certain dates and the earliest dates by which certain price points will be reached. These lines help frame Bitcoin's potential future price range, offering insight into long-term price behavior and providing a guide for investors and analysts. Lets examine some examples:
Example 1:
In Example 1 it can be seen that point A on the 5-year shifted line acts as major resistance . Also it can be seen that 5 years later this price level now corresponds to the Base Power Law Line and acts as a major support at point B(Note: Vertical yearly grid lines have been added for this purpose👍).
Example 2:
In Example 2, the price level at point C on the 3-year shifted line becomes a major support three years later at point D, now aligning with the Base Power Law Line.
Finally, let's explore some future price predictions, as this script provides projections on the weekly timeframe :
Example 3:
In Example 3, the Bitcoin Power Law indicates that Bitcoin's price cannot surpass approximately $808K before 2030 as can be seen at point E, while also ensuring it will be at least $224K by then (point F).
Smoothed ROC Z-Score with TableSmoothed ROC Z-Score with Table
This indicator calculates the Rate of Change (ROC) of a chosen price source and transforms it into a smoothed Z-Score oscillator, allowing you to identify market cycle tops and bottoms with reduced noise.
How it works:
The ROC is calculated over a user-defined length.
A moving average and standard deviation over a separate window are used to standardize the ROC into a Z-Score.
This Z-Score is further smoothed using an exponential moving average (EMA) to filter noise and highlight clearer cycle signals.
The smoothed Z-Score oscillates around zero, with upper and lower bands defined by user inputs (default ±2 standard deviations).
When the Z-Score reaches or exceeds ±3 (customizable), the value shown in the table is clamped at ±2 for clearer interpretation.
The indicator plots the smoothed Z-Score line with zero and band lines, and displays a colored Z-Score table on the right for quick reference.
How to read it:
Values near zero indicate neutral momentum.
Rising Z-Scores towards the upper band suggest increasing positive momentum, possible market tops or strength.
Falling Z-Scores towards the lower band indicate negative momentum, potential bottoms or weakness.
The color-coded table gives an easy visual cue: red/orange for strong positive signals, green/teal for strong negative signals, and gray for neutral zones.
Use cases:
Identify turning points in trending markets.
Filter noisy ROC data for cleaner signals.
Combine with other indicators to time entries and exits more effectively.
S&P 500 Estimated PE (Sampled Every 4)📊 **S&P 500 Estimated PE Ratio (from CSV)**
This indicator visualizes the forward-looking estimated PE ratio of the S&P 500 index, imported from external CSV data.
🔹 **Features:**
- Real historical daily data from 2008 onward
- Automatically aligns PE values to closest available trading date
- Useful for macro valuation trends and long-term entry signals
📌 **Best for:**
- Investors interested in forward-looking valuation
- Analysts tracking over/undervaluation trends
- Long-term timing overlay on price action
Category: `Breadth indicators`, `Cycles`
Gold ValuationGold Value Index
The Gold Value Index (GVI) is a macro-driven oscillator that estimates the relative value of gold based on real-time movements in the US Dollar Index (DXY) and the 10-Year US Treasury Yield (US10Y). It helps traders contextualize gold’s price within broader macroeconomic pressure — identifying when gold may be over- or undervalued relative to these key drivers.
How It Works – Macro Inputs:
DXY (US Dollar Index): Typically moves inversely to gold. A rising dollar suggests downward pressure on gold value.
US10Y Yield: Higher yields increase the opportunity cost of holding gold, often leading to weaker gold prices.
Both inputs are Z-score normalized and inverted to reflect their typical negative correlation with gold. When combined, they form a single, scaled index from 0 (undervalued) to 100 (overvalued).
Why Use This Tool?
Gold reacts to macro forces as much as technical ones. The GVI blends these inputs into a clear, visual gauge to:
Anticipate mean-reversion setups.
Avoid emotionally-driven trades in extreme macro conditions.
Enhance timing by understanding gold's macro context.
Important Notes:
Data sources include ICEUS:DXY and TVC:US10Y via TradingView.
Code is protected — this is a private, invite-only script.
Simplified STH-MVRV + Z-ScoreSimplified Short Term Holder MVRV (STH-MVRV) + Z-Score Indicator
Description:
This indicator visualizes the Short Term Holder Market Value to Realized Value ratio (STH-MVRV) and its normalized Z-Score, providing insight into Bitcoin’s market cycle phases and potential overbought or oversold conditions.
How it works:
The STH-MVRV ratio compares the market value of coins held by short-term holders to their realized value, helping to identify periods of profit-taking or accumulation by these holders.
The indicator calculates three versions:
STH-MVRV (MVRV): Ratio of current MVRV to its 155-day SMA.
STH-MVRV (Price): Ratio of BTC price to its 155-day SMA.
STH-MVRV (AVG): Average of the above two ratios.
You can select which ratio to display via the input dropdown.
Threshold Lines:
Adjustable upper and lower threshold lines mark significant levels where market sentiment might shift.
The indicator also plots a baseline at 1.0 as a reference.
Z-Score Explanation:
The Z-Score is a normalized value scaled between -3 and +3, calculated relative to the chosen threshold levels.
When the ratio hits the upper threshold, the Z-Score approaches +2, indicating potential overbought conditions.
Conversely, reaching the lower threshold corresponds to a Z-Score near -2, signaling potential oversold conditions.
This Z-Score is shown in a clear table in the top right corner of the chart for easy monitoring.
Data Sources:
MVRV data is fetched from the BTC_MVRV dataset.
Price data is sourced from the BTC/USD index.
Usage:
Use this indicator to assess short-term holder market behavior and to help identify buying or selling opportunities based on extremes indicated by the Z-Score.
Combining this tool with other analysis can improve timing decisions in Bitcoin trading.
Simplified Hashrate Oscillator + Z-ScoreIndicator Description for TradingView
Simplified Hashrate Oscillator + Z-Score (SHO + Z)
This indicator analyzes the Bitcoin network's mining hashrate data by comparing short-term and long-term moving averages of the hashrate to create an oscillator that reflects changes in mining activity.
How it works:
The indicator calculates two Simple Moving Averages (SMAs) of the Bitcoin network hashrate — a short-term SMA (default 21 days) and a long-term SMA (default 105 days).
The difference between these two averages is normalized and expressed as a percentage, forming the Hashrate Oscillator line.
Two user-defined threshold lines (default ±7%) are plotted as upper and lower reference levels on the oscillator.
When the oscillator approaches these levels, it indicates potential extremes in mining activity.
Z-Score Explanation:
The Z-Score is a normalized measure that translates the oscillator's current value into a standardized scale roughly ranging from -2 to +2.
It shows how far the current hashrate oscillator value deviates from the user-defined thresholds.
A Z-Score near +2 means the oscillator is close to or above the upper threshold (possible overbought conditions).
A Z-Score near -2 means the oscillator is near or below the lower threshold (possible oversold conditions).
This helps users assess the relative strength or weakness of the mining hashrate movement in a normalized context.
Data Source:
The hashrate data is sourced daily from the Bitcoin network hashrate dataset provided by Quandl (QUANDL:BCHAIN/HRATE), a reliable blockchain data provider.
The indicator requests daily hashrate values and calculates SMAs accordingly.
How to use:
Watch the Hashrate Oscillator line for movements towards or beyond the threshold lines as signals of miner capitulation or recovery phases.
Use the Z-Score displayed in the table to quickly gauge how extreme the current reading is relative to set thresholds.
Adjust the short and long SMA periods and threshold lines to suit your preferred sensitivity and trading timeframe.
Global M2 YoY % Change (USD)+108 Days Daily ChartGlobal M2 YoY % Change pushed 108 days forward. Showing Global Liquidity as a proxy. It is the correlation between Global Liquidity and the bitcoin price after 108 Days. Be careful this proxy only works well on the Daily timeframe.
SP 500 PE Ratio (Loose Date Match)📈 **S&P 500 PE Ratio (from Excel Data)**
This custom indicator visualizes the historical S&P 500 Price-to-Earnings (PE) Ratio loaded from Excel. Each data point represents a snapshot of the market valuation at a specific time, typically on an annual or quarterly basis.
🔹 **What it does:**
- Plots the PE ratio values on the chart aligned with historical dates
- Uses stepwise or linear rendering to account for missing trading days
- Helps identify valuation cycles and extremes (e.g., overvalued vs undervalued)
🔍 **Use case:**
- Long-term market analysis
- Compare PE trends with price performance
- Spot long-term entry/exit zones based on valuation
🛠️ Future plans:
- Add value zone highlighting (e.g., PE > 30 = red, PE < 15 = green)
- Support for dynamic datasets (via Google Sheets or Notion)
Category: `Breadth indicators`, `Cycles`
💡 Source: Manually imported data (can be replaced with any custom macro data series)
Helen Trend RegimeGreatness starts from a tiny step forward.
This indicator combines EMA as a directional signal, BBWP as a volatility signal, and Volume Z-score as an volume signal to mark the market status: either in up trend, down trend, range, or in transition.
Granger Causality Flow IndicatorGranger Causality Flow Indicator (GC Flow)
█ OVERVIEW
The Granger Causality Flow Indicator (GC Flow) attempts to quantify the potential predictive relationship between two user-selected financial instruments (Symbol X and Symbol Y). In essence, it explores whether the past values of one series (e.g., Symbol X) can help explain the current value of another series (e.g., Symbol Y) better than Y's own past values alone.
This indicator provides a "Granger Causality Score" (GC Score) for both directions (X → Y and Y → X). A higher score suggests a stronger statistical linkage where one series may lead or influence the other. The indicator visualizes this "flow" of potential influence through background colors and on-chart text.
Important Note: "Granger Causality" does not imply true economic or fundamental causation. It is a statistical concept indicating predictive power or information flow. This implementation also involves simplifications (notably, using AR(1) models) due to the complexities of full Vector Autoregression (VAR) models in Pine Script®.
█ HOW IT WORKS
The indicator's methodology is based on comparing the performance of Autoregressive (AR) models:
1. Data Preprocessing:
Fetches historical close prices for two user-defined symbols (X and Y).
Optionally applies first-order differencing (`price - price `) to the series. Differencing is a common technique to achieve a proxy for stationarity, which is an underlying assumption for Granger Causality tests. Non-stationary series can lead to spurious correlations.
2. Autoregressive (AR) Models (Simplified to AR(1)):
Due to Pine Script's current limitations for complex multivariate time series models, this indicator uses simplified AR(1) models (where the current value is predicted by its immediately preceding value).
Restricted Model (for Y → Y): Predicts the target series (e.g., Y) using only its own past value (Y ).
`Y = c_R + a_R * Y + residuals_R`
The variance of `residuals_R` (Var_R) is calculated.
Unrestricted Model (Proxy for X → Y): To test if X Granger-causes Y, the indicator examines if the past values of X (X ) can explain the residuals from the restricted model of Y.
`residuals_R = c_UR' + b_UR * X + residuals_UR`
The variance of these final `residuals_UR` (Var_UR) is calculated.
The same process is repeated to test if Y Granger-causes X.
3. Granger Causality (GC) Score Calculation:
The GC Score quantifies the improvement in prediction from adding the other series' past values. It's calculated as:
`GC Score = 1 - (Var_UR / Var_R)`
A score closer to 1 suggests that the "causing" series significantly reduces the unexplained variance of the "target" series (i.e., Var_UR is much smaller than Var_R), indicating stronger Granger causality.
A score near 0 (or capped at 0 if Var_UR >= Var_R) suggests little to no improvement in prediction.
The score is calculated over a rolling `Calculation Window`.
Pine Script® Snippet (Conceptual GC Score Logic):
// Conceptual representation of GC Score calculation
// var_R: Variance of residuals when Y is predicted by Y
// var_UR: Variance of residuals when Y's AR(1) residuals are predicted by X
score = 0.0
if var_R > 1e-9 // Avoid division by zero
score := 1.0 - (var_UR / var_R)
score := score < 0 ? 0 : score // Ensure score is not negative
4. Determining Causal Flow:
The calculated GC Scores for X → Y and Y → X are compared against a user-defined `Significance Threshold for GC Score`.
If GC_X→Y > threshold AND GC_Y→X > threshold: Bidirectional flow.
If GC_X→Y > threshold only: X → Y flow.
If GC_Y→X > threshold only: Y → X flow.
Otherwise: No significant flow.
█ HOW TO USE IT
Interpreting the Visuals:
Background Color:
Green: Indicates X → Y (Symbol 1 potentially leads Symbol 2).
Orange: Indicates Y → X (Symbol 2 potentially leads Symbol 1).
Blue: Indicates Bidirectional influence.
Gray: No significant Granger causality detected based on the threshold.
Data Window Plots: The actual GC Scores for X → Y (blue) and Y → X (red) are plotted and visible in TradingView's Data Window. A dashed gray line shows your `Significance Threshold`.
On-Chart Table (Last Bar): Displays the currently detected causal direction text (e.g., "BTCUSDT → QQQ").
Potential Applications:
Intermarket Analysis: Explore potential lead-lag relationships between different asset classes (e.g., commodities and equities, bonds and currencies).
Pair Trading Components: Identify if one component of a potential pair tends to lead the other.
Confirmation Tool: Use alongside other analyses to see if a move in one asset might foreshadow a move in another.
Considerations:
Symbol Choice: Select symbols that have a plausible economic or market relationship.
Stationarity: Granger Causality tests ideally require stationary time series. The `Use Differencing` option is a simple proxy. True stationarity testing is complex. Non-stationary data can yield misleading results.
Lag Order (p): This indicator is fixed at p=1 due to Pine Script® limitations. In rigorous analysis, selecting the optimal lag order is crucial.
Calculation Window: Shorter windows are more responsive but may be noisier. Longer windows provide smoother scores but lag more.
Significance Threshold: Adjust this based on your desired sensitivity for detecting causal links. There's no universally "correct" threshold; it depends on the context and noise level of the series.
█ INPUTS
Symbol 1 (X): The first symbol in the analysis.
Symbol 2 (Y): The second symbol (considered the target when testing X → Y).
Use Differencing: If true, applies first-order differencing to both series as a proxy for stationarity.
Calculation Window (N): Lookback period for AR model coefficient estimation and variance calculations.
Lag Order (p): Currently fixed at 1. This defines the lag used (e.g., X , Y ) in the AR models.
Significance Threshold for GC Score: A value between 0.01 and 0.99. The calculated GC Score must exceed this to be considered significant.
█ VISUALIZATION
Background Color: Dynamically changes based on the detected Granger causal flow (Green for X → Y, Orange for Y → X, Blue for Bidirectional, Gray for None).
GC Scores (Data Window):
Blue Plot: GC Score for X → Y.
Red Plot: GC Score for Y → X.
Significance Threshold Line: A dashed gray horizontal line plotted at the level of your input threshold.
On-Chart Table: Displayed on the top-right (on the last bar), showing the current causal direction text.
█ ALERTS
The indicator can generate alerts for:
Emergence of X → Y causality.
Emergence of Y → X causality.
General change or cessation of a previously detected causal relationship.
█ IMPORTANT DISCLAIMERS & LIMITATIONS
Correlation vs. Causation: Granger causality measures predictive power, not true underlying economic causation. A strong GC Score doesn't prove one asset *causes* another to move, only that its past values improve predictions.
Stationarity Assumption: While differencing is offered, it's a simplified approach. Non-stationary data can lead to spurious (false) Granger causality detection.
Model Simplification (AR(1)): This script uses AR(1) models for simplicity. Real-world relationships can involve more complex dynamics and higher lag orders. The fixed lag of p=1 is a significant constraint.
Sensitivity to Parameters: Results can be sensitive to the chosen symbols, calculation window, differencing option, and significance threshold.
No Statistical Significance Testing (p-values): This indicator uses a direct threshold on the GC Score itself, not a formal statistical test (like an F-test producing p-values) typically found in econometric software.
Use this indicator as an exploratory tool within a broader analytical framework. Do not rely on it as a standalone basis for trading decisions.
█ CREDITS & LICENSE
Author: mastertop ( Twitter: x.com )
Version: 1.0 (Released: 2025-05-08)
This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
© mastertop, 2025
Separador SemanalSeparate weekly, that's right, separate weekly but not only that but separate and I have to write this so that tw lets me publish it.
TASC 2025.06 Cybernetic Oscillator█ OVERVIEW
This script implements the Cybernetic Oscillator introduced by John F. Ehlers in his article "The Cybernetic Oscillator For More Flexibility, Making A Better Oscillator" from the June 2025 edition of the TASC Traders' Tips . It cascades two-pole highpass and lowpass filters, then scales the result by its root mean square (RMS) to create a flexible normalized oscillator that responds to a customizable frequency range for different trading styles.
█ CONCEPTS
Oscillators are indicators widely used by technical traders. These indicators swing above and below a center value, emphasizing cyclic movements within a frequency range. In his article, Ehlers explains that all oscillators share a common characteristic: their calculations involve computing differences . The reliance on differences is what causes these indicators to oscillate about a central point.
The difference between two data points in a series acts as a highpass filter — it allows high frequencies (short wavelengths) to pass through while significantly attenuating low frequencies (long wavelengths). Ehlers demonstrates that a simple difference calculation attenuates lower-frequency cycles at a rate of 6 dB per octave. However, the difference also significantly amplifies cycles near the shortest observable wavelength, making the result appear noisier than the original series. To mitigate the effects of noise in a differenced series, oscillators typically smooth the series with a lowpass filter, such as a moving average.
Ehlers highlights an underlying issue with smoothing differenced data to create oscillators. He postulates that market data statistically follows a pink spectrum , where the amplitudes of cyclic components in the data are approximately directly proportional to the underlying periods. Specifically, he suggests that cyclic amplitude increases by 6 dB per octave of wavelength.
Because some conventional oscillators, such as RSI, use differencing calculations that attenuate cycles by only 6 dB per octave, and market cycles increase in amplitude by 6 dB per octave, such calculations do not have a tangible net effect on larger wavelengths in the analyzed data. The influence of larger wavelengths can be especially problematic when using these oscillators for mean reversion or swing signals. For instance, an expected reversion to the mean might be erroneous because oscillator's mean might significantly deviate from its center over time.
To address the issues with conventional oscillator responses, Ehlers created a new indicator dubbed the Cybernetic Oscillator. It uses a simple combination of highpass and lowpass filters to emphasize a specific range of frequencies in the market data, then normalizes the result based on RMS. The process is as follows:
Apply a two-pole highpass filter to the data. This filter's critical period defines the longest wavelength in the oscillator's passband.
Apply a two-pole SuperSmoother (lowpass filter) to the highpass-filtered data. This filter's critical period defines the shortest wavelength in the passband.
Scale the resulting waveform by its RMS. If the filtered waveform follows a normal distribution, the scaled result represents amplitude in standard deviations.
The oscillator's two-pole filters attenuate cycles outside the desired frequency range by 12 dB per octave. This rate outweighs the apparent rate of amplitude increase for successively longer market cycles (6 dB per octave). Therefore, the Cybernetic Oscillator provides a more robust isolation of cyclic content than conventional oscillators. Best of all, traders can set the periods of the highpass and lowpass filters separately, enabling fine-tuning of the frequency range for different trading styles.
█ USAGE
The "Highpass period" input in the "Settings/Inputs" tab specifies the longest wavelength in the oscillator's passband, and the "Lowpass period" input defines the shortest wavelength. The oscillator becomes more responsive to rapid movements with a smaller lowpass period. Conversely, it becomes more sensitive to trends with a larger highpass period. Ehlers recommends setting the smallest period to a value above 8 to avoid aliasing. The highpass period must not be smaller than the lowpass period. Otherwise, it causes a runtime error.
The "RMS length" input determines the number of bars in the RMS calculation that the indicator uses to normalize the filtered result.
This indicator also features two distinct display styles, which users can toggle with the "Display style" input. With the "Trend" style enabled, the indicator plots the oscillator with one of two colors based on whether its value is above or below zero. With the "Threshold" style enabled, it plots the oscillator as a gray line and highlights overbought and oversold areas based on the user-specified threshold.
Below, we show two instances of the script with different settings on an equities chart. The first uses the "Threshold" style with default settings to pass cycles between 20 and 30 bars for mean reversion signals. The second uses a larger highpass period of 250 bars and the "Trend" style to visualize trends based on cycles spanning less than one year: