Trapped Traders EBPThe Trapped Traders Indicator is used to predict overall Market bias, with green being longs, and red being shorts.
The autofibs are 0%,25%,50%,and 100%. After an autofib and directional bias is generated, you'll want to look for an entry on a lower time frame somewhere between the 25% and 50% ideally.
A simple trading plan:
Use the indicator on the 4 Hour chart. Wait until you get an autofib. Zoom down to the 5 minute chart and wait for price to reach the 25% retracement. Look for an entry using an entry model of your choice. For example: an engulfing 5 minute bar in the direction of your bias, an order block, fair value gap, or choch in your favor.
This method of trading was introduced to me by Omar Agag. Cheers to prosperity, brother!
Good luck! And happy trading!
Forecasting
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).
WC Cross Clouds with Arrows - Customizable EditionThis is an enhanced and fully customizable version inspired by the original "WC CROSS CLOUDS with Arrows" indicator by AlfsDipz (thank you for the great foundation!).
What it shows:
• Two clouds for visual trend context:
- Static black WMA cloud (default WMA 21 & 24) – helps identify overall market structure
- Directional cloud (default SMA 9 & 21, but fully configurable) – green when fast MA is above slow MA (bullish), red when below (bearish)
• Clean signals with arrows + text:
- Green triangle up + "LFG" → New bullish regime starts (fresh crossover upward)
- Red triangle down + "DBD" → New bearish regime starts (fresh crossover downward)
• Small realtime label showing current regime + bars since last signal
New features / improvements compared to original:
• Fully user-configurable MA lengths for both clouds
• Choose MA type for the directional cloud (SMA, EMA, or WMA)
• Customizable source (close, hl2, open, etc.)
• Cleaner signal logic (only shows arrows when trend direction actually changes)
• No duplicate/false signals during ranging markets
• Works in Pine Script v6 (latest version)
How to use:
- Green cloud + "LFG" arrow → potential long opportunity
- Red cloud + "DBD" arrow → potential short / exit long
- Use together with your own price action, support/resistance, volume, etc.
Feel free to use, modify, expand, fork, or build upon this script however you like!
Credit to AlfsDipz for the original concept and cloud style that inspired this version.
Happy trading everyone!
Dove– Chesapeake, VA
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.
Bitcoin Power Law Bottom PriceThis is a super simplified version of Bitcoin Rainbow Wave script.
I removed everything except the power law bottom band.
ChunkbrAI-NN INDIChunkbrAI-NN INDI: The Neural Network Odyssey
A Native Pine Script Neural Network Research Engine
Welcome to ChunkbrAI-NN 5.3. This is not a standard technical indicator; it is a proof-of-concept Artificial Intelligence engine built entirely from scratch within Pine Script.
Neural Networks typically require iterating over massive datasets, a task that usually times out on TradingView. ChunkbrAI solves this by introducing a novel "Chunking Architecture"—a system that breaks history into digestible learning blocks and trains a Multilayer Perceptron (MLP) using a "Chunking" approach.
It features a living ecosystem where neurons have "genes," grow mature, and adapt to market regimes using a highly sophisticated Context-Aware normalization engine.
-----------------------------------------------------------
The Core Concept: "The Time Wheel"
To bypass Pine Script's execution limits, this script does not train linearly from the beginning of time. Instead, it operates like a spinning wheel of experience.
* The Chunk System: On every bar update, the engine reaches back into history (up to 5000 bars) and grabs random or sequential "Chunks" of data. It treats these chunks as isolated training samples.
* Experience Replay: By constantly revisiting past market scenarios (Chunks), the network slowly converges its weights, learning to recognize patterns across different eras of price action.
-----------------------------------------------------------
Architecture & Modules
A. The Neural Core (MLP)
At the heart is a raw neural network built with arrays:
* Topology: A dense network with a customizable Hidden Layer (Default: 60 Neurons).
* Timewarp (Stride): When enabled, the network uses "dilated" inputs (skipping bars, e.g., 1, 3, 5...). This increases the network's Field of View without increasing computational load.
* Forecasting: The network outputs a standardized prediction which is then de-normalized to project the future price path on your chart.
B. The Context System (The "Eyes")
Raw prices confuse neural networks. A $1000 move in Bitcoin is massive in 2016 but noise in 2024. ChunkbrAI uses a relativistic Context System:
* Regime Detection: It uses a Zero-Lag Moving Average (ZLMA) and Non-Linear Regression to measure the current market "Vibe" (Volatility & Trend).
* Dynamic Normalization: The inputs are scaled based on this context. If the market is volatile, the data is compressed; if calm, it is expanded. This ensures the brain receives consistent signal patterns regardless of the absolute price.
C. The Gene System (Neuro-Plasticity)
This is the experimental "biology" layer. Neurons are not just static math; they have life cycles.
* Maturity: Neurons start "Young" (highly plastic, high mutation rate). As they successfully reduce error, they become "Wise" (stable, low mutation).
* Mutation: If a "Wise" neuron begins failing (high error), it is demoted and forced to mutate. This allows the brain to "forget" obsolete behaviors and adapt to new market paradigms automatically.
* Profiles: You can initialize the brain with different personalities (e.g., Dreamer, Young Chaos, Zen Monk).
D. The Brain Scheduler (Adaptive Learning)
A static Learning Rate (LR) is inefficient. The Brain Scheduler acts as the heartbeat:
* Panic vs. Flow: It monitors the derivative of the error. If the error spikes (Panic), the Scheduler slows down learning to prevent the model from exploding. If the error smooths out (Flow), it accelerates learning (Infinite LR Mode).
-----------------------------------------------------------
Forecasting Modes
The script provides two distinct ways to visualize the future:
1. Direct Projection (Green Line):
The network takes the current window of price action and predicts the immediate next step. If Timewarp is active, it interpolates the result to draw a smooth curve.
2. Autoregression (Cyan Line):
Available in "Auto" mode. The network feeds its *own* predictions back into itself as inputs to generate multi-step forecasts.
* Wave Segmentation: The script intelligently guesses the current market cycle length and attempts to project that specific duration forward.
-----------------------------------------------------------
Operation Manual
The script has two distinct training loops: first, when you add it to a chart, Pine runs through the available historical bars once, and this initial history pass is the main training phase where the network iterates chunk-by-chunk using your configured chunk count/iterations (e.g., if chunk count is 3, it performs 3 chunk updates per step), but pushing chunk count, iterations, or model sizing too high can hit Pine’s execution limits; after that, once real-time candles start printing, the script can either keep training (weights continue updating) or freeze the weights and run inference only, producing predictions from the learned parameters, and if live training is enabled it can also simulate “bars-back” style training during live mode by iterating across prior bars as if doing another history pass—which again can run into limits if chunks/iterations/sizing are too heavy—so when changing parameters to evaluate behavior you change them carefully and individually, because multiple simultaneous increases make it hard to attribute effects and can more easily trigger those execution constraints.
Weight Persistence (Save/Load):
Pine Script can’t write files or persist weights directly, so ChunkbrAI uses a library-based workaround that’s honestly tricky and kind of a pain: you enable the weight-export alerts so the script emits the weights (W1/W2/biases etc.) as text, and those payloads are chunked as well; then, outside TradingView, I use a separate Python script to parse the alert emails, reconstruct and format the chunked weights properly, and generate the corresponding library code files; after that, the libraries have to be published/updated, and only then can the main script “restore” by reading the published lib constants on chart load, effectively starting with the pre-trained weights instead of relying purely on the fresh history-run training pass. I don’t recommend this process unless you really have to—it’s fragile and high-effort—but until TradingView implements some simple built-in data storage for scripts, it’s basically the only practical way to save and reload your models.
-----------------------------------------------------------
Limitations & Notes
* Calculation Limits: This script pushes Pine Script to its absolute edge. If you increase Chunk Size or Hidden Size too much, you WILL hit execution limits. Use the defaults as a baseline.
* Non-Deterministic: Because the "Wheel" picks random chunks for training, two instances of this script might evolve slightly different brains unless you use the Restore Weights feature.
* Experimental: This is a research tool designed to explore Neural Networks and Genetic Algorithms on the chart. Treat it as an educational engine, not financial advice.
Credits: Concept and Engineering by funkybrown.
ES to SPX Lead (RTH Adaptive)Very simple script designed especially to trade CFD but also scalping.
Only RTH (you'll understand why)
Not a stand-alone indicator, e.g., an external event may hit the index and /ES leading nature will become meaningless. Same with a sudden crash on a Mag7 stock.
Uses Z Score to evaluate if /Es is leading SPX (or not) and /ES VWAP to establish bullish (+1) or bearish territory (-1). Histogram is the product of Z Score times VWAP status, red or green depending.
Z score goes from -2 to +2.
Zscore reading: 0.4 < |Z| < 1.2 is the trading zone.
|Z| <0.4 is sort of neutral shifting gears zone, a no-trade and may be transition moment.
Middle numbers show max. limits based on actual volatility (i.e. when to exit and when definitely not to enter a trade).
Grey stripes is NO TRADE zone.
Final number is the composite histogram value.
So:
Textbook bullish: /ES above VWAP and Z Score positive
Textbook negative: /ES below VWAP and Z score negative
If Green Histogram & negative Z Score, you may enter bearish pullback trades making sure Z score is in the sweet spot bracket.
If Red histogram & negative Z score, it's a conflict state, signals are not alined. Holds a bullish nature but it may be a warning sign.
Script produced by Chat GPT after several iterations.
Standard Deviation Linesplot standard deviation lines for 1sd, 2sd, 3sd. The user gives the data for the standard deviation and the time.
UTC-5 Time MarkersFor model 110 of DTT use flout with this as a bias and you will catch high wr high rr trades for this certain time window of continuation or reversal
Current Candle DateTimeThis is a simple script that users can easily see that datetime of the current candle. This is useful when backtesting and you want to be able to quickly glance and see where we are up to. Useful for when you are backtesting a strategy and trying to stay within a particular trading session.
The indicator will display in the top right hand corner, so it wont get in the way of any other analysis.
NY PM Session Highlighter (For Hawaiian Traders)Purpose: This script is designed for traders targeting the New York PM Session (1:30 PM – 4:00 PM ET). Based on 5-year historical data for ES and NQ, this window represents a high-probability period for 2:1 Risk-to-Reward setups as institutional traders rebalance and drive price toward the daily close.
Key Features:
DST-Automated Tracking: Uses the America/New_York timezone to ensure the lines stay accurate during Daylight Saving transitions.
Visual Guidance: Draws a dashed vertical line at the 1:30 PM ET start and the 4:00 PM ET close.
Session Boxing: Highlights the background in a soft blue to define the "trading zone," helping you ignore the low-volume "lunch doldrums" that occur immediately before.
Hawaii-Friendly: Automatically adjusts to your local Hawaii Standard Time (HST) so you don't have to calculate the 5 or 6-hour offset manually.
Trade Logic:
Wait for the 1:30 PM ET (8:30 AM HST) line.
Look for a sweep of the 12:00 PM – 1:00 PM (Lunch) range.
Enter on a Market Structure Shift (MSS) or Fair Value Gap (FVG).
Target a 2:1 Reward-to-Risk ratio, aiming to exit by the 4:00 PM ET line.
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.
Adaptive AI SuperTrend [AlgoPoint]🚀 Adaptive AI SuperTrend
Adaptive AI SuperTrend is a high-performance trading terminal that redefines trend-following by integrating Machine Learning (ML) principles with advanced market regime detection. Unlike static indicators, this system dynamically recalibrates its internal parameters to match the ever-changing volatility of the financial markets.
Equipped with a custom "Wizard Engine," it filters out market noise during consolidation and identifies high-probability trend continuation points, making it an essential tool for scalpers, day traders, and swing traders alike.
🧠 What Makes it "AI"?
While traditional indicators use fixed rules, Adaptive AI SuperTrend utilizes Algorithmic Intelligence to make real-time decisions:
KNN-Inspired Adaptation: The engine analyzes the last 150 bars of volatility and trend strength to automatically adjust its sensitivity.
Market Regime Intelligence: It distinguishes between "Trending" and "Ranging" states using a sophisticated Squeeze Momentum module, preventing "whipsaws" during low-volume periods.
Self-Backtesting Logic: The indicator continuously calculates its own historical Win-Rate. If the probability of success falls below a certain threshold, it suppresses lower-quality signals.
🛠 Key Features
Dynamic Consolidation Boxes: Automatically identifies and wraps "choppy" price action in professional gray boxes. It waits for 3+ bars of consolidation before marking the zone, helping you spot breakout opportunities early.
Multi-Strategy Aggression:
- Conservative: Filtered signals for long-term trend following.
- Balanced: Optimized for daily volatility.
- Aggressive: High-frequency signals for capturing micro-trends.
Dual-Exit Risk Management:
- ATR TP-SL Mode: Sets mathematical targets based on market volatility with persistent on-screen lines.
- Smart Trailing Mode: Rides the trend to its exhaustion point. Includes intelligent labeling (🎯 TP or 🛑 SL) based on the trade's net profitability.
- RSI Pullback Confirmation: Beyond simple trend flips, it detects "buy the dip" or "sell the rip" opportunities within an existing trend using RSI 50-level crossovers.
📊 Real-Time Analytics Dashboard
The integrated AlgoPoint Dashboard provides a surgical view of the market:
- Market State: Instant "Trending" vs. "Ranging" (Consolidation) detection.
- Trend Strength: ADX-based momentum tracking.
- Strategy Status: Real-time feedback on your active aggression and exit modes.
🎨 Clean Charting & Customization
Built for professional clarity, you have total control over the UI:
Toggle Consolidation Boxes on/off.
Toggle ATR Target Lines and Exit Labels.
Customize background filters and dashboard visibility.
Smart Take ProfitThis script for EURUSD on the M3 timeframe detects Take Profit zones close to a reversal, automatically displays TP1, TP2, and Stop Loss, and follows the RSI + Bollinger Band + ATR logic.
It triggers an exit signal when the price touches a Bollinger Band, when the RSI is in an extreme zone, or when there is a rejection candle.
It automatically calculates the TP at 0.8 ATR, TP2 at 1.0 ATR, and the Stop Loss at 0.6 ATR.
It operates on the EURUSD M3 timeframe. You decide the entry point. This indicator is not a trading strategy.
Volume Conviction Index v1.0Volume Conviction Index V1 (VCI V1)
A robust, outlier-resistant volume oscillator designed to reveal real market participation and conviction behind price moves.
- Brief explainer -
v1.0 : Added a median line to show the movement and ultimate conviction of current price waves irrespective of current conviction. conviction can be extremely low (below zero line), yet price can be pumping, which shows the end of the current trend may be exhausting. divergence happens with this indicator is VERY FAST when tuned into it.
Core features:
• Median + MAD-based Z-score on volume (ignores extreme spikes/noise)
• Weighted blend: 60% robust deviation + 40% directional conviction (recent change % + relative volume %)
• Aggressive low-TF filter: optional rolling median line around zero to slice through 1min/3min chop
• Positive bars (teal) = unusual upward participation / conviction
• Negative bars (orange) = unusual weakness or drying volume
Use cases:
• Confirm breakouts, reversals, or exhaustion (e.g., spike on neckline breach)
• Filter false moves in low-liquidity or noisy periods
• Pair with Median Anchor Oscillator (MAO), Real Deviation Strength (RDS), and Anchor Pulse Wave (APW) for full conviction suite
V1 is raw and minimal — no signals, labels, or alerts yet. Feedback welcome for V2!
Companion suite:
• Median Anchor Oscillator
• Real Deviation Strength (RDS)
• Anchor Pulse Wave
© RU55IANROUL3TT3
Pivot Scannerpivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alertspivot scanner based on pivots ema and ai alerts
Last Candle + Previous Day + Pre-Market- RangeV2 of the Indicator (Test)
Last Candle + Previous Day + Pre-Market Script – Features
Last Candle Levels (Current Timeframe)
Draws horizontal lines at the high and low of the last confirmed candle.
Optional display of the candle range in percentage.
Lines automatically update and move correctly when zooming or changing the timeframe.
Previous Day High / Low
Shows the high and low of the previous trading day as dashed lines.
Lines are automatically updated and extend to the right, following the price scale.
Works on any timeframe chart.
Pre-Market High / Low
Highlights the pre-market session (default 04:00–09:30) with dotted lines.
Only calculated during intraday charts.
Lines behave exactly like the daily range lines: zoomable, shiftable, and extendable.
Optional toggle to enable or disable.
Customization Options
Colors for TF candle, daily range, and pre-market range lines.
Length of line extension to the right can be adjusted.
Toggle which levels to show: current TF, previous day, pre-market.
Stable & Safe in Pine Script v6
No repaint issues.
Works reliably on all intraday and daily charts.
Compatible with zooming and chart shifting.
If you want, I can also create a very short “user guide” with screenshots / labels in the chart, so it’s immediately clear what each toggle and line represents.
Do you want me to do that next?
Crypto Prev Day/Week Hi-Lo (UTC)escription
Crypto Prev + This Day/Week Hi-Lo (UTC) plots key high/low levels for crypto markets using a 24-hour session anchored to 00:00 UTC.
This indicator is designed for traders who treat crypto as a true 24/7 market and want consistent, global day/week levels that don’t shift with daylight savings.
What it plots
PDH / PDL = Previous Day High / Previous Day Low
PWH / PWL = Previous Week High / Previous Week Low
TWH / TWL = This Week High / This Week Low
00:00 UTC vertical line = marks the start of a new UTC day
Abbreviations
PDH = Previous Day High
PDL = Previous Day Low
PWH = Previous Week High
PWL = Previous Week Low
TWH = This Week High
TWL = This Week Low
UTC = Coordinated Universal Time (global standard time reference)
Short Option Intrinsic + Option Price + Time ValueThis code print out and plot the intrinsic values, time values and the option price on the screen. This tells your how likely a short option will be exercised. User needs to select the option type (call, or put). Then input strike price and the current option price.
AI Academy: Volume k-NN [PhenLabs]📊 AI Academy: Volume k-NN
Version: PineScript™ v6
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📌 Description
AI Academy: Volume k-NN (Theory Edition) is an educational indicator designed to demystify how artificial intelligence pattern recognition works directly on your TradingView charts. Rather than being a black-box signal generator, this tool visualizes the entire k-Nearest Neighbors algorithm process in real-time, showing you exactly how AI identifies similar historical patterns and generates predictions.
The indicator scans up to 2,000 historical bars to find patterns that match your current price action, then uses an ensemble of the closest matches to project potential future movement. What sets this apart is the integrated “AI Grimoire”—an interactive educational book overlay that teaches core machine learning concepts through four illuminating chapters.
Whether you’re a trader curious about AI methodology or a developer learning algorithmic concepts, this indicator transforms abstract machine learning theory into tangible, visual understanding.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🚀 Points of Innovation
• First TradingView indicator to visualize k-NN algorithm execution in real-time with full transparency
• Interactive “AI Grimoire” educational overlay teaches machine learning concepts while you trade
• Dual-mode pattern matching combines price action with optional volume confirmation
• Confidence-based opacity system visually communicates prediction reliability
• Historical match visualization shows exactly which past patterns informed the prediction
• Ghost bar projections display averaged ensemble predictions with adjustable forecast horizons
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔧 Core Components
• Pattern Capture Engine: Converts recent price action into logarithmic returns for normalized comparison across different price levels
• k-NN Search Algorithm: Calculates Euclidean distance between current pattern and historical patterns to find closest matches
• Volume Weighting System: Optional feature that incorporates volume patterns into distance calculations with adjustable influence
• Ensemble Predictor: Averages future returns from k-nearest historical matches to generate consensus forecast
• Confidence Calculator: Measures average distance of top matches to determine prediction reliability on 0-100% scale
• AI Grimoire Display: Table-based educational overlay rendering book-style content with chapter navigation
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔥 Key Features
• Adjustable Pattern Length: Define how many bars constitute the current pattern for matching (5-100 bars)
• Configurable Search Depth: Control how far back the algorithm searches for historical matches (500-4,900 bars)
• Flexible k-Neighbors: Select how many closest matches inform the prediction (1-20 neighbors)
• Volume Toggle: Enable or disable volume pattern matching for different market conditions
• Volume Influence Slider: Fine-tune the weight given to volume vs. price patterns (0-100%)
• Ghost Bar Count: Adjust how many future bars the indicator projects (3-15 bars)
• Minimum Confidence Filter: Set threshold to hide low-confidence predictions
• Historical Match Display: Toggle visibility of colored boxes marking source patterns
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎨 Visualization
• Blue Scanner Box: Highlights current pattern being analyzed labeled “AI INPUT (The Prompt)”
• Green Historical Boxes: Mark past patterns where price subsequently moved bullish
• Red Historical Boxes: Mark past patterns where price subsequently moved bearish
• Ghost Bars: Semi-transparent candles projecting into the future showing predicted price path
• Confidence Label: Displays prediction confidence percentage and number of matches used
• AI Grimoire Book: Leather-bound book overlay in top-right corner with navigable chapters
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📖 Usage Guidelines
Algorithm Settings
• Pattern Length — Default: 20 | Range: 5-100 | Controls how many recent bars define the pattern. Shorter values find more matches but less specific. Longer values find fewer but more precise matches.
• Search Depth — Default: 2000 | Range: 500-4900 | Determines how many historical bars to scan. Higher values find more potential matches but increase computation time.
• k-Neighbors — Default: 5 | Range: 1-20 | Number of closest matches to use for prediction. Higher values smooth predictions but may dilute strong signals.
• Ghost Bar Count — Default: 5 | Range: 3-15 | How many future bars to project. Shorter horizons are typically more reliable.
• Use Volume Matching — Default: Off | When enabled, patterns must match on both price AND volume characteristics.
• Volume Influence — Default: 30% | Range: 0-100% | Weight given to volume pattern when volume matching is enabled.
Visualization Settings
• Bullish/Bearish Match Colors — Customize colors for historical match boxes based on outcome direction.
• Min Confidence % — Default: 60 | Predictions below this threshold will not display.
• Show Historical Matches — Default: On | Toggle visibility of source pattern boxes on chart.
Education Settings
• Select Chapter — Navigate through AI Grimoire chapters or keep book closed for clean chart view.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ Best Use Cases
• Learning how k-Nearest Neighbors algorithm functions in a trading context
• Understanding the relationship between historical patterns and forward predictions
• Identifying when current market conditions resemble past scenarios
• Supplementing discretionary analysis with pattern-based confluence
• Teaching others machine learning concepts through visual demonstration
• Validating whether volume confirms price pattern formations
• Building intuition for what AI “sees” when analyzing charts
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ Limitations
• Past pattern similarity does not guarantee future outcome similarity
• Requires sufficient historical data (minimum 500+ bars) to function properly
• Computation-intensive on lower timeframes with maximum search depth
• Cannot predict truly novel “black swan” events not represented in historical data
• Volume matching less effective on assets with inconsistent volume reporting
• Predictions become less reliable as forecast horizon extends further out
• Educational overlay may obstruct chart view on smaller screens
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
💡 What Makes This Unique
• Full Transparency: Unlike black-box AI tools, every step of the algorithm is visualized on your chart
• Integrated Education: The AI Grimoire teaches machine learning concepts without leaving TradingView
• Theory Meets Practice: See exactly which historical patterns inform each prediction
• Honest Uncertainty: Confidence scoring and opacity fading acknowledge when the AI “doesn’t know”
• Dual-Mode Analysis: Optional volume weighting adds institutional-quality analysis dimension
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔬 How It Works
1. Pattern Capture: On each bar, the indicator captures the most recent price changes as logarithmic returns, creating a normalized “fingerprint” of current market behavior. If volume matching is enabled, volume changes are captured similarly.
2. Historical Search: The algorithm iterates through up to 2,000 historical bars, calculating the Euclidean distance between the current pattern fingerprint and each historical pattern. Distance combines price similarity and optional volume similarity based on weight settings.
3. Neighbor Selection: All historical patterns are ranked by similarity (lowest distance = most similar). The k-closest matches are selected as the “ensemble council” that will inform the prediction.
4. Confidence Calculation: Average distance of top-k matches determines confidence. Tighter clustering of similar patterns yields higher confidence scores, while scattered or distant matches produce lower confidence.
5. Prediction Generation: Future returns from each historical match (what happened AFTER those patterns) are averaged together. This ensemble average is applied to current price to generate ghost bar projections.
6. Visualization: Historical match locations are marked with colored boxes (green for bullish outcomes, red for bearish). Ghost bars render with opacity tied to confidence level—higher confidence means more solid bars.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
💡 Note:
This indicator is designed primarily for educational purposes —to help traders understand how AI pattern recognition algorithms function. While the predictions can supplement your analysis, they should never be used as the sole basis for trading decisions. The AI Grimoire chapters explain key concepts including why AI “hallucinates” during unprecedented market events. Always combine with proper risk management and additional confirmation.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Trader HQ - Multi Time Frame EMA🔷 Indicator Title
MTF 200 EMA Pro — Triple Timeframe Trend Filter
🔷 Short Description (Tagline)
A professional multi-timeframe 200 EMA framework that overlays up to three higher and lower timeframe trend filters on a single chart for superior market alignment and trade confirmation.
🔷 Full Description (Paste This in TradingView)
📈 MTF 200 EMA Pro — Triple Timeframe Trend Filter
MTF 200 EMA Pro is a professional-grade multi-timeframe trend analysis tool designed to help traders identify high-probability directional bias across multiple timeframes.
This indicator allows you to overlay up to three independent 200-period Exponential Moving Averages from different timeframes onto one chart, providing instant insight into higher, medium, and lower timeframe trend alignment.
By stacking multiple 200 EMAs, traders can eliminate low-quality setups, avoid countertrend trades, and operate in harmony with dominant market structure.
🔧 Key Features
✅ Up to 3 independent 200 EMAs
✅ Individual timeframe selection per EMA
✅ Clean overlay on any chart
✅ Adjustable display per line
✅ Real-time multi-timeframe calculations
✅ Works on all markets and sessions
🎯 How to Use
This indicator is designed as a primary trend filter.
Example configuration:
• EMA 1 → Lower timeframe (Execution)
• EMA 2 → Medium timeframe (Momentum)
• EMA 3 → Higher timeframe (Structure)
Bullish Bias Example
Price above all 200 EMAs
Lower EMA above higher EMA
Pullbacks hold above structure
Bearish Bias Example
Price below all 200 EMAs
Lower EMA below higher EMA
Rejections at structure
When EMAs are aligned, trend probability increases.
📊 Best Use Cases
✔ Futures Trading
✔ Options & Equity Trading
✔ Forex & Crypto
✔ Prop Firm Evaluations
✔ Trend-Following Systems
✔ Momentum Strategies
⚠️ Risk Disclaimer
This indicator is a trend visualization and filtering tool only. It does not provide financial advice. Always apply proper risk management and confirm signals with your own strategy.






















