DafeSPALibDafeSPALib: The Shadow Portfolio Adaptation & Strategy Selection Engine
This is not a backtester. This is a live, adaptive portfolio manager. It is a reinforcement learning system that learns which of your strategies to trust in the ever-changing chaos of the market.
█ CHAPTER 1: THE PHILOSOPHY - BEYOND A SINGLE STRATEGY
The search for a single "holy grail" trading strategy is a fool's errand. No single set of rules can perform optimally in all market conditions. A trend-following system that thrives in a bull run will be decimated by a choppy, range-bound market. A mean-reversion strategy that profits from ranges will be run over by a powerful breakout.
The DafeSPALib (Shadow Portfolio Adaptation Library) was created to solve this fundamental problem. It is built on a powerful principle from modern quantitative finance: instead of searching for one perfect strategy, a truly robust system should intelligently allocate to a portfolio of different strategies, dynamically favoring the one that is currently most effective.
This is not just a concept; it is a complete, production-grade engine built in Pine Script. It allows a developer to run multiple "shadow portfolios"—hypothetical trading accounts for each of your strategies—in parallel, in real time. The library tracks the actual equity curve, win rate, Sharpe ratio, and drawdown of each strategy. It then uses a sophisticated selection algorithm to determine which strategy is the "alpha" in the current market regime and tells you which one to follow. It is an AI portfolio manager that lives on your chart.
█ CHAPTER 2: THE CORE INNOVATIONS - WHAT MAKES THIS A REVOLUTIONARY ENGINE?
This library is not a simple strategy switcher. It is a suite of genuine, academically recognized machine learning and statistical concepts, adapted for the Pine Script environment.
Shadow Portfolio Tracking: This is the heart of the system. For each of your strategy "arms," the library maintains a complete, independent set of performance analytics. It doesn't just keep a simple "score." It tracks every hypothetical trade, calculates real P&L;, and updates a full suite of institutional metrics, including the Sharpe Ratio (risk-adjusted return), Sortino Ratio (downside-risk-adjusted return), Profit Factor , and Maximum Drawdown . This provides a rich, data-driven foundation for all decision-making.
Advanced Selection Algorithms: The library doesn't just pick the strategy with the highest recent win rate. It uses sophisticated, battle-tested algorithms from the "multi-armed bandit" problem in machine learning to solve the critical "explore vs. exploit" dilemma:
Thompson Sampling: The default and most powerful. Instead of just picking the "best" arm, it samples from each arm's learned probability distribution of success (its Beta distribution). This naturally balances "exploitation" (using the strategy that works) with "exploration" (giving less-proven strategies a chance to shine), making it incredibly robust against changing conditions.
Upper Confidence Bound (UCB): A deterministic algorithm that is "optimistic in the face of uncertainty." It favors strategies that have both a high win rate and a high degree of uncertainty (fewer trades), encouraging intelligent exploration.
Epsilon-Greedy: A classic RL algorithm that mostly exploits the best-known strategy but, with a small probability (epsilon), explores a random one to prevent getting stuck on a sub-optimal choice.
Trauma-Based Memory Compression: This is a groundbreaking, proprietary concept. When the market experiences a "regime shock" (a sudden explosion in volatility, a violent trend reversal), a simple learning system can be paralyzed or make catastrophic errors. The SPA engine's "trauma" cycle is an intelligent response. It does not erase all learned knowledge. Instead, it compresses the memory : it preserves the direction of what it has learned (e.g., "Strategy A is generally better than B") but it destroys the confidence. The AI "remembers" its experiences but becomes highly uncertain, forcing it to re-learn and adapt to the new market personality with incredible speed. Think of it like PTSD for an AI: the memory of the event remains, but the trust is shattered.
Multi-Layer Concept Drift Detection: This is the system's "earthquake detector." It is constantly scanning for signs that the market's fundamental character is changing ("concept drift"). It uses three layers of detection— Structural (trend slope changes), Volatility (ATR explosions), and Participation (volume anomalies)—to identify a regime shock and trigger the trauma compression cycle.
█ CHAPTER 3: A DUAL-PURPOSE FRAMEWORK - MODES OF OPERATION
This library, along with its companion DAFE libraries, is designed for ultimate flexibility. As a developer, you have complete freedom to use these tools independently or as a fully integrated system.
MODE 1: STANDALONE ENGINE OPERATION (Independent Power)
The DafeSPALib can be used entirely on its own to build a powerful portfolio-of-strategies indicator without any external ML. This approach is perfect for comparing, validating, and dynamically selecting from your own existing, rule-based trading ideas.
The Workflow:
Your indicator initializes the SPA engine with a set number of "arms" (e.g., 4).
On each bar, you calculate the signals for each of your independent strategies (e.g., an EMA Crossover, an RSI Mean Reversion, a Bollinger Breakout).
You feed this array of signals ( ) into the SPA's feed_signals() function.
The SPA engine updates the shadow portfolio for each of the four strategies based on these signals. You then call the select() function, and the SPA's chosen algorithm (e.g., Thompson Sampling) will return the index of the single strategy arm that it trusts the most right now.
Your indicator's final output signal is the signal from that selected arm.
The Result: A complete, self-contained meta-strategy. Your indicator is no longer just one strategy; it is an intelligent manager that dynamically switches between multiple strategies, adapting to the market by selecting the one with the best real-time, risk-adjusted performance.
MODE 2: BRIDGED SUPER-SYSTEM OPERATION (The Ultimate AI)
This is the pinnacle of the DAFE ecosystem. In this advanced mode, the DafeSPALib acts as the "strategic brain" or "portfolio manager" that is fused with a tactical machine learning engine (like the DafeRLMLLib) via a master communication protocol (the DafeMLSPABridge).
The Workflow:
The ML engine generates proposals.
The Bridge Library translates these proposals into a portfolio of micro-strategies.
The SPA engine (this library) receives this portfolio of signals, tracks their shadow performance, and uses its advanced selection algorithms to choose the single best micro-strategy to follow. This becomes the final trade decision.
The final P&L; from the SPA's selection is then routed back through the Bridge to the ML engine as a highly qualified reward signal for learning.
The Result: A hybrid intelligence that is more robust and adaptive than either system alone. The ML provides tactical creativity, while the SPA provides ruthless, performance-based strategic oversight.
█ CHAPTER 4: THE DEVELOPER'S MASTERCLASS - IMPLEMENTATION GUIDE
This library is a professional framework. This guide provides the complete, unabridged instructions and templates required to integrate the DAFE SPA engine into your own custom Pine Script indicators.
PART I: THE INPUTS TEMPLATE (THE CONTROL PANEL)
To give your users full control over the AI, copy this entire block of inputs into your indicator script. It is professionally organized with groups and detailed tooltips.
// ╔════════════════════════════════════════════════════════╗
// ║ INPUTS TEMPLATE (COPY INTO YOUR SCRIPT) ║
// ╚════════════════════════════════════════════════════════╝
// INPUT GROUPS
string G_SPA_ENGINE = "════════════ 🧠 SPA ENGINE ════════════"
string G_SPA_DRIFT = "════════════ 🌊 CONCEPT DRIFT ══════════"
string G_SPA_DASH = "════════════ 📋 DIAGNOSTICS ═══════════"
// SPA ENGINE
int i_spa_num_arms = input.int(4, "Number of Strategy Arms", minval=2, maxval=10, group=G_SPA_ENGINE,
tooltip="The number of parallel strategies the SPA will track.")
string i_spa_selection = input.string("Thompson Sampling", "🤖 Selection Algorithm",
options= , group=G_SPA_ENGINE,
tooltip="The machine learning algorithm used to select the best arm. " +
"• Thompson Sampling: Bayesian approach, samples from each arm's success probability. Balances explore/exploit perfectly (Recommended). " +
"• UCB: Optimistic approach that favors arms with high uncertainty. Excellent for exploration. " +
"• Epsilon-Greedy: Mostly exploits the best arm, but explores randomly with a small probability (epsilon). " +
"• Softmax: Selects arms based on a probability distribution weighted by their performance.")
float i_spa_epsilon = input.float(0.15, "🧭 Epsilon (for Epsilon-Greedy)", minval=0.01, maxval=0.5, step=0.01, group=G_SPA_ENGINE,
tooltip="The probability of taking a random action to explore. This value automatically decays over time.")
float i_spa_decay = input.float(0.995, "🧠 Memory Decay Rate", minval=0.98, maxval=0.9999, step=0.0005, group=G_SPA_ENGINE,
tooltip="Controls recency bias. A value of 0.995 means the AI gives slightly more weight to recent performance. Lower values create a very short-term memory.")
// CONCEPT DRIFT & TRAUMA
bool i_spa_use_drift = input.bool(true, "🌊 Enable Concept Drift & Trauma", group=G_SPA_DRIFT,
tooltip="Allows the engine to detect market regime shocks and trigger a 'Trauma Compression' cycle to accelerate re-learning.")
float i_spa_trauma_sens = input.float(2.0, "Trauma Sensitivity", minval=1.2, maxval=4.0, step=0.1, group=G_SPA_DRIFT,
tooltip="How sensitive the shock detector is. A lower value will trigger trauma cycles more frequently on smaller volatility/volume spikes.")
// DIAGNOSTICS
bool i_spa_show_dash = input.bool(true, "📋 Show Diagnostics Dashboard", group=G_SPA_DASH)
PART II: THE IMPLEMENTATION LOGIC (THE HEART OF YOUR SCRIPT)
This is the boilerplate code you will adapt to your indicator. It shows the complete loop of feeding signals, detecting drift, and selecting the best strategy.
// ╔═══════════════════════════════════════════════════════╗
// ║ USAGE EXAMPLE (ADAPT TO YOUR SCRIPT) ║
// ╚═══════════════════════════════════════════════════════╝
// 1. INITIALIZE THE ENGINE (happens only on the first bar)
int sel_method_id = i_spa_selection == "Thompson Sampling" ? 0 : i_spa_selection == "Upper Confidence Bound (UCB)" ? 1 : i_spa_selection == "Epsilon-Greedy" ? 2 : 3
var spa.SPAEngine engine = spa.init(
num_arms = i_spa_num_arms,
arm_names = array.from("TrendArm", "ReversionArm", "BreakoutArm", "MomentumArm"), // Give your arms names!
selection_method = sel_method_id,
decay_rate = i_spa_decay,
trauma_sensitivity = i_spa_trauma_sens,
epsilon = i_spa_epsilon
)
// 2. DEFINE YOUR STRATEGY SIGNALS (runs on every bar)
// These are your own custom, rule-based strategies. The signal should be +1 for Buy, -1 for Sell, 0 for Neutral.
int trend_signal = close > ta.ema(close, 200) and ta.crossover(ta.ema(close, 20), ta.ema(close, 50)) ? 1 :
close < ta.ema(close, 200) and ta.crossunder(ta.ema(close, 20), ta.ema(close, 50)) ? -1 : 0
int reversion_signal = ta.crossunder(ta.rsi(close, 14), 30) ? 1 : ta.crossover(ta.rsi(close, 14), 70) ? -1 : 0
int breakout_signal = ta.crossover(close, ta.highest(high, 20) ) ? 1 : ta.crossunder(close, ta.lowest(low, 20) ) ? -1 : 0
int momentum_signal = ta.crossover(ta.mom(close, 10), 0) ? 1 : ta.crossunder(ta.mom(close, 10), 0) ? -1 : 0
// Create an array of your signals. The order MUST be consistent.
array all_signals = array.from(trend_signal, reversion_signal, breakout_signal, momentum_signal)
// 3. THE MAIN LOOP (Feed -> Detect -> Select) - runs on every bar
// --- FEED: Update the shadow portfolios with the latest signals and price ---
engine := spa.feed_signals(engine, all_signals, close)
// --- DETECT: Run the concept drift engine ---
if i_spa_use_drift
float trend_slope = ta.linreg(close, 20, 0) - ta.linreg(close, 20, 1)
engine := spa.detect_drift(engine, close, volume, ta.atr(14), trend_slope)
engine := spa.apply_trauma_cycle(engine) // This will compress memory if a shock was detected
// --- SELECT: Ask the engine for its best choice ---
= spa.select(engine)
engine := updated_engine // CRITICAL: Always update the engine state
// --- ACT: Use the final, selected signal for your indicator's logic ---
int final_signal = array.get(all_signals, selected_arm)
string selected_name = spa.get_name(engine, selected_arm)
// Example: Color bars based on the final, SPA-vetted signal
barcolor(final_signal == 1 ? color.new(color.green, 70) : final_signal == -1 ? color.new(color.red, 70) : na)
// 4. DISPLAY DIAGNOSTICS
if i_spa_show_dash and barstate.islast
string diag_text = spa.diagnostics(engine)
label.new(bar_index, high, diag_text,
style=label.style_label_down,
color=color.new(#0A0A14, 10),
textcolor=#00E5FF,
size=size.small,
textalign=text.align_left)
█ DEVELOPMENT PHILOSOPHY
The DafeSPALib was born from the realization that market adaptation is the true holy grail of trading. While any single strategy is brittle, a portfolio of strategies, managed by an intelligent selection algorithm, is antifragile—it can learn, adapt, and potentially thrive in the face of chaos. This library is an open-source tool for the systems thinker, the quantitative analyst, and the professional developer. It is designed to provide the foundational architecture for building the most robust, adaptive, and intelligent trading systems on the TradingView platform.
This library is a tool for that wisdom. It is not about having the single smartest algorithm, but about having a disciplined, data-driven process for selecting the one that is working right now.
█ DISCLAIMER & IMPORTANT NOTES
THIS IS A LIBRARY FOR ADVANCED DEVELOPERS: This script does nothing on its own. It is a powerful engine that must be integrated into other indicators and fed with valid strategy signals.
PERFORMANCE IS HYPOTHETICAL: The shadow portfolio tracking is a simulation. It does not account for slippage, fees (unless manually added to P&L;), or the psychological pressure of live trading.
LEARNING REQUIRES DATA: The selection algorithms require a sufficient number of trades (at least 20-30 per arm) to make statistically meaningful decisions. The engine will be less reliable during the initial "warm-up" period.
"You don't need to be a rocket scientist. Investing is not a game where the guy with the 160 IQ beats the guy with the 130 IQ."
— Warren Buffett
Taking you to school. - Dskyz, Create with RL.
Statistics
Pulse Mean AcceleratorPulse Mean Accelerator (PMA) | MisinkoMaster
Pulse Mean Accelerator (PMA) is a high-speed adaptive trend engine designed to dynamically accelerate or stabilize its behavior depending on how aggressively price moves relative to its underlying structure. Instead of acting like a traditional moving average that simply lags behind price, PMA attempts to anticipate momentum expansion by accelerating when price pulses strengthen and stabilizing when market movement slows.
The result is a responsive yet smooth trend-following tool that adapts to both trending and consolidating markets. PMA is particularly useful for traders who want earlier participation in expanding trends without sacrificing structural clarity.
By combining adaptive acceleration, volatility awareness, and layered smoothing, PMA balances speed and stability to help traders remain aligned with developing momentum.
Key Features
Adaptive acceleration that reacts when price movement intensifies
Automatically slows down during consolidation to reduce noise
Multiple moving average types supported for flexibility
Volatility-aware responsiveness adjustment
Optional confirmation logic to filter weak signals
Multiple smoothing modes for balancing speed vs stability
Dynamic candle coloring reflecting active trend state
Automatic Long and Short markers when direction changes
Works across fast intraday and slower swing environments
Designed to reduce lag while preserving structure
How It Works
Pulse Mean Accelerator begins with a moving average structure but enhances it by measuring how aggressively price moves relative to that baseline. When price starts moving faster than the average, acceleration increases, allowing the indicator to catch up quickly.
When price slows or becomes erratic, acceleration reduces, preventing excessive reaction to noise.
Volatility measurements are incorporated to scale this acceleration, ensuring that responsiveness adapts naturally to current market conditions. Strong moves result in quicker adaptation, while quiet markets lead to smoother, calmer behavior.
Additional smoothing layers can then be applied, allowing traders to choose between faster responsiveness or more stable structure depending on their trading style.
Optional confirmation logic ensures that signals are not triggered solely by temporary price spikes, helping filter weaker moves.
The outcome is a moving average framework that behaves more like a dynamic trend engine rather than a static lagging indicator.
Trend Detection Logic
Trend direction is determined by how price behaves relative to the accelerated mean structure.
Bullish phases occur when price maintains strength above the adaptive mean while momentum confirms upward pressure. Bearish phases occur when price weakens below the structure and downward momentum dominates.
Signals appear when participation shifts strongly enough to confirm directional change, helping traders detect transitions from consolidation to expansion phases.
Acceleration Behavior
A defining characteristic of PMA is its pulse acceleration mechanism.
• Strong price pulses increase responsiveness
• Weak or slow price movement reduces acceleration
• Volatility conditions influence adaptation speed
• Structure remains smooth when momentum is weak
This dynamic adjustment helps traders enter trends earlier while avoiding excessive reactions during sideways markets.
Smoothing Modes
PMA includes multiple smoothing options so users can tune responsiveness:
• Raw acceleration for fastest reaction
• Exponential stabilization for balanced behavior
• Additional smoothing layers for structural clarity
• Double smoothing for maximum noise reduction
This flexibility allows PMA to be tailored for scalping, intraday trading, or higher-timeframe trend following.
Visual Signals
The indicator provides several visual cues for ease of interpretation:
• Candle coloring reflects active trend direction
• Adaptive mean and accelerated mean are plotted together
• Long and Short markers appear when trend shifts occur
• Filled areas highlight separation between price and structure
These features help traders read market structure quickly without relying on numerical interpretation.
Inputs Overview
Users can customize behavior through adjustable components including:
• Price source selection used in calculations
• Moving average type controlling base structure
• Length settings affecting responsiveness
• Acceleration sensitivity determining reaction speed
• Volatility measurement type influencing adaptation
• Smoothing mode selection for stability control
• Optional confirmation filtering for signal validation
These controls allow the tool to be tuned for both aggressive and conservative trading approaches.
Usage Notes
Ideal for traders needing faster adaptation to momentum expansion
Helps detect early stages of trend acceleration
Useful for filtering sideways noise while remaining reactive to breakouts
Works well in volatile assets where traditional averages lag
Can be combined with support/resistance or volume tools for confirmation
Higher smoothing settings suit swing traders, lower smoothing benefits intraday traders
Confirmation mode reduces false signals in choppy markets
Parameter tuning improves performance across different assets
Best Use Scenarios
Pulse Mean Accelerator performs particularly well in:
• Momentum expansion phases
• Breakouts from consolidation ranges
• Trend continuation environments
• High-volatility market conditions
• Assets showing periodic acceleration bursts
• Markets transitioning from low to high volatility
It is especially effective where traditional moving averages react too slowly to developing moves.
Summary
Pulse Mean Accelerator transforms traditional moving average logic into an adaptive trend engine capable of accelerating when price momentum expands and stabilizing during calm conditions. By blending acceleration, volatility awareness, and flexible smoothing, it provides traders with a faster yet structured view of market direction.
PMA is best suited for traders seeking earlier trend participation while maintaining smooth, readable structure across both fast-moving and consolidating markets.
Logarithmic Fair Value Anchor | PWLogarithmic Fair Value Anchor
This indicator overlays a dynamic "fair value" estimate on the price chart, anchored to the momentum and historical relationship of a user-selected reference asset (e.g., gold, broad liquidity proxies, or major indices). It combines logarithmic deviation analysis with relative valuation to adapt to the anchor's behavior, offering a flexible tool for exploring cross-asset divergences, mean-reversion setups, and contextual extremes.
Core Mechanics and Math Overview
The fair value starts with a baseline: an EMA-smoothed ratio of price to the anchor over the lookback period (default 180 bars). This ratio reflects the historical "normal" relationship between the chart symbol and the anchor.
Anchor momentum is added via the smoothed 1-period ROC of the anchor, scaled by a user-adjustable Momentum Influence Scale (default 5.0 — lower values increase responsiveness). This scaled influence is exponentially applied to adjust the baseline ratio. An optional correlation filter weights the adjustment using absolute log-price correlation (with threshold and manual multiplier). The result is DEMA-smoothed (default length 14) for a responsive yet stable fair value line.
Deviation bands are built multiplicatively around this fair value using exp(deviation * level), preserving log-scale compatibility. Three band types are available:
Log Stdev: Standard deviation of log(price / fair value) — dynamic, volatility-responsive.
Static Sigma: Fixed user-defined deviation (default 0.15) — consistent relative widths.
ATR: Relativized ATR converted to log deviation — range-based smoothing for volatile markets.
Bands use asymmetric multipliers (defaults 1.8 upper / 1.25 lower) with three levels, fills, and markers for visual clarity.
Key Features
Anchor Flexibility: Choose from Gold (XAUUSD), Silver (XAGUSD), S&P 500 (SPX), BTC, or experimental proxies (GLI/M2 aggregates from FRED/ECONOMICS data).
Trend and Visuals: Trend detection (price vs. offset fair value) with optional bar coloring, background highlights for extremes, and diamond markers for overbought/oversold.
Enhanced Info Table (toggleable): Shows current fair value, selected anchor, band type, bias (LONG/SHORT/NEUTRAL), trend duration, trend quality (% clean bars), strength rating (icon-based), z-score deviation (effective band multiple in sigmas + approximate percentile), and valuation (Overvalued/Undervalued/Fair).
Customization: Lookback, offset, smoothing, momentum scale, correlation weighting, band type, multipliers, bar color toggle — adaptable to different assets/timeframes.
What Makes This Approach Distinct
The script uses a smoothed price-to-anchor ratio as its baseline, then applies scaled logarithmic momentum influence to create a fair value that respects both history and external dynamics. This differs from pure moving averages or direct ratio models by incorporating cross-asset momentum in a log framework. Band variety and detailed trend quality/strength metrics provide practical tools for navigating volatility regimes and assessing trend reliability — features not commonly combined in one overlay.
Usage Suggestions
Crypto: Anchor to GLI/M2 for liquidity context; ATR bands help manage volatility. Watch high z-score/percentile or low trend quality for reversals.
Equities/Commodities: Gold for inflation views, S&P for market ties; static sigma for stable benchmarks.
General Tips: Use log scale for visual alignment. Offset (default 90) projects fair value forward. Leverage table metrics — e.g., quality >80% for stronger trends, strength icons for momentum conviction, valuation extremes for mean-reversion ideas. Test anchors and scales to fit your market.
This is an exploratory relative-valuation overlay — results vary by anchor, conditions, and settings. Not financial advice; backtest thoroughly and verify independently.
Notes
Pine Script v6; requires access to external symbols via request.security().
Minor repainting possible on realtime bars due to smoothing and external data.
Community feedback welcome for refinements!
Market Regime AnalyzerStatistical regime detection with forward-looking transition probabilities. Combines drift testing, variance ratios, and volume delta to classify markets into 5 regimes and quantify transition probabilities.
What Regime Are We In, and What's Likely Next?
That's the question this indicator answers with statistical rigor and forward-looking probabilities.
The Problem:
Most traders classify regimes arbitrarily: "Bull if price > 200 MA" or "Bear if RSI < 30." These rules ignore statistical significance, volume confirmation, and mean reversion patterns. The result? Late entries, false signals, and confusion when markets transition.
The Solution:
Market Regime Analyzer combines drift detection, variance ratio testing, and volume delta analysis to classify markets into 5 distinct regimes. Then it calculates the probability of transitioning to each regime based on historical patterns.
The Benefit:
Know not just where you are, but where you're likely going - with probabilities, not guesses.
The Five Market Regimes
🟢 Strong Bull (Regime 1)
- Statistically significant upward drift (t-stat > 1.96)
- Strong buying pressure (volume delta > 0.3)
- No mean reversion detected
- **Trade:** Trend-following strategies, ride the momentum
🟢 Weak Bull (Regime 2)
- Upward drift present
- BUT weak volume OR mean reversion detected
- **Trade:** Reduce position size, tighten stops, prepare for consolidation
⚪ Consolidation (Regime 3)
- No statistically significant drift
- Mixed volume signals
- Mean reversion likely present
- **Trade:** Range-trading, avoid trend-following systems
🔴 Weak Bear (Regime 4)
- Downward drift present
- BUT weak volume pressure
- **Trade:** Cautious shorts, reduce exposure, prepare for bounce
🔴 Strong Bear (Regime 5)
- Statistically significant downward drift (t-stat < -1.96)
- Strong selling pressure (volume delta < -0.3)
- No mean reversion detected
- **Trade:** Trend-following shorts, protective puts
The Statistical Framework
1. Drift Detection with T-Statistics
Instead of guessing if there's a trend, we test it statistically.
How it works:
- Calculates mean return over lookback period
- Standardizes by volatility
- Compares to significance threshold (default 1.96 = 95% confidence)
What it tells you:
- T-stat > 1.96: Statistically significant uptrend
- T-stat < -1.96: Statistically significant downtrend
- In between: No significant trend (consolidation)
Why it matters:
Only trades trends that are statistically validated, not just visually apparent.
2. Mean Reversion Testing (Variance Ratio)
Based on Lo & MacKinlay (1988) research, this detects when markets are range-bound.
How it works:
- Compares variance at different time scales
- Variance Ratio < 0.8 indicates mean reversion
What it tells you:
- Mean reversion = NO: Trends can continue
- Mean reversion = YES: Expect price to return to mean, not breakout
Why it matters:
Prevents chasing breakouts in range-bound markets.
3. Volume Delta Analysis
Total volume tells you HOW MUCH traded. Volume delta tells you WHO won.
How it works:
- Buying pressure - Selling pressure = Volume Delta
- Normalized to show relative strength
What it tells you:
- Strong positive delta (>0.3): Buyers in control
- Strong negative delta (<-0.3): Sellers in control
- Weak delta: No clear winner
Why it matters:
Price can move up on weak buying or down on weak selling. Volume delta reveals the truth.
4. Transition Probability Matrix
Historical regime changes predict future regime changes.
How it works:
- Tracks every regime transition over last 100 bars (configurable)
- Builds probability distribution for next regime
- Updates continuously
Example:
Current: Strong Bull
Historical transitions from Strong Bull:
- Stayed Strong Bull: 45%
- Became Weak Bull: 30%
- Became Consolidation: 20%
- Became Weak Bear: 4%
- Became Strong Bear: 1%
What it tells you:
Strong Bull has 75% chance of staying bullish (45% + 30%), only 5% chance of bearish turn.
Why it matters:
Adapts to your specific market's behavior patterns.
How to Use This Indicator
Strategy Adaptation
In Strong Bull/Bear Regimes:
- Use trend-following strategies
- Wider stops, let winners run
- Add to positions on pullbacks
- High confidence in directional trades
In Weak Bull/Bear Regimes:
- Reduce position sizes by 50%
- Tighter stops
- Take profits earlier
- Prepare for regime change
In Consolidation:
- Switch to range-trading strategies
- Avoid trend-following systems
- Sell resistance, buy support
- Wait for regime change before trend trades
Risk Management
Position Sizing:
- Strong regime + high continuation probability (>60%) = Normal size
- Weak regime OR high transition probability = Half size
- Consolidation = Quarter size or skip
Stop Loss Placement:
- Strong regime: Use wider stops (2x ATR)
- Weak regime: Tighter stops (1x ATR)
- Consolidation: Very tight stops (0.5x ATR)
Entry Timing
Best entries:
- Regime just changed to Strong Bull/Bear
- High probability (>50%) of staying in current regime
- No divergence signals present
- Drift and volume delta aligned
Avoid entries:
- High probability of regime change
- Divergence signals appearing
- Mean reversion detected in trending regime
- Weak volume despite price movement
Reading the Dashboard
Current Regime
Color-coded for instant recognition:
- Dark Green = Strong Bull
- Light Green = Weak Bull
- Gray = Consolidation
- Light Red = Weak Bear
- Dark Red = Strong Bear
Annualized Drift
Expected annual return based on recent trend.
- Positive = Upward bias
- Negative = Downward bias
- Near zero = No directional edge
T-Statistic
Measures statistical significance of drift.
- > 1.96 = 95% confident in uptrend
- < -1.96 = 95% confident in downtrend
- Between = Not statistically significant
Mean Reversion
- Yes = Expect price to return to mean (range-bound)
- No = Trends can continue (trending market)
Volume Pressure
Normalized volume delta strength.
- > 0.3 = Strong buying
- < -0.3 = Strong selling
- Near 0 = Balanced
Transition Probabilities
Shows most likely next regime.
- Highest probability = Most likely outcome
- Evenly distributed = High uncertainty
- Concentrated = High confidence in direction
Practical Examples
Example 1: Strong Bull with High Continuation
Dashboard shows:
Current Regime: Strong Bull
Drift: +22% annualized
T-Stat: 3.2
Mean Reversion: No
Volume Pressure: +0.45
Probabilities:
→ Strong Bull: 50%
→ Weak Bull: 25%
→ Consolidation: 20%
→ Bears: 5%
Interpretation:
- Strong uptrend (t-stat 3.2 >> 1.96)
- No mean reversion = trends can continue
- Strong buying pressure (0.45 > 0.3)
- 75% chance stays bullish (50% + 25%)
Action:
- Full position size on long setups
- Use trend-following entries
- Wider stops (2x ATR)
- High conviction trades
Example 2: Weak Bull Before Consolidation
Dashboard shows:
Current Regime: Weak Bull
Drift: +8% annualized
T-Stat: 1.2
Mean Reversion: Yes
Volume Pressure: +0.15
Probabilities:
→ Strong Bull: 10%
→ Weak Bull: 30%
→ Consolidation: 50%
→ Weak Bear: 10%
Interpretation:
- Weak drift (t-stat 1.2 < 1.96)
- Mean reversion detected = range-bound likely
- Weak volume (0.15 < 0.3)
- 50% chance of consolidation
Action:
- Reduce long positions
- Tighten stops
- Prepare for range-bound trading
- Avoid new trend trades
Example 3: Regime Transition Alert
Previous: Weak Bull
Current: Consolidation
Volume divergence signal appeared:
Price made new high, volume delta weakened
Interpretation:
- Trend exhausted
- Buyers losing control
- Regime confirmed the transition
Action:
- Exit trend-following longs
- Switch to range-trading approach
- Wait for new regime before new directional trades
Settings Guide
### Regime Detection Period (50)
Number of bars for statistical calculations.
- **30-40:** More responsive, catches changes faster, more regime switches
- **50 (default):** Balanced for daily/4H charts
- **75-100:** More stable, fewer false regime changes, slower to adapt
Transition History Depth (100)
How much history to use for probabilities.
- **50-75:** Adapts quickly to recent behavior
- **100 (default):** Balanced robustness
- **150-200:** More stable probabilities, slower to adapt
Volume Delta Period (14)
Period for volume calculations.
- **7-10:** More sensitive to volume shifts
- **14 (default):** Standard period
- **20-30:** Smoother, less noise
Significance Threshold (1.96)
T-statistic required for trend classification.
- **1.64:** 90% confidence, more trend regimes detected
- **1.96 (default):** 95% confidence, balanced
- **2.58:** 99% confidence, very conservative, mostly consolidation
Best Practices
Do:
- Wait for regime confirmation (at least 3-5 bars in new regime)
- Use probabilities to size positions appropriately
- Combine with support/resistance for entries
- Respect mean reversion signals
- Adapt strategy to current regime
Don't:
- Trade every regime change immediately
- Ignore high transition probabilities
- Use trend strategies in consolidation
- Override statistical signals with gut feel
- Trade against Strong regimes without clear setup
Timeframe Recommendations
Daily Charts:
- Default settings work well
- Most reliable regime detection
- Best for swing trading
4H Charts:
- Use default or slightly higher lookback (60-75)
- Good for active swing trading
- More regime changes than daily
1H Charts:
- Reduce lookback to 30-40
- More noise, use with caution
- Better for intraday position trading
15M and below:
- Not recommended
- Too much noise for statistical validity
- Regimes change too frequently
Combining with Other Indicators
Works Well With:
Moving Averages
- Use regime for directional bias
- MAs for specific entry/exit points
Support/Resistance
- Regime shows context
- S/R shows specific levels
- High probability at confluence
Volume Profile
- Regime shows regime
- Profile shows where volume is
- Target high-volume nodes
RSI/MACD
- Regime provides context
- Momentum shows entry timing
- Combine for higher probability
Example Combined Setup
Regime: Strong Bull
Price: Above 200 MA
Level: Pullback to support
RSI: Oversold (30)
Volume Delta: Still positive
Setup: Long entry
Reason: Trend intact, healthy pullback, buyers still present
Divergence Signals
The indicator shows volume divergence warnings:
Bearish Divergence (Red Triangle Down)
- Price makes new high
- Volume delta makes lower high
- Warning: Buyers weakening, potential reversal
Bullish Divergence (Green Triangle Up)
- Price makes new low
- Volume delta makes higher low
- Warning: Sellers weakening, potential reversal
How to use:
- Divergence in Strong regime = early warning of regime change
- Confirms when regime actually transitions
- Don't trade divergence alone, wait for regime confirmation
Limitations
This Indicator Cannot:
**Predict black swan events** - Unexpected news overrides all technical regimes
**Work in all markets** - Needs liquid markets with reliable volume data
**Guarantee profits** - Probabilities are not certainties
**Replace fundamental analysis** - Technical regimes can diverge from fundamentals
Works Best:
- Liquid markets (major indices, forex, crypto, large-cap stocks)
- Daily and 4H timeframes
- Combined with other analysis
- With proper risk management
- In normal market conditions
Common Questions
"Why did the regime stay consolidation despite strong price move?"
The indicator detected mean reversion (variance ratio < 0.8), indicating the move will likely reverse. Or the move wasn't statistically significant (t-stat < 1.96). Trust the statistics over visual appearance.
"Probabilities show 30% for each regime. What does that mean?"
High uncertainty. The market is at an inflection point. Reduce position sizes and wait for clearer regime formation.
"Can I use this for day trading?"
Not recommended on timeframes below 1H. Statistical tests need sufficient data. Better suited for swing trading.
"Why does this show Strong Bull when my momentum indicators show weakness?"
Momentum can weaken while the trend remains statistically significant. The indicator focuses on drift and volume, not momentum. Consider it a different perspective.
Technical Notes
Volume Delta Approximation
Uses OHLCV data to approximate order flow:
- Buy volume ≈ Volume on up-closes
- Sell volume ≈ Volume on down-closes
- Delta = Buy - Sell
**Note:** Real order flow (from futures or Level 2) is more precise. This approximation works well on liquid markets.
Statistical Tests
Drift T-Test:
- Null hypothesis: No drift (mean return = 0)
- Reject if |t-stat| > threshold
- Based on standard hypothesis testing
Variance Ratio:
- Compares 2-period variance to 1-period variance
- Ratio = 1 for random walk
- Ratio < 1 for mean reversion
- Threshold of 0.8 based on empirical testing
Transition Probability Implementation
Due to Pine Script v5 limitations (no native 2D arrays), the 5×5 transition matrix is stored as a flat 1D array of 25 elements:
- Position maps to index: `row × 5 + col`
- Example: Transition from Regime 2 to Regime 4 is at index `1 × 5 + 3 = 8`
- Laplace smoothing (0.1) prevents zero probabilities
- Row sums normalized to calculate probabilities
This approach is computationally efficient and maintains statistical accuracy.
No Repainting
All calculations confirmed on bar close. Regime changes appear when the bar closes, not during formation. Historical analysis is accurate.
Alert Conditions
Regime Change
- Triggers when regime transitions to any new state
- Message shows new regime number (1-5)
Bearish Divergence
- Triggers when price makes new high but volume delta doesn't confirm
Bullish Divergence
- Triggers when price makes new low but volume delta doesn't confirm
Disclaimer
FOR EDUCATIONAL PURPOSES ONLY
This indicator uses statistical methods to analyze market regimes. It does not predict the future or guarantee trading success.
Markets are probabilistic, not deterministic. A 70% probability of staying bullish means 30% chance of regime change. Always use proper risk management.
Past regime transitions do not guarantee future transitions. Market structure can change. Statistical relationships can break down.
Never risk more than you can afford to lose. Use stop losses on every trade. Test thoroughly before live trading. Consult a qualified financial advisor.
© 2026 | Open Source
Statistical rigor meets practical application
Seasonality (100% reliable for the W)Quant Seasonality Pro (QuantSeaz)
Quant Seasonality Pro is a data-driven seasonal projection tool that extracts historical day-of-year return patterns and transforms them into a forward-looking price curve. Using log returns, cycle filters, and volatility-based scaling (ATR), it generates a dynamically anchored seasonal roadmap directly on your chart.
The indicator allows you to switch between Trading Days (stocks/forex) and Calendar Days (crypto), apply U.S. election cycle filters, and analyze historical data precisly. The projected curve is detrended to isolate true seasonal structure and then scaled to current market volatility for realistic visualization.
A built-in statistical dashboard provides:
Confidence (%) based on historical win rates
Expected Alpha (%) over the selected forward window
ATR % (noise level)
Viability ratio (Alpha adjusted for risk)
This tool is designed for contextual edge — not signal automation. It helps traders align positioning with historical seasonal tendencies while maintaining proper risk management and independent confirmation.
29 Sniper Execution Window (UTC-5)29 Sniper Execution Window (UTC-5)
This indicator highlights the exact time window I execute my 29 Sniper model — 9:35 to 10:10 New York time.
This is the only period I allow trades.
Liquidity has been engineered, direction is revealed, and higher-timeframe FVG magnets are in play. Anything outside this window is noise.
The shaded session removes hesitation, eliminates FOMO, and keeps execution disciplined and repeatable.
No chasing. No guessing. Just execution when the market is ready.
Rules are simple:
If it sets up in the window, I take it.
If it doesn’t — I do nothing.
This tool exists to protect edge, not create signals.
Volume Z-Score Volume Z-Score measures how current volume deviates from its historical average to detect extreme market activity or exhaustion.
DafeRLMLLibDafeRLMLLib: The Reinforcement Learning & Machine Learning Engine
This is not an indicator. This is an artificial intelligence. A state-based, self-learning engine designed to bring the power of professional quantitative finance to the Pine Script ecosystem. Welcome to the next frontier of trading analysis.
█ CHAPTER 1: THE PHILOSOPHY - FROM STATIC RULES TO DYNAMIC LEARNING
Technical analysis has, for a century, been a discipline of static, human-defined rules. "If RSI is below 30, then buy." "If the 50 EMA crosses the 200 EMA, then sell." These are fixed heuristics. They are brittle. They fail to adapt to the market's ever-changing personality—its shifts between trend and range, high and low volatility, risk-on and risk-off sentiment. An indicator built on static rules is an automaton, destined to fail when the environment it was designed for inevitably changes.
The DafeRLMLLib was created to shatter this paradigm. It is not a tool with fixed rules; it is a framework for discovering optimal rules. It is a true Reinforcement Learning (RL) and Machine Learning (ML) engine, built from the ground up in Pine Script. Its purpose is not to follow a pre-programmed strategy, but to learn a strategy through trial, error, and feedback.
This library provides a complete, professional-grade toolkit for developers to build indicators that think, adapt, and evolve. It observes the market state, selects an action, receives a reward signal based on the outcome, and updates its internal "brain" to improve its future decisions. This is not just a step forward; it is a quantum leap into the future of on-chart intelligence.
█ CHAPTER 2: THE CORE INNOVATIONS - WHAT MAKES THIS A TRUE ML ENGINE?
This library is not a collection of simple moving averages labeled as "AI." It is a suite of genuine, academically recognized machine learning algorithms, adapted for the unique constraints and opportunities of the Pine Script environment.
Multi-Algorithm Architecture: You are not locked into one learning model. The library provides a choice of powerful RL algorithms:
Q-Learning with TD(λ) Eligibility Traces: A classic, robust algorithm for learning state-action values. We've enhanced it with eligibility traces (Lambda), allowing the agent to more efficiently assign credit or blame to a sequence of past actions, dramatically speeding up the learning process.
REINFORCE Policy Gradient with Baseline: A more advanced method that directly learns a "policy"—a probability distribution over actions—instead of just values. The baseline helps to stabilize learning by reducing variance.
Actor-Critic Architecture: The state-of-the-art. This hybrid model combines the best of both worlds. The "Actor" (the policy) decides what to do, and the "Critic" (the value function) evaluates how good that action was. The Critic's feedback is then used to directly improve the Actor's decisions.
Prioritized Experience Replay: Like a human, the AI learns more from surprising or significant events. Instead of learning from experiences in a simple chronological order, the library stores them in a ReplayBuffer. It then replays these memories to the learning algorithms, prioritizing experiences that resulted in a large prediction error. This makes learning incredibly efficient.
Meta-Learning & Self-Tuning: An AI that cannot learn how to learn is still a dumb machine. The MetaState module is a meta-learning layer that monitors the agent's own performance over time. If it detects that performance is degrading, it will automatically increase the learning rate ("Synaptic Plasticity"). If performance is improving, it will decrease the learning rate to stabilize the learned strategy. It tunes its own hyperparameters.
Catastrophic Forgetting Prevention: A common failure mode for simple neural networks is "catastrophic forgetting," where learning a new task completely erases knowledge of a previous one. This library includes mechanisms like soft_reset and L2 regularization to prevent the agent's learned weights from exploding or being wiped out by a single bad run of trades, ensuring more stable, long-term learning.
The Universal Socket Interface: How does the AI "see" the market? Through DataSockets. This brilliant, extensible interface allows a developer to connect any data series—an RSI, a volume metric, a volatility reading, a custom calculation—to the AI's "brain." Each socket normalizes its input, tracks its own statistics, and feeds into the state-building process. This makes the library universally adaptable to any trading idea.
█ CHAPTER 3: A DUAL-PURPOSE FRAMEWORK - MODES OF OPERATION
This library is a foundational component of the DAFE AI ecosystem, designed for ultimate flexibility. It can be used in two primary modes: as a powerful standalone intelligence, or as the core cognitive engine within a larger, bridged super-system. Understanding these modes is key to unlocking its full potential.
MODE 1: STANDALONE ENGINE OPERATION (Independent Power
The DafeRLMLLib can be used entirely on its own to create a complete, self-learning trading indicator. This approach is perfect for building focused, single-purpose tools that are designed to master a specific task. In this mode, the developer is responsible for creating the full feedback loop within their own indicator script.
The Workflow:
Your indicator initializes the ML agent.
On each bar, it feeds the agent market data via the socket interface.
It asks the agent for an action (e.g., Buy, Sell, Hold).
Your script then executes its own internal trade logic based on the agent's decision.
Your script is responsible for tracking the Profit & Loss (PnL) of the resulting simulated trade.
When the trade is closed, your script feeds the final PnL directly back into the agent's learn() function as the "reward" signal.
The Result: A pure, state-based learning system. The agent directly learns the consequences of its own actions. This is excellent for discovering novel, micro-level trading patterns and for building indicators that are designed to operate with complete autonomy.
MODE 2: BRIDGED SUPER-SYSTEM OPERATION (Synergistic Intelligence)
This is the pinnacle of the DAFE ecosystem. In this advanced mode, the DafeRLMLLib acts as the core "cognitive engine" or the "tactical brain" within a larger, multi-library system. It can be fused with a strategic portfolio management engine (like the DafeSPALib) via a master communication protocol (the DafeMLSPABridge).
The Workflow:
The ML engine (this library) generates a set of creative, state-based proposals or predictions.
The Bridge Library translates these proposals into a portfolio of micro-strategies.
The SPA (Strategy Portfolio Allocation) engine, acting as a high-level manager, analyzes the real-time performance of these micro-strategies and selects the one it trusts the most. This becomes the final decision. The PnL from the SPA's final, performance-vetted decision is then routed back through the Bridge as a highly-qualified reward signal for the ML engine.
The Result: A hybrid intelligence that is more robust and adaptive than either system alone. The ML engine provides tactical creativity, while the SPA engine provides ruthless, strategic, performance-based oversight. The ML proposes, the SPA disposes, and the ML learns from the SPA's wisdom. This creates a system of checks, balances, and continuous, synergistic learning, perfect for building an ultimate, all-in-one "drawing indicator" or trading system.
As a developer, the choice is yours. Use this library independently to build powerful, specialized learning tools, or use it as the foundational brain for a truly comprehensive trading AI.
█ CHAPTER 4: A GUIDE FOR DEVELOPERS - INTEGRATING THE BRAIN
We have made it incredibly simple to bring your indicators to life with the DAFE AI. This is the true purpose of the library—to empower you. This section provides the full, unabridged input template and usage guide.
PART I: THE INPUTS TEMPLATE
To give your users full control over the AI, copy this entire block of inputs into your indicator script. It is professionally organized with groups and detailed tooltips.
// ╔═════════════════════════════════════════════════════╗
// ║ INPUTS TEMPLATE (COPY INTO YOUR SCRIPT) ║
// ╚═════════════════════════════════════════════════════╝
// INPUT GROUPS
string G_RL_AGENT = "═══════════ 🧠 AGENT CONFIGURATION ════════════"
string G_RL_LEARN = "═══════════ 📚 LEARNING PARAMETERS ═══════════"
string G_RL_REWARD = "═══════════ 💰 REWARD SYSTEM ═══════════════"
string G_RL_REPLAY = "═══════════ 📼 EXPERIENCE REPLAY ════════════"
string G_RL_META = "═══════════ 🔮 META-LEARNING ═══════════════"
string G_RL_DASH = "═══════════ 📋 DIAGNOSTICS DASHBOARD ═════════"
// AGENT CONFIGURATION
string i_rl_algorithm = input.string("Actor-Critic", "🤖 Algorithm",
options= , group=G_RL_AGENT,
tooltip="Selects the core learning algorithm. " +
"• Q-Learning: Classic, robust, and fast for discrete states. Learns the 'value' of actions. " +
"• Policy Gradient: Learns a direct probability distribution over actions. " +
"• Actor-Critic: The state-of-the-art. The 'Actor' decides, the 'Critic' evaluates. " +
"• Ensemble: Runs both Q-Learning and Policy Gradient and chooses the action with the highest confidence. " +
"RECOMMENDATION: Start with 'Q-Learning' for stability or 'Actor-Critic' for performance.")
int i_rl_num_features = input.int(8, "Number of Features (Sockets)", minval=2, maxval=12, group=G_RL_AGENT,
tooltip="Defines the size of the AI's 'vision'. This MUST match the number of sockets you connect.")
int i_rl_num_actions = input.int(3, "Number of Actions", minval=2, maxval=5, group=G_RL_AGENT,
tooltip="Defines what the AI can do. 3 is standard (0=Neutral, 1=Buy, 2=Sell).")
// LEARNING PARAMETERS
float i_rl_learning_rate = input.float(0.05, "🎓 Learning Rate (Alpha)", minval=0.001, maxval=0.2, step=0.005, group=G_RL_LEARN,
tooltip="How strongly the AI updates its knowledge. Low (0.01-0.03) is stable. High (0.1+) is aggressive.")
float i_rl_discount = input.float(0.95, "🔮 Discount Factor (Gamma)", minval=0.8, maxval=0.99, step=0.01, group=G_RL_LEARN,
tooltip="Determines the agent's 'foresight'. High (0.95+) for trend following. Low (0.85) for scalping.")
float i_rl_epsilon = input.float(0.15, "🧭 Exploration Rate (Epsilon)", minval=0.01, maxval=0.5, step=0.01, group=G_RL_LEARN,
tooltip="For Q-Learning. The probability of taking a random action to explore. Decays automatically over time.")
float i_rl_lambda = input.float(0.7, "⚡ Eligibility Trace (Lambda)", minval=0.0, maxval=0.95, step=0.05, group=G_RL_LEARN,
tooltip="For Q-Learning. A powerful accelerator that allows a reward to be 'traced' back through a sequence of actions.")
// REWARD SYSTEM
string i_rl_reward_mode = input.string("Normalized", "💰 Reward Shaping Mode",
options= , group=G_RL_REWARD,
tooltip="Modifies the raw PnL reward signal to guide learning. " +
"• Normalized: Creates a stable reward signal (Recommended). " +
"• Asymmetric: Punishes losses more than it rewards gains. Teaches risk aversion. " +
"• Risk-Adjusted: Divides PnL by risk (e.g., ATR). Teaches better risk/reward.")
// EXPERIENCE REPLAY
bool i_rl_use_replay = input.bool(true, "📼 Enable Experience Replay", group=G_RL_REPLAY,
tooltip="Allows the agent to store and re-learn from past experiences. Dramatically improves learning stability. HIGHLY RECOMMENDED.")
int i_rl_replay_capacity = input.int(500, "Replay Buffer Size", minval=100, maxval=2000, group=G_RL_REPLAY)
int i_rl_replay_batch = input.int(4, "Replay Batch Size", minval=1, maxval=10, group=G_RL_REPLAY)
// META-LEARNING
bool i_rl_use_meta = input.bool(true, "🔮 Enable Meta-Learning", group=G_RL_META,
tooltip="Allows the agent to self-tune its own learning rate based on performance trends.")
// DIAGNOSTICS DASHBOARD
bool i_rl_show_dash = input.bool(true, "📋 Show Diagnostics Dashboard", group=G_RL_DASH)
PART II: THE IMPLEMENTATION LOGIC
This is the boilerplate code you will adapt to your indicator. It shows the complete Observe-Act-Learn loop.
// ╔═══════════════════════════════════════════════════════╗
// ║ USAGE EXAMPLE (ADAPT TO YOUR SCRIPT) ║
// ╚═══════════════════════════════════════════════════════╝
// 1. INITIALIZE THE AGENT (happens only on the first bar)
int algo_id = i_rl_algorithm == "Q-Learning" ? 0 : i_rl_algorithm == "Policy Gradient" ? 1 : i_rl_algorithm == "Actor-Critic" ? 2 : 3
int reward_id = i_rl_reward_mode == "Raw PnL" ? 0 : i_rl_reward_mode == "Normalized" ? 1 : i_rl_reward_mode == "Asymmetric" ? 2 : 3
var rl.RLAgent agent = rl.init(algo_id, i_rl_num_features, i_rl_num_actions, i_rl_learning_rate, 54, i_rl_replay_capacity, i_rl_epsilon, i_rl_discount, i_rl_lambda, reward_id)
// 2. CONNECT THE "SENSES" (happens only on the first bar)
if barstate.isfirst
// Connect your indicator's data series to the AI's sockets. The number MUST match 'i_rl_num_features'.
agent := rl.connect_socket(agent, "rsi", ta.rsi(close, 14), "oscillator", 1.0)
agent := rl.connect_socket(agent, "atr_norm", ta.atr(14)/close*100, "custom", 0.8)
// ... connect all other features ...
// 3. THE MAIN LOOP (Observe -> Act -> Learn) - runs on every bar
var bool in_trade = false
var int trade_direction = 0
var float entry_price = 0.0
var int last_state_hash = 0
var int last_action_taken = 0
// --- OBSERVE: Build the current market state ---
rl.RLState current_state = rl.build_state(agent)
// --- ACT: Ask the AI for a decision ---
= rl.select_action(agent, current_state)
agent := updated_agent // CRITICAL: Always update the agent state
// --- EXECUTE: Your custom trade logic goes here ---
if not in_trade and ai_action.action != 0 // Assuming 0 is "Hold"
in_trade := true
trade_direction := ai_action.action == 1 ? 1 : -1 // Assuming 1=Buy, 2=Sell
entry_price := close
last_state_hash := current_state.hash // Store the state at the moment of entry
last_action_taken := ai_action.action
// --- LEARN: Check for trade closure and provide feedback ---
bool trade_is_closed = false
float reward = 0.0
if in_trade
// Your custom exit condition here (e.g., stop loss, take profit, opposite signal)
bool exit_condition = bar_index > ta.valuewhen(in_trade, bar_index, 0) + 20
if exit_condition
trade_is_closed := true
pnl = trade_direction == 1 ? (close - entry_price) / entry_price : (entry_price - close) / entry_price
reward := pnl * 100
in_trade := false
// If a trade was closed on THIS bar, feed the experience to the AI
if trade_is_closed
agent := rl.learn(agent, last_state_hash, last_action_taken, reward, current_state, true)
// 4. DISPLAY DIAGNOSTICS
if i_rl_show_dash and barstate.islast
string diag_text = rl.diagnostics(agent)
label.new(bar_index, high, diag_text, style=label.style_label_down, color=color.new(#0A0A14, 10), textcolor=#00FF41, size=size.small, textalign=text.align_left)
█ DEVELOPMENT PHILOSOPHY
The DafeRLMLLib was born from a desire to push the boundaries of Pine Script and to empower the entire TradingView developer community. We believe that the future of technical analysis is not just in creating more complex algorithms, but in building systems that can learn, adapt, and optimize themselves. This library is an open-source framework designed to be a launchpad for a new generation of truly intelligent indicators on TradingView.
This library is designed to help you and your users discover what "the best trades" are, not by following a fixed set of rules, but by learning from the market's own feedback, one trade at a time.
█ DISCLAIMER & IMPORTANT NOTES
THIS IS A LIBRARY FOR ADVANCED DEVELOPERS: This script does nothing on its own. It is a powerful engine that must be integrated into other indicators.
REINFORCEMENT LEARNING IS COMPLEX: RL is not a magic bullet. It requires careful feature engineering (choosing the right sockets), a well-defined reward signal, and a sufficient amount of training data (trades) to converge on a profitable strategy.
ALL TRADING INVOLVES RISK: The AI's decisions are based on statistical probabilities learned from past data. It does not predict the future with certainty.
"The goal of a successful trader is to make the best trades. Money is secondary."
— Alexander Elder
Taking you to school. - Dskyz, Create with RL.
Initial Balance FDAX1!Initial Balance FDAX — a fork of the original Initial Balance indicator by noop-noop, adapted specifically for FDAX / GER40 trading.
What's changed:
🕐 Timezone-proof IB detection — the script uses hour(time, "Europe/Berlin") internally, so the Initial Balance is always calculated correctly regardless of your chart's timezone setting. No more manual time shifting. DST (CET ↔ CEST) is handled automatically.
📻 Two IB session modes:
Frankfurt Trading Hours — IB 08:00–09:00 CET (Frankfurt trading opens at 08:00)
XETRA — IB 09:00–10:00 CET (XETRA cash market opens at 09:00)
⚙️ A.T. default settings — all default values are pre-configured for the Fix PIPS community setup. Use TradingView's built-in Defaults → Reset to defaults to restore them at any time.
All original features preserved: IB levels (IBH/IBL/IBM), extensions (x2, x3), 50% intermediate levels, IB delta analytics, customizable colors and line styles.
Credits: Based on the original work by noop-noop. Forked and customized for the Fix PIPS community.
WickPressureLibWickPressureLib: The Regime Dynamics Engine
DESCRIPTION:
WickPressureLib/b] is not a standard candlestick pattern library. It is an advanced analytical engine designed to deconstruct the internal dynamics of price action. It provides a definitive toolkit for analyzing candle microstructure and quantifying order flow pressure through statistical modeling.
█ CHAPTER 1: THE PHILOSOPHY — BEYOND PATTERNS, INTO DYNAMICS
A candlestick wick represents a specific market event: a rejection of price. Traditional analysis often labels these simply as "bullish" or "bearish." This library aims to go deeper by treating each candle as a dataset of opposing forces.
The WickPressureLib translates static price action into dynamic metrics. It deconstructs the candle into core components and subjects them to multi-layered analysis. It calculates Kinetic Force , estimates institutional Delta , tracks the Siege Decay of key levels, and uses Thompson Sampling (a Bayesian probability algorithm) to assess the statistical weight of each formation.
This library does not just identify patterns; it quantifies the forces that create them. It is designed for developers who need quantitative, data-driven metrics rather than subjective interpretation.
█ CHAPTER 2: THE ANALYTICAL PIPELINE — SIX LAYERS OF LOGIC
The engine's capabilities come from a six-stage processing pipeline. Each layer builds upon the last to create a comprehensive data object.
LAYER 1 — DELTA ESTIMATION: Uses a proprietary model to approximate order flow (Delta) within a single candle based on the relationship between wicks, body, and total range.
LAYER 2 — SIEGE ANALYSIS: A concept for measuring structural integrity. Every time a price level is tested by a wick, its "Siege Decay" score is updated. Repeated tests without a breakout result in a decayed score, indicating weakening support/resistance.
LAYER 3 — MAGNETISM ENGINE: Calculates the probability of a wick being "filled" (mean reversion) based on trend strength and volume profile. Distinguishes between rejection wicks and exhaustion wicks.
LAYER 4 — REGIME DETECTION: Context-aware analysis using statistical tools— Shannon Entropy (disorder), DFA (trend vs. mean-reversion), and Hurst Exponent (persistence)—to classify the market state (e.g., "Bull Trend," "Bear Range," "Choppy").
LAYER 5 — ADAPTIVE LEARNING (THOMPSON SAMPLING): Uses a Bayesian Multi-Armed Bandit algorithm to track performance. It maintains a set of "Agents," each tracking a different wick pattern type. Based on historical outcomes, the system updates the probability score for each pattern in real-time.
LAYER 6 — CONTEXTUAL ROUTING: The final layer of logic. The engine analyzes the wick, determines its pattern type, and routes it to the appropriate Agent for probability assessment, weighted by the current market regime.
█ CHAPTER 3: CORE FUNCTIONS
analyze_wick() — The Master Analyzer
The primary function. Accepts a bar index and returns a WickAnalysis object containing over 15 distinct metrics:
• Anomaly Score: Z-Score indicating how statistically rare the wick's size is.
• Kinetic Force: Metric combining range and relative volume to quantify impact.
• Estimated Delta: Approximation of net buying/selling pressure.
• Siege Decay: Structural integrity of the tested level.
• Magnet Score: Probability of the wick being filled.
• Win Probability: Adaptive success rate based on the Thompson Sampling engine.
scan_clusters() — Liquidity Zone Detection
Scans recent price history to identify "Pressure Clusters"—zones where multiple high-pressure wicks have overlapped. Useful for finding high-probability supply and demand zones.
detect_regime() — Context Engine
Uses statistical methods to determine the market's current personality (Trending, Ranging, or Volatile). This output allows the analysis to adapt dynamically to changing conditions.
█ CHAPTER 4: DEVELOPER INTEGRATION GUIDE
This library is a low-level engine for building sophisticated indicators.
1. Import the Library:
import DskyzInvestments/DafeWickLib/1 as wpk
2. Initialize the Agents:
var agents = wpk.create_learning_agents()
3. Analyze the Market:
regime = wpk.detect_regime(100)
wick_data = wpk.analyze_wick(0, regime, agents)
prob = wpk.get_probability(wick_data, regime)
4. Update Learning (Feedback Loop):
agent_id = wpk.get_agent_by_pattern(wick_data)
agents := wpk.update_learning_agent(agents, agent_id, 1.0) // +1 win, -1 loss
█ CHAPTER 5: THE DEVELOPER'S FRAMEWORK — INTEGRATION GUIDE
This library serves as a professional integration framework. This guide provides instructions and templates required to connect the DAFE components into a unified custom Pine Script indicator.
PART I: THE INPUTS TEMPLATE (CONTROL PANEL)
To provide users full control over the system, include the input templates from all connected libraries. This section details the bridge-specific controls.
// ╔═════════════════════════════════════════════════════════╗
// ║ BRIDGE INPUTS TEMPLATE (COPY INTO YOUR SCRIPT) ║
// ╚═════════════════════════════════════════════════════════╝
// INPUT GROUPS
string G_BRIDGE_MAIN = "════════════ 🌉 BRIDGE CONFIG ════════════"
string G_BRIDGE_EXT = "════════════ 🌐 EXTERNAL DATA ════════════"
// BRIDGE MAIN CONFIG
float i_bridge_min_conf = input.float(0.55, "Min Confidence to Trade",
minval=0.4, maxval=0.8, step=0.01, group=G_BRIDGE_MAIN,
tooltip="Minimum blended confidence required for a trade signal.")
int i_bridge_warmup = input.int(100, "System Warmup Bars",
minval=50, maxval=500, group=G_BRIDGE_MAIN,
tooltip="Bars required for data gathering before signals begin.")
// EXTERNAL DATA SOCKETS
bool i_ext_enable = input.bool(true, "🌐 Enable External Data Sockets",
group=G_BRIDGE_EXT,
tooltip="Enables analysis of external market data (e.g., VIX, DXY).")
// Example for one external socket
string i_ext1_name = input.string("VIX", "Socket 1: Name", group=G_BRIDGE_EXT, inline="ext1")
string i_ext1_sym = input.symbol("TVC:VIX", "Symbol", group=G_BRIDGE_EXT, inline="ext1")
string i_ext1_type = input.string("volatility", "Data Type",
options= ,
group=G_BRIDGE_EXT, inline="ext1")
float i_ext1_weight = input.float(1.0, "Weight", minval=0.1, maxval=2.0, step=0.1, group=G_BRIDGE_EXT, inline="ext1")
PART II: IMPLEMENTATION LOGIC (THE CORE LOOP)
This boilerplate code demonstrates the complete, unified pipeline structure.
// ╔════════════════════════════════════════════════════════╗
// ║ USAGE EXAMPLE (ADAPT TO YOUR SCRIPT) ║
// ╚════════════════════════════════════════════════════════╝
// 1. INITIALIZE ENGINES (First bar only)
var rl.RLAgent agent = rl.init(...)
var spa.SPAEngine spa_engine = spa.init(...)
var bridge.BridgeState bridge_state = bridge.init_bridge(i_spa_num_arms, i_rl_num_actions, i_bridge_min_conf, i_bridge_warmup)
// 2. CONNECT SOCKETS (First bar only)
if barstate.isfirst
// Connect internal sockets
agent := rl.connect_socket(agent, "rsi", ...)
// Register external sockets
if i_ext_enable
ext_socket_1 = bridge.create_ext_socket(i_ext1_name, i_ext1_sym, i_ext1_type, i_ext1_weight)
bridge_state := bridge.register_ext_socket(bridge_state, ext_socket_1)
// 3. MAIN LOOP (Every bar)
// --- A. UPDATE EXTERNAL DATA ---
if i_ext_enable
= request.security(i_ext1_sym, timeframe.period, )
bridge_state := bridge.update_ext_by_name(bridge_state, i_ext1_name, ext1_c, ext1_h, ext1_l)
bridge_state := bridge.aggregate_ext_sockets(bridge_state)
// --- B. RL/ML PROPOSES ---
rl.RLState ml_state = rl.build_state(agent)
= rl.select_action(agent, ml_state)
agent := updated_agent
// --- C. BRIDGE TRANSLATES ---
array arm_signals = bridge.generate_arm_signals(ml_action.action, ml_action.confidence, i_spa_num_arms, i_rl_num_actions, 0)
// --- D. SPA DISPOSES ---
spa_engine := spa.feed_signals(spa_engine, arm_signals, close)
= spa.select(spa_engine)
spa_engine := updated_spa
string arm_name = spa.get_name(spa_engine, selected_arm)
// --- E. RECONCILE REGIME & COMPUTE RISK ---
bridge_state := bridge.reconcile_regime(bridge_state, ml_regime_id, ml_regime_name, ml_conf, spa_regime_id, spa_conf, ...)
float risk = bridge.compute_risk(bridge_state, ml_action.confidence, spa_conf, ...)
// --- F. MAKE FINAL DECISION ---
bridge_state := bridge.make_decision(bridge_state, ml_action.action, ml_action.confidence, selected_arm, arm_name, final_spa_signal, spa_conf, risk, 0.25)
bridge.UnifiedDecision final_decision = bridge_state.decision
// --- G. EXECUTE ---
if final_decision.should_trade
// Plot signals, manage positions based on final_decision.direction
// --- H. LEARN (FEEDBACK LOOP) ---
if (trade_is_closed)
bridge_state := bridge.compute_reward(bridge_state, selected_arm, ...)
agent := rl.learn(agent, ..., bridge_state.reward.shaped_reward, ...)
// --- I. PERFORMANCE & DIAGNOSTICS ---
bridge_state := bridge.update_performance(bridge_state, actual_market_direction)
if barstate.islast
label.new(bar_index, high, bridge.bridge_diagnostics(bridge_state), textalign=text.align_left)
█ DEVELOPMENT PHILOSOPHY
DafeMLSPABridge represents a hierarchical design philosophy. We believe robust systems rely not on a single algorithm, but on the intelligent integration of specialized subsystems. A complete trading logic requires tactical precision (ML), strategic selection (SPA), and environmental awareness (External Sockets). This library provides the infrastructure for these components to communicate and coordinate.
█ DISCLAIMER & IMPORTANT NOTES
• LIBRARY FOR DEVELOPERS: This script is an integration tool and produces no output on its own. It requires implementation of DafeRLMLLib and DafeSPALib.
• COMPUTATION: Full bridged systems are computationally intensive.
• RISK: All automated decisions are based on statistical probabilities from historical data. They do not predict future market movements with certainty.
"The whole is greater than the sum of its parts." — Aristotle
Create with DAFE.
Quant Seasonality ProQuant Seasonality Pro (QuantSeaz)
Quant Seasonality Pro is a data-driven seasonal projection tool that extracts historical day-of-year return patterns and transforms them into a forward-looking price curve. Using log returns, cycle filters, and volatility-based scaling (ATR), it generates a dynamically anchored seasonal roadmap directly on your chart.
The indicator allows you to switch between Trading Days (stocks/forex) and Calendar Days (crypto), apply U.S. election cycle filters, and analyze precisly historical data. The projected curve is detrended to isolate true seasonal structure and then scaled to current market volatility for realistic visualization.
A built-in statistical dashboard provides:
Confidence (%) based on historical win rates
Expected Alpha (%) over the selected forward window
ATR % (noise level)
Viability ratio (Alpha adjusted for risk)
This tool is designed for contextual edge — not signal automation. It helps traders align positioning with historical seasonal tendencies while maintaining proper risk management and independent confirmation.
Hope you enjoy it
Forex Visual Market ClockWhat it is
The Forex Visual Market Clock is a professional-grade session dashboard designed to help traders identify global liquidity cycles at a glance. Inspired by classic 24-hour market clocks, this indicator renders a persistent, high-contrast table on your chart that tracks market opens, closes, and the high-volume overlaps between the world's major financial hubs.
How it works
• Local Time Synchronization: The indicator translates global UTC market hours into your specific local timezone using IANA identifiers. This ensures that your "You Are Here" highlight (the white box) stays perfectly aligned with your actual wall clock.
• Automatic DST Management: The script natively handles Daylight Savings Time transitions for the selected local timezone, eliminating the need for manual GMT offset adjustments.
• Liquidity Visualization:
o Color-Coded Tracks: Each city is represented by a unique color-coded bar (Green for London, Orange for New York, Blue for Sydney, Yellow for Tokyo).
o Volume Peak Logic: A dedicated "VOLUME" row turns red during the London/New York overlap, signaling the period of highest historical volatility and liquidity.
• Engineered for Efficiency: Wrapped in barstate.islast logic, the script updates tick-by-tick without degrading chart performance, making it ideal for fast-paced M5 trading.
Inputs
• Local Timezone: A dropdown menu to select your region (e.g., America/Los_Angeles). This defines which hour the white "current time" box highlights.
• Display Corner: A layout setting to anchor the dashboard to any corner of your screen (Upper Left, Upper Right, Lower Left, or Lower Right).
• Visual Controls: Users can customize the opacity of the session bars and the thickness of the grey frame to suit their specific chart theme.
ATR% Z-Score Z-Score of ATR% measures price volatility intensity relative to its historical average to identify extreme panic.
Multi-Strategy Filter: Pivot/Breakout/VWAP/RSI/MACDStrategy Overview: Multi-Confirmation Technical Scanner
This filter is a high-probability trend-following system that combines three core trading methodologies: Pivot Points (for institutional levels), Breakout Trading (for price action momentum), and VWAP (for volume-weighted value tracking). To ensure accuracy and avoid false breakouts, a signal is only generated when at least three of these core strategies align, further validated by a "Sweet Spot" RSI (momentum confirmation without being overbought) and a bullish MACD crossover. This multi-layered approach identifies stocks with strong institutional support and significant upward momentum.
Position Size Dashboard (Gold / Forex / Indices)A clean, MT5-accurate position sizing tool that instantly calculates lot size based on risk and stop-loss range. Designed for discretionary and prop-firm traders who want fast, no-nonsense sizing without manual math. Supports Gold (XAUUSD), Forex pairs, and Indices, with clear on-chart dashboard output.
How to Use (Step-by-Step)
Add the indicator to your chart
Open Settings → Inputs
Enter your Risk ($) (e.g., 100)
Enter SL Range
Forex → pips
Gold / Indices → price points
Enable or disable Gold / Forex / Indices rows as needed
Choose dashboard position, colors, and text size
Click OK → Lot size is calculated instantly and shown on chart
Initial Balance Trader NXiIB (Initial Balance) can be trade at IBL or IBH. My setup based on 30min IB zone. This strategy can be trade in GOLD, SP500 or Currencies etc. Can be combine with VP (Volume profile)
Visit us for more:
www.traderxi.com
SPX SPY 5Min Lock🔹 DESCRIPTION (Public Library)
This indicator overlays SPX price levels directly onto the SPY chart by converting SPX levels into SPY prices using a session-locked SPY/SPX ratio.
Instead of mentally translating SPX levels, you see them mapped precisely on SPY, where you actually trade.
How it works
• Calculates the SPY-to-SPX price ratio
• Locks the ratio at the first 5-minute RTH candle close (9:35am ET)
• Uses that fixed ratio for the entire session
• Converts SPX levels into accurate SPY-equivalent prices
• Draws clean labels (and optional short stubs) directly on SPY
Why the 5-minute lock
SPY and SPX can drift slightly during the day. Locking the ratio at 9:35am creates stable, non-moving levels that stay consistent throughout RTH, making them far more usable for intraday trading.
Best use cases
• SPY / SPX options traders
• Index-based level traders
• GEX, gamma, and macro level mapping
• Traders who think in SPX but execute in SPY
Customization
• Adjustable SPX level spacing (5 / 10 / 25)
• Number of levels above and below price
• Label size and offset
• Live or Locked ratio mode
• Optional short line stubs
• Info table with ratio and lock status
MACD (Standard) + ATR BoxJust a MACD with a ATR values box so no need for wasting a standalone indicator just for the ATR value. You can also calculate the ATR stop loss calculation.
TSX Sector ETF Overlay// --- Plot Data with Standard Colors ---
plot(xiu, title="TSX 60", color=color.white, linewidth=2)
plot(xfn, title="Financials", color=color.blue, linewidth=2)
plot(xeg, title="Energy", color=color.orange, linewidth=2)
plot(xma, title="Materials", color=color.yellow, linewidth=2)
plot(xgd, title="Gold Miners", color=color.yellow, linewidth=1)
plot(xit, title="Tech", color=color.purple, linewidth=2)
plot(xre, title="REITs", color=color.red, linewidth=2)
plot(xut, title="Utilities", color=color.green, linewidth=2)
plot(xst, title="Staples", color=color.teal, linewidth=2)
Bybit Fees Calculator + Correct Fee LogicОнлайн - расчет Суммы комиссий для сделки на криптобирже BYBIT для Вашей заданной суммы сделки и плеча.
Текущая ставка Funding Rate автоматически обновляется в режиме онлайн по запросу к бирже BYBIT.
________________________________________________________________________________
Online calculation of the amount of fees for a trade on the BYBIT crypto exchange for your specified trade amount and leverage.
The current Funding Rate is automatically updated online upon request to the BYBIT exchange.
Bybit Fees Calculator + Smart FundingРасчет Суммы комиссий для сделки на криптобирже BYBIT для Вашей заданной суммы сделки и плеча.
Внимание!! Для биржи BYBIT пока недоступно автоматическое считывание текущей ставки Funding Rate. Нужно вводить вручную в настройки индикатора . Брать - с сайта биржи или с индикатора Trading View - ставка Финансирования.
__________________________________________________________________________________
Calculation of the amount of commissions for a trade on the BYBIT crypto exchange for your specified trade amount and leverage.
Attention!! Automatic reading of the current Funding Rate is not yet available for the BYBIT exchange. You need to enter it manually in the indicator settings. You can take it from the exchange website or from the Trading View indicator - Funding Rate.
DafePatternsLibDafePatternLib: The Adaptive Pattern Recognition Engine
DafePatternLib is not a static pattern library. It is an adaptive recognition engine. It doesn't just find patterns; it tracks, weights, and filters them based on their performance in the live market.
█ CHAPTER 1: THE PHILOSOPHY — BEYOND STATIC RULES, INTO DYNAMIC LEARNING
For decades, chart pattern analysis has been trapped in a rigid paradigm. An indicator coded to find a "Bullish Engulfing" will signal that pattern with the same confidence every time, regardless of whether it has been failing consistently for weeks. It has no memory and no ability to adapt.
DafePatternLib was created to change this. It is built on a performance-based reinforcement framework. This library is not just a collection of detection functions; it is a self-weighting logic system. It tracks outcomes. It remembers what works. Over time, it amplifies the signals of high-probability patterns and filters out those that are failing in the current market regime.
This is not a black box. It is an open-source, observable learning system. It strengthens and weakens its own internal weights based on positive and negative feedback, evolving into a tool adapted to the specific asset you are trading.
█ CHAPTER 2: CORE INNOVATIONS
This library introduces several advanced concepts for algorithmic analysis:
Reinforcement Learning Engine: The core of the system. Every high-confidence pattern is logged into "Active Memory." The library tracks the outcome against projected stops and targets. If successful, the weight for that pattern category is strengthened. If it fails, the weight is reduced. This creates a continuous feedback loop.
Adaptation Rate (Plasticity): You have direct control over the engine's "plasticity"—its ability to learn. High plasticity allows fast adaptation to new conditions; lower plasticity creates a stable, long-term model.
Dynamic Volatility Scaling (DVS): Markets breathe. DVS is a proprietary function that calculates a real-time volatility scalar by comparing current ATR to historical averages. This scalar automatically adjusts lookback periods and sensitivities. In high volatility, engines look for larger structures; in low volatility, they tighten focus.
Smart Confidence Score: The output is not a simple "true/false." Every pattern includes two scores:
• Raw Confidence: Static confidence based on the pattern's textbook definition.
• Net Confidence: The adaptive score (Raw Confidence × Learned Bias). A performing pattern sees its confidence boosted; a failing pattern gets penalized.
Intelligent Filtering: If the learned bias for a category (e.g., "Candle") drops below a threshold (e.g., 0.8), the library automatically filters those signals, treating them as low-probability noise until performance improves.
█ CHAPTER 3: ANATOMY OF THE LOGIC — HOW IT THINKS
The LogicWeights (The Core)
The central data structure holding the system's "memory." It stores a floating-point weight or "bias" for each of the five major categories (Candle, Harmonic, Structure, Geometry, VSA). Initialized at 1.0 (neutral).
update_core() (The Learning Process)
The heart of the reinforcement loop. When a pattern resolves (win/loss), this function applies a positive or negative adjustment to the corresponding category weight. Weights are constrained between 0.5 (distrust) and 2.0 (trust).
manage_memory() (Short-Term Memory)
Maintains an array of active signals. On every bar, it checks if targets or stops have been hit. Resolved patterns trigger update_core(). Unresolved patterns eventually expire, applying a minor penalty to discourage stagnation.
scan_pattern_universe() (Master Controller)
The main exported function. On every bar, it:
Calculates the Dynamic Volatility Scalar (DVS).
Runs all pattern detection engines (VSA, Geometry, Candles, etc.) adapted to DVS.
Identifies the single best pattern based on raw confidence.
Passes it to memory for tracking.
Applies the learned bias to calculate Net Confidence.
Returns the final, adaptively weighted PatternResult.
█ CHAPTER 4: DEVELOPER INTEGRATION GUIDE
Designed for simplicity and power.
1. Import the Library:
import DskyzInvestments/DafePatternLib/1 as pattern
2. Call the Scanner:
The library handles DVS, scanning, memory, and learning internally.
pattern.PatternResult signal = pattern.scan_pattern_universe()
3. Use the Result:
if signal.is_active
label.new(bar_index, signal.entry, "Conf: " + str.tostring(signal.net_confidence, "#") + "%")
With just these lines, you integrate a self-weighting, multi-pattern recognition engine.
█ INPUTS TEMPLATE (COPY INTO YOUR SCRIPT)
// ═══════════════════════════════════════════════════════════
// INPUT GROUPS
// ═══════════════════════════════════════════════════════════
string G_AI_ENGINE = "══════════ 🧠 LOGIC ENGINE ══════════"
string G_AI_PATTERNS = "══════════ 🔬 PATTERN SELECTION ══════════"
string G_AI_VISUALS = "══════════ 🎨 VISUALS & SIGNALS ══════════"
string G_AI_DASH = "══════════ 📋 LOGIC STATE DASHBOARD ══════════"
string G_AI_ALERTS = "══════════ 🔔 ALERTS ══════════"
// ═══════════════════════════════════════════════════════════
// LOGIC ENGINE CONTROLS
// ═══════════════════════════════════════════════════════════
bool i_enable_ai = input.bool(true, "✨ Enable Adaptive Engine", group = G_AI_ENGINE,
tooltip="Master switch to enable the pattern recognition and learning system.")
float i_plasticity = input.float(0.03, "Adaptation Rate", minval=0.01, maxval=0.1, step=0.01, group = G_AI_ENGINE,
tooltip="Controls adaptation speed. • Low (0.01-0.02): Stable learning. • Medium (0.03-0.05): Balanced. • High (0.06+): Fast adaptation.")
float i_filter_threshold = input.float(0.8, "Adaptive Filter Threshold", minval=0.5, maxval=1.0, step=0.05, group = G_AI_ENGINE,
tooltip="Hide signals from categories with a learned bias below this value.")
// ═══════════════════════════════════════════════════════════
// PATTERN SELECTION
// ═══════════════════════════════════════════════════════════
bool i_scan_candles = input.bool(true, "🕯️ Candlestick Patterns", group = G_AI_PATTERNS, inline="row1")
bool i_scan_vsa = input.bool(true, "📦 Volume Spread Analysis", group = G_AI_PATTERNS, inline="row1")
bool i_scan_geometry = input.bool(true, "📐 Geometric Patterns", group = G_AI_PATTERNS, inline="row2")
bool i_scan_structure = input.bool(true, "📈 Market Structure (SMC)", group = G_AI_PATTERNS, inline="row2")
bool i_scan_harmonic = input.bool(false, "🦋 Harmonic Setups", group = G_AI_PATTERNS, inline="row3")
// ═══════════════════════════════════════════════════════════
// VISUALS & DASHBOARD
// ═══════════════════════════════════════════════════════════
bool i_show_signals = input.bool(true, "Show Signals", group = G_AI_VISUALS)
bool i_show_dashboard = input.bool(true, "Show Logic Dashboard", group = G_AI_DASH)
█ DEVELOPMENT PHILOSOPHY
DafePatternLib was born from a vision to bring dynamic logic to technical analysis. We believe an indicator should not be a static tool, but an intelligent partner that adapts. This library is an open-source framework empowering developers to build the next generation of smart indicators.
█ DISCLAIMER
• LIBRARY FOR DEVELOPERS: This script produces no visual output on its own. It is an engine for developers.
• ADAPTIVE, NOT PREDICTIVE: Reinforcement learning optimizes based on recent history. It is a statistical edge, not a crystal ball.
• RISK WARNING: Patterns and confidence scores are for informational purposes.
"The key to trading success is emotional discipline. If intelligence were the key, there would be a lot more people making money trading." — Victor Sperandeo
Create with DAFE.






















