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.
Statistics
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!
DafeLiquidityEngineDafeLiquidityEngine: The Institutional Liquidity & Microstructure Engine
This is not a volume indicator. This is a complete, institutional-grade quantitative laboratory for the analysis of market liquidity. It is a toolkit for seeing the invisible architecture of the order book and trading the cause, not the effect.
█ CHAPTER 1: THE PHILOSOPHY - BEYOND VOLUME, INTO LIQUIDITY
The standard volume bar is a lie. It tells you that the market was active, but it tells you nothing about the quality of that activity. Was it a deep, liquid market that could easily absorb large orders, or a thin, fragile market on the verge of a violent cascade? Was the volume driven by informed, institutional flow, or by reactive, retail panic?
The DafeLiquidityEngine was created to answer these critical questions. This library is not a simple "mashup" of existing indicators; it is a foundational, original work that brings a suite of concepts from academic and institutional quantitative finance directly into the Pine Script environment. Its purpose is to move beyond the one-dimensional view of volume and provide a multi-faceted, high-resolution picture of the market's true, underlying liquidity structure.
b]This is not an indicator that gives buy or sell signals. It is a far more powerful tool: a measurement device. It provides you with the crucial intelligence to assess the quality of the market environment. It tells you when liquidity is deep and signals can be trusted, and when liquidity has vanished and risk is extreme. It is the definitive engine for understanding the hidden structure of the market auction.
█ CHAPTER 2: THE CORE INNOVATIONS - A UNIVERSITY-LEVEL TOOLKIT
This library's value is rooted in its implementation of sophisticated, academically recognized models for liquidity and price impact, many for the first time on this platform.
Multi-Scale Delta Divergence Engine: The engine doesn't just calculate one Cumulative Volume Delta (CVD). It calculates two simultaneously: a fast delta (representing scalpers and retail flow) and a slow delta (representing institutional accumulation/distribution). Its true genius lies in its ability to analyze the divergence between these two flows, classifying the market into one of five distinct states like "Absorption" (institutions absorbing retail selling) or "Stealth" (institutions quietly building a position).
Advanced Bid-Ask Spread Estimation: Without access to Level 2 data, how can you know the spread? This library uses two renowned academic models—the Corwin-Schultz estimator (using high-low data) and the Roll spread estimator (using serial covariance)—to create a high-fidelity proxy for the live bid-ask spread. This is a direct measure of market tightness.
Amihud Illiquidity Ratio: A classic, powerful measure of illiquidity. It calculates the absolute price return per dollar of volume traded. A high Amihud score means that even small amounts of volume are causing large, violent price swings—a clear sign of a dangerously illiquid market.
Kyle's Lambda (Price Impact): This is the professional's measure of market impact. Lambda calculates how much the price moves for every unit of signed order flow. A high Lambda value indicates a "thin" order book where a single large market order can cause a significant price cascade. It is a direct measure of market fragility.
The Volume Clock Engine: This module analyzes the market in "volume time" instead of chronological time. It detects volume "droughts" and "floods," measures the "participation rate" against historical norms, and analyzes the acceleration of volume to determine if a move is gaining or losing institutional support.
The Composite Liquidity Regime: The capstone of the engine. It synthesizes the intelligence from all other modules into a single, unified classification of the market's liquidity state, from "Deep" and "Normal" to "Thin," "Desert," and the dreaded "Frozen." For developers, this provides a simple, powerful output: a risk_multiplier and a signal_penalty to automatically adjust position sizing and signal confidence based on the current liquidity environment.
█ CHAPTER 3: A DEEP DIVE INTO THE ENGINE'S MODULES
This is your guide to the engine room. Each module is a specialized analytical tool.
The DeltaState Module: This is the heart of the divergence engine. It provides you with the raw and Z-scored values for both fast and slow delta, their velocity, and the final divergence classification ("absorption," "exhaustion," etc.) along with a confidence score. This is your primary tool for detecting conflicts between retail and institutional flow.
The SpreadState Module: This gives you a direct, quantitative measure of market tightness. Use the spread_z score to see if the current bid-ask spread is statistically wide or tight, and the spread_regime to know if the market is "Blown" (extremely wide and risky) or "Tight" (liquid and efficient).
The AmihudState & KyleState Modules: These are your professional-grade risk assessment tools. A rising illiquidity_z score from Amihud is a clear warning that the market is becoming fragile. A rising lambda_z from Kyle's Lambda tells you that price impact is increasing, and the risk of a slippage cascade is high.
The VolumeClockState Module: This is your lens into market participation. The vol_clock_regime ("drought," "low," "normal," "elevated," "flood") tells you the character of the current volume, while the vol_trend_strength provides a measure of the momentum of participation.
The LiquidityRegime Module: This is the final, synthesized verdict. It provides a single, easy-to-use regime name ("Flush," "Deep," "Normal," "Thin," "Desert," "Frozen") that encapsulates the combined intelligence of the entire system. Crucially, it also outputs the risk_multiplier and signal_penalty—direct, actionable factors you can use to modulate your own strategy's behavior.
█ CHAPTER 4: THE DEVELOPER'S MASTERCLASS - IMPLEMENTATION GUIDE
The DafeLiquidityEngine is a professional framework designed for seamless integration. This guide provides the complete instructions for leveraging its power.
PART I: THE INPUTS TEMPLATE (THE CONTROL PANEL)
While this is a library, a high-quality indicator built upon it would expose these parameters to the user for fine-tuning. This is the recommended input structure.
// ╔═════════════════════════════════════════════════════════╗
// ║ INPUTS TEMPLATE ║
// ╚═════════════════════════════════════════════════════════╝
// INPUT GROUPS
string G_LIQ_ENGINE = "═══════════ 💧 LIQUIDITY ENGINE ════════════"
string G_LIQ_DELTA = "═══════════ 📊 DELTA & DIVERGENCE ══════════"
string G_LIQ_RISK = "═══════════ ⚖️ RISK & SPREAD ════════════"
// ENGINE CONFIG
int i_liq_fast = input.int(8, "Fast Delta Length", minval=3, maxval=20, group=G_LIQ_ENGINE, tooltip="Lookback for the 'fast' retail/scalper delta.")
int i_liq_slow = input.int(34, "Slow Delta Length", minval=21, maxval=100, group=G_LIQ_ENGINE, tooltip="Lookback for the 'slow' institutional delta.")
int i_liq_zlookback = input.int(50, "Normalization Lookback", minval=20, maxval=200, group=G_LIQ_ENGINE, tooltip="The lookback period for all Z-Score calculations, which makes the metrics adaptive to the asset.")
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 lifecycle of creating, updating, and using the engine.
// ╔═════════════════════════════════════════════════════════╗
// ║ USAGE EXAMPLE (ADAPT TO YOUR SCRIPT) ║
// ╚═════════════════════════════════════════════════════════╝
// 1. IMPORT THE LIBRARY
import YourUsername/DafeLiquidityEngine/1 as liq
// 2. INITIALIZE THE ENGINE (happens only on the first bar)
// The 'engine' must be a 'var' to retain its state across bars.
var liq.LiquidityEngine engine = liq.create_engine(i_liq_fast, i_liq_slow, i_liq_zlookback)
// 3. UPDATE THE ENGINE (runs on every bar)
// Feed the current bar's OHLCV data into the engine. It handles all internal calculations.
engine := liq.update(engine, open, high, low, close, volume)
// 4. EXTRACT INTELLIGENCE (runs on every bar)
// Get the final, synthesized output state from the engine.
liq.LiquidityState state = liq.get_state(engine)
// 5. USE THE INTELLIGENCE TO BUILD YOUR LOGIC
// --- Example 1: Creating a Sophisticated Signal Filter ---
bool my_raw_buy_signal = ta.crossover(ta.ema(close, 10), ta.ema(close, 20))
// The liquidity engine provides a simple penalty score. 1.0 = good liquidity, 0.2 = bad liquidity.
float liquidity_penalty = state.signal_penalty
// Only trust the signal if liquidity is good enough.
bool final_buy_signal = my_raw_buy_signal and liquidity_penalty > 0.6
plotshape(final_buy_signal, "Filtered Buy", ...)
// --- Example 2: Dynamic Position Sizing ---
float base_position_size = 10000 // Your base size in dollars
// The engine provides a risk multiplier. 1.0 = normal risk, 0.3 = high risk (reduce size).
float liquidity_risk_multiplier = state.risk_multiplier
float final_position_size = base_position_size * liquidity_risk_multiplier
// Now use 'final_position_size' in your strategy logic.
// --- Example 3: Building a Divergence-Based Strategy ---
if state.divergence_type == "accumulation" and state.divergence_confidence > 0.7
// This is a high-confidence signal that institutions are quietly buying while price is falling.
// A powerful setup for a long entry.
strategy.entry("Accumulation Long", strategy.long)
// --- Example 4: Displaying the State on a Dashboard ---
if barstate.islast
label.new(bar_index, high, "Liquidity Regime: " + state.liq_regime_name +
" Risk Multiplier: " + str.tostring(state.risk_multiplier, "#.##") +
" Divergence: " + state.divergence_type)
█ DEVELOPMENT PHILOSOPHY
The DafeLiquidityEngine was born from a single, guiding principle: liquidity is the fuel of the market. Price cannot move without it, and its absence or presence dictates the character of every trading session. This library provides, for the first time, a comprehensive, institutional-grade toolkit for quantifying this elusive but critical variable. It is a tool for the serious developer and the quantitative trader who is not satisfied with surface-level analysis, but who seeks to understand the deep, structural mechanics of the market auction.
█ 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 imported and used by other indicator developers to build their own tools.
THIS IS AN ESTIMATION ENGINE: The algorithms used (Corwin-Schultz, Kyle's Lambda, Delta Estimation) are highly respected academic and institutional proxies for true order book data. They are high-fidelity estimates, not a direct feed of Level 2 data.
CONTEXT IS KEY: The output of this engine is contextual intelligence, not direct trading signals. A "Thin" liquidity regime is not a signal to sell; it is a signal to reduce position size, widen stops, and be wary of false breakouts.
Create with DAFE.
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.
DafeVIXEngineDAFE VIX Intelligence Engine: The Definitive Guide to Market Volatility
This is a professional-grade intelligence engine that decodes the multi-dimensional language of market fear. It analyzes the VIX Term Structure, Volatility Surprise, and Regime Physics to provide a probabilistic forecast of market stability and transitions.
█ CHAPTER 1: THE PHILOSOPHY - BEYOND THE VIX NUMBER
For most traders, the VIX is a single number—a simple "fear gauge." This is a dangerously incomplete view. The VIX is not a single data point; it is the observable surface of a deep, complex, multi-dimensional field of information. Its true power lies not in its absolute level, but in its relationship to itself across time (its slope), its relationship to its future expectations (its term structure), and its relationship to the market's actual, realized volatility (the volatility risk premium).
The DAFE VIX Intelligence Engine was created to provide a complete, institutional-grade view of this hidden information field. This script is not a simple "mashup" of existing indicators; it is a foundational, original work that introduces a suite of proprietary algorithms and concepts to the TradingView platform. It deconstructs the entire VIX complex and analyzes it through the lens of quantitative finance and statistical modeling.
Its purpose is not to give you simple buy or sell signals. Its purpose is to provide you with a master "weather report" for the market. It answers the most critical questions a professional trader must ask before putting on any position: What is the current volatility regime? Is the market stable or fragile? And what is the probability that the entire environment is about to change? This is a tool for quantifying the unseen risks and opportunities in the market.
█ CHAPTER 2: THE CORE INNOVATIONS - ORIGINALITY & USEFULNESS
This engine's value is rooted in its synthesis of concepts from professional derivatives analysis, applied to the VIX in a novel and accessible way. Every component is designed to extract a unique and powerful layer of intelligence.
Multi-Source Data Ingestion & Validation: The engine doesn't just rely on the standard VIX. It intelligently pulls data from the entire VIX family, including the VIX9D (9-day VIX) and VX1! (the front-month VIX future). Crucially, it includes a sophisticated Stale Data Detection system. If it detects that the CBOE data is not updating (a common issue), it seamlessly falls back to a high-fidelity Realized Volatility model (blending Parkinson and Yang-Zhang estimators), ensuring you always have a reliable reading.
Term Structure Analysis: This is the heart of the engine and a concept rarely seen outside of institutional platforms. It analyzes the slope of the VIX futures curve (VX1! - VIX) to determine if the market is in Contango (normal, calm) or Backwardation (stressed, fearful). An inverted term structure is one of the most reliable leading indicators of market stress.
Volatility Surprise (VRP) Engine: The engine quantifies the Volatility Risk Premium by comparing implied volatility (the VIX) to the actual, historical realized volatility of the underlying asset. This allows it to detect when "fear is overpriced" (VIX is much higher than reality, a potential bullish signal for equities) or "fear is underpriced" (VIX is lower than reality, signaling dangerous complacency).
Probabilistic Regime Transition Model: This is the engine's predictive powerhouse. It doesn't just tell you the current regime; it calculates the probability of a transition. It does this by analyzing the "acceleration" of key volatility metrics—the rate of change of the term structure slope, the rate of change of realized volatility, and the "mean-reversion pressure" building up in the system. A high transition probability is a powerful early warning that the entire market character is about to shift.
Intelligent Instrument Profiling: The engine includes a smart detection system that identifies the asset you are trading (e.g., NQ, ES, BTC, Gold) and automatically applies a pre-calibrated "Sensitivity Profile." It understands that a VIX of 25 has a different implication for Nasdaq than it does for Bitcoin, and it adjusts its risk calculations accordingly.
█ CHAPTER 3: THE ANALYTICAL PIPELINE - HOW THE ENGINE THINKS
The VIX Intelligence Engine operates on a clear, five-stage pipeline to transform raw data into high-level intelligence.
STAGE 1: DATA INGESTION & VALIDATION: The engine pulls data from VIX, VIX9D, and VX1!. It simultaneously calculates the realized volatility of the primary asset. It runs a continuous check for stale data. If the VIX data is found to be stale, it transparently switches to a fallback model, blending the last known VIX value with the live realized volatility reading.
STAGE 2: MULTI-DIMENSIONAL ANALYSIS: The validated volatility data is analyzed across four key dimensions:
Level: The raw VIX value is converted to a Z-Score to measure its statistical rarity.
Slope: The rate of change of the VIX is calculated to measure its momentum.
Term Structure: The VX1! - VIX spread and the VIX9D - VIX spread are calculated to determine the shape of the futures curve.
Surprise: The VIX - Realized Volatility spread is calculated to quantify the Volatility Risk Premium.
STAGE 3: REGIME CLASSIFICATION: A weighted scoring model synthesizes all the metrics from Stage 2 to classify the market into one of seven distinct volatility regimes: Compression, Low Vol, Normal, Elevated, Expansion, Panic, or Euphoria. Each regime is assigned a color and a confidence score.
STAGE 4: TRANSITION PROBABILITY: This is the predictive layer. The engine analyzes the second derivative (acceleration) of its core metrics. A sharp acceleration in the term structure slope, combined with a build-up of mean-reversion pressure, will result in a high "Transition Probability" score, warning you that the current regime is becoming unstable.
STAGE 5: FINAL OUTPUT & VISUALIZATION: All of this intelligence is rendered into the intuitive lower pane display, the on-chart detection dots, and the comprehensive dashboard.
█ CHAPTER 4: A GUIDE FOR DEVELOPERS - INTEGRATING THE ENGINE
This script is published as a standalone indicator, but its core logic is designed to be extracted and used as a library. This guide provides the complete input template and a conceptual workflow for integrating this VIX intelligence into your own systems.
PART I: THE INPUTS TEMPLATE (THE CONTROL PANEL)
To give your users full control over the VIX engine, you can replicate these inputs in your own script.
// ╔═════════════════════════════════════════════════════╗
// ║ INPUTS TEMPLATE (COPY INTO YOUR SCRIPT) ║
// ╚═════════════════════════════════════════════════════╝
// INPUT GROUPS
string GRP_ENGINE = "══════════ 🌡️ VIX ENGINE ══════════"
string GRP_DISPLAY = "══════════ 📊 DISPLAY LAYERS ══════════"
string GRP_DETECT = "══════════ 🔍 DETECTION OVERLAYS ══════════"
string GRP_VIZ = "══════════ 🎨 VISUALIZATION ══════════"
string GRP_DASH = "══════════ 📋 DASHBOARD ══════════"
// VIX ENGINE
int i_zLookback = input.int(50, "Z-Score Lookback", minval=20, maxval=200, group=GRP_ENGINE,
tooltip="Normalization period for all Z-score calculations. • 30-40: Adaptive • 50: Standard • 100+: Very stable")
int i_rvLookback = input.int(20, "Realized Vol Lookback", minval=10, maxval=50, group=GRP_ENGINE,
tooltip="Lookback for Parkinson + Yang-Zhang realized volatility estimators.")
// DISPLAY LAYERS
bool i_showVixLevel = input.bool(true, "Show VIX Level Z-Score", group=GRP_DISPLAY)
bool i_showVixSlope = input.bool(true, "Show VIX Slope", group=GRP_DISPLAY)
bool i_showTermStructure = input.bool(true, "Show Term Structure", group=GRP_DISPLAY)
bool i_showVolSurprise = input.bool(true, "Show Vol Surprise", group=GRP_DISPLAY)
bool i_showTransition = input.bool(true, "Show Transition Probability", group=GRP_DISPLAY)
bool i_showDangerBar = input.bool(true, "Show Danger Bar", group=GRP_DISPLAY)
// DETECTION OVERLAYS
bool i_showRegimeDots = input.bool(true, "Show Regime Detection Dots", group=GRP_DETECT)
bool i_showTransitionWarning = input.bool(true, "Show Transition Warnings", group=GRP_DETECT)
bool i_showStaleDots = input.bool(true, "Show Stale Data Warnings", group=GRP_DETECT)
bool i_showSurpriseDetection = input.bool(true, "Show Vol Surprise Detections", group=GRP_DETECT)
float i_transitionThreshold = input.float(0.4, "Transition Warning Threshold", minval=0.1, maxval=0.9, step=0.05, group=GRP_DETECT)
// VISUALIZATION & DASHBOARD
string i_vizMode = input.string("Layered Analysis", "Visualization Mode", options= , group=GRP_VIZ)
string i_colorTheme = input.string("Quantum Dark", "Color Theme", options= , group=GRP_VIZ)
bool i_showDash = input.bool(true, "Show Dashboard", group=GRP_DASH)
// ... other dash inputs
PART II: THE IMPLEMENTATION WORKFLOW (CONCEPTUAL)
If this were a library, here is how you would use its exported functions to build a sophisticated signal filter.
// import DskyzInvestments/DafeVIXEngineLib/1 as vix
//
// // 1. INITIALIZE & RUN THE ENGINE (happens on every bar)
// // The engine would contain all the logic from this indicator.
// = vix.run_analysis(zLookback, rvLookback)
//
// // 2. USE THE INTELLIGENCE TO CREATE FILTERS FOR YOUR STRATEGY
//
// // A simple trend-following strategy
// bool my_buy_signal = ta.crossover(ta.ema(close, 20), ta.ema(close, 50))
// bool my_sell_signal = ta.crossunder(ta.ema(close, 20), ta.ema(close, 50))
//
// // --- Build the VIX Filter ---
// // We only want to take trend-following trades if the VIX engine confirms a stable, low-volatility environment.
// bool vix_filter_pass = state.regime_id <= 2 and // Must be in "Normal" regime or better
// state.transition_prob < 0.5 and // Regime must be stable
// state.danger_score < 50 and // Overall danger must be low
// state.data_confidence > 0.7 // VIX data must be reliable
//
// // --- Apply the filter to your signals ---
// bool final_buy_signal = my_buy_signal and vix_filter_pass
// bool final_sell_signal = my_sell_signal and vix_filter_pass
//
// // 3. PLOT YOUR FILTERED SIGNALS
// plotshape(final_buy_signal, "Filtered Buy", ...)
/pine]
█ CHAPTER 5: A VISUAL GUIDE - DECODING THE DISPLAYS
THE ON-CHART OVERLAYS (THE DOTS)
These dots are your real-time alerts, plotted directly on the price chart.
Colored Dots (Above Price): These are the Regime Detection Dots . Their color corresponds to the currently detected volatility regime (e.g., Green for Low Vol, Yellow for Elevated, Red for Panic). Their transparency indicates the confidence of the classification—a solid dot is a high-confidence reading.
Purple Dots (Below Price): These are the Transition Warning Dots . They appear when the engine's predictive model calculates a high probability that the market regime is about to shift. This is a critical early warning to tighten stops or defer new entries.
Gold/Red Dots (Below Price): These are the Volatility Surprise Detections . A gold dot signals that fear is significantly "overpriced" (VIX > RV), a condition that often precedes a bounce in equities. A red dot signals that fear is "underpriced" (VIX < RV), indicating dangerous complacency.
Gray Dots (Below Price): These are Stale Data Warnings , providing transparent feedback that the engine is currently operating in its fallback mode using realized volatility.
THE LOWER INDICATOR PANE (THE ENGINE ROOM)
This is where the raw data from all analytical layers is visualized. Choose from four distinct modes:
Layered Analysis: The default professional view. Each major component (VIX Level, Slope, Term Structure, Surprise, Transition Prob) gets its own layer, allowing you to see which factor is driving the current analysis.
Regime Heatmap: A color-block visualization where the color of each block is determined by a specific metric's state, creating a "heatmap" of market risk.
Oscillator Stack: Renders the core metrics as a set of zero-centric oscillators, ideal for spotting momentum and divergences within the volatility data itself.
Risk Waterfall: A unique cascading visualization that cumulatively stacks the risk from each component, with the final line representing the total, blended risk assessment.
THE DASHBOARD (MISSION CONTROL)
The dashboard is a comprehensive, institutional-grade summary of the entire VIX ecosystem.
VIX Family Data: Displays the live values for VIX, VIX9D, and VX1!, along with a data confidence score.
Instrument Profile: Shows the detected asset and its automatically applied sensitivity profile.
State Variables: The core Z-Score and Slope readings that power the engine.
Volatility Regime: The final, classified regime name, its duration, and the confidence of the reading.
Term Structure: A complete breakdown of the VIX curve analysis, showing the state (Contango/Backwardation), the slope, and the level of inversion.
Vol Surprise: Quantifies the Volatility Risk Premium, showing the spread between Implied and Realized vol and classifying it as "Overpriced" or "Underpriced."
Transition Engine: The predictive output, showing the raw Transition Probability and the predicted next regime.
Danger Assessment: The final, synthesized "Danger Score" from 0-100, providing a single, unambiguous measure of market fragility.
█ DEVELOPMENT PHILOSOPHY
The DAFE VIX Intelligence Engine was born from the conviction that volatility is the master variable in all financial markets. By deconstructing the VIX complex and analyzing its components through the lens of quantitative finance, we have created a tool that provides a level of contextual awareness previously unavailable to retail traders. This is not just about measuring fear; it's about understanding its structure, its momentum, and its probable future state. It is a tool for quantifying the unseen.
█ DISCLAIMER & IMPORTANT NOTES
THIS IS AN ADVANCED ANALYTICAL TOOL: This indicator provides intelligence on market volatility, not direct buy or sell signals. It is designed to be used as a master filter and contextual guide for your existing trading strategies.
DATA DEPENDENCY: The accuracy of the engine is dependent on a live, reliable data feed for the CBOE VIX family. While the engine has a robust fallback system, its full power is realized with live data.
ALL TRADING INVOLVES RISK: The probabilities and classifications are based on historical statistical models. They are a powerful edge, not a guarantee of future outcomes.
Create with DAFE.
Sector Divergence DashboardStatistical arbitrage dashboard for markets and sector ETFs
This Sector Divergence Dashboard is a tool designed to identify mean-reversion opportunities across U.S. equity sectors. I've built it to help me with portfolio management and sector allocation by identifying uncorrelated sectors and divergences between indices and sector ETFs. These divergences are often good investment opportunities.
The indicator also helps you with sector rotation by identifying when sectors have diverged too far from their historical relationships with the broader market. This is a similar methodology used daily in institutional portfolio management and hedge funds.
In this dashboard, you can see:
Z-Score Analysis on log price ratios to detect statistical anomalies
Dual-timeframe correlation tracking to identify relationship breakdowns
Composite scoring that combines divergence magnitude, correlation shifts, and momentum
Correlation heatmap for instant relationship assessment across all pairs
You see exactly which pairs are statistically mispriced and likely to revert to their historical mean.
NOTE: This dashboard is computationally heavy and might take up to one minute to load in your TradingView.
The Mathematics
1. Price Ratio Z-Score
The indicator calculates the logarithmic price ratio between two assets (e.g., SPY/XLE) and measures how many standard deviations this ratio has moved from its historical average. A z-score of +2.0 means the pair is 2 standard deviations expensive relative to history. This can be a mean-reversion setup.
2. Correlation Breakdown Detection
Short-term correlation (35 bars) is compared against long-term correlation (100 bars). You can change these parameters BTW. When correlations diverge significantly, it signals that the normal relationship has temporarily broken, potentially creating trading opportunities.
3. Relative Performance
Measures the momentum difference between pairs over 300 bars (roughly 60 weeks on daily charts). This captures longer-term structural shifts versus short-term noise.
4. Composite Score
All three metrics are normalized and weighted to create a single ranking score:
50% Z-Score Weight - Primary driver of mean reversion probability
25% Correlation Breakdown - Relationship stability metric
25% Relative Performance - Momentum/trend context
Features
1. Correlation Heatmap
Visualize all pairwise correlations
Color-coded from red (negative correlation) to green (strong positive)
Spot which sectors are moving together or decoupling
2. Divergence Rankings Table
Top 15 SPY-vs-sector pairs ranked by composite opportunity score
Z-scores, correlations, performance differentials, and signals
Color-coded from gray (neutral) to red (extreme divergence)
Scan it daily for setups
3. Deep Dive Chart
Detailed z-score visualization for any selected pair
Visual zones showing normal range, signal threshold, and strong signal areas
Short-term and long-term correlation overlays
Real-time information label with current metrics and signal status
Perfect for analyzing specific opportunities in depth
You can define which symbols you want to deep dive in the parameters
Parameter Guide
Short-Term Correlation - Recent relationship strength
Long-Term Correlation - Historical baseline relationship
Z-Score Length - Mean reversion lookback period
Relative Performance - Longer-term momentum context
Pro Tip : Increase z-score length to 150+ for fewer but stronger signals. Decrease to 50-75 for more frequent opportunities (but more noisy).
Use Cases
Sector Rotation: Identify which sectors are over/undervalued relative to the market
Portfolio Rebalancing: Data-driven signals for tactical asset allocation adjustments
Pairs Trading: Statistical arbitrage between correlated instruments
Risk Management: Monitor correlation stability across your portfolio
Market Regime Detection: Spot when sector relationships are breaking down
Swing Trading: Mean-reversion setups with clear entry/exit rules
Example:
XLK, a key tech ETF, is typically very correlated with the S&P 500 with a 0.88 correlation. Our dashboard detected a divergence between both, which signals a buy/rotation to XLK.
Let me know if you have any requests, improvements suggestions or feedback :)
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.
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.
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.
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.
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.
Expectancy Reality Check Most trading discussions focus on entries.
This tool focuses on math.
Expectancy Reality Check is a symbol-agnostic calculator that shows whether your assumed edge is mathematically viable — before you trade it.
It does not generate signals.
It does not predict price.
It exists to answer one question:
“If my assumptions are correct, does this strategy deserve capital?”
What this tool does
Given your assumptions for:
Win rate
Reward-to-Risk (R)
Costs per trade
Risk per trade
Trade frequency
the indicator computes:
Expected Value (R per trade)
Expected Value per month
Break-even win rate (cost-adjusted)
Edge vs break-even (percentage points)
Risk-of-ruin proxy (fixed-fractional approximation)
Estimated sample size needed to validate your win rate at a chosen confidence level
All values are expressed in R-units, not currency, to remain portfolio-independent.
How to use it
Enter honest assumptions — not best-case backtest results.
Observe:
Is EV meaningfully positive?
How small is the margin above break-even?
How many trades are required before results are statistically meaningful?
Decide whether the strategy is worth:
testing,
refining,
or discarding.
If the math fails here, execution quality will not save it.
What this tool is not
❌ Not a strategy
❌ Not a signal generator
❌ Not a performance backtest
❌ Not a guarantee of results
It is a reality check, not a promise.
Notes on methodology
Expectancy is computed in standard R-unit form.
Break-even win rate is adjusted for per-trade costs.
Risk-of-ruin is a proxy, based on a Lundberg-type root for i.i.d. outcomes under fixed fractional risk.
Sample size guidance uses a normal approximation for binomial confidence intervals.
All calculations assume stationarity — real markets may violate this.
Use judgment.
Who this is for
Traders designing rule-based systems
Traders comparing multiple strategies
Traders tired of “high win rate” marketing
Anyone who wants math before emotion
Final note
A strategy with:
high win rate but negative expectancy
or positive expectancy but no statistical margin
is not an edge — it’s noise.
Systems over feelings.
Forex Renko LeaderboardForex Warlord: Kinetic Velocity Leaderboard
This indicator is a specialized dashboard designed to rank the 7 Major Forex pairs based on their real-time "Kinetic Velocity" and acceleration. Unlike standard strength meters that measure relative price change, the Warlord Engine calculates exactly how fast a pair is generating net profits per second, accounting for the "Physics" of the market: drag (spread costs) and inertia (lag).
It is designed specifically for momentum traders who need to know not just which pair is moving, but which pair is moving fast enough to overcome the cost of the spread and generate immediate net return.
HOW IT WORKS
The script runs a "Virtual Renko" simulation on your time-based chart (works best on 1-second or 1-minute timeframes). It tracks price movement in "Bricks" and calculates a standardized "Score" for each pair.
The Score represents "Net Pips per Second."
-- A positive score (> 0.00) means the price is moving fast enough to clear the spread and generate profit.
-- A negative score (< 0.00) means the price is moving too slowly, and the spread cost is eating the volatility.
The system then applies a "Smart Decay" penalty. If a pair is moving fast but starting to decelerate (slowing down), its score is penalized to prevent you from buying the top.
HOW TO USE IT
1. Attach the indicator to any chart (EURUSD, 1-Second or 1-Minute recommended for high-speed scalping).
2. Look at the Dashboard on the right side of the screen.
3. Identify the Rank #1 Pair. This is the currency currently moving with the highest velocity.
4. Check the "Action" Column:
-- TRADE (Green): The pair is Rank #1 AND its velocity is high enough to be profitable.
-- NO TRADE (Red): The pair is moving too slowly, or the spread cost is too high relative to the move.
-- SPREAD > MAX (Red): The calculated move does not clear your specified "Max Broker Cost."
-- NO TRADE (ZONE) (Red): The market is in the "Dead Zone" (typically 17:00-18:00 EST), where spreads widen and liquidity vanishes.
5. Check the "State" Icon:
-- Rocket: The pair is accelerating. This is the ideal entry signal.
-- Warning: The pair is decelerating. Caution is advised as momentum is fading.
ALERTS
The indicator features a built-in alert system. You can create an alert in TradingView to notify you specifically when the "Renko Leaderboard Ranking" changes. This allows you to wait for the market to tell you which pair is taking the lead without staring at the screen.
INPUTS & SETTINGS
-- Renko Brick Size (Pips): The most critical tuning knob. Determines the sensitivity of the engine. Smaller bricks (e.g., 2-3 pips) make it hyper-sensitive for scalping. Larger bricks (e.g., 10 pips) tune it for swing trends. Changing this instantly recalculates the entire board.
-- Max Broker Cost (Pips): Your "Hurdle Rate." If a pair's projected profit does not clear this cost (default 1.0 pip), the dashboard will forbid the trade.
-- Dead Zone Start/End (Hour): Hard-coded risk management. By default, it blocks all signals between 17:00 and 18:00 EST (New York Close) to protect you from high-spread rollover hours.
-- HMA Time Dilation: A smoothing factor to prevent noise on 1-second charts.
DISCLAIMER
This tool is for informational purposes only. It measures past velocity to rank current momentum. Past performance is not indicative of future results. Always verify the actual bid/ask spread on your broker before executing, as the script uses a fixed spread calculation.
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.
Volume Z-Score Volume Z-Score measures how current volume deviates from its historical average to detect extreme market activity or exhaustion.
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.
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
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
ATR% Z-Score Z-Score of ATR% measures price volatility intensity relative to its historical average to identify extreme panic.
Chitranjan Shastri: Fixed Ultra-Clear Pilotits simple for everyday market you have to insert everyday points manually so its give you ranger where you to trade or where you have to ignore trade
Daily Range Risk Filter by nq.rew1ndThe Daily Range Risk Filter is a TradingView indicator that measures intraday range consumption to help traders assess how much of the day’s potential movement has already occurred. It provides a visual heatmap, session-specific analysis, and probability metrics to guide risk management and prevent overtrading.
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.






















