Bubble Risk ModelThe question of whether markets can be objectively assessed for overextension has occupied financial researchers for decades. Charles Kindleberger, in his seminal work "Manias, Panics, and Crashes" (1978), documented that speculative bubbles follow remarkably consistent patterns across centuries and asset classes. Yet identifying these patterns in real time remains notoriously difficult. The Bubble Risk Model attempts to address this challenge not by predicting crashes, but by systematically measuring the statistical characteristics that historically precede fragile market conditions.
The theoretical foundation draws from two distinct research traditions. The first is the work on regime-switching models pioneered by James Hamilton (1989), who demonstrated that economic time series often exhibit discrete shifts between different behavioral states. The second is the literature on tail risk and market fragility, most notably articulated by Nassim Taleb in "The Black Swan" (2007), which emphasizes that extreme events carry disproportionate importance and that traditional risk measures systematically underestimate their probability.
Rather than attempting to build a probabilistic model requiring assumptions about underlying distributions, the Bubble Risk Model operates as a deterministic state-inference system. This distinction matters. Lawrence Rabiner's foundational tutorial on Hidden Markov Models (1989) established the mathematical framework for inferring hidden states from observable data through Bayesian updating. The present model borrows the conceptual architecture of states and transitions but replaces probabilistic inference with rule-based logic. States are not computed through forward-backward algorithms but inferred through deterministic thresholds. This trade-off sacrifices theoretical elegance for practical robustness and interpretability.
The measurement framework rests on four empirically grounded components. The first captures trailing twelve-month returns, reflecting the well-documented momentum effect identified by Jegadeesh and Titman (1993), who found that securities with strong past performance tend to continue outperforming over intermediate horizons. The second component measures trend persistence as the proportion of positive daily returns over a quarterly window, drawing on the research by Campbell and Shiller (1988) showing that price trends exhibit serial correlation that deviates from random walk assumptions. The third normalizes the distance between current prices and their long-term moving average by volatility, addressing the cross-sectional comparability problem noted by Fama and French (1992) when analyzing assets with different variance characteristics. The fourth component calculates return efficiency as the ratio of returns to realized volatility, a concept related to the Sharpe ratio but stripped of distributional assumptions that often fail in practice.
The aggregation methodology deliberately prioritizes worst-case scenarios. Rather than averaging component scores, the model uses quantile-based aggregation with an explicit tail penalty. This design choice reflects the asymmetric error costs in bubble detection: failing to identify fragility carries greater consequences than occasional false positives. The approach aligns with the precautionary principle advocated by Taleb and colleagues in their work on fragility and antifragility (2012), which argues that systems exposed to tail risks require conservative assessment frameworks.
Normalization presents a particular challenge. Raw metrics like year-over-year returns are not directly comparable across asset classes with different volatility profiles. The model addresses this through percentile ranking over multiple historical windows, typically two and five years. This dual-window approach provides regime stability, preventing the normalization from adapting too quickly during extended bull markets where elevated readings become statistically normal. The methodology draws on the concept of lookback bias documented by Lo and MacKinlay (1990), who demonstrated that single-window statistical measures can produce misleading results when market regimes shift.
The state machine introduces controlled inertia into the system. Once the model enters a particular state, transitions become progressively more difficult as the state matures. This transition resistance mechanism prevents rapid oscillation near threshold boundaries, a problem that plagues many indicator-based systems. The concept parallels the hysteresis effects described in economic literature by Dixit (1989), where systems exhibit path dependence and resist returning to previous states even when underlying conditions change.
Volatility regime detection adds contextual interpretation. Research by Engle (1982) on autoregressive conditional heteroskedasticity established that volatility clusters, with periods of high volatility tending to follow other high-volatility periods. The model scales its maturity thresholds inversely with volatility: in calm markets, states mature slowly and persist longer; in turbulent markets, information decays faster and states become more transient. This adaptive behavior reflects the empirical observation that low-volatility environments often precede significant market dislocations, as documented by Brunnermeier and Pedersen (2009) in their work on liquidity spirals.
The confidence metric addresses internal model consistency. When individual components diverge substantially, the overall score becomes less reliable regardless of its absolute level. This approach draws on ensemble methods in machine learning, where disagreement among predictors signals increased uncertainty. Dietterich (2000) provides theoretical justification for this principle, demonstrating that ensemble disagreement correlates with prediction error.
Distribution drift detection monitors whether the model's calibration remains valid. By comparing recent score distributions to longer historical baselines, the model can identify when market structure has shifted sufficiently to potentially invalidate its historical percentile rankings. This self-diagnostic capability reflects the concern raised by Andrews (1993) about parameter instability in time series models, where structural breaks can render previously estimated relationships unreliable.
The cross-asset analysis extends the framework beyond individual securities. By calculating scores for multiple asset classes simultaneously and measuring their correlation, the model distinguishes between idiosyncratic overextension affecting a single asset and systemic conditions affecting markets broadly. This differentiation matters for portfolio construction, as documented by Longin and Solnik (2001), who found that correlations between international equity markets increase significantly during periods of market stress.
Several limitations deserve explicit acknowledgment. The model cannot identify timing. Overextended conditions can persist far longer than rational analysis might suggest, a phenomenon documented by Shiller (2000) in his analysis of speculative episodes. The model provides no mechanism for determining when fragile conditions will resolve. Additionally, the cross-asset analysis lacks lead-lag detection, meaning it cannot distinguish whether assets became overextended simultaneously or sequentially. Finally, the rule-based nature of state inference means the model cannot express graduated probability assessments; states are discrete rather than continuous.
The philosophical stance underlying the model is one of epistemic humility. It does not claim to identify bubbles definitively or predict their collapse. Instead, it provides a systematic framework for measuring characteristics that have historically been associated with fragile market conditions. The distinction between information and action remains the user's responsibility. States describe current conditions; how to respond to those conditions requires judgment that no quantitative model can provide.
Practical guide for traders
This section translates the model's outputs into actionable intelligence for both retail traders managing personal portfolios and professional traders operating within institutional frameworks. The interpretation differs not in kind but in scale and consequence.
Understanding the score
The primary output is a continuous score ranging from zero to one. Lower scores indicate elevated bubble risk; higher scores suggest more sustainable market conditions. This inverse relationship may seem counterintuitive but reflects the model's construction: it measures how extreme current conditions are relative to historical norms, with extremity mapping to fragility.
A score above 0.50 generally indicates normal market conditions where standard investment approaches remain appropriate. Scores between 0.30 and 0.50 represent an elevated zone where caution is warranted but not alarm. Scores below 0.30 enter the extreme territory where historical precedent suggests increased fragility. These thresholds are not magical boundaries but represent statistical rarity: a score below 0.30 indicates conditions that occur in roughly the bottom quintile of historical observations.
For retail traders, a score in the normal range means continuing with established strategies without modification. In the elevated range, this might mean pausing new position additions while maintaining existing holdings. In the extreme range, retail traders should consider whether their portfolio could withstand a significant drawdown and whether their time horizon permits waiting for recovery. For professional traders, the score integrates into broader risk frameworks: normal conditions permit full risk budgets, elevated conditions might trigger reduced position sizing or tighter stop losses, and extreme conditions could warrant defensive positioning or increased hedging activity.
Reading the states
The model classifies conditions into three discrete states: Normal, Elevated, and Extreme. These states differ from the continuous score by incorporating persistence and transition resistance. A market can have a score temporarily dipping below 0.30 without triggering an Extreme state if the condition proves transient.
The Normal state indicates business as usual. Market conditions fall within historical norms across all measured dimensions. For retail traders, this means standard portfolio management applies. For professional traders, full strategy deployment remains appropriate with normal risk parameters.
The Elevated state signals heightened attention. At least one dimension of market behavior has moved outside normal ranges, though not to extreme levels. Retail traders should review portfolio concentration and ensure diversification remains intact. Professional traders might reduce leverage slightly, tighten risk limits, or increase monitoring frequency.
The Extreme state represents statistically rare conditions. Multiple dimensions show readings that historically occur infrequently. Retail traders should seriously evaluate whether they can tolerate potential drawdowns and consider reducing exposure to volatile assets. Professional traders should implement defensive protocols, potentially reducing gross exposure, increasing cash allocations, or adding protective positions.
Interpreting transitions
State transitions carry more information than states themselves. The model tracks whether conditions are entering, persisting in, or exiting particular states.
An Entry into Extreme represents the most important signal. It indicates a regime shift from normal or elevated conditions into territory associated with historical fragility. For retail traders, this warrants immediate portfolio review. For professional traders, this typically triggers predefined defensive protocols.
Persistence in a state indicates stability. Whether Normal or Extreme, persistence suggests the current regime has become established. For retail traders, persistence in Extreme over extended periods actually reduces immediate concern; the dangerous moment was the entry, not the continuation. For professional traders, persistent Extreme states require maintained vigilance but do not necessarily demand additional action beyond what the initial entry triggered.
An Exit from Extreme suggests improving conditions. For retail traders, this might warrant cautious return to normal positioning over time. For professional traders, exits permit gradual normalization of risk budgets, though institutional memory typically counsels slower reentry than the mathematical signal might suggest.
Duration and its meaning
The model distinguishes between Tactical, Accelerating, and Structural durations in critical zones.
Tactical duration (10-39 bars in critical territory) represents short-term overextension. Many Tactical episodes resolve without significant market disruption. Retail traders should note the condition but need not take dramatic action. Professional traders might implement modest hedges or reduce marginal positions.
Accelerating indicates Tactical duration combined with actively deteriorating scores. This combination historically precedes more significant corrections. Retail traders should consider lightening positions in their most volatile holdings. Professional traders typically implement more substantial hedges.
Structural duration (40+ bars in critical territory) indicates persistent overextension that has become a market feature rather than a temporary condition. Paradoxically, Structural conditions are both more concerning and less immediately actionable than Accelerating conditions. The market has demonstrated ability to sustain extreme readings. Retail traders should maintain heightened awareness but recognize that timing remains impossible. Professional traders often find Structural conditions require strategy adaptation rather than simple defensive positioning.
Confidence and what it tells you
The Confidence reading indicates internal model consistency. High confidence means all four underlying components agree in their assessment. Low confidence means components diverge significantly.
High confidence combined with Extreme state represents the clearest signal. The model is both indicating fragility and agreeing with itself about that assessment. Retail and professional traders alike should treat this combination with maximum seriousness.
Low confidence in any state reduces signal reliability. For retail traders, low confidence suggests waiting for clearer conditions before making significant portfolio changes. For professional traders, low confidence warrants increased skepticism about the score and potentially reduced position sizing in either direction.
Alignment and model health
The Alignment indicator monitors whether the model's calibration remains valid relative to recent market behavior.
Good alignment means recent score distributions match longer-term historical patterns. The model's percentile rankings remain meaningful. Both retail and professional traders can interpret scores at face value.
Degraded alignment indicates that recent market behavior has shifted somewhat from historical norms. Scores remain interpretable but with reduced precision. Retail traders should apply wider uncertainty bands to their interpretation. Professional traders might reduce position sizing slightly or require additional confirmation before acting.
Poor alignment signals significant distribution shift. The model may be comparing current conditions to an increasingly irrelevant historical baseline. Retail traders should rely more heavily on other information sources during Poor alignment periods. Professional traders typically reduce model weight in their decision frameworks until alignment recovers.
Volatility regime context
The volatility regime provides essential context for score interpretation.
Low volatility combined with Extreme state creates maximum concern. Research consistently shows that low-volatility environments can precede significant market dislocations. The market's apparent calm masks underlying fragility. Retail traders should recognize that low volatility does not mean low risk; it often means compressed risk premiums that will eventually normalize, potentially violently. Professional traders typically maintain or increase defensive positioning despite the market's calm appearance.
High volatility combined with Extreme state is actually less immediately concerning than low volatility. The market has already acknowledged stress; risk premiums have expanded; potential sellers may have already sold. Retail traders should resist the urge to panic sell during high-volatility extremes, as much of the adjustment may have already occurred. Professional traders recognize that high-volatility extremes often represent better entry points than low-volatility extremes.
Normal volatility requires no regime adjustment to interpretation. Scores mean what they appear to mean.
Cross-asset analysis
When enabled, the model calculates scores for multiple asset classes simultaneously, enabling systemic versus idiosyncratic risk assessment.
Systemic risk (multiple assets in Extreme with high correlation) indicates market-wide fragility. Diversification benefits are reduced precisely when most needed. Retail traders should recognize that their portfolio's apparent diversification may not protect them during systemic events. Professional traders implement cross-asset hedges and consider tail-risk protection.
Broad risk (multiple assets in Extreme with low correlation) suggests widespread but potentially unrelated overextension. Diversification may still provide some protection. Retail traders can take modest comfort in genuine diversification. Professional traders analyze which assets might offer relative value.
Isolated risk (single asset in Extreme while others remain Normal) indicates asset-specific rather than market-wide conditions. Retail traders holding the affected asset should evaluate their position specifically. Professional traders may find relative value opportunities going long unaffected assets against the extended one.
Scattered risk represents a few assets showing elevation without clear pattern. This typically warrants monitoring rather than action for both retail and professional traders.
Parameter guidance
The Short Percentile parameter (default 504 bars, approximately two years) controls the shorter normalization window. Increasing this value makes the model more conservative, requiring more extreme readings to flag concern. Retail traders should generally leave this at default. Professional traders might increase it for assets with shorter reliable history.
The Long Percentile parameter (default 1260 bars, approximately five years) controls the longer normalization window. This provides regime stability. Again, default settings suit most applications.
The Critical Threshold (default 0.30) determines where the Extreme state boundary lies. Lowering this value makes the model less sensitive, flagging fewer Extreme conditions. Raising it increases sensitivity. Retail traders seeking fewer false alarms might lower this to 0.25. Professional traders seeking earlier warning might raise it to 0.35.
The Structural Duration parameter (default 40 bars) determines when Tactical conditions become Structural. Shorter values provide earlier Structural classification. Longer values require more persistence before reclassification.
The State Maturity and Transition Resistance parameters control how readily the model changes states. Higher values create more stable states with fewer transitions. Lower values create more responsive but potentially noisier state changes. Default settings balance responsiveness against stability.
The Adaptive Smoothing parameters control how the model filters noise. In extreme zones, longer smoothing periods reduce whipsaws but increase lag. In normal zones, shorter periods maintain responsiveness. Most traders should leave these at defaults.
What the model cannot do
The model cannot predict when overextended conditions will resolve. Markets can remain irrational longer than any trader can remain solvent, as the saying goes. Extended Extreme readings may persist for months or even years before any correction materializes.
The model cannot distinguish between healthy bull markets and dangerous bubbles in their early stages. Both initially appear as strong returns and positive momentum. The model begins flagging concern only when statistical extremity develops, which may occur well into an advance.
The model cannot account for fundamental changes in market structure. If a new paradigm genuinely justifies higher valuations (rare but not impossible), the model will continue flagging extremity against historical norms that may no longer apply. The Alignment indicator provides partial protection against this failure mode but cannot eliminate it.
The model cannot replace judgment. It provides systematic measurement of conditions that have historically preceded fragility. Whether and how to act on that measurement remains entirely the trader's responsibility. Retail traders must still evaluate their personal circumstances, time horizons, and risk tolerance. Professional traders must still integrate model output with fundamental analysis, portfolio constraints, and client mandates.
References
Andrews, D.W.K. (1993). Tests for Parameter Instability and Structural Change with Unknown Change Point. Econometrica, 61(4).
Brunnermeier, M.K., & Pedersen, L.H. (2009). Market Liquidity and Funding Liquidity. Review of Financial Studies, 22(6).
Campbell, J.Y., & Shiller, R.J. (1988). Stock Prices, Earnings, and Expected Dividends. Journal of Finance, 43(3).
Dietterich, T.G. (2000). Ensemble Methods in Machine Learning. Multiple Classifier Systems.
Dixit, A. (1989). Entry and Exit Decisions under Uncertainty. Journal of Political Economy, 97(3).
Engle, R.F. (1982). Autoregressive Conditional Heteroscedasticity with Estimates of the Variance of United Kingdom Inflation. Econometrica, 50(4).
Fama, E.F., & French, K.R. (1992). The Cross-Section of Expected Stock Returns. Journal of Finance, 47(2).
Hamilton, J.D. (1989). A New Approach to the Economic Analysis of Nonstationary Time Series and the Business Cycle. Econometrica, 57(2).
Jegadeesh, N., & Titman, S. (1993). Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency. Journal of Finance, 48(1).
Kindleberger, C.P. (1978). Manias, Panics, and Crashes: A History of Financial Crises. Basic Books.
Lo, A.W., & MacKinlay, A.C. (1990). Data-Snooping Biases in Tests of Financial Asset Pricing Models. Review of Financial Studies, 3(3).
Longin, F., & Solnik, B. (2001). Extreme Correlation of International Equity Markets. Journal of Finance, 56(2).
Rabiner, L.R. (1989). A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition. Proceedings of the IEEE, 77(2).
Shiller, R.J. (2000). Irrational Exuberance. Princeton University Press.
Taleb, N.N. (2007). The Black Swan: The Impact of the Highly Improbable. Random House.
Taleb, N.N., & Douady, R. (2012). Mathematical Definition, Mapping, and Detection of (Anti)Fragility. Quantitative Finance, 13(11).
ポートフォリオ管理
A Perfectly Simple Risk CalculatorA Perfectly Simple Risk Calculator
I use bad risk.
I learned my lesson.
This tool will tell me how many contracts to use according to my risk amount.
Thank you Grok for writing me this code.
Sigmoid Risk AllocatorThe Sigmoid Risk Allocator is a dynamic position sizing indicator that tells you how much of your capital to allocate based on current market conditions. Unlike simple "risk-on/risk-off" signals, this indicator gives you smooth, gradual transitions based on a sigmoid function.
Why a Sigmoid Curve?
Most position sizing approaches use fixed thresholds: "If drawdown > 20%, buy. Otherwise, don't." This creates all-or-nothing decisions.
Using the sigmoid (S-curve) makes this decision different. It creates a smooth transition where:
Small drawdowns → Stay near your baseline allocation
Moderate drawdowns → Gradually increase exposure
Large drawdowns → Approach maximum allocation
The sigmoid curve naturally "saturates" at the extremes, preventing you from going all-in too early or panicking out too fast. This is very useful to meek traders psychology and risk management in check.
What's a Sigmoid Function?
The sigmoid function is a mathematical S-curve defined as:
σ(x) = 1 / (1 + e^(-x))
This formula takes any input value and smoothly maps it to a number between 0 and 1. The curve has three key properties that make it ideal for position sizing in investing:
Smooth transitions: No sudden jumps. Allocation changes gradually.
Saturation at extremes: The curve flattens near 0 and 1, preventing overreaction and overexposure.
Sensitive in the middle: Most of the action happens around the midpoint.
To convert this into an allocation percentage, the indicator uses:
Allocation = α_min + (α_max - α_min) × σ(k × (Risk - Midpoint))
Where:
- `α_min` = Your minimum allocation (default 50%)
- `α_max` = Your maximum allocation (default 100%)
- `Risk` = Current risk metric (drawdown %, volatility, or Kelly %)
- `Midpoint` = The risk level where allocation sits halfway between min and max (default 15%)
- `k` = Steepness—how quickly allocation changes around the midpoint
Example : With defaults, if drawdown hits 15% (the midpoint), your allocation will be 75% (halfway between 50% and 100%). As the drawdown increases beyond 15%, the allocation curves toward 100%. As it decreases toward 0%, allocation curves toward 50%.
Cool, isn't it?
Asymmetric Response: Fast In, Slow Out
The indicator uses different steepness values for scaling in vs. scaling out. This is great to increase trend following. This is something I'm proud of too in this indicator.
k_increase = 30 (steep curve): When drawdowns appear, allocation ramps up quickly to catch the opportunity
k_decrease = 5 (slower curve): When conditions normalize, allocation decreases slowly to avoid selling the rebound
This asymmetry reflects how markets behave—drawdowns often overshoot fundamentals (rewarding quick entries), while recoveries tend to be more orderly (rewarding patience on exits).
Three Risk Metrics
You can choose what drives your allocation:
Drawdown (Default)
Volatility - Scales your position inversely to current market volatility.
Kelly Criterion - Automatically calculates optimal position size. The indicator applies a conservative "half Kelly" by default.
Use Cases
Position sizing for swing trading or trend following
Risk management overlay for any existing strategy
Drawdown-based DCA (dollar cost averaging) decisions
Volatility-adjusted exposure management
Feel free to provide feedback and share your thoughts!
- Henrique Centieiro
SILVER (XAGUSD) Targets📌 AG Target – XAU-Based Silver Target Levels
AG Target is a ratio-based indicator designed to analyze Silver (XAGUSD) using the price of Gold (XAUUSD) as a reference.
The indicator projects dynamic target, support, and resistance levels on the silver chart by dividing the Gold price by historically significant XAU/XAG ratios.
🔍 How It Works
Retrieves XAUUSD (Gold spot price)
Divides it by predefined XAU/XAG ratio levels
Plots the resulting values directly on the XAGUSD chart
Fixed ratio levels used:
44.260
39.628
31.707
These ratios represent historically important zones in the Gold–Silver ratio.
🎨 Visual Logic
Green line → XAG price is above the level
Red line → XAG price is below the level
Line thickness increases with level importance
🚨 Alert System
The indicator includes individual alerts and one combined alert:
Separate alerts for each ratio level crossover
A single combined alert triggers when XAG price crosses any of the target levels
Alerts are triggered only on real cross events, avoiding repeated signals.
🏷️ Label Features
Automatic target labels on the last bar
Toggle labels on/off
Adjustable transparency, size, and horizontal offset
Labels display:
Current target price
Corresponding XAU/XAG ratio
🎯 Who Is This For?
Traders using the Gold–Silver ratio
Macro and ratio-based analysts
Medium to long-term silver traders
Users who prefer clean, objective price levels on their charts
⚠️ Disclaimer
This indicator is not financial advice.
It is designed as a ratio-based reference tool and should be used together with other technical or fundamental analysis methods.
AurumAurum is a clean, institutional-grade system designed to capture high-probability momentum bursts. It filters noise using a multi-timeframe approach and visualizes volatility with a unique "Framed" Bollinger Cloud (150-200 deviation).
💎 Strategy Mechanics
Trend & Momentum: Trades are taken only when the fast 10/50 EMA Cross aligns with the macro 800 EMA (Red/White bias).
Volatility Cloud: A custom shaded zone highlights the outer limits of price action, helping identify overextended moves.
Mechanical Exits: The strategy automatically closes 100% of the position at 1:1 Risk/Reward (TP1) to lock in gains efficiently.
📊 Dynamic HUD & Visuals
Live Trade Flags: Entry, SL, and TP lines are dotted and anchored to the current candle, featuring solid-background labels (Yellow, Red, White) for instant readability.
Visual Runners: Projects TP2 (1.5R) and TP3 (2.0R) levels on the chart as visual guides for manual management.
Key Levels: Auto-plots yesterday's High/Low and the 200 BB Basis (Yellow) for immediate support/resistance context.
Customization: Includes a built-in "No-Trade Zone" time filter and toggles for every visual element.
Disclaimer: For educational purposes only. Trade responsibly.
3-Daumen-Regel mit 4 Daumen, YTD-Linie, SMA200 und ATR
The script calculates the following values and displays them in a table:
- YTD line
- SMA
- ATR and ATR
- Difference to YTD
- Difference to SMA200
The table also includes a four-point rating for:
- the first 5 trading days of the year
- price relative to SMA
- price relative to YTD line
- the first month of the trading year
Universe_PRMP (Universe_Professional Risk Management Panel)Description
Universe_PRMP (Universe_Professional Risk Management Panel)
This comprehensive tool is designed to bring institutional-grade risk discipline to retail traders. Managing risk is the most critical part of trading, especially in high-leverage environments. This script automates the complex calculations of position sizing and profit/loss projection.
How to Use:
Initial Setup: When you add the script to your chart, it will prompt you to select two price levels. The first click sets your Stop Loss (SL) and the second sets your Take Profit (TP).
Account Configuration: Open the script settings (the gear icon) to input your Account Balance and the Percentage of Risk you are willing to take per trade (standard is 1% or 2%).
Market Conditions: Enter your broker's current Spread in pips to ensure the lot size calculation accounts for the cost of entry.
Active Monitoring:
Suggested Lot: The dashboard will immediately show the exact lot size you should enter in your trading platform.
Real-Time Projection: As price moves, the dashboard tracks whether your trade is active, hit the target, or stopped out.
Visual Labels: Red (SL) and Green (TP) labels on the chart provide clear visual cues for your exit points.
Key Features:
Dynamic Position Sizing: Automatically adjusts lot size based on the distance between entry and SL.
Spread Integration: Protects your capital by including transaction costs in the risk calculation.
Ticker Sensitivity: The panel recognizes symbol changes to prevent calculation errors across different pairs.
Visual Status Indicators: Color-coded status alerts to keep you emotionally detached and strategically focused.
DISCLAIMER:
This script is an educational and utility tool designed for risk calculation purposes only. It does not provide trading signals or investment advice. Past performance is not indicative of future results. Use this tool at your own risk.
AI Adaptive Trend Navigator Strategy Echo EditionAI Adaptive Trend Navigator Strategy
This is a professional long-only automated strategy optimized for Taiwan Index Futures (TX). Based on the LuxAlgo clustering framework, this version features advanced logic iteration for institutional-grade backtesting and execution.
1. Realistic Cost Modeling To ensure backtest reliability, this strategy is pre-configured with:
Slippage: 2 ticks (Approx. 400 TWD per side).
Commission: 100 TWD per side.
Total Cost: 500 TWD per side. This provides a rigorous stress test for real-world trading environments.
2. State Consistency & Logic Continuity Optimized the underlying array handling to ensure "State Persistence." This eliminates the logic gaps common in real-time script execution, ensuring that historical signals are 100% consistent with live alerts.
3. Adaptive AI Clustering Utilizes K-means clustering to dynamically select the optimal ATR factors based on current market volatility, allowing the strategy to "evolve" as market regimes shift.
🧠 開發理念:追求實戰一致性的量化策略 本策略旨在為台指期(TX)提供一套具備真實參考價值的自動化系統。
✨ Echo 版核心優化點
數據連續性迭代:修正底層邏輯,確保訊號在即時盤勢中穩定不跳斷。
真實交易成本模擬:預設 2 點滑價 與 單邊 100 TWD 手續費,單邊總成本對標 500 TWD,拒絕虛假神單,挑戰最嚴苛的回測環境。
台指期專屬參數調校:融入針對台灣市場波動特性的預設參數與過濾邏輯。
🛡️ 進階實戰過濾
空間緩衝區 (Buffer Strategy):價格需有效突破緩衝區才觸發,精準過濾盤整雜訊。
AI 信心評分系統:只有當動能穩定度達標時才會發進場訊號。
冷卻保護機制:有效抑制訊號在洗盤區間過度頻繁跳動。
⚠️ Disclaimer: Backtest results do not guarantee future performance.
Sharpe Ratio [Alpha Extract]A sophisticated risk-adjusted return measurement system that calculates annualized Sharpe Ratio with dynamic color-coded visualization distinguishing return quality across positive and negative performance regimes. Utilizing rolling period calculations with smoothed moving average comparison, this indicator delivers institutional-grade performance assessment with overbought/oversold threshold detection for extreme risk-adjusted return conditions. The system's four-tier color classification combined with histogram fills and background highlighting provides comprehensive visual feedback on whether current returns justify their volatility risk across varying market cycles.
🔶 Advanced Sharpe Ratio Calculation Engine
Implements classic Sharpe Ratio methodology measuring mean daily return divided by return standard deviation with annualization factor for consistent interpretation. The system calculates daily percentage returns, computes rolling mean and standard deviation over configurable periods, applies square root of 365 scaling for annualized comparison, and generates unbounded ratio values where higher positive readings indicate superior risk-adjusted performance.
// Core Sharpe Ratio Framework
Daily_Return = close / close - 1
Mean_Return = ta.sma(Daily_Return, Period)
StdDev_Return = ta.stdev(Daily_Return, Period)
Sharpe_Ratio = (Mean_Return / StdDev_Return) * sqrt(365)
🔶 Dynamic Four-Tier Color Classification
Features sophisticated color logic distinguishing between strong positive returns (green), weakening positive returns (yellow), weakening negative returns (orange), and strong negative returns (red) based on relationship to smoothed average. The system compares current Sharpe against SMA-smoothed baseline, applying green when positive and accelerating, yellow when positive but decelerating, orange when negative but improving, and red when negative and deteriorating for nuanced regime assessment.
🔶 Smoothed Baseline Comparison Framework
Implements SMA smoothing of Sharpe Ratio with configurable period to establish momentum reference line for trend determination within risk-adjusted returns. The system calculates simple moving average of raw Sharpe values, uses this smoothed line as directional benchmark, and determines whether current risk-adjusted performance is strengthening or weakening relative to recent average for color classification logic.
🔶 Extreme Threshold Detection System
Provides overbought and oversold level identification with configurable upper and lower bounds marking exceptional risk-adjusted return extremes. The system defaults to +4.3 for overbought threshold (extremely favorable risk-return profile) and -2.3 for oversold threshold (severely unfavorable risk-return profile), applying dashed horizontal reference lines and background highlighting when Sharpe breaches these statistical extremes requiring attention.
🔶 Histogram Fill Visualization Architecture
Creates gradient-filled histogram between Sharpe Ratio line and zero baseline using dynamic color matching with 30% transparency for intuitive positive/negative return distinction. The system fills area above zero with bullish colors (green/yellow) and below zero with bearish colors (orange/red), providing immediate visual confirmation of whether returns are compensating for volatility risk or destroying risk-adjusted value.
🔶 Background Zone Highlighting Framework
Implements subtle background coloring when Sharpe enters extreme overbought or oversold zones, alerting traders to statistically significant risk-adjusted return conditions. The system applies semi-transparent red background when ratio exceeds +4.3 (exceptionally strong risk-adjusted returns potentially unsustainable) and green background when below -2.3 (severely poor risk-adjusted returns potentially reversionary), creating visual alerts without obscuring price action.
🔶 Annualization Methodology Integration
Utilizes standard square root of time scaling (sqrt(365)) to convert rolling period Sharpe calculations into annualized format for cross-temporal comparison. The system applies this mathematical transformation ensuring Sharpe values represent expected annual risk-adjusted returns regardless of calculation period length, enabling consistent interpretation whether using 100-day or 200-day rolling windows.
🔶 Zero-Line Reference System
Provides critical zero-line plot serving as boundary between positive risk-adjusted returns (capital allocation justified by return/risk profile) and negative risk-adjusted returns (strategy destroying value on risk-adjusted basis). The system emphasizes this threshold as decision point where values above zero suggest continuation while values below zero indicate reconsideration of exposure.
🔶 Momentum-Based Color
Transitions Implements intelligent color switching logic that considers both absolute Sharpe value and its momentum relative to smoothed average, creating four distinct regimes for granular performance assessment. The system enables identification of bullish acceleration (green), bullish deceleration (yellow), bearish improvement (orange), and bearish acceleration (red) for nuanced position management beyond simple positive/negative classification.
🔶 Configurable Period Optimization
Features adjustable calculation period and smoothing length enabling optimization across different trading timeframes and volatility regimes. The system defaults to 150-period calculation (approximately 6-7 months of daily data) with 30-period smoothing, but allows customization from short-term tactical assessment to long-term strategic evaluation based on investment horizon and strategy requirements.
🔶 Performance Optimization Framework
Employs efficient rolling calculations with streamlined daily return processing and optimized standard deviation computation for smooth real-time updates. The system includes minimal computational overhead through single-pass mean and variance calculations, enabling consistent performance across extended historical periods while maintaining accuracy of risk-adjusted return measurements.
This indicator delivers sophisticated risk-adjusted return analysis through classic Sharpe Ratio methodology with enhanced visual classification distinguishing return quality and momentum. Unlike simple return-focused indicators, Sharpe Ratio penalizes volatility ensuring traders evaluate whether returns justify the risk undertaken. The system's four-tier color coding, smoothed baseline comparison, and extreme threshold detection make it essential for portfolio managers and systematic traders seeking objective performance assessment beyond raw price gains. High positive Sharpe values indicate efficient return generation relative to volatility risk, while negative values signal value destruction on risk-adjusted basis requiring strategy reassessment. The indicator excels at identifying periods when risk-taking is rewarded (green zones) versus periods when volatility exceeds returns (red zones) across cryptocurrency, forex, and equity markets for optimal capital allocation decisions.
Position Size FTWhy you should use this indicator:
It gives you the exact position size in seconds, based on your equity, your risk %, and your real stop location, so you don’t guess.
It keeps your risk consistent even when the stop is wider or tighter, so one “normal” trade can’t become a big loss.
It blocks stupid mistakes like reusing the last size, moving the stop, or oversizing when you feel confident.
It makes drawdown control automatic: drop from 1% to 0.5% or 0.25% and the tool enforces it without you negotiating with yourself.
This tool is your “no excuses” position sizer.
You tell it your account size and how much you’re willing to lose on one trade. Then, for every chart, it calculates the position size that matches your stop distance. So your risk stays the same even when the stop is wide or tight.
If you use it on every chart, you stop doing the two things that destroy accounts: guessing size and oversizing.
Account Equity ($)
Set this to your current account value. Update it at least once a week, or after a big win or loss. If this number is wrong, every size it prints will be wrong.
Risk per Trade (%)
This is the percent you are willing to lose if the stop gets hit.
My recommendation if you trade my system
0.25% if you’re new, or if you’re not consistent yet. This keeps you alive while you learn.
0.5% as your normal size when you’re trading well.
1% only when your account is at an all time high and the market is clean.
0.25% when you are in a drawdown (especially if you are down more than 10%) and the market feels messy.
Max Position Size (%)
This is a safety cap. Even if the math says you can take a huge position, the tool will limit it.
I recommend 25%.
It stops you from loading too much into one trade, especially on tight stops where position size can explode.
LOD/HOD Lookback Bars
This tells the tool which low or high to use for the stop reference.
Use 1 if you are using the current day Low of Day or High of Day.
Use 2 if you are using the previous day Low of Day or High of Day.
If you switch between those two in your strategy, you should switch this setting to match the setup. Otherwise the sizing will be off.
Table Position, Text Size, Text Color
This is just display.
Pick a corner that doesn’t block your chart.
Keep Text Size on Normal.
Use black text if your chart background is light, and white text if your background is dark.
My clean default setup
Account Equity = your real number
Risk per Trade = 0.5%
Max Position Size = 25%
Lookback Bars = 1 most of the time, 2 when the setup calls for previous day levels
Table Position = anywhere you like, keep it out of the way
The simple rule
If the tool is on the chart, sizing becomes automatic. If sizing is automatic, discipline gets easier. And if discipline gets easier, you stop donating money to the market.
Relative Strength Scatter PlotThis is a modication to the indicator ably coded by LOAMEX but with some minor modifications and uses Australian Stock Exchange indices instead of US. This makes it easier for those to use in other countries becasue it has the template for adding indices and the benchmark.
Refer to the LOAMEX indicator for information or the text in this open source pinescript.
The plot shows the relative strength of various indices to a benchmark index, in this case, the ASX XJO200. Indices or sectors located close to the top right hand quadrant are showing the best out performance and thus make up the best source to create your watchlist.
Similarly, you can put stocks in your portfolio into the indicator and see which ones are closest to the upper right of the plot. Those residing in the bottom left quadrant need to be pruned from your portfolio or watched more carefully with closer stop losses.
Titan V40.0 Optimal Portfolio ManagerTitan V40.0 Optimal Portfolio Manager
This script serves as a complete portfolio management ecosystem designed to professionalize your entire investment process. It is built to replace emotional guesswork with a structured, mathematically driven workflow that guides you from discovering broad market trends to calculating the exact dollar amount you should allocate to each asset. Whether you are managing a crypto portfolio, a stock watchlist, or a diversified mix of assets, Titan V40.0 acts as your personal "Portfolio Architect," helping you build a scientifically weighted portfolio that adapts dynamically to market conditions.
How the 4-Step Workflow Operates
The system is organized into four distinct operational modes that you cycle through as you analyze the market. You simply change the "Active Workflow Step" in the settings to progress through the analysis.
You begin with the Macro Scout, which is designed to show you where capital is flowing in the broader economy. This mode scans 15 major sectors—ranging from Technology and Energy to Gold and Crypto—and ranks them by relative strength. This high-level view allows you to instantly identify which sectors are leading the market and which are lagging, ensuring you are always fishing in the right pond.
Once you have identified a leading sector, you move to the Deep Dive mode. This tool allows you to select a specific target sector, such as Semiconductors or Precious Metals, and instantly scans a pre-loaded internal library of the top 20 assets within that industry. It ranks these assets based on performance and safety, allowing you to quickly cherry-pick the top three to five winners that are outperforming their peers.
After identifying your potential winners, you proceed to the Favorites Monitor. This step allows you to build a focused "bench" of your top candidates. by inputting your chosen winners from the Deep Dive into the Favorites slots in the settings, you create a dedicated watchlist. This separates the signal from the noise, letting you monitor the Buy, Hold, or Sell status of your specific targets in real-time without the distraction of the rest of the market.
The final and most powerful phase is Reallocation. This is where the script functions as a true Portfolio Architect. In this step, you input your current portfolio holdings alongside your new favorites. The script treats this combined list as a single "unified pool" of candidates, scoring every asset purely on its current merit regardless of whether you already own it or not. It then generates a clear Action Plan. If an asset has a strong trend and a high score, it issues a BUY or ADD signal with a specific target dollar amount based on your total equity. If an asset is stable but not a screaming buy, it issues a MAINTAIN signal to hold your position. If a trend has broken, it issues an EXIT signal, advising you to cut the position to zero to protect capital.
Smart Logic Under the Hood
What makes Titan V40.0 unique is its "Regime Awareness." The system automatically detects if the broad market is in a Risk-On (Bull) or Risk-Off (Bear) state using a global proxy like SPY or BTC. In a Risk-On regime, the system is aggressive, allowing capital to be fully deployed into high-performing assets. In a Risk-Off regime, the system automatically forces a "Cash Drag," mathematically reducing allocation targets to keep a larger portion of your portfolio in cash for safety.
Furthermore, the scoring engine uses Risk-Adjusted math. It does not simply chase high returns; it actively penalizes volatility. A stock that is rising steadily will be ranked higher than a stock that is wildly erratic, even if their total returns are similar. This ensures that your "Maintenance" positions—assets you hold that are doing okay but not spectacular—still receive a proper allocation target, preventing you from being forced to sell good assets prematurely while ensuring you are effectively positioned for the highest probability of return.
Asset Drift ModelThis Asset Drift Model is a statistical tool designed to detect whether an asset exhibits a systematic directional tendency in its historical returns. Unlike traditional momentum indicators that react to price movements, this indicator performs a formal hypothesis test to determine if the observed drift is statistically significant, economically meaningful, and structurally stable across time. The result is a classification that helps traders understand whether historical evidence supports a directional bias in the asset.
The core question the indicator answers is simple: Has this asset shown a reliable tendency to move in one direction over the past three years, and is that tendency strong enough to matter?
What is drift and why does it matter
In financial economics, drift refers to the expected rate of return of an asset over time. The concept originates from the geometric Brownian motion model, which describes asset prices as following a random walk with an added drift component (Black and Scholes, 1973). If drift is zero, price movements are purely random. If drift is positive, the asset tends to appreciate over time. If negative, it tends to depreciate.
The existence of drift has profound implications for trading strategy. Eugene Fama's Efficient Market Hypothesis (Fama, 1970) suggests that in efficient markets, risk-adjusted drift should be minimal because prices already reflect all available information. However, decades of empirical research have documented persistent anomalies. Jegadeesh and Titman (1993) demonstrated that stocks with positive past returns continue to outperform, a phenomenon known as momentum. DeBondt and Thaler (1985) found evidence of long-term mean reversion. These findings suggest that drift is not constant and can vary across assets and time periods.
For practitioners, understanding drift is fundamental. A positive drift implies that long positions have a statistical edge over time. A negative drift suggests short positions may be advantageous. No detectable drift means the asset behaves more like a random walk, where directional strategies have no inherent advantage.
How professionals use drift analysis
Institutional investors and hedge funds have long incorporated drift analysis into their systematic strategies. Quantitative funds typically estimate drift as part of their alpha generation process, using it to tilt portfolios toward assets with favorable expected returns (Grinold and Kahn, 2000).
The challenge lies not in calculating drift but in determining whether observed drift is genuine or merely statistical noise. A naive approach might conclude that any positive average return indicates positive drift. However, financial returns are noisy, and short samples can produce misleading estimates. This is why professional quants rely on formal statistical inference.
The standard approach involves testing the null hypothesis that expected returns equal zero against the alternative that they differ from zero. The test statistic is typically a t-ratio: the sample mean divided by its standard error. However, financial returns often exhibit serial correlation and heteroskedasticity, which invalidate simple standard errors. To address this, practitioners use heteroskedasticity and autocorrelation consistent standard errors, commonly known as HAC or Newey-West standard errors (Newey and West, 1987).
Beyond statistical significance, professional investors also consider economic significance. A statistically significant drift of 0.5 percent annually may not justify trading costs. Conversely, a large drift that fails to reach statistical significance due to high volatility may still inform portfolio construction. The most robust conclusions require both statistical and economic thresholds to be met.
Methodology
The Asset Drift Model implements a rigorous inference framework designed to minimize false positives while detecting genuine drift.
Return calculation
The indicator uses logarithmic returns over non-overlapping 60-day periods. Non-overlapping returns are essential because overlapping returns introduce artificial autocorrelation that biases variance estimates (Richardson and Stock, 1989). Using 60-day horizons rather than daily returns reduces noise and captures medium-term drift relevant for position traders.
The sample window spans 756 trading days, approximately three years of data. This provides 12 independent observations for the full sample and 6 observations per half-sample for structural stability testing.
Statistical inference
The indicator calculates the t-statistic for the null hypothesis that mean returns equal zero. To account for potential residual autocorrelation, it applies a simplified HAC correction with one lag, appropriate for non-overlapping returns where autocorrelation is minimal by construction.
Statistical significance requires the absolute t-statistic to exceed 2.0, corresponding to approximately 95 percent confidence. This threshold follows conventional practice in financial econometrics (Campbell, Lo, and MacKinlay, 1997).
Power analysis
A critical but often overlooked aspect of hypothesis testing is statistical power: the probability of detecting drift when it exists. With small samples, even substantial drift may fail to reach significance due to high standard errors. The indicator calculates the minimum detectable effect at 95 percent confidence and requires observed drift to exceed this threshold. This prevents classifying assets as having no drift when the test simply lacks power to detect it.
Robustness checks
The indicator applies multiple robustness checks before classifying drift as genuine.
First, the sign test examines whether the proportion of positive returns differs significantly from 50 percent. This non-parametric test is robust to distributional assumptions and verifies that the mean is not driven by outliers.
Second, mean-median agreement ensures that the mean and median returns share the same sign. Divergence indicates skewness that could distort inference.
Third, structural stability splits the sample into two halves and requires consistent signs of both means and t-statistics across sub-periods. This addresses the concern that drift may be an artifact of a specific regime rather than a persistent characteristic (Andrews, 1993).
Fourth, the variance ratio test detects mean-reverting behavior. Lo and MacKinlay (1988) showed that if returns follow a random walk, the variance of multi-period returns should scale linearly with the horizon. A variance ratio significantly below one indicates mean reversion, which contradicts persistent drift. The indicator blocks drift classification when significant mean reversion is detected.
Classification system
Based on these tests, the indicator classifies assets into three categories.
Strong evidence indicates that all criteria are met: statistical significance, economic significance (at least 3 percent annualized drift), adequate power, and all robustness checks pass. This classification suggests the asset has exhibited reliable directional tendency that is both statistically robust and economically meaningful.
Weak evidence indicates statistical significance without economic significance. The drift is detectable but small, typically below 3 percent annually. Such assets may still have directional tendency but the magnitude may not justify concentrated positioning.
No evidence indicates insufficient statistical support for drift. This does not prove the asset is driftless; it means the available data cannot distinguish drift from random variation. The indicator provides the specific reason for rejection, such as failed power analysis, inconsistent sub-samples, or detected mean reversion.
Dashboard explanation
The dashboard displays all relevant statistics for transparency.
Classification shows the current drift assessment: Positive Drift, Negative Drift, Positive (weak), Negative (weak), or No Drift.
Evidence indicates the strength of evidence: Strong, Weak, or None, with the specific reason for rejection if applicable.
Inference shows whether the sample is sufficient for analysis. Blocked indicates fewer than 10 observations. Heuristic indicates 10 to 19 observations, where asymptotic approximations are less reliable. Allowed indicates 20 or more observations with reliable inference.
The t-statistics for full sample and both half-samples show the test statistics and sample sizes. Double asterisks denote significance at the 5 percent level.
Power displays OK if observed drift exceeds the minimum detectable effect, or shows the MDE threshold if power is insufficient.
Sign Test shows the z-statistic for the proportion test. An asterisk indicates significance at 10 percent.
Mean equals Median indicates agreement between central tendency measures.
Struct(m) shows structural stability of means across half-samples, including the standardized level deviation.
Struct(t) shows whether t-statistics have consistent signs across half-samples.
VR Test shows the variance ratio and its z-statistic. An asterisk indicates the ratio differs significantly from one.
Econ. Sig. indicates whether drift exceeds the 3 percent annual threshold.
Drift (ann.) shows the annualized drift estimate.
Regime indicates whether the asset exhibits mean-reverting behavior based on the variance ratio test.
Practical applications for traders
For discretionary traders, the indicator provides a quantitative foundation for directional bias decisions. Rather than relying on intuition or simple price trends, traders can assess whether historical evidence supports their directional thesis.
For systematic traders, the indicator can serve as a regime filter. Trend-following strategies may perform better on assets with detectable positive drift, while mean-reversion strategies may suit assets where drift is absent or the variance ratio indicates mean reversion.
For portfolio construction, drift analysis helps identify assets where long-only exposure has historical justification versus assets requiring more balanced or tactical positioning.
Limitations
This indicator performs retrospective analysis and does not predict future returns. Past drift does not guarantee future drift. Markets evolve, regimes change, and historical patterns may not persist.
The three-year sample window captures medium-term tendencies but may miss shorter regime changes or longer structural shifts. The 60-day return horizon suits position traders but may not reflect intraday or weekly dynamics.
Small samples yield heuristic rather than statistically robust results. The indicator flags such cases but users should interpret them with appropriate caution.
References
Andrews, D.W.K. (1993) Tests for parameter instability and structural change with unknown change point. Econometrica, 61(4).
Black, F. and Scholes, M. (1973) The pricing of options and corporate liabilities. Journal of Political Economy, 81(3).
Campbell, J.Y., Lo, A.W. and MacKinlay, A.C. (1997) The econometrics of financial markets. Princeton: Princeton University Press.
DeBondt, W.F.M. and Thaler, R. (1985) Does the stock market overreact? Journal of Finance, 40(3).
Fama, E.F. (1970) Efficient capital markets: a review of theory and empirical work. Journal of Finance, 25(2).
Grinold, R.C. and Kahn, R.N. (2000) Active portfolio management. 2nd ed. New York: McGraw-Hill.
Jegadeesh, N. and Titman, S. (1993) Returns to buying winners and selling losers. Journal of Finance, 48(1).
Lo, A.W. and MacKinlay, A.C. (1988) Stock market prices do not follow random walks. Review of Financial Studies, 1(1).
Newey, W.K. and West, K.D. (1987) A simple, positive semi-definite, heteroskedasticity and autocorrelation consistent covariance matrix. Econometrica, 55(3).
Richardson, M. and Stock, J.H. (1989) Drawing inferences from statistics based on multiyear asset returns. Journal of Financial Economics, 25(2).
Mission Control Dashboard (AI, Crypto, Liquidity) FASTCONCEPT Price is a lagging indicator. Liquidity is a leading indicator. "Mission Control Dashboard (AI, Crypto, Liquidity) FAST" is a sophisticated macroeconomic dashboard designed to audit the "plumbing" of the financial system in real-time. Unlike standard indicators that rely solely on price action, this tool pulls data from the Federal Reserve (FRED), Treasury Statements, Corporate Financials (10-K/10-Q), and On-Chain Stablecoin metrics to visualize the structural flows driving the market.
THE "UNIFIED FIELD" SOLVER One of the hardest challenges in cross-asset scripting is "Time Dilation"—synchronizing 24/7 Crypto markets (Bitcoin) with Mon-Fri Traditional markets (Stocks/Bonds).
Standard scripts fail on weekends, showing mismatched data.
This engine uses a Weekly Anchor system. It calculates all momentum and liquidity metrics based on "Week-to-Date" or "Month-Ago" anchors. This ensures that a "Liquidity Drain" looks identical whether you are viewing a Bitcoin chart on Saturday or an Apple chart on Monday.
THE CHRONOS LOGIC The dashboard is sorted by Time Sensitivity (Speed of impact), from fast-twitch tactical signals to slow-moving structural fundamentals.
1. TACTICAL (Reacts in 24–48h)
Stablecoin Flight: Measures the immediate flow of capital from Volatile Assets to Stablecoins (USDT/USDC). A spike (>0.5%) indicates fear/sidelining.
Liquidity Alpha: Calculates the efficiency of capital. It subtracts "Friction" (Dollar Strength + Yields) from "Flow" (Liquidity Beta). High Alpha means money is flowing easily into risk assets.
Alt Euphoria: Tracks the overheating of the Altcoin market (TOTAL3). Green indicates sustainable growth; Red (>45%) warns of a "blow-off top."
Retail FOMO: A sentiment gauge comparing Coinbase Stock ( NASDAQ:COIN ) performance vs. Bitcoin ( CRYPTOCAP:BTC ). When Retail outperforms the Asset, local tops often follow.
2. LIQUIDITY & MACRO (Reacts in 1–4 Weeks)
Debt Wall (10Y): The Rate-of-Change of the US 10-Year Treasury Yield. Spiking yields act as gravity on risk assets.
Liquidity Beta: The raw "Quantity of Money." Tracks the 4-week change in Net Liquidity (Fed Balance Sheet - TGA + Stablecoins).
TGA Balance: The Critical Monitor. Tracks the Treasury General Account. When the TGA rises (Red), the government is draining liquidity from the banking system. When it falls (Green), it releases cash.
Note: This script includes an auto-scaler to handle TGA data in both Billions and Millions.
3. STRUCTURAL (Reacts in 3–12 Months)
AI Capex (YoY & QoQ): The "Floor" of the 2025/2026 cycle. Tracks the Capital Expenditure of the Hyperscalers (MSFT, GOOGL, AMZN, META). As long as this remains high (>30%), the infrastructure boom supports the tech narrative.
PMI Manufacturing: Tracks the ISM Manufacturing cycle. Contraction (<50) often forces Fed intervention.
Micron Inventory: A lead indicator for the hardware cycle.
HOW TO USE
Status Colors: The traffic light system helps you assess risk at a glance.
🟢 GREEN (Healthy): Flow is positive, friction is low, fundamentals are strong.
🔴 RED (Danger): Liquidity is draining (TGA spike), yields are shock-rising, or FOMO is excessive.
Zero Configuration: The script auto-detects asset classes and scales units (Billions/Trillions) automatically.
DATA SOURCES
Federal Reserve Economic Data (FRED)
Daily Treasury Statement (DTS)
CryptoCap (TradingView)
Nasdaq/Corporate Financials
Disclaimer: This tool is for informational purposes only and does not constitute financial advice. Macro data feeds are subject to reporting delays.
BTC Fundamental Value Hypothesis [OmegaTools]BTC Fundamental Value Hypothesis is a macro-valuation and regime-detection model designed to contextualize Bitcoin’s price through relative market-cap comparisons against major capital reservoirs: Gold, Silver, the Altcoin market, and large-cap equities. Instead of relying on traditional on-chain metrics or purely technical signals, this tool frames BTC as an asset competing for global liquidity and “store-of-value mindshare”, then estimates an implied fair value based on how BTC historically coexists (or diverges) from these benchmark universes.
Core concept: relative market-cap anchoring
The indicator builds a reference-based fair price by translating external market capitalizations into implied BTC valuation using a dominance framework. In practice, you choose one or more reference universes (Gold, Silver, Altcoins, Stocks). For each selected universe, the script computes how large BTC “should be” relative to that universe (dominance ratio), and converts that into an implied BTC price. The final fair price is the average of the implied prices from the enabled universes.
Two dominance modes: automatic vs manual
1. Automatic Dominance % (default)
When enabled, the model estimates dominance ratios dynamically using a 252-period simple moving average of BTC market cap divided by each reference market cap. This produces an adaptive baseline that follows structural changes over time and reduces sensitivity to short-term spikes.
2. Manual Dominance %
If you prefer a discretionary macro thesis, you can directly input dominance parameters for each reference universe. This is useful when you want to stress-test scenarios (e.g., “BTC should converge toward X% of Gold’s market cap”) or align the model with a specific long-term adoption narrative.
Reference universes and data construction
- BTC market cap: pulled from CRYPTOCAP:BTC.
- Gold and Silver market caps: derived from the corresponding futures symbols (GC1!, SI1!) multiplied by an assumed total above-ground quantity (constant tonnage converted to troy ounces). This provides a practical and tradable proxy for spot valuation context.
- Altcoin market cap: pulled from CRYPTOCAP:TOTAL2 (total crypto market excluding BTC).
- Stocks market cap proxy (Σ3): a deliberately conservative equity benchmark built from three mega-cap stocks (AAPL, MSFT, AMZN) using total shares outstanding (request.financial) multiplied by price. This avoids index licensing complexity while still tracking a meaningful slice of global equity beta/liquidity.
Valuation output: overvalued vs undervalued (log-based)
The valuation readout is expressed as a percentage derived from the logarithmic distance between BTC price and the model’s fair price. This choice makes valuation comparable across long time horizons and reduces distortion during exponential growth phases. A positive valuation indicates BTC trading below the model’s implied value (undervalued), while a negative valuation indicates trading above it (overvalued).
Oscillator: relative momentum and regime confirmation
In addition to fair value, the indicator includes a momentum differential oscillator built from RSI(50):
- BTC RSI is compared to the average RSI of the selected reference universes.
- The oscillator highlights when BTC strength is leading or lagging the broader macro benchmarks.
- Color is rendered through a gradient to provide immediate regime readability (risk-on vs risk-off behavior, expansion vs contraction phases).
Visualization and UI components
- Fair Price overlay: the computed fair price is plotted directly on the BTC chart for immediate comparison with spot price action.
- Valuation shading: the area between price and fair price is filled to visually emphasize dislocation and potential mean-reversion zones.
- Oscillator panel: a zero-centered oscillator with filled bands helps you identify persistent trend regimes versus transitional conditions.
- Summary table: a right-side table displays the current valuation (over/under) and, when Automatic mode is enabled, the live dominance ratios used in the model (BTC/GOLD, BTC/SILVER, BTC/ALTC, BTC/STOCKS).
How to use it (practical workflows)
- Macro valuation context: use fair price as a structural anchor to assess whether BTC is trading at a premium or discount relative to external liquidity baselines.
- Regime filtering: combine valuation with the oscillator to distinguish “cheap but weak” from “cheap and strengthening” (and the inverse for tops).
- Mean-reversion mapping: large, persistent deviations from fair value often highlight speculative extremes or capitulation zones; this can support systematic entries/exits, position sizing, or hedging decisions.
- Scenario analysis: switch to Manual Dominance % to model adoption outcomes, policy-driven shifts, or multi-year re-rating assumptions.
Important notes and limitations (read before use)
- This is a hypothesis-driven macro model, not a literal intrinsic value calculation. Results depend on dominance assumptions, proxies, and data availability.
- Gold/Silver market caps are approximations based on futures pricing and fixed supply constants; real-world supply dynamics, above-ground estimates, and spot/futures basis can differ.
- The Stocks (Σ3) benchmark is a proxy and intentionally not “the whole market”. It is designed to represent a large-cap liquidity reference, not total equity capitalization.
- Always validate signals with additional context (market structure, volatility regime, risk management rules). This indicator is best used as a macro layer in a broader decision framework.
Designed for clarity, macro discipline, and repeatability
BTC Fundamental Value Hypothesis by OmegaTools is built for traders and investors who want a clean, data-driven way to interpret BTC through the lens of competing asset classes and capital flows. It is particularly effective on higher timeframes (Daily/Weekly) where macro relationships are more stable and valuation signals are less noisy.
© OmegaTools, Eros
Time Anchored FX LevelFX-Anchored Price Level
This indicator anchors a historical price at a specific date and time, and optionally links that anchor to a secondary FX rate to create a dynamic, currency-aware price level.
Thus, e.g. one visualize a past BTCEUR price on a BTCUSD chart now.
At the selected timestamp, the script captures the chart price using the chosen timeframe and price source.
If a secondary ticker is provided (for example, an FX rate), the anchored value is fixed in that secondary currency and then converted back to the chart currency on every bar. The result is a moving level that reflects changes in the exchange rate over time.
If no secondary ticker is set, the indicator behaves as a classic time-anchored price level and plots a constant historical price.
Key features
* Anchor a price to an exact date and time (string input with optional hour offset)
* Optional secondary ticker for FX or cross-rate conversion
* Dynamic level plotted as a series (updates like a moving average)
* User-selectable calculation timeframe and price source (Open, Close, etc.)
* Visual anchor marker at the original timestamp
* Last-bar price label for clear readability
Typical use cases
* FX buyback or re-entry levels after converting proceeds into another currency
* Evaluating historical prices in constant-currency terms
* Comparing past executions to current market conditions
* Anchoring risk or valuation levels across time and exchange rates
This tool is designed for traders who need precise, time-anchored reference levels that remain meaningful as currencies and markets evolve.
Reflation Proxy: (QQQ/GSG) vs QQQ (Base-100)This indicator builds a single “reflation impulse” line by standardizing the QQQ/GSG ratio (growth equities vs commodities) and comparing it to QQQ over the same Base-100 lookback window. The result highlights when commodities are catching up to or outperforming growth (reflation/broadening impulse) versus when growth is dominating real assets (disinflation/duration regime). The main line is smoothed with a user-defined EMA and includes three configurable control EMAs (21/50/100 by default). Rising readings generally reflect growth leadership; a rollover into a sustained decline tends to mark reflation pressure building under the surface.
Manual PNL TrackerEnter your USD position size, direction and entry price to track it realtime in the chart without needing to use TV brokers for it.
Sigmoid Allocation Indicator & DashboardTL;DR This sigmoid-based allocation indicator tells you percentage of your portfolio to invest based on how much the market has dropped.
Market at all-time high? → Stay defensive, invest less (e.g., 30%)
Market crashed hard? → Get aggressive, invest more (e.g., 100%)
The "sigmoid" part just means the transition between these two extremes follows a smooth S-shaped curve.
Description
This indicator is a sigmoid-based allocation system that dynamically adjusts a portfolio exposure based on market drawdown.
It compares multiple steepness curves (K values) to find your optimal risk profile for leveraged ETF strategies, but it can also be used to scale in-out from stocks, crypto and to understand whether to use leverage or not.
The Sigmoid Allocation Dashboard helps you to dynamically adjust a portfolio allocation based on how much a market has dropped from its all-time high.
I've implemented it using a sigmoid (S-curve) function, that dynamically calculates the optimal allocation percentages. Depending on the market conditions, the S curves transition between defensive and aggressive allocations.
The Math Behind It (if you are a geek like me)
This indicator uses the sigmoid function to create smooth S-curve transitions:
α(D) = α_min + (α_max - α_min) × σ(k × (D - D_mid))
Where:
σ(x) = 1 / (1 + e^(-x)) ← Standard sigmoid function
You can also check it here:
// Sigmoid function: σ(x) = 1 / (1 + e^(-x))
sigmoid(float x) =>
1.0 / (1.0 + math.exp(-x))
// Alpha calculation: α(D) = α_min + (α_max - α_min) × σ(k × (D - D_mid))
calcAlpha(float drawdown, float k, float a_min, float a_max, float d_midpoint) =>
sig_input = k * (drawdown - d_midpoint) / 100.0
a_min + (a_max - a_min) * sigmoid(sig_input)
User parameters (you can tweak this):
Allocation Min (%): Your baseline allocation when markets are at ATH (default: 30%)
Allocation Max (%): Your maximum allocation during deep drawdowns (default: 100%)
D_mid (%): The drawdown level where you want to be at the midpoint (default: 25%)
Why do I like sigmoid and not a linear line?
Unlike linear models, the sigmoid creates "floors" and "ceilings" for your allocation. It transitions smoothly, no sudden jumps, and you never exceed your defined min/max bounds.
Understand the K Values (Steepness)
The K parameter controls how quickly your allocation shifts from defensive to aggressive.
Lower K (for example K=5) will give you a gradual transition, but at 0% drawdown you are already at a 46% allocation.
A higher like (like K=40) will give you a sharp transition, but at 0% drawdown you are close to the minimum allocation. On the other hand, a higher K will give close to 100% allocation when the markets are at new lows.
The example below illustrates this well, then the S&P 500 reached new lows in October 2022:
Different K values will affect the sigmoid curves (and you allocations differently). The chart below illustrates well how K affects the sigmoid curves:
Read the Dashboard
The main dashboard shows:
Current drawdown from ATH
Allocation % for each K value
Suggested action (Defensive → MAX LONG)
Use the Reference Chart
The static reference panel shows what your allocation would be at various drawdown levels (0%, 10%, 20%, 30%, 40%, 50%), helping you plan ahead.
Identify Zones
The color-coded chart background shows:
- 🟢 Green Zone: Aggressive positioning - "Buy the Dip"
- 🟡 Yellow Zone: Transition zone - Scaling in/out
- 🔴 Red Zone: Defensive positioning - Protect ya gains
Use Cases
Use case 1: Leveraged ETF Portfolio Management (this is my main use case)
When holding leveraged ETFs like TQQQ or UPRO, volatility makes it important to:
- Reduce exposure near all-time highs (when crashes hurt most)
- Increase exposure during drawdowns (when recovery potential is highest)
Example Strategy:
- At ATH: Hold 30% TQQQ, 70% cash/bonds or other uncorrelated assets
- At 25% drawdown: Hold 65% TQQQ, 35% cash/bonds
- At 40%+ drawdown: Hold 100% TQQQ
Use case 2: Diversified Leveraged Portfolio
Compare different K values for different assets:
- Use K = 10 for broad market (QQQ/SPY exposure via TQQQ/UPRO)
- Use K = 25 for sector bets (TECL, SOXL, TMF) that you want to scale into faster
Use case 3: Systematic Rebalancing Signals
Use the alerts to trigger rebalancing:
- Alert when K3 allocation crosses above 90% (time to add)
- Alert when drawdown exceeds your D_mid threshold
- Alert when market returns to within 5% of ATH
Tips for Best Results
It works best in longer time frames
Adjust the ATR lookback window
Match your risk tolerance level
I use this for index investing and stocks and haven't tried with crypto
Thanks for using the indicator and let me know if you have any feedback :)
- Henrique Centieiro
BTC - Standard of Living BenchmarkerOVERVIEW
Most traders track their wealth in USD or EUR — currencies that are structurally designed to lose value. This is a "Money Illusion." To understand if you are truly becoming wealthier, you must measure your Bitcoin not against fiat, but against the Standard of Living assets you eventually want to buy.
The Standard of Living Benchmarker is a macro-ratio engine that swaps the denominator of your chart. It answers the only question that matters for long-term wealth: "Is my Bitcoin stack gaining ground against the real world?"
THE "Stuff" BENCHMARKS
I have pre-selected four critical pillars of a high standard of living (that can be switched/cycled in the settings window):
• Gold: The historical baseline for "Hard Money" (TVC:GOLD).
• Equities: The primary engine of global productivity (S&P 500).
• Real Estate: Measured via the Vanguard Real Estate ETF (VNQ).
• Energy: The fundamental cost of human progress (Crude Oil).
THE CORE CALCULATION
The calculation is a simple, non-manipulated ratio:
• The Formula: Ratio = BTC_Price / Asset_Price
• This means: We are looking at the direct barter-rate between Bitcoin and the asset. For example, when the "Energy" mode is selected, the chart doesn't show dollars; it shows exactly how many Barrels of Oil one single Bitcoin can buy at today's close.
THE LIFESTYLE BASKET (The 5th Denominator)
Individual ratios tell you how Bitcoin is doing against one asset, but life isn't lived in a single asset. To solve this, I introduced the Lifestyle Basket .
What is a "Lifestyle Share"? A synthetic "Life Token" that represents a diversified slice of human prosperity. It is an equal-weighted basket consisting of:
• 25% Gold (Inflation Hedge)
• 25% S&P 500 (Global Growth)
• 25% Real Estate (Shelter)
• 25% Crude Oil (Energy/Consumption)
HOW TO READ THE CHART
• How to interpret the ratio: If the dashboard shows that 1 BTC buys 50 Lifestyle Shares , it means your Bitcoin stack has the purchasing power to acquire 50 equal units of the world's most critical assets.
• The Purchasing Power Line (Orange): When this line moves UP, Bitcoin is outperforming the real world. You are getting "wealthier" in a tangible sense. When it moves DOWN, your Bitcoin is losing purchasing power against that specific asset class.
• The Opportunity Zones: We plot a 200-day Mean with Standard Deviation bands.
• Upper Band (Red): Bitcoin is historically "Expensive" compared to the asset. This has historically been a high-probability zone to swap BTC for "Stuff" (Real Estate, Gold, etc.).
• Lower Band (Green): Bitcoin is "Cheap" compared to the asset. This is the zone where "Stuff" should be sold to acquire more Bitcoin.
WHY THIS IS "FRESH"
Unlike standard indicators that use RSI or MACD to find price momentum, this is a Macro-Audit . It ignores the noise of the US Dollar and focuses on the Ratio of Reality . It allows the "Infinite Hodler" to know when they are overextended in Bitcoin and when it is mathematically time to diversify into hard real-world assets.
DISCLAIMER
This script is for educational and macro-analytical purposes only. It does not constitute financial advice. Benchmarks are proxies for asset classes and may not reflect individual local prices (e.g., local real estate).
Tags: bitcoin, macro, gold, realestate, oil, benchmark, purchasing power, wealth, satoshi, Rob Maths, robmaths, Rob_Maths
Risk Management◼ Turtle Trading Risk Management
This script helps you size your position and manage your risk, using volatility, based on Turtle Trading Strategy.
If volatility is high, size will be smaller, if volatility is low, size will be larger.
It uses N=20 days, daily ATR (customisable), to calculate volatility.
If the account is in drawdown, reduces risk amount as per Turtle Trading rules.
You can display the full table, or a smaller compact table
Calculadora CFDs v1.2 - 2026MT5 Lot & Margin Calculator for CFDs (Multi-Asset)
General Description
This tool is designed for CFD traders using platforms like MetaTrader 5 who need a fast and accurate way to calculate lot size (volume) before entering the market. The calculator solves the issue of varying contract sizes across different assets (Oil, Natural Gas, Gold, Forex, etc.) and precisely calculates the margin withheld by the broker.
Key Features:
Customizable Database: Pre-configure up to 20 different assets with their respective Contract Sizes. Once set, the script automatically detects the chart's ticker and applies the saved parameters.
Note: To find the correct Contract Size, go to MT5, right-click on the asset, select "Specification," and look for the "Contract Size" value.
Exact Margin Management: Calculate exactly how many lots to enter in MT5 based on the specific USD amount you want the broker to set aside as collateral (Margin). This value is fully adjustable in the settings.
Smart Leverage Logic: Includes automated logic for standard 2026 industry leverage levels (1:50 Forex, 1:10 Energies/Metals, 1:15 Cash Indices, 1:2 Crypto), with a manual override option.
High-Contrast Visualization: A clean and professional table interface with adjustable positioning on the chart (Top Right/Left, Bottom Right/Left).
Real-Time Data: All calculations are performed using the live price and data source of the ticker currently displayed on your chart.
Instructions for Use:
In the "Inputs" tab, enter your frequent tickers (e.g., XTIUSD, NAT.GAS) and their contract sizes according to your broker's specifications.
Define the "Margin to Retain" (the amount in USD you wish to use as collateral for the trade).
The indicator will instantly display the MT5 LOT size to enter into your trading terminal.
Use the "Save as Default" option in the settings to ensure your 20 assets remain saved for future sessions.






















