ATR/Tick Based Contract Size CalculatorContract size calculator with custom inputs for ATR based stops with multiplier or hard tick based calculations for stop size.Pine Script®指标由sajoseph11提供8
Position Size Calculator (Jean-Guy)🟢 Overview Most traders fail because they don't account for the "hidden" costs of trading. This indicator is a high-precision risk management tool designed to show you your True Net Result before you even click the "Buy" or "Sell" button. By integrating exchange fees directly into the position sizing logic, this script reveals the gap between your theoretical profit and what actually hits your account. 🚀 Key Features - True Net R/R & P&L: Automatically calculates your Reward/Risk ratio and Profit/Loss by subtracting entry and exit fees. - Dual Risk Management: Choose to risk a fixed dollar amount ($) or a precise percentage (%) of your total bag. - Execution HUD: A clean table in the top-right corner displays Margin Required, Leverage, and Net Outcomes. - Optimized UI: Includes a "Safety Margin" row at the top to prevent TradingView's hover menu from hiding your R/R data. - High-Visibility Visuals: 90% opacity zones for entry/SL/TP to help you align with your market structure. 📊 Advantages & Disadvantages PROS ✅ - Fee Integration: Set your specific exchange fee % (default 0.1%). - Net Reality: Shows you that a $100 risk is actually a $108.1 loss after fees—keeping you disciplined. - Visual Alignment: The fixed box helps you stay focused on your Discount/Premium zones without cluttering the chart . CONS ❌ - Manual Input: Does not sync with TradingView's built-in Long/Short drawing tools. - Static Box: The visual representation remains at the current price area and doesn't scroll with price action. - Initial Setup: Requires entering prices manually once before moving lines via the settings. 🛠️ How to use 1) Configure: Set your Account Balance and Risk level (e.g., $100 or 1%). 2) Input Prices: Enter your Entry, Stop Loss, and Take Profit prices. 3) Check the HUD: Look at the R/R NET (in green). If the net ratio doesn't fit your strategy, skip the trade. 4) Execute: Use the Margin Req. and Leverage data to fill your exchange order form exactly.Pine Script®指标由Jean-Guy29提供3
SentinelIndexOverview The Sentinelindex is a comprehensive risk-assessment tool designed to expose the divergence between market price action and underlying macroeconomic reality. While the S&P 500 might print new highs, the Sentinelindex looks beneath the surface to see if the move is backed by liquidity, economic stability, and institutional conviction. This indicator aggregates three non-correlated pillars of market health into a single, easy-to-read 0-100 normalized score. The Three Pillars of the Sentinel Score Liquidity (M2 Money Supply YoY): Markets run on fuel, and that fuel is money. By tracking the Year-over-Year change in the M2 Money Supply (via FRED data), the indicator penalizes the score when liquidity is contracting or stagnating, signaling a "dry" environment where rallies are harder to sustain. Economic Clock (Yield Curve 10Y-2Y): The 10Y-2Y spread is the most reliable recession predictor in history. However, the real danger isn't just inversion—it's de-inversion. This script specifically monitors the critical phase where the curve returns to positive territory (0 to 1.0), a zone historically associated with market pivots and economic shifts. The Shadow (Insider Sell/Buy Ratio): The ultimate "Smart Money" signal. This component tracks the behavior of corporate insiders (CEOs, CFOs). When those with the most information are selling into a rally at a high ratio, the Sentinel Score spikes, revealing a "Distribution Phase" that retail traders often miss. How to Interpret the Score 0 - 40 (Green): Healthy Accumulation. High liquidity, stable macro, and calm insiders. The trend is likely supported by fundamentals. 40 - 75 (Orange): Tactical Caution. Divergences are forming. Liquidity is tightening or the Yield Curve is shifting. The ice is getting thinner. 75 - 100 (Red): Distribution Alert. Maximum risk. While prices may be high, the "Smart Money Shadow" indicates institutional exiting and macro headwinds. Capital protection becomes the priority. Instructions for Users Manual Input: Due to the proprietary nature of aggregate Insider Trading data, the Insider Sell/Buy Ratio must be updated manually once a week (typically every Monday) in the script settings. We recommend using a 1-week aggregate ratio from reliable sources like OpenInsider. Data Source: This indicator automatically fetches real-time data from the Federal Reserve (FRED). Ensure your TradingView account has access to FRED symbols (default for most users). Best Timeframes: Daily (D) or Weekly (W) for high-level macro analysis.Pine Script®指标由luigiloconsole72提供0
Position Size Calculator (Jean-Guy)Overview Most traders fail because they don't account for the "hidden" costs of trading . This indicator is a high-precision risk management tool designed to show you your True Net Result before you even click the "Buy" or "Sell" button. By integrating exchange fees directly into the position sizing logic, this script reveals the gap between your theoretical profit and what actually hits your account. Key Features • True Net R/R & P&L : Automatically calculates your Reward/Risk ratio and Profit/Loss by subtracting entry and exit fees. • Dual Risk Management : Choose to risk a fixed dollar amount ($) or a precise percentage (%) of your total bag. • Execution HUD : A clean table in the top-right corner displays Margin Required, Leverage, and Net Outcomes. • Optimized UI : Includes a "Safety Margin" row at the top to prevent TradingView's hover menu from hiding your R/R data. • High-Visibility Visuals : 90% opacity zones for entry/SL/TP to help you align with your market structure. Advantages & Disadvantages PROS ✅ • Fee Integration : Set your specific exchange fee % (default 0.1%). • Net Reality : Shows you that a $100 risk is actually a $108.1 loss after fees—keeping you disciplined. • Visual Alignment : The fixed box helps you stay focused on your Discount/Premium zones . CONS ❌ • Manual Input : Does not sync with TradingView's built-in Long/Short drawing tools. • Static Box : The visual representation remains at the current price area and doesn't scroll. • Initial Setup : Requires entering prices manually once before moving lines via settings. How to use Set your account balance and risk level. Enter your Entry, Stop Loss, and Take Profit prices. Check the R/R NET (in green). If it doesn't fit your strategy, skip the trade . Use the Margin Req. and Leverage data to fill your exchange order form exactly. Update V2 : - Added Lots/Units Display: The dashboard now calculates and shows the exact position size in Lots/Units for faster order execution. - Fixed Opacity Bug: Implemented a forced cleanup logic (line.delete) to prevent color stacking. Your zones will now maintain a consistent transparency over time. - New Default Visibility: Set the native opacity to 90 for a cleaner, non-intrusive look that keeps price action visible. - Code Optimization: Improved script stability for the multi-asset backtesting phasePine Script®指标由Jean-Guy29提供2
Sector Divergence DashboardStatistical arbitrage dashboard for markets and sector ETFs This Sector Divergence Dashboard is a tool designed to identify mean-reversion opportunities across U.S. equity sectors. I've built it to help me with portfolio management and sector allocation by identifying uncorrelated sectors and divergences between indices and sector ETFs. These divergences are often good investment opportunities. The indicator also helps you with sector rotation by identifying when sectors have diverged too far from their historical relationships with the broader market. This is a similar methodology used daily in institutional portfolio management and hedge funds. In this dashboard, you can see: Z-Score Analysis on log price ratios to detect statistical anomalies Dual-timeframe correlation tracking to identify relationship breakdowns Composite scoring that combines divergence magnitude, correlation shifts, and momentum Correlation heatmap for instant relationship assessment across all pairs You see exactly which pairs are statistically mispriced and likely to revert to their historical mean. NOTE: This dashboard is computationally heavy and might take up to one minute to load in your TradingView. The Mathematics 1. Price Ratio Z-Score The indicator calculates the logarithmic price ratio between two assets (e.g., SPY/XLE) and measures how many standard deviations this ratio has moved from its historical average. A z-score of +2.0 means the pair is 2 standard deviations expensive relative to history. This can be a mean-reversion setup. 2. Correlation Breakdown Detection Short-term correlation (35 bars) is compared against long-term correlation (100 bars). You can change these parameters BTW. When correlations diverge significantly, it signals that the normal relationship has temporarily broken, potentially creating trading opportunities. 3. Relative Performance Measures the momentum difference between pairs over 300 bars (roughly 60 weeks on daily charts). This captures longer-term structural shifts versus short-term noise. 4. Composite Score All three metrics are normalized and weighted to create a single ranking score: 50% Z-Score Weight - Primary driver of mean reversion probability 25% Correlation Breakdown - Relationship stability metric 25% Relative Performance - Momentum/trend context Features 1. Correlation Heatmap Visualize all pairwise correlations Color-coded from red (negative correlation) to green (strong positive) Spot which sectors are moving together or decoupling 2. Divergence Rankings Table Top 15 SPY-vs-sector pairs ranked by composite opportunity score Z-scores, correlations, performance differentials, and signals Color-coded from gray (neutral) to red (extreme divergence) Scan it daily for setups 3. Deep Dive Chart Detailed z-score visualization for any selected pair Visual zones showing normal range, signal threshold, and strong signal areas Short-term and long-term correlation overlays Real-time information label with current metrics and signal status Perfect for analyzing specific opportunities in depth You can define which symbols you want to deep dive in the parameters Parameter Guide Short-Term Correlation - Recent relationship strength Long-Term Correlation - Historical baseline relationship Z-Score Length - Mean reversion lookback period Relative Performance - Longer-term momentum context Pro Tip : Increase z-score length to 150+ for fewer but stronger signals. Decrease to 50-75 for more frequent opportunities (but more noisy). Use Cases Sector Rotation: Identify which sectors are over/undervalued relative to the market Portfolio Rebalancing: Data-driven signals for tactical asset allocation adjustments Pairs Trading: Statistical arbitrage between correlated instruments Risk Management: Monitor correlation stability across your portfolio Market Regime Detection: Spot when sector relationships are breaking down Swing Trading: Mean-reversion setups with clear entry/exit rules Example: XLK, a key tech ETF, is typically very correlated with the S&P 500 with a 0.88 correlation. Our dashboard detected a divergence between both, which signals a buy/rotation to XLK. Let me know if you have any requests, improvements suggestions or feedback :)Pine Script®指标由HenriqueCentieiro提供34
Expectancy Reality Check Most trading discussions focus on entries. This tool focuses on math. Expectancy Reality Check is a symbol-agnostic calculator that shows whether your assumed edge is mathematically viable — before you trade it. It does not generate signals. It does not predict price. It exists to answer one question: “If my assumptions are correct, does this strategy deserve capital?” What this tool does Given your assumptions for: Win rate Reward-to-Risk (R) Costs per trade Risk per trade Trade frequency the indicator computes: Expected Value (R per trade) Expected Value per month Break-even win rate (cost-adjusted) Edge vs break-even (percentage points) Risk-of-ruin proxy (fixed-fractional approximation) Estimated sample size needed to validate your win rate at a chosen confidence level All values are expressed in R-units, not currency, to remain portfolio-independent. How to use it Enter honest assumptions — not best-case backtest results. Observe: Is EV meaningfully positive? How small is the margin above break-even? How many trades are required before results are statistically meaningful? Decide whether the strategy is worth: testing, refining, or discarding. If the math fails here, execution quality will not save it. What this tool is not ❌ Not a strategy ❌ Not a signal generator ❌ Not a performance backtest ❌ Not a guarantee of results It is a reality check, not a promise. Notes on methodology Expectancy is computed in standard R-unit form. Break-even win rate is adjusted for per-trade costs. Risk-of-ruin is a proxy, based on a Lundberg-type root for i.i.d. outcomes under fixed fractional risk. Sample size guidance uses a normal approximation for binomial confidence intervals. All calculations assume stationarity — real markets may violate this. Use judgment. Who this is for Traders designing rule-based systems Traders comparing multiple strategies Traders tired of “high win rate” marketing Anyone who wants math before emotion Final note A strategy with: high win rate but negative expectancy or positive expectancy but no statistical margin is not an edge — it’s noise. Systems over feelings.Pine Script®指标由SystemsOverFeelings提供1
Sector Rotation & Allocation StrategySector Rotation & Allocation Strategy Overview This advanced indicator analyzes the relationship between Defensive and Cyclical sectors to identify market regimes and generate precise buy/sell signals. It automatically detects which asset you're viewing and provides tailored recommendations based on current sector rotation dynamics. What It Does Identifies Market Regime – Determines if markets are in Risk-On (growth) or Risk-Off (defensive) mode Auto-Detects Your Asset – Classifies the current chart into one of 11 sectors Generates Trading Signals – Provides BUY/SELL signals based on sector alignment with market conditions Multi-Timeframe Analysis – Offers allocation recommendations from 1 week to 12 months Value Assessment – Scores each asset 0-100 to determine if it's a good trade NOW How It Works Market Regime Detection The indicator compares Defensive Sectors (Health Care, Consumer Staples, Utilities) against Cyclical Sectors (Technology, Financials, Energy, Industrials, Materials, Real Estate, Discretionary, Communication). Risk-On Market (Green, >0): Cyclical sectors outperforming Economic growth expected Investors favoring growth stocks Action : Buy cyclicals, reduce defensives Risk-Off Market (Red, <0): Defensive sectors outperforming Uncertainty or fear in markets Flight to safety occurring Action : Buy defensives, reduce cyclicals Understanding the Four Tables 1. MARKET REGIME (Top Left) Market Regime : Current state – RISK-ON or RISK-OFF Bias : Which sector type is favored right now Strength : STRONG/MODERATE/WEAK – conviction level Current Sector : Your asset's sector classification Signal : Trading recommendation for your specific asset 2. SECTOR RANKINGS (Top Right) Shows relative strength of all 11 sectors vs SPY benchmark. Rel Str : Percentage outperformance/underperformance vs market Signal : ✓ = Outperforming, ✗ = Underperforming, − = Neutral 3. ALLOCATION RECOMMENDATIONS (Bottom Center) Suggested portfolio allocation between Defensive and Cyclical sectors. 1 Week : Tactical – follows current regime closely (70/30 split) 1 Month : Near-term positioning (65/35 split) 3 Months : Medium-term allocation (60/40 split) 6 Months : Balanced approach (50/50 split) 12 Months : Strategic/Contrarian – assumes mean reversion (40/60 split) 4. ASSET ANALYSIS (Bottom Left) Sector : Auto-detected sector classification Value Rating : STRONG BUY / BUY / HOLD / REDUCE / AVOID Value Score : 0-100 numerical assessment Rel Strength : How this asset performs vs SPY Regime Fit : Is this asset aligned with current market regime? Trading Signals Explained BUY Signals Oscillator crosses above oversold (30) Asset's sector is gaining momentum Regime is favorable for that sector SELL Signals Oscillator crosses below overbought (70) Asset's sector is losing momentum Regime is turning unfavorable for that sector How Value Score Works (0-100) Relative Strength (40 points max) : Asset outperforming SPY by 5%+ → 40 points Asset outperforming SPY by 2-5% → 30 points Asset outperforming SPY by 0-2% → 20 points Asset underperforming slightly → 10 points Asset underperforming significantly → 0 points Sector Alignment (30 points max) : Defensive in Risk-Off OR Cyclical in Risk-On → 30 points Misaligned sector → 0 points Unclassified → 15 points Momentum (30 points max) : RSI > 60 → 30 points RSI 50-60 → 20 points RSI 40-50 → 10 points RSI < 40 → 0 points Interpretation : 80-100 : STRONG BUY – High conviction opportunity 65-79 : BUY – Favorable setup 45-64 : HOLD – No clear edge 30-44 : REDUCE – Unfavorable conditions 0-29 : AVOID – High risk of underperformance Best Practices Use Daily Timeframe or Higher – More reliable signals Combine with Price Action – Confirm with support/resistance Monitor Regime Changes – Transitions offer the highest ROI Respect Risk Management – Always use stop losses Don't Fight the Regime – Buying defensives during Risk-On is low probability Disclaimer This indicator is for educational and informational purposes only. Past performance does not guarantee future results. Conduct your own research before making investment decisions. Version: 6.0 Author: @bigcitytom Last Updated: February 2026Pine Script®指标由bigcitytom提供17
Prop Firms No-Trade News (NFP/CPI/FOMC) - 30m WarningProp Firms No-Trade News (NFP / CPI / FOMC) — 30m Warning This indicator is designed for traders operating under **prop firm rules**, where trading during high-impact economic news is restricted or prohibited. It highlights **no-trade windows** around the most critical U.S. macroeconomic events and helps you stay compliant, disciplined, and risk-aware. Covered High-Impact Events * **Non-Farm Payrolls (NFP)** → Automatically calculated (1st Friday of each month at 08:30 ET) * **Consumer Price Index (CPI)** → Manually configurable * **FOMC Rate Decision / Policy Statement** → Manually configurable How It Works * **30-minute warning alert** before each event * **No-trade window shading** on the chart * **Optional labels** for: * Upcoming no-trade period * Exact news release moment * **Customizable buffers**: * Minutes before the event * Minutes after the event Alerts Included * 30-minute pre-news warning * No-trade window start * No-trade window end * News release time All alerts can be used for **manual trading discipline** or automated workflows. Who This Is For * Prop firm traders (evaluation or funded) * Futures and index traders * Traders who want **rule-based protection against emotional or impulsive trading during news** Notes * News times are based on **U.S. Eastern Time (ET)** * CPI and FOMC dates must be updated manually according to the official economic calendar * This tool does **not execute trades** — it enforces awareness and disciplinePine Script®指标由ggarritano提供7
Risk:Reward Tool Pro - MECTRADER (Minimalist)This is an optimized and refined version of my previous Risk/Reward tool. In this update, I have focused on visual clarity by removing all background color fills (shaded zones) to provide a much more minimalist and professional charting experience. Key Improvements: Zero Visual Distractions: All linefills have been removed, allowing traders to focus purely on price action and market structure without cluttered backgrounds. Clean Aesthetics: Take Profit levels feature dashed lines for easy target identification, while Entry and Stop Loss levels remain solid for clear boundary definition. Performance Focused: The script has been streamlined for a lightweight footprint, making it ideal for users who run multiple indicators simultaneously. Core Features: Tick-Based Calculation: Automatically calculate up to 5 Take Profit levels based on ticks. Quick SL Setup: Simple input for Stop Loss distance. Dynamic Labels: Real-time price display for every level on the right side of the chart. Dual Mode: Full support for both Long and Short positions. Designed for traders who demand technical precision without sacrificing the visual workspace.Pine Script®指标由MEC-Trader提供20
Fixed Risk + Contracts 2.0This is the upgraded version of my Contracts/Risk indicator, released in January 2026. Users will trade responsibly (and never overleverage again!) 1. Pre-Select Your Ticker MES ES NQ MNQ MYM YM M2K MCL MGC GC SIL SI 2. Input Current Account Balance and Risk % Each Trade To Grow Your Account 3. Input Stop Amount In Ticks (Use Position Tool for ease) 4. Contract Risk Is Calculated Automatically! Add to your favourites and comment below if you have any suggestions :)Pine Script®指标由tradeina提供13
Herramienta Risk:Reward Pro - MECTRADEROverview: This is an advanced Risk/Reward management tool specifically designed for traders who execute based on Ticks (perfect for Futures like NQ/ES, Gold, or Forex). The main focus of this script is visual clarity and precision. Key Features: ✅ Clean Visuals (No Dimming): Built using linefill technology with a 92% transparency rate. This ensures the price action remains vibrant and clear. Unlike standard boxes, this tool does not darken or "muddy" the candles when the price enters the zone. ✅ Tick-Based Calculation: Define your Stop Loss and up to 5 Take Profit levels using Ticks for maximum precision. ✅ Toggleable TP Levels: You can enable or disable TP1 through TP5 individually to match your scaling-out strategy. ✅ Dynamic Labels: Automatically displays the level name (Entry, SL, TP) along with the exact price value on the right-side scale. ✅ Long/Short Toggle: Switch between buy and sell setups instantly with a single drop-down selection. How to use: Add the script to your chart. Open Settings and choose your Mode (LONG or SHORT). Use the Precision Crosshair icon next to "Price Entry" to pick your execution level directly from the chart. Adjust your Stop Loss and Profit Ticks. The tool will project your risk zones professionally without interfering with your technical analysis.Pine Script®指标由MEC-Trader提供48
Vertical Scale Rulerfor consistency, confirm appropriate sl 1111111111 11111111111Pine Script®指标由Jiumian提供0
Farjeat Lot & Risk CalculatorThis indicator will be of great help in measuring the lot size you should use in each of your operations, accurately managing your risk and profit.Pine Script®指标由erickfarjeat提供44
ICT Macros & Visual Risk CalculatorThis "all-in-one" indicator is specifically designed for ICT (Inner Circle Trader) methodology practitioners who trade high-volatility time windows (Macros). It combines automated visual identification of these sessions with an advanced risk calculator that dynamically draws position blocks (Long/Short) based on pips, ensuring fast and precise execution.Pine Script®指标由abelratrade提供已更新 24
Money managementnever forget your money management ! never.....................................................................................Pine Script®指标由roinono提供11
Risk/Reward vs Win Rate HeatmapThis indicator overlays two decision-support tables on your main chart: 1. Reward:Risk vs Win Rate Heatmap A matrix that shows whether a given combination of Win Rate (%) and Reward:Risk (R:R) is expected to be: Profitable (green) Break-even (amber) Not Profitable (red) The color is based on the standard expectancy concept: E = p * R - (1 -p) where p is win probability and R is Reward:Risk. The diagonal amber cells represent the break-even boundary. 2. Drawdown Table A quick reference table showing how much % gain is required to recover after a capital drawdown (e.g., -20% requires +25% to return to break-even). This is meant to anchor capital preservation and risk management decisions. ________________________________________ How to Use Set your expected Win Rate and R:R in the inputs. Enable Show highlight to display a status icon on the matching cell: Profitable: 💰 Break-even: ⚠ Not profitable: 🚫 (All icons are customizable.) Use the heatmap to sanity-check whether your strategy parameters make sense, and use the drawdown table as a reminder of why protecting capital matters. ________________________________________ Inputs & Customization Position: Place each table anywhere on the chart (default layout provided). Colors: Header colors and heatmap colors are customizable (defaults included). Fonts: Title, headers, labels, legend, and icon font sizes are configurable. Icons: Set your own symbols for Profitable / Break-even / Not profitable (with optional auto-contrast). ________________________________________ Notes This script is educational and provides a visual framework to reason about expectancy and drawdowns. It does not generate trade signals and does not guarantee profitability. Results depend on the accuracy of your inputs and real-world execution (slippage, fees, market regime, etc.). ________________________________________ Disclaimer This indicator is for educational purposes only and is not financial advice. You are responsible for any trading decisions and risk management.Pine Script®指标由Yesid_Correa_Cano提供已更新 7
Weekly SMA20 Relative Strength Matrix (8x8)weekly SMA 20 asset rank matrix, helps view multiple assets and their long term trends at the same timePine Script®指标由jordanjnoone提供1
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 CentieiroPine Script®指标由HenriqueCentieiro提供18
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). Pine Script®指标由EdgeTools提供已更新 49
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.Pine Script®指标由tradeina提供21
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.Pine Script®指标由tcspirit提供已更新 7
Somma 30 Ticker PonderataCalcolo della equity del proprio portafogli con i pesiPine Script®指标由frz986提供已更新 0
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 Pine Script®指标由fin0ygr8提供已更新 11