VolCorrBeta [NariCapitalTrading]Indicator Overview: VolCorrBeta
The VolCorrBeta indicator is designed to analyze and interpret intermarket relationships. This indicator combines volatility, correlation, and beta calculations to provide a comprehensive view of how certain assets (BTC, DXY, CL) influence the ES futures contract (I tailored this indicator to the ES contract, but it will work for any symbol).
Functionality
Input Symbols
BTCUSD : Bitcoin to USD
DXY : US Dollar Index
CL1! : Crude Oil Futures
ES1! : S&P 500 Futures
These symbols can be customized according to user preferences. The main focus of the indicator is to analyze how the price movements of these assets correlate with and lead the price movements of the ES futures contract.
Parameters for Calculation
Correlation Length : Number of periods for calculating the correlation.
Standard Deviation Length : Number of periods for calculating the standard deviation.
Lookback Period for Beta : Number of periods for calculating beta.
Volatility Filter Length : Length of the volatility filter.
Volatility Threshold : Threshold for adjusting the lookback period based on volatility.
Key Calculations
Returns Calculation : Computes the daily returns for each input symbol.
Correlation Calculation : Computes the correlation between each input symbol's returns and the ES futures contract returns over the specified correlation length.
Standard Deviation Calculation : Computes the standard deviation for each input symbol's returns and the ES futures contract returns.
Beta Calculation : Computes the beta for each input symbol relative to the ES futures contract.
Weighted Returns Calculation : Computes the weighted returns based on the calculated betas.
Lead-Lag Indicator : Calculates a lead-lag indicator by averaging the weighted returns.
Volatility Filter : Smooths the lead-lag indicator using a simple moving average.
Price Target Estimation : Estimates the ES price target based on the lead-lag indicator (the yellow line on the chart).
Dynamic Stop Loss (SL) and Take Profit (TP) Levels : Calculates dynamic SL and TP levels using volatility bands.
Signal Generation
The indicator generates buy and sell signals based on the filtered lead-lag indicator and confirms them using higher timeframe analysis. Signals are debounced to reduce frequency, ensuring that only significant signals are considered.
Visualization
Background Coloring : The background color changes based on the buy and sell signals for easy visualization (user can toggle this on/off).
Signal Labels : Labels with arrows are plotted on the chart, showing the signal type (buy/sell), the entry price, TP, and SL levels.
Estimated ES Price Target : The estimated price target for ES futures is plotted on the chart.
Correlation and Beta Dashboard : A table displayed in the top right corner shows the current correlation and beta values for relative to the ES futures contract.
Customization
Traders can customize the following parameters to tailor the indicator to their specific needs:
Input Symbols : Change the symbols for BTC, DXY, CL, and ES.
Correlation Length : Adjust the number of periods used for calculating correlation.
Standard Deviation Length : Adjust the number of periods used for calculating standard deviation.
Lookback Period for Beta : Change the lookback period for calculating beta.
Volatility Filter Length : Modify the length of the volatility filter.
Volatility Threshold : Set a threshold for adjusting the lookback period based on volatility.
Plotting Options : Customize the colors and line widths of the plotted elements.
Tìm kiếm tập lệnh với "Futures"
Henry's Vwap-VolumeThis Indicator is meant to provide Futures Volume and Vwap Signal in spot charts of Nifty and Banknifty Traders.
Concepts and Features of this indicators are as follows :
1) Now u don't have to select and change to futures scrip often or have both spot and futures chart in same window to watch the Futures Volume and Vwap.
2) U get Both Volume and Vwap signal as a indicator in single pane.
3) Its for Nifty and Banknifty Traders specially.
4)Volume with moving average is from the futures chart of banknifty or nifty,also may select any other futures script as per ur need.
(MOVING AVERAGE of VOLUME is plotted in Blue columns over the Volume.)
5)Vwap signal is also derived from the futures chart of banknifty or nifty,also may select any other futures script as per ur need.
(VWAP SIGNAL is plotted in GREEN or RED as background.If futures price higher than Vwap then Green , opposite for Red. )
6)The idea of this script is to give extra confirmation of a clear down or uptrend while u are in the spot chart.(nifty and banknifty)
7) U can select and change any scrip u like.But I urge to use futures chart of banknifty or nifty.
I hope this indicator will help a lot of retail investor save their hard earned money in the stock market and benefit from Mr. NK's strategy.
How to Use :
Go Long - when background is Green.
Go Short -when background is Red.
(Also take confirmation from the blue columns -moving average of volumes.volume higher or less than it.)
Limitations :
U can only use it for intraday,less than 1D timeframe.
Will not work in sideways market.
Take help of other indicators also like Rsi,adx,etc.
Best of Luck,
Henry
Crude Roll Trade SimulatorEDIT : The screen cap was unintended with the script publication. The yellow arrow is pointing to a different indicator I wrote. The "Roll Sim" indicator is shown below that one. Yes I could do a different screen cap, but then I'd have to rewrite this and frankly I don't have time. END EDIT
If you have ever wanted to visualize the contango / backwardation pressure of a roll trade, this script will help you approximate it.
I am writing this description in haste so go with me on my rough explanations.
A "roll trade" is one involving futures that are continually rolled over into future months. Popular roll trade instruments are USO (oil futures) and UVXY (volatility futures).
Roll trades suffer hits from contango but get rewarded in periods of backwardation. Use this script to track the contango / backwardation pressure on what you are trading.
That involves identifying and providing both the underlying indexes and derivatives for both the front and back month of the roll trade. What does that mean? Well the defaults simulate (crudely) the UVXY roll trade: The folks at Proshares buy futures that expire 60 days away and then sell those 30 days later as short term futures (again, this is a crude description - see the prospectus) and we simulate that by providing the Roll Sim indicator the symbols VIX and VXV along with VIXY and VIXM. We also provide the days between the purchase and sale of the rolled futures contract (in sessions, which is 22 days by my reckoning).
The script performs ema smoothing and plots both the index lines (VIX and VXV as solid lines in our case) and the derivatives (VIXY and VIXM as dotted lines in our case) with the line graphs offset by the number of sessions between the buy and sell. The gap you see represents the contango / backwardation the derivative roll trades are experiencing and gives you an idea how much movement has to happen for that gap to widen, contract or even invert. The background gets painted red in periods of backwardation (when the longer term futures cost less than when sold as short term futures).
Fortunately indexes are calibrated to the same underlying factors, so their values relative to each other are meaningful (ie VXV of 18 and VIX of 15 are based on the same calculation on premiums for S&P500 symbols, with VXV being normally higher for time value). That means the indexes graph well without and adjustments needed. Unfortunately derivatives suffer contango / backwardation at different rates so the value of VIXY vs VIXM isn't really meaningful (VIXY may take a reverse split one year while VIXM doesn't) ... what is meaningful is their relative change in value day to day. So I have included a "front month multiplier" which can be used to get the front month line "moved up or down" on the screen so it can be compared to the back month.
As a practical matter, I have come to hide the lines for the derivatives (like VIXY and VIXM) and just focus on the gap changes between the indexes which gives me an idea of what is going on in the market and what contango/backwardation pressure is likely to exist next week.
Hope it is useful to you.
Adaptive Market Wave TheoryAdaptive Market Wave Theory
🌊 CORE INNOVATION: PROBABILISTIC PHASE DETECTION WITH MULTI-AGENT CONSENSUS
Adaptive Market Wave Theory (AMWT) represents a fundamental paradigm shift in how traders approach market phase identification. Rather than counting waves subjectively or drawing static breakout levels, AMWT treats the market as a hidden state machine —using Hidden Markov Models, multi-agent consensus systems, and reinforcement learning algorithms to quantify what traditional methods leave to interpretation.
The Wave Analysis Problem:
Traditional wave counting methodologies (Elliott Wave, harmonic patterns, ABC corrections) share fatal weaknesses that AMWT directly addresses:
1. Non-Falsifiability : Invalid wave counts can always be "recounted" or "adjusted." If your Wave 3 fails, it becomes "Wave 3 of a larger degree" or "actually Wave C." There's no objective failure condition.
2. Observer Bias : Two expert wave analysts examining the same chart routinely reach different conclusions. This isn't a feature—it's a fundamental methodology flaw.
3. No Confidence Measure : Traditional analysis says "This IS Wave 3." But with what probability? 51%? 95%? The binary nature prevents proper position sizing and risk management.
4. Static Rules : Fixed Fibonacci ratios and wave guidelines cannot adapt to changing market regimes. What worked in 2019 may fail in 2024.
5. No Accountability : Wave methodologies rarely track their own performance. There's no feedback loop to improve.
The AMWT Solution:
AMWT addresses each limitation through rigorous mathematical frameworks borrowed from speech recognition, machine learning, and reinforcement learning:
• Non-Falsifiability → Hard Invalidation : Wave hypotheses die permanently when price violates calculated invalidation levels. No recounting allowed.
• Observer Bias → Multi-Agent Consensus : Three independent analytical agents must agree. Single-methodology bias is eliminated.
• No Confidence → Probabilistic States : Every market state has a calculated probability from Hidden Markov Model inference. "72% probability of impulse state" replaces "This is Wave 3."
• Static Rules → Adaptive Learning : Thompson Sampling multi-armed bandits learn which agents perform best in current conditions. The system adapts in real-time.
• No Accountability → Performance Tracking : Comprehensive statistics track every signal's outcome. The system knows its own performance.
The Core Insight:
"Traditional wave analysis asks 'What count is this?' AMWT asks 'What is the probability we are in an impulsive state, with what confidence, confirmed by how many independent methodologies, and anchored to what liquidity event?'"
🔬 THEORETICAL FOUNDATION: HIDDEN MARKOV MODELS
Why Hidden Markov Models?
Markets exist in hidden states that we cannot directly observe—only their effects on price are visible. When the market is in an "impulse up" state, we see rising prices, expanding volume, and trending indicators. But we don't observe the state itself—we infer it from observables.
This is precisely the problem Hidden Markov Models (HMMs) solve. Originally developed for speech recognition (inferring words from sound waves), HMMs excel at estimating hidden states from noisy observations.
HMM Components:
1. Hidden States (S) : The unobservable market conditions
2. Observations (O) : What we can measure (price, volume, indicators)
3. Transition Matrix (A) : Probability of moving between states
4. Emission Matrix (B) : Probability of observations given each state
5. Initial Distribution (π) : Starting state probabilities
AMWT's Six Market States:
State 0: IMPULSE_UP
• Definition: Strong bullish momentum with high participation
• Observable Signatures: Rising prices, expanding volume, RSI >60, price above upper Bollinger Band, MACD histogram positive and rising
• Typical Duration: 5-20 bars depending on timeframe
• What It Means: Institutional buying pressure, trend acceleration phase
State 1: IMPULSE_DN
• Definition: Strong bearish momentum with high participation
• Observable Signatures: Falling prices, expanding volume, RSI <40, price below lower Bollinger Band, MACD histogram negative and falling
• Typical Duration: 5-20 bars (often shorter than bullish impulses—markets fall faster)
• What It Means: Institutional selling pressure, panic or distribution acceleration
State 2: CORRECTION
• Definition: Counter-trend consolidation with declining momentum
• Observable Signatures: Sideways or mild counter-trend movement, contracting volume, RSI returning toward 50, Bollinger Bands narrowing
• Typical Duration: 8-30 bars
• What It Means: Profit-taking, digestion of prior move, potential accumulation for next leg
State 3: ACCUMULATION
• Definition: Base-building near lows where informed participants absorb supply
• Observable Signatures: Price near recent lows but not making new lows, volume spikes on up bars, RSI showing positive divergence, tight range
• Typical Duration: 15-50 bars
• What It Means: Smart money buying from weak hands, preparing for markup phase
State 4: DISTRIBUTION
• Definition: Top-forming near highs where informed participants distribute holdings
• Observable Signatures: Price near recent highs but struggling to advance, volume spikes on down bars, RSI showing negative divergence, widening range
• Typical Duration: 15-50 bars
• What It Means: Smart money selling to late buyers, preparing for markdown phase
State 5: TRANSITION
• Definition: Regime change period with mixed signals and elevated uncertainty
• Observable Signatures: Conflicting indicators, whipsaw price action, no clear momentum, high volatility without direction
• Typical Duration: 5-15 bars
• What It Means: Market deciding next direction, dangerous for directional trades
The Transition Matrix:
The transition matrix A captures the probability of moving from one state to another. AMWT initializes with empirically-derived values then updates online:
From/To IMP_UP IMP_DN CORR ACCUM DIST TRANS
IMP_UP 0.70 0.02 0.20 0.02 0.04 0.02
IMP_DN 0.02 0.70 0.20 0.04 0.02 0.02
CORR 0.15 0.15 0.50 0.10 0.10 0.00
ACCUM 0.30 0.05 0.15 0.40 0.05 0.05
DIST 0.05 0.30 0.15 0.05 0.40 0.05
TRANS 0.20 0.20 0.20 0.15 0.15 0.10
Key Insights from Transition Probabilities:
• Impulse states are sticky (70% self-transition): Once trending, markets tend to continue
• Corrections can transition to either impulse direction (15% each): The next move after correction is uncertain
• Accumulation strongly favors IMP_UP transition (30%): Base-building leads to rallies
• Distribution strongly favors IMP_DN transition (30%): Topping leads to declines
The Viterbi Algorithm:
Given a sequence of observations, how do we find the most likely state sequence? This is the Viterbi algorithm—dynamic programming to find the optimal path through the state space.
Mathematical Formulation:
δ_t(j) = max_i × B_j(O_t)
Where:
δ_t(j) = probability of most likely path ending in state j at time t
A_ij = transition probability from state i to state j
B_j(O_t) = emission probability of observation O_t given state j
AMWT Implementation:
AMWT runs Viterbi over a rolling window (default 50 bars), computing the most likely state sequence and extracting:
• Current state estimate
• State confidence (probability of current state vs alternatives)
• State sequence for pattern detection
Online Learning (Baum-Welch Adaptation):
Unlike static HMMs, AMWT continuously updates its transition and emission matrices based on observed market behavior:
f_onlineUpdateHMM(prev_state, curr_state, observation, decay) =>
// Update transition matrix
A *= decay
A += (1.0 - decay)
// Renormalize row
// Update emission matrix
B *= decay
B += (1.0 - decay)
// Renormalize row
The decay parameter (default 0.85) controls adaptation speed:
• Higher decay (0.95): Slower adaptation, more stable, better for consistent markets
• Lower decay (0.80): Faster adaptation, more reactive, better for regime changes
Why This Matters for Trading:
Traditional indicators give you a number (RSI = 72). AMWT gives you a probabilistic state assessment :
"There is a 78% probability we are in IMPULSE_UP state, with 15% probability of CORRECTION and 7% distributed among other states. The transition matrix suggests 70% chance of remaining in IMPULSE_UP next bar, 20% chance of transitioning to CORRECTION."
This enables:
• Position sizing by confidence : 90% confidence = full size; 60% confidence = half size
• Risk management by transition probability : High correction probability = tighten stops
• Strategy selection by state : IMPULSE = trend-follow; CORRECTION = wait; ACCUMULATION = scale in
🎰 THE 3-BANDIT CONSENSUS SYSTEM
The Multi-Agent Philosophy:
No single analytical methodology works in all market conditions. Trend-following excels in trending markets but gets chopped in ranges. Mean-reversion excels in ranges but gets crushed in trends. Structure-based analysis works when structure is clear but fails in chaotic markets.
AMWT's solution: employ three independent agents , each analyzing the market from a different perspective, then use Thompson Sampling to learn which agents perform best in current conditions.
Agent 1: TREND AGENT
Philosophy : Markets trend. Follow the trend until it ends.
Analytical Components:
• EMA Alignment: EMA8 > EMA21 > EMA50 (bullish) or inverse (bearish)
• MACD Histogram: Direction and rate of change
• Price Momentum: Close relative to ATR-normalized movement
• VWAP Position: Price above/below volume-weighted average price
Signal Generation:
Strong Bull: EMA aligned bull AND MACD histogram > 0 AND momentum > 0.3 AND close > VWAP
→ Signal: +1 (Long), Confidence: 0.75 + |momentum| × 0.4
Moderate Bull: EMA stack bull AND MACD rising AND momentum > 0.1
→ Signal: +1 (Long), Confidence: 0.65 + |momentum| × 0.3
Strong Bear: EMA aligned bear AND MACD histogram < 0 AND momentum < -0.3 AND close < VWAP
→ Signal: -1 (Short), Confidence: 0.75 + |momentum| × 0.4
Moderate Bear: EMA stack bear AND MACD falling AND momentum < -0.1
→ Signal: -1 (Short), Confidence: 0.65 + |momentum| × 0.3
When Trend Agent Excels:
• Trend days (IB extension >1.5x)
• Post-breakout continuation
• Institutional accumulation/distribution phases
When Trend Agent Fails:
• Range-bound markets (ADX <20)
• Chop zones after volatility spikes
• Reversal days at major levels
Agent 2: REVERSION AGENT
Philosophy: Markets revert to mean. Extreme readings reverse.
Analytical Components:
• Bollinger Band Position: Distance from bands, percent B
• RSI Extremes: Overbought (>70) and oversold (<30)
• Stochastic: %K/%D crossovers at extremes
• Band Squeeze: Bollinger Band width contraction
Signal Generation:
Oversold Bounce: BB %B < 0.20 AND RSI < 35 AND Stochastic < 25
→ Signal: +1 (Long), Confidence: 0.70 + (30 - RSI) × 0.01
Overbought Fade: BB %B > 0.80 AND RSI > 65 AND Stochastic > 75
→ Signal: -1 (Short), Confidence: 0.70 + (RSI - 70) × 0.01
Squeeze Fire Bull: Band squeeze ending AND close > upper band
→ Signal: +1 (Long), Confidence: 0.65
Squeeze Fire Bear: Band squeeze ending AND close < lower band
→ Signal: -1 (Short), Confidence: 0.65
When Reversion Agent Excels:
• Rotation days (price stays within IB)
• Range-bound consolidation
• After extended moves without pullback
When Reversion Agent Fails:
• Strong trend days (RSI can stay overbought for days)
• Breakout moves
• News-driven directional moves
Agent 3: STRUCTURE AGENT
Philosophy: Market structure reveals institutional intent. Follow the smart money.
Analytical Components:
• Break of Structure (BOS): Price breaks prior swing high/low
• Change of Character (CHOCH): First break against prevailing trend
• Higher Highs/Higher Lows: Bullish structure
• Lower Highs/Lower Lows: Bearish structure
• Liquidity Sweeps: Stop runs that reverse
Signal Generation:
BOS Bull: Price breaks above prior swing high with momentum
→ Signal: +1 (Long), Confidence: 0.70 + structure_strength × 0.2
CHOCH Bull: First higher low after downtrend, breaking structure
→ Signal: +1 (Long), Confidence: 0.75
BOS Bear: Price breaks below prior swing low with momentum
→ Signal: -1 (Short), Confidence: 0.70 + structure_strength × 0.2
CHOCH Bear: First lower high after uptrend, breaking structure
→ Signal: -1 (Short), Confidence: 0.75
Liquidity Sweep Long: Price sweeps below swing low then reverses strongly
→ Signal: +1 (Long), Confidence: 0.80
Liquidity Sweep Short: Price sweeps above swing high then reverses strongly
→ Signal: -1 (Short), Confidence: 0.80
When Structure Agent Excels:
• After liquidity grabs (stop runs)
• At major swing points
• During institutional accumulation/distribution
When Structure Agent Fails:
• Choppy, structureless markets
• During news events (structure becomes noise)
• Very low timeframes (noise overwhelms structure)
Thompson Sampling: The Bandit Algorithm
With three agents giving potentially different signals, how do we decide which to trust? This is the multi-armed bandit problem —balancing exploitation (using what works) with exploration (testing alternatives).
Thompson Sampling Solution:
Each agent maintains a Beta distribution representing its success/failure history:
Agent success rate modeled as Beta(α, β)
Where:
α = number of successful signals + 1
β = number of failed signals + 1
On Each Bar:
1. Sample from each agent's Beta distribution
2. Weight agent signals by sampled probabilities
3. Combine weighted signals into consensus
4. Update α/β based on trade outcomes
Mathematical Implementation:
// Beta sampling via Gamma ratio method
f_beta_sample(alpha, beta) =>
g1 = f_gamma_sample(alpha)
g2 = f_gamma_sample(beta)
g1 / (g1 + g2)
// Thompson Sampling selection
for each agent:
sampled_prob = f_beta_sample(agent.alpha, agent.beta)
weight = sampled_prob / sum(all_sampled_probs)
consensus += agent.signal × agent.confidence × weight
Why Thompson Sampling?
• Automatic Exploration : Agents with few samples get occasional chances (high variance in Beta distribution)
• Bayesian Optimal : Mathematically proven optimal solution to exploration-exploitation tradeoff
• Uncertainty-Aware : Small sample size = more exploration; large sample size = more exploitation
• Self-Correcting : Poor performers naturally get lower weights over time
Example Evolution:
Day 1 (Initial):
Trend Agent: Beta(1,1) → samples ~0.50 (high uncertainty)
Reversion Agent: Beta(1,1) → samples ~0.50 (high uncertainty)
Structure Agent: Beta(1,1) → samples ~0.50 (high uncertainty)
After 50 Signals:
Trend Agent: Beta(28,23) → samples ~0.55 (moderate confidence)
Reversion Agent: Beta(18,33) → samples ~0.35 (underperforming)
Structure Agent: Beta(32,19) → samples ~0.63 (outperforming)
Result: Structure Agent now receives highest weight in consensus
Consensus Requirements by Mode:
Aggressive Mode:
• Minimum 1/3 agents agreeing
• Consensus threshold: 45%
• Use case: More signals, higher risk tolerance
Balanced Mode:
• Minimum 2/3 agents agreeing
• Consensus threshold: 55%
• Use case: Standard trading
Conservative Mode:
• Minimum 2/3 agents agreeing
• Consensus threshold: 65%
• Use case: Higher quality, fewer signals
Institutional Mode:
• Minimum 2/3 agents agreeing
• Consensus threshold: 75%
• Additional: Session quality >0.65, mode adjustment +0.10
• Use case: Highest quality signals only
🌀 INTELLIGENT CHOP DETECTION ENGINE
The Chop Problem:
Most trading losses occur not from being wrong about direction, but from trading in conditions where direction doesn't exist . Choppy, range-bound markets generate false signals from every methodology—trend-following, mean-reversion, and structure-based alike.
AMWT's chop detection engine identifies these low-probability environments before signals fire, preventing the most damaging trades.
Five-Factor Chop Analysis:
Factor 1: ADX Component (25% weight)
ADX (Average Directional Index) measures trend strength regardless of direction.
ADX < 15: Very weak trend (high chop score)
ADX 15-20: Weak trend (moderate chop score)
ADX 20-25: Developing trend (low chop score)
ADX > 25: Strong trend (minimal chop score)
adx_chop = (i_adxThreshold - adx_val) / i_adxThreshold × 100
Why ADX Works: ADX synthesizes +DI and -DI movements. Low ADX means price is moving but not directionally—the definition of chop.
Factor 2: Choppiness Index (25% weight)
The Choppiness Index measures price efficiency using the ratio of ATR sum to price range:
CI = 100 × LOG10(SUM(ATR, n) / (Highest - Lowest)) / LOG10(n)
CI > 61.8: Choppy (range-bound, inefficient movement)
CI < 38.2: Trending (directional, efficient movement)
CI 38.2-61.8: Transitional
chop_idx_score = (ci_val - 38.2) / (61.8 - 38.2) × 100
Why Choppiness Index Works: In trending markets, price covers distance efficiently (low ATR sum relative to range). In choppy markets, price oscillates wildly but goes nowhere (high ATR sum relative to range).
Factor 3: Range Compression (20% weight)
Compares recent range to longer-term range, detecting volatility squeezes:
recent_range = Highest(20) - Lowest(20)
longer_range = Highest(50) - Lowest(50)
compression = 1 - (recent_range / longer_range)
compression > 0.5: Strong squeeze (potential breakout imminent)
compression < 0.2: No compression (normal volatility)
range_compression_score = compression × 100
Why Range Compression Matters: Compression precedes expansion. High compression = market coiling, preparing for move. Signals during compression often fail because the breakout hasn't occurred yet.
Factor 4: Channel Position (15% weight)
Tracks price position within the macro channel:
channel_position = (close - channel_low) / (channel_high - channel_low)
position 0.4-0.6: Center of channel (indecision zone)
position <0.2 or >0.8: Near extremes (potential reversal or breakout)
channel_chop = abs(0.5 - channel_position) < 0.15 ? high_score : low_score
Why Channel Position Matters: Price in the middle of a range is in "no man's land"—equally likely to go either direction. Signals in the channel center have lower probability.
Factor 5: Volume Quality (15% weight)
Assesses volume relative to average:
vol_ratio = volume / SMA(volume, 20)
vol_ratio < 0.7: Low volume (lack of conviction)
vol_ratio 0.7-1.3: Normal volume
vol_ratio > 1.3: High volume (conviction present)
volume_chop = vol_ratio < 0.8 ? (1 - vol_ratio) × 100 : 0
Why Volume Quality Matters: Low volume moves lack institutional participation. These moves are more likely to reverse or stall.
Combined Chop Intensity:
chopIntensity = (adx_chop × 0.25) + (chop_idx_score × 0.25) +
(range_compression_score × 0.20) + (channel_chop × 0.15) +
(volume_chop × i_volumeChopWeight × 0.15)
Regime Classifications:
Based on chop intensity and component analysis:
• Strong Trend (0-20%): ADX >30, clear directional momentum, trade aggressively
• Trending (20-35%): ADX >20, moderate directional bias, trade normally
• Transitioning (35-50%): Mixed signals, regime change possible, reduce size
• Mid-Range (50-60%): Price trapped in channel center, avoid new positions
• Ranging (60-70%): Low ADX, price oscillating within bounds, fade extremes only
• Compression (70-80%): Volatility squeeze, expansion imminent, wait for breakout
• Strong Chop (80-100%): Multiple chop factors aligned, avoid trading entirely
Signal Suppression:
When chop intensity exceeds the configurable threshold (default 80%), signals are suppressed entirely. The dashboard displays "⚠️ CHOP ZONE" with the current regime classification.
Chop Box Visualization:
When chop is detected, AMWT draws a semi-transparent box on the chart showing the chop zone. This visual reminder helps traders avoid entering positions during unfavorable conditions.
💧 LIQUIDITY ANCHORING SYSTEM
The Liquidity Concept:
Markets move from liquidity pool to liquidity pool. Stop losses cluster at predictable locations—below swing lows (buy stops become sell orders when triggered) and above swing highs (sell stops become buy orders when triggered). Institutions know where these clusters are and often engineer moves to trigger them before reversing.
AMWT identifies and tracks these liquidity events, using them as anchors for signal confidence.
Liquidity Event Types:
Type 1: Volume Spikes
Definition: Volume > SMA(volume, 20) × i_volThreshold (default 2.8x)
Interpretation: Sudden volume surge indicates institutional activity
• Near swing low + reversal: Likely accumulation
• Near swing high + reversal: Likely distribution
• With continuation: Institutional conviction in direction
Type 2: Stop Runs (Liquidity Sweeps)
Definition: Price briefly exceeds swing high/low then reverses within N bars
Detection:
• Price breaks above recent swing high (triggering buy stops)
• Then closes back below that high within 3 bars
• Signal: Bullish stop run complete, reversal likely
Or inverse for bearish:
• Price breaks below recent swing low (triggering sell stops)
• Then closes back above that low within 3 bars
• Signal: Bearish stop run complete, reversal likely
Type 3: Absorption Events
Definition: High volume with small candle body
Detection:
• Volume > 2x average
• Candle body < 30% of candle range
• Interpretation: Large orders being filled without moving price
• Implication: Accumulation (at lows) or distribution (at highs)
Type 4: BSL/SSL Pools (Buy-Side/Sell-Side Liquidity)
BSL (Buy-Side Liquidity):
• Cluster of swing highs within ATR proximity
• Stop losses from shorts sit above these highs
• Breaking BSL triggers short covering (fuel for rally)
SSL (Sell-Side Liquidity):
• Cluster of swing lows within ATR proximity
• Stop losses from longs sit below these lows
• Breaking SSL triggers long liquidation (fuel for decline)
Liquidity Pool Mapping:
AMWT continuously scans for and maps liquidity pools:
// Detect swing highs/lows using pivot function
swing_high = ta.pivothigh(high, 5, 5)
swing_low = ta.pivotlow(low, 5, 5)
// Track recent swing points
if not na(swing_high)
bsl_levels.push(swing_high)
if not na(swing_low)
ssl_levels.push(swing_low)
// Display on chart with labels
Confluence Scoring Integration:
When signals fire near identified liquidity events, confluence scoring increases:
• Signal near volume spike: +10% confidence
• Signal after liquidity sweep: +15% confidence
• Signal at BSL/SSL pool: +10% confidence
• Signal aligned with absorption zone: +10% confidence
Why Liquidity Anchoring Matters:
Signals "in a vacuum" have lower probability than signals anchored to institutional activity. A long signal after a liquidity sweep below swing lows has trapped shorts providing fuel. A long signal in the middle of nowhere has no such catalyst.
📊 SIGNAL GRADING SYSTEM
The Quality Problem:
Not all signals are created equal. A signal with 6/6 factors aligned is fundamentally different from a signal with 3/6 factors aligned. Traditional indicators treat them the same. AMWT grades every signal based on confluence.
Confluence Components (100 points total):
1. Bandit Consensus Strength (25 points)
consensus_str = weighted average of agent confidences
score = consensus_str × 25
Example:
Trend Agent: +1 signal, 0.80 confidence, 0.35 weight
Reversion Agent: 0 signal, 0.50 confidence, 0.25 weight
Structure Agent: +1 signal, 0.75 confidence, 0.40 weight
Weighted consensus = (0.80×0.35 + 0×0.25 + 0.75×0.40) / (0.35 + 0.40) = 0.77
Score = 0.77 × 25 = 19.25 points
2. HMM State Confidence (15 points)
score = hmm_confidence × 15
Example:
HMM reports 82% probability of IMPULSE_UP
Score = 0.82 × 15 = 12.3 points
3. Session Quality (15 points)
Session quality varies by time:
• London/NY Overlap: 1.0 (15 points)
• New York Session: 0.95 (14.25 points)
• London Session: 0.70 (10.5 points)
• Asian Session: 0.40 (6 points)
• Off-Hours: 0.30 (4.5 points)
• Weekend: 0.10 (1.5 points)
4. Energy/Participation (10 points)
energy = (realized_vol / avg_vol) × 0.4 + (range / ATR) × 0.35 + (volume / avg_volume) × 0.25
score = min(energy, 1.0) × 10
5. Volume Confirmation (10 points)
if volume > SMA(volume, 20) × 1.5:
score = 10
else if volume > SMA(volume, 20):
score = 5
else:
score = 0
6. Structure Alignment (10 points)
For long signals:
• Bullish structure (HH + HL): 10 points
• Higher low only: 6 points
• Neutral structure: 3 points
• Bearish structure: 0 points
Inverse for short signals
7. Trend Alignment (10 points)
For long signals:
• Price > EMA21 > EMA50: 10 points
• Price > EMA21: 6 points
• Neutral: 3 points
• Against trend: 0 points
8. Entry Trigger Quality (5 points)
• Strong trigger (multiple confirmations): 5 points
• Moderate trigger (single confirmation): 3 points
• Weak trigger (marginal): 1 point
Grade Scale:
Total Score → Grade
85-100 → A+ (Exceptional—all factors aligned)
70-84 → A (Strong—high probability)
55-69 → B (Acceptable—proceed with caution)
Below 55 → C (Marginal—filtered by default)
Grade-Based Signal Brightness:
Signal arrows on the chart have transparency based on grade:
• A+: Full brightness (alpha = 0)
• A: Slight fade (alpha = 15)
• B: Moderate fade (alpha = 35)
• C: Significant fade (alpha = 55)
This visual hierarchy helps traders instantly identify signal quality.
Minimum Grade Filter:
Configurable filter (default: C) sets the minimum grade for signal display:
• Set to "A" for only highest-quality signals
• Set to "B" for moderate selectivity
• Set to "C" for all signals (maximum quantity)
🕐 SESSION INTELLIGENCE
Why Sessions Matter:
Markets behave differently at different times. The London open is fundamentally different from the Asian lunch hour. AMWT incorporates session-aware logic to optimize signal quality.
Session Definitions:
Asian Session (18:00-03:00 ET)
• Characteristics: Lower volatility, range-bound tendency, fewer institutional participants
• Quality Score: 0.40 (40% of peak quality)
• Strategy Implications: Fade extremes, expect ranges, smaller position sizes
• Best For: Mean-reversion setups, accumulation/distribution identification
London Session (03:00-12:00 ET)
• Characteristics: European institutional activity, volatility pickup, trend initiation
• Quality Score: 0.70 (70% of peak quality)
• Strategy Implications: Watch for trend development, breakouts more reliable
• Best For: Initial trend identification, structure breaks
New York Session (08:00-17:00 ET)
• Characteristics: Highest liquidity, US institutional activity, major moves
• Quality Score: 0.95 (95% of peak quality)
• Strategy Implications: Best environment for directional trades
• Best For: Trend continuation, momentum plays
London/NY Overlap (08:00-12:00 ET)
• Characteristics: Peak liquidity, both European and US participants active
• Quality Score: 1.0 (100%—maximum quality)
• Strategy Implications: Highest probability for successful breakouts and trends
• Best For: All signal types—this is prime time
Off-Hours
• Characteristics: Thin liquidity, erratic price action, gaps possible
• Quality Score: 0.30 (30% of peak quality)
• Strategy Implications: Avoid new positions, wider stops if holding
• Best For: Waiting
Smart Weekend Detection:
AMWT properly handles the Sunday evening futures open:
// Traditional (broken):
isWeekend = dayofweek == saturday OR dayofweek == sunday
// AMWT (correct):
anySessionActive = not na(asianTime) or not na(londonTime) or not na(nyTime)
isWeekend = calendarWeekend AND NOT anySessionActive
This ensures Sunday 6pm ET (when futures open) correctly shows "Asian Session" rather than "Weekend."
Session Transition Boosts:
Certain session transitions create trading opportunities:
• Asian → London transition: +15% confidence boost (volatility expansion likely)
• London → Overlap transition: +20% confidence boost (peak liquidity approaching)
• Overlap → NY-only transition: -10% confidence adjustment (liquidity declining)
• Any → Off-Hours transition: Signal suppression recommended
📈 TRADE MANAGEMENT SYSTEM
The Signal Spam Problem:
Many indicators generate signal after signal, creating confusion and overtrading. AMWT implements a complete trade lifecycle management system that prevents signal spam and tracks performance.
Trade Lock Mechanism:
Once a signal fires, the system enters a "trade lock" state:
Trade Lock Duration: Configurable (default 30 bars)
Early Exit Conditions:
• TP3 hit (full target reached)
• Stop Loss hit (trade failed)
• Lock expiration (time-based exit)
During lock:
• No new signals of same type displayed
• Opposite signals can override (reversal)
• Trade status tracked in dashboard
Target Levels:
Each signal generates three profit targets based on ATR:
TP1 (Conservative Target)
• Default: 1.0 × ATR
• Purpose: Quick partial profit, reduce risk
• Action: Take 30-40% off position, move stop to breakeven
TP2 (Standard Target)
• Default: 2.5 × ATR
• Purpose: Main profit target
• Action: Take 40-50% off position, trail stop
TP3 (Extended Target)
• Default: 5.0 × ATR
• Purpose: Runner target for trend days
• Action: Close remaining position or continue trailing
Stop Loss:
• Default: 1.9 × ATR from entry
• Purpose: Define maximum risk
• Placement: Below recent swing low (longs) or above recent swing high (shorts)
Invalidation Level:
Beyond stop loss, AMWT calculates an "invalidation" level where the wave hypothesis dies:
invalidation = entry - (ATR × INVALIDATION_MULT × 1.5)
If price reaches invalidation, the current market interpretation is wrong—not just the trade.
Visual Trade Management:
During active trades, AMWT displays:
• Entry arrow with grade label (▲A+, ▼B, etc.)
• TP1, TP2, TP3 horizontal lines in green
• Stop Loss line in red
• Invalidation line in orange (dashed)
• Progress indicator in dashboard
Persistent Execution Markers:
When targets or stops are hit, permanent markers appear:
• TP hit: Green dot with "TP1"/"TP2"/"TP3" label
• SL hit: Red dot with "SL" label
These persist on the chart for review and statistics.
💰 PERFORMANCE TRACKING & STATISTICS
Tracked Metrics:
• Total Trades: Count of all signals that entered trade lock
• Winning Trades: Signals where at least TP1 was reached before SL
• Losing Trades: Signals where SL was hit before any TP
• Win Rate: Winning / Total × 100%
• Total R Profit: Sum of R-multiples from winning trades
• Total R Loss: Sum of R-multiples from losing trades
• Net R: Total R Profit - Total R Loss
Currency Conversion System:
AMWT can display P&L in multiple formats:
R-Multiple (Default)
• Shows risk-normalized returns
• "Net P&L: +4.2R | 78 trades" means 4.2 times initial risk gained over 78 trades
• Best for comparing across different position sizes
Currency Conversion (USD/EUR/GBP/JPY/INR)
• Converts R-multiples to currency based on:
- Dollar Risk Per Trade (user input)
- Tick Value (user input)
- Selected currency
Example Configuration:
Dollar Risk Per Trade: $100
Display Currency: USD
If Net R = +4.2R
Display: Net P&L: +$420.00 | 78 trades
Ticks
• For futures traders who think in ticks
• Converts based on tick value input
Statistics Reset:
Two reset methods:
1. Toggle Reset
• Turn "Reset Statistics" toggle ON then OFF
• Clears all statistics immediately
2. Date-Based Reset
• Set "Reset After Date" (YYYY-MM-DD format)
• Only trades after this date are counted
• Useful for isolating recent performance
🎨 VISUAL FEATURES
Macro Channel:
Dynamic regression-based channel showing market boundaries:
• Upper/lower bounds calculated from swing pivot linear regression
• Adapts to current market structure
• Shows overall trend direction and potential reversal zones
Chop Boxes:
Semi-transparent overlay during high-chop periods:
• Purple/orange coloring indicates dangerous conditions
• Visual reminder to avoid new positions
Confluence Heat Zones:
Background shading indicating setup quality:
• Darker shading = higher confluence
• Lighter shading = lower confluence
• Helps identify optimal entry timing
EMA Ribbon:
Trend visualization via moving average fill:
• EMA 8/21/50 with gradient fill between
• Green fill when bullish aligned
• Red fill when bearish aligned
• Gray when neutral
Absorption Zone Boxes:
Marks potential accumulation/distribution areas:
• High volume + small body = absorption
• Boxes drawn at these levels
• Often act as support/resistance
Liquidity Pool Lines:
BSL/SSL levels with labels:
• Dashed lines at liquidity clusters
• "BSL" label above swing high clusters
• "SSL" label below swing low clusters
Six Professional Themes:
• Quantum: Deep purples and cyans (default)
• Cyberpunk: Neon pinks and blues
• Professional: Muted grays and greens
• Ocean: Blues and teals
• Matrix: Greens and blacks
• Ember: Oranges and reds
🎓 PROFESSIONAL USAGE PROTOCOL
Phase 1: Learning the System (Week 1)
Goal: Understand AMWT concepts and dashboard interpretation
Setup:
• Signal Mode: Balanced
• Display: All features enabled
• Grade Filter: C (see all signals)
Actions:
• Paper trade ONLY—no real money
• Observe HMM state transitions throughout the day
• Note when agents agree vs disagree
• Watch chop detection engage and disengage
• Track which grades produce winners vs losers
Key Learning Questions:
• How often do A+ signals win vs B signals? (Should see clear difference)
• Which agent tends to be right in current market? (Check dashboard)
• When does chop detection save you from bad trades?
• How do signals near liquidity events perform vs signals in vacuum?
Phase 2: Parameter Optimization (Week 2)
Goal: Tune system to your instrument and timeframe
Signal Mode Testing:
• Run 5 days on Aggressive mode (more signals)
• Run 5 days on Conservative mode (fewer signals)
• Compare: Which produces better risk-adjusted returns?
Grade Filter Testing:
• Track A+ only for 20 signals
• Track A and above for 20 signals
• Track B and above for 20 signals
• Compare win rates and expectancy
Chop Threshold Testing:
• Default (80%): Standard filtering
• Try 70%: More aggressive filtering
• Try 90%: Less filtering
• Which produces best results for your instrument?
Phase 3: Strategy Development (Weeks 3-4)
Goal: Develop personal trading rules based on system signals
Position Sizing by Grade:
• A+ grade: 100% position size
• A grade: 75% position size
• B grade: 50% position size
• C grade: 25% position size (or skip)
Session-Based Rules:
• London/NY Overlap: Take all A/A+ signals
• NY Session: Take all A+ signals, selective on A
• Asian Session: Only A+ signals with extra confirmation
• Off-Hours: No new positions
Chop Zone Rules:
• Chop >70%: Reduce position size 50%
• Chop >80%: No new positions
• Chop <50%: Full position size allowed
Phase 4: Live Micro-Sizing (Month 2)
Goal: Validate paper trading results with minimal risk
Setup:
• 10-20% of intended full position size
• Take ONLY A+ signals initially
• Follow trade management religiously
Tracking:
• Log every trade: Entry, Exit, Grade, HMM State, Chop Level, Agent Consensus
• Calculate: Win rate by grade, by session, by chop level
• Compare to paper trading (should be within 15%)
Red Flags:
• Win rate diverges significantly from paper trading: Execution issues
• Consistent losses during certain sessions: Adjust session rules
• Losses cluster when specific agent dominates: Review that agent's logic
Phase 5: Scaling Up (Months 3-6)
Goal: Gradually increase to full position size
Progression:
• Month 3: 25-40% size (if micro-sizing profitable)
• Month 4: 40-60% size
• Month 5: 60-80% size
• Month 6: 80-100% size
Scale-Up Requirements:
• Minimum 30 trades at current size
• Win rate ≥50%
• Net R positive
• No revenge trading incidents
• Emotional control maintained
💡 DEVELOPMENT INSIGHTS
Why HMM Over Simple Indicators:
Early versions used standard indicators (RSI >70 = overbought, etc.). Win rates hovered at 52-55%. The problem: indicators don't capture state. RSI can stay "overbought" for weeks in a strong trend.
The insight: markets exist in states, and state persistence matters more than indicator levels. Implementing HMM with state transition probabilities increased signal quality significantly. The system now knows not just "RSI is high" but "we're in IMPULSE_UP state with 70% probability of staying in IMPULSE_UP."
The Multi-Agent Evolution:
Original version used a single analytical methodology—trend-following. Performance was inconsistent: great in trends, destroyed in ranges. Added mean-reversion agent: now it was inconsistent the other way.
The breakthrough: use multiple agents and let the system learn which works . Thompson Sampling wasn't the first attempt—tried simple averaging, voting, even hard-coded regime switching. Thompson Sampling won because it's mathematically optimal and automatically adapts without manual regime detection.
Chop Detection Revelation:
Chop detection was added almost as an afterthought. "Let's filter out obviously bad conditions." Testing revealed it was the most impactful single feature. Filtering chop zones reduced losing trades by 35% while only reducing total signals by 20%. The insight: avoiding bad trades matters more than finding good ones.
Liquidity Anchoring Discovery:
Watched hundreds of trades. Noticed pattern: signals that fired after liquidity events (stop runs, volume spikes) had significantly higher win rates than signals in quiet markets. Implemented liquidity detection and anchoring. Win rate on liquidity-anchored signals: 68% vs 52% on non-anchored signals.
The Grade System Impact:
Early system had binary signals (fire or don't fire). Adding grading transformed it. Traders could finally match position size to signal quality. A+ signals deserved full size; C signals deserved caution. Just implementing grade-based sizing improved portfolio Sharpe ratio by 0.3.
🚨 LIMITATIONS & CRITICAL ASSUMPTIONS
What AMWT Is NOT:
• NOT a Holy Grail : No system wins every trade. AMWT improves probability, not certainty.
• NOT Fully Automated : AMWT provides signals and analysis; execution requires human judgment.
• NOT News-Proof : Exogenous shocks (FOMC surprises, geopolitical events) invalidate all technical analysis.
• NOT for Scalping : HMM state estimation needs time to develop. Sub-minute timeframes are not appropriate.
Core Assumptions:
1. Markets Have States : Assumes markets transition between identifiable regimes. Violation: Random walk markets with no regime structure.
2. States Are Inferable : Assumes observable indicators reveal hidden states. Violation: Market manipulation creating false signals.
3. History Informs Future : Assumes past agent performance predicts future performance. Violation: Regime changes that invalidate historical patterns.
4. Liquidity Events Matter : Assumes institutional activity creates predictable patterns. Violation: Markets with no institutional participation.
Performs Best On:
• Liquid Futures : ES, NQ, MNQ, MES, CL, GC
• Major Forex Pairs : EUR/USD, GBP/USD, USD/JPY
• Large-Cap Stocks : AAPL, MSFT, TSLA, NVDA (>$5B market cap)
• Liquid Crypto : BTC, ETH on major exchanges
Performs Poorly On:
• Illiquid Instruments : Low volume stocks, exotic pairs
• Very Low Timeframes : Sub-5-minute charts (noise overwhelms signal)
• Binary Event Days : Earnings, FDA approvals, court rulings
• Manipulated Markets : Penny stocks, low-cap altcoins
Known Weaknesses:
• Warmup Period : HMM needs ~50 bars to initialize properly. Early signals may be unreliable.
• Regime Change Lag : Thompson Sampling adapts over time, not instantly. Sudden regime changes may cause short-term underperformance.
• Complexity : More parameters than simple indicators. Requires understanding to use effectively.
⚠️ RISK DISCLOSURE
Trading futures, stocks, options, forex, and cryptocurrencies involves substantial risk of loss and is not suitable for all investors. Adaptive Market Wave Theory, while based on rigorous mathematical frameworks including Hidden Markov Models and multi-armed bandit algorithms, does not guarantee profits and can result in significant losses.
AMWT's methodologies—HMM state estimation, Thompson Sampling agent selection, and confluence-based grading—have theoretical foundations but past performance is not indicative of future results.
Hidden Markov Model assumptions may not hold during:
• Major news events disrupting normal market behavior
• Flash crashes or circuit breaker events
• Low liquidity periods with erratic price action
• Algorithmic manipulation or spoofing
Multi-agent consensus assumes independent analytical perspectives provide edge. Market conditions change. Edges that existed historically can diminish or disappear.
Users must independently validate system performance on their specific instruments, timeframes, and broker execution environment. Paper trade extensively before risking capital. Start with micro position sizing.
Never risk more than you can afford to lose completely. Use proper position sizing. Implement stop losses without exception.
By using this indicator, you acknowledge these risks and accept full responsibility for all trading decisions and outcomes.
"Elliott Wave was a first-order approximation of market phase behavior. AMWT is the second—probabilistic, adaptive, and accountable."
Initial Public Release
Core Engine:
• True Hidden Markov Model with online Baum-Welch learning
• Viterbi algorithm for optimal state sequence decoding
• 6-state market regime classification
Agent System:
• 3-Bandit consensus (Trend, Reversion, Structure)
• Thompson Sampling with true Beta distribution sampling
• Adaptive weight learning based on performance
Signal Generation:
• Quality-based confluence grading (A+/A/B/C)
• Four signal modes (Aggressive/Balanced/Conservative/Institutional)
• Grade-based visual brightness
Chop Detection:
• 5-factor analysis (ADX, Choppiness Index, Range Compression, Channel Position, Volume)
• 7 regime classifications
• Configurable signal suppression threshold
Liquidity:
• Volume spike detection
• Stop run (liquidity sweep) identification
• BSL/SSL pool mapping
• Absorption zone detection
Trade Management:
• Trade lock with configurable duration
• TP1/TP2/TP3 targets
• ATR-based stop loss
• Persistent execution markers
Session Intelligence:
• Asian/London/NY/Overlap detection
• Smart weekend handling (Sunday futures open)
• Session quality scoring
Performance:
• Statistics tracking with reset functionality
• 7 currency display modes
• Win rate and Net R calculation
Visuals:
• Macro channel with linear regression
• Chop boxes
• EMA ribbon
• Liquidity pool lines
• 6 professional themes
Dashboards:
• Main Dashboard: Market State, Consensus, Trade Status, Statistics
📋 AMWT vs AMWT-PRO:
This version includes all core AMWT functionality:
✓ Full Hidden Markov Model state estimation
✓ 3-Bandit Thompson Sampling consensus system
✓ Complete 5-factor chop detection engine
✓ All four signal modes
✓ Full trade management with TP/SL tracking
✓ Main dashboard with complete statistics
✓ All visual features (channels, zones, pools)
✓ Identical signal generation to PRO
✓ Six professional themes
✓ Full alert system
The PRO version adds the AMWT Advisor panel—a secondary dashboard providing:
• Real-time Market Pulse situation assessment
• Agent Matrix visualization (individual agent votes)
• Structure analysis breakdown
• "Watch For" upcoming setups
• Action Command coaching
Both versions generate identical signals . The Advisor provides additional guidance for interpreting those signals.
Taking you to school. - Dskyz, Trade with probability. Trade with consensus. Trade with AMWT.
Minervini Trend Template upgrade - TP Minervini Trend Template (SMA/EMA + RS vs Major Indices)
Credits: Original script by © yogy.frestarahmawan (MPL 2.0).
Modified & updated by: © TradersPod (added MA selection + RS comparison vs major index futures).
This indicator is a simple checklist tool based on Mark Minervini’s “Trend Template” concept. It helps you quickly see if a stock is behaving like a leading stock in an uptrend by evaluating key trend and strength conditions.
What it does:
>The script checks 8 conditions and shows the results in a table panel on your chart:
>Price is above MA150 and MA200
>MA150 is above MA200 (a classic “healthy uptrend” structure)
>MA200 is rising vs ~1 month ago (uses 22 bars back)
>MA50 is above MA150 and MA200
>Price is above MA50
>Price is at least 25% above the 52-week low (stronger stocks tend to be far from lows)
>Price is within 25% of the 52-week high (leaders often stay near highs)
>RS is > Major Indices (TradersPod upgrade)
At the bottom, it also totals how many conditions are met: (X of 8).
TradersPod upgrades included
1) SMA/EMA selection
You can choose whether the trend template uses:
SMA (Simple Moving Average)
or
EMA (Exponential Moving Average)
This lets you match your preferred moving-average style without changing the logic.
2) RS must beat the major indices (futures)
Instead of the old “RS > 70” rule, this updated version requires the stock’s RS Rating to be greater than the strongest (highest RS) among:
-Nasdaq Futures (NQ)
-S&P 500 Futures (ES)
-Dow Jones Futures (YM)
The table shows the RS Rating for each index futures symbol and then confirms whether the stock is stronger than the best-performing major index.
In other words:
If the stock can’t outperform the major indices, it’s probably not a true “leader.”
Inputs / settings
MA Type: SMA or EMA
High/Low Lookback Length: default 260 bars (approx. 52 weeks on daily charts)
Show 52-week High/Low: toggle on/off
Major Indices Symbols: you can change the futures tickers if your broker/data feed uses different symbols
Panel Position: choose where the table appears
Notes (important)
The RS calculation uses the chart’s timeframe (ex: Daily, Weekly). On Weekly charts, the lookbacks become weeks (not days).
This tool is a trend/strength filter, not a full trading strategy. Always add your own risk management, entries, and exits.
Pair Creation🙏🏻 The one and only pair construction tech you need, unlike others:
Applies one consistent operation to all the data features (not only prices). Then, the script outputs these, so you can apply other calculations on these outputs.
calculates a very fast and native volatility based hedge ratio, that also takes into account point value (think SPY vs ES) so you can easily use it in position sizing
Has built-in forward pricing aka cost of carry model , so you can de-drift pairs from cost of carry, discover spot price of oil based on futures, and ofc find arbitrage opportunities
Also allows to make a pair as a product of 2 series, useful for triangular arbitrage
This script can make a pair in 2 ways:
Ratio, by dividing leg 1 by leg 2
Product, by multiplying leg 1 by leg 2
The real mathematically right way to construct a pair is a ratio/product (Spreads are in fact = 2 legged portfolio, but I ain't told ya that ok). Why? Because a pair of 2 entities has a mathematically unique beauty, it allows direct comparisons and relationship analysis, smth you can't do directly with 3 and more components.
Multiplication (think inversions like (EURUSD -> USDEUR), and use cases for triangular arbitrage) is useful sometimes too.
...
Quickguide:
First, "Legs" are pair components: make a pair of related assets. Don’t be guided exclusively by clustering, cointegrations, mutual information etc. Common sense and exogenous info can easily made them all Forward pricing model: is useful when u work with spot vs futures pairs. Otherwise: put financing, storage and yield all on zeros, this way u will turn it off and have a pure ratio/product of 2 legs.
Look at the 2 numbers on the script’s status line: the first one would always be 1), and the second one is a variable.
First number (always 1) is multiplier for your position size on leg 1
The second number is the multiplier for your position size on leg 2 in the opposite direction.
If both legs are related, trading your sizes with these multipliers makes you do statistical arbitrage -> trading ~ volatility in risk free mode, while the relationship between the assets is still in place.
Also guys srsly, nobody ‘ever’ made a universal law that somewhy somehow for whatever secret conspiracy reason one shall only trade pairs in mean reverting style xd. You can do whatever you want:
Tilt hedge ratio significantly based on relative strength of legs
Trade the pair in momentum style
Ignore hedge ratio all together
And more and more, the limit is your imagination, e.g.:
Anticipate hedge ratio changes based on exogenous info and act accordingly
Scalp a pair just like any other asset
Make a pair out of 2 pairs
Like I mean it, whatever you desire
About forward pricing model:
It’s applied only to leg 2;
Direct: takes spot price and finds out implied futures price
Inverse: takes futures price and finds out implied spot price (try on oil)
Pls read online how to choose parameters, it’s open access reliable info
About the hedge ratio I use:
You prolly noticed the way I prefer to use inferred volumes vs the “real” ones. In pairs it’s especially meaningful, because real volumes lose sense in pair creation. And while volumes are closely tied to volatility, the inferred volumes ‘Are’ volatility irl (and later can be converted to currency space by using point value, allowing direct comparisons symbol vs symbol).
This hedge ratio is a good example of how discovering the real nature of entities beats making 100s of inventions, why domain knowledge and proper feature engineering beats difficult bulky models, neural networks etc. How simple data understanding & operations on it is all you need.
This script simply does this:
Takes inferred volume delta of both assets, makes a ratio, normalizes it by tick sizes and points values of both legs, calculates a typical value of this series.
That’s it, no step 2, we’re done. No Kalman filters, no TLS regression, no vine copulas, or whatever new fancy keywords you can come up with etc.
...
^^ comparing real ES prices vs theoretical ones by forward-pricing model. Financing: 0.04, yield 0.0175
^^ EURUSD, 6E futures with theoretical futures price calculated with interest rate differential 0.02 (4% USD - 2% EUR interest rates)
^^4 different pairs (RTY/ES, YM/ES, NQ/ES, ES/ZN) each with different plot style (pick one you like in script's Style settings)
^^ YM/RTY pair, each plot represents ratio of different features: ratio of prices, ratio of inferred volume deltas, ratio of inferred volumes, ratio of inferred tick counts (also can be turned on/off in Style settings)
...
How can u upgrade it and make a step forward yourself:
On tradingview missing values are automatically fixed by backfilling, and this never becomes a thing until you hit high frequency data. You can do better and use Kalman filter for filling missing values.
Script contains the functions I use everywhere to calculate inferred volume delta, inferred volume, and inferred tick count.
...
∞
Donchian Predictive Channel (Zeiierman)█ Overview
Donchian Predictive Channel (Zeiierman) extends the classic Donchian framework into a predictive structure. It does not just track where the range has been; it projects where the Donchian mid, high, and low boundaries are statistically likely to move based on recent directional bias and volatility regime.
By quantifying the linear drift of the Donchian midline and the expansion or compression rate of the Donchian range, the indicator generates a forward propagation cone that reflects the prevailing trend and volatility state. This produces a cleaner, more analytically grounded projection of future price corridors, and it remains fully aligned with the signal precision of the underlying Donchian logic.
█ How It Works
⚪ Donchian Core
The script first computes a standard Donchian Channel over a configurable Length:
Upper Band (dcHi) – highest high over the lookback.
Lower Band (dcLo) – lowest low over the lookback.
Midline (dcMd) – simple midpoint of upper and lower: (dcHi + dcLo)/ 2.
f_getDonchian(length) =>
hi = ta.highest(high, length)
lo = ta.lowest(low, length)
md = (hi + lo) * 0.5
= f_getDonchian(lenDC)
⚪ Slope Estimation & Range Dynamics
To turn the Donchian Channel into a predictive model, the script measures how both the midline and the range are changing over time:
Midline Slope (mSl) – derived from a 1-bar difference in linear regression of the midline.
Range Slope (rSl) – derived from a 1-bar difference in linear regression of the Donchian range (dcHi − dcLo).
This pair describes both directional drift (uptrend vs. downtrend) and range expansion/compression (volatility regime).
f_getSlopes(midLine, rngVal, length) =>
mSl = ta.linreg(midLine, length, 0) - ta.linreg(midLine, length, 1)
rSl = ta.linreg(rngVal, length, 0) - ta.linreg(rngVal, length, 1)
⚪ Forward Projection Engine
At the last bar, the indicator constructs a set of forward points for the mid, upper, and lower projections over Forecast Bars:
The midline is projected linearly using the midline slope per bar.
The range is adjusted using the range slope per bar, creating either a widening cone (expansion) or a tightening cone (compression).
Upper and lower projections are then anchored around the projected midline, with logic that keeps the structure consistent and prevents pathological flips when slope changes sign.
f_generatePoints(hi0, md0, lo0, steps, midSlp, rngSlp) =>
upPts = array.new()
mdPts = array.new()
dnPts = array.new()
fillPts = array.new()
hi_vals = array.new_float()
md_vals = array.new_float()
lo_vals = array.new_float()
curHiLocal = hi0
curLoLocal = lo0
curMidLocal = md0
segBars = math.floor(steps / 3)
segBars := segBars < 1 ? 1 : segBars
for b = 0 to steps
mdProj = md0 + midSlp * b
prevRange = curHiLocal - curLoLocal
rngProj = prevRange + rngSlp * b
hiTemp = 0.0
loTemp = 0.0
if midSlp >= 0
hiTemp := math.max(curHiLocal, mdProj + rngProj * 0.5)
loTemp := math.max(curLoLocal, mdProj - rngProj * 0.5)
else
hiTemp := math.min(curHiLocal, mdProj + rngProj * 0.5)
loTemp := math.min(curLoLocal, mdProj - rngProj * 0.5)
hiProj = hiTemp < mdProj ? curHiLocal : hiTemp
loProj = loTemp > mdProj ? curLoLocal : loTemp
if b % segBars == 0
curHiLocal := hiProj
curLoLocal := loProj
curMidLocal := mdProj
array.push(hi_vals, curHiLocal)
array.push(md_vals, curMidLocal)
array.push(lo_vals, curLoLocal)
array.push(upPts, chart.point.from_index(bar_index + b, curHiLocal))
array.push(mdPts, chart.point.from_index(bar_index + b, curMidLocal))
array.push(dnPts, chart.point.from_index(bar_index + b, curLoLocal))
ptSet.new(upPts, mdPts, dnPts)
⚪ Rejection Signals
The script also tracks failed Donchian breakouts and marks them as potential reversal/reversion cues:
Signal Down: Triggered when price makes an attempt above the upper Donchian band but then pulls back inside and closes above the midline, provided enough bars have passed since the last signal.
Signal Up: Triggered when price makes an attempt below the lower Donchian band but then snaps back inside and closes below the midline, also requiring sufficient spacing from the previous signal.
// Base signal conditions (unfiltered)
bearCond = high < dcHi and high >= dcHi and close > dcMd and bar_index - lastMarker >= lenDC
bullCond = low > dcLo and low <= dcLo and close < dcMd and bar_index - lastMarker >= lenDC
// Apply MA filter if enabled
if signalfilter
bearCond := bearCond and close < ma // Bearish only below MA
bullCond := bullCond and close > ma // Bullish only above MA
signalUp := false
signalDn := false
if bearCond
lastMarker := bar_index
signalDn := true
if bullCond
lastMarker := bar_index
signalUp := true
█ How to Use
The Donchian Predictive Channel is designed to outline possible future price trajectories. Treat it as a directional guide, not a fixed prediction tool.
⚪ Map Future Support & Resistance
Use the projected upper and lower paths as dynamic future reference levels:
Projected upper band ≈ is likely a resistance corridor if the current trend and volatility persist.
Projected lower band ≈ likely support corridor or expected downside range.
⚪ Trend Path & Volatility Cone
Because the projection is driven by midline and range slopes, the channel behaves like a trend + volatility cone:
Steep positive midline slope + expanding range → accelerating, high-volatility trend.
Flat midline + compressing range → coiling/contracting regime ahead of potential expansion.
This helps you distinguish between a gentle drift and an aggressive move that likely needs more risk buffer.
⚪ Reversion & Rejection Signals
The Donchian-based signals are especially useful for mean-reversion and fade-style trades.
A Signal Down near the upper band can mark a failed breakout and a potential rotation back toward the midline or the lower projected band.
A Signal Up near the lower band can flag a failed breakdown and a potential snap-back up the channel.
When Filter Signals is enabled, these signals are only generated when they align with the chart’s directional bias as defined by the moving average. Bullish signals are allowed only when the price is above the MA, and bearish signals only when the price is below it.
This reduces noise and helps ensure that reversions occur in harmony with the prevailing trend environment.
█ Settings
Length – Donchian lookback length. Higher values produce a smoother channel with fewer but more stable signals. Lower values make the channel more reactive and increase sensitivity at the cost of more noise.
Forecast Bars – Number of bars used for projecting the Donchian channel forward.
Higher values create a broader, longer-term projection. Lower values focus on short-horizon price path scenarios.
Filter Signals – Enables directional filtering of Donchian signals using the selected moving average. When ON, bullish signals only trigger when the price is above the MA, and bearish signals only trigger when the price is below it. This helps reduce noise and aligns reversions with the broader trend context.
Moving Average Type – The type of moving average used for signal filtering and optional plotting.
Choose between SMA, EMA, WMA, or HMA depending on desired responsiveness. Faster averages (EMA, HMA) react quickly, while slower ones (SMA, WMA) smooth out short-term noise.
Moving Average Length – Lookback length of the moving average. Higher values create a slower, more stable trend filter. Lower values track price more tightly and can flip the directional bias more frequently.
-----------------
Disclaimer
The content provided in my scripts, indicators, ideas, algorithms, and systems is for educational and informational purposes only. It does not constitute financial advice, investment recommendations, or a solicitation to buy or sell any financial instruments. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
Camarilla Pivot Plays (Lite) [BruzX]█ OVERVIEW
This indicator implements the Camarilla Pivot Points levels and a system for suggesting particular plays. It only 3rd, 4th, and 6th levels, as these are the only ones used by the system. It also optionally shows the Central Pivot Range, which is in fact between S2 and R2. In total, there are 12 possible plays, grouped into two groups of six. The algorithm evaluates in real-time which plays fulfil their precondition and shows the candidate plays. The user must then decide if and when to take the play.
█ CREDITS
The Camarilla pivot plays are defined in a strategy developed by Thor Young, and the whole system is explained in his book "A Complete Day Trading System". This description is self-sufficient for effective use.
█ FEATURES
Display the 3rd, 4th and 6th Camarilla pivot levels
Works for stocks, futures, indices, forex and crypto
Automatically switches between RTH and ETH data based on criteria defined by the system.
Option to force RTH/ETH data and force a close price to be used in the calculation.
Preconditions for the plays can be toggled on/off
Works correctly on both RTH and ETH charts
Well-documented options tooltips
Well-documented and high-quality open-source code for those who are interested
█ HOW TO USE
The defaults work well; at a minimum, just add the indicator and watch the plays being called. For US futures, you will probably want to chat the "Timezone for sessions" to New York and the regular session times to 09:30 - 16:00. The following diagram shows its key features.
By default, the indicator draws plays 1 days back; this can be changed up to 20 days. The labels can be shifted left/right using the "label offset" option to avoid overlapping with other labels in this indicator or those of another indicator.
An information box at the top-right of the chart shows:
The data currently in use for the main pivots. This can switch in the pre-market if the H/L range exceeds the previous day's H/L, and if it does, you will see that switch at the time that it happens
Whether the current day's pivots are in a higher or lower range compared to the previous day's.
The width of the pivots compared to the previous day
The current candidate plays fulfilling preconditions. You then need to watch the price action to decide whether to take the play.
The resistance pivots are all drawn in the same colour (red by default), as are the support pivots (green by default). You can change the resistance and support colours, but it is not possible to have different colours for different levels of the same kind.
█ CONCEPTS
The indicator is focused around daily Camarilla pivots and evaluates the preconditions for 12 possible plays: 6 when in a higher range, 6 when in a lower range. The plays are labelled by two letters—the first indicates the range, the second indicates the play—as shown in this diagram:
The pivots can be calculated using only RTH (Regular Trading Hours) data, or ETH (Extended Trading Hours) data, which includes the pre-market and post-market. The indicator implements logic to automatically choose the correct data, based on the rules defined by the strategy. This is user-overridable. With the default options, ETH will be used when the H/L range in the previous day's post-market or current day's pre-market exceeds that of the previous day's regular market. In auto mode, the chosen pivots are considered the main pivots for that day and are the ones used for play evaluation. The "other" pivots can also be shown—"other" here meaning using ETH data when the main pivots use RTH data, and vice versa.
The plays must fulfil a set of preconditions. There are preconditions for valid region and range, price sweeps into levels, correct pivot width, opening position, price action, and whether neutral range plays and premarket plays are enabled. When all the preconditions are fulfilled, the play will be shown as a candidate.
█ NOTE FOR FUTURES
Futures don't officially have a pre-market or post-market like equities. Let's take ES on CME as an example. It trades from 18:00 ET Sunday to 17:00 Friday (ET), with a daily pause between 17:00 and 18:00 ET. However, most of the trading activity is done between 09:30 and 16:00, which you can tell from the volume spikes at those times, and this coincides with NYSE/NASDAQ regular hours. So we define a pseudo-pre-market from 18:00 the previous day to 09:30 on the current day, then a pseudo-regular market from 08:30 to 16:00, then a pseudo-post-market from 16:00 to 17:00. The indicator then works exactly the same as with equities—all the options behave the same, just with different session times defined for the pre-, regular, and post-market, with "RTH" meaning just the regular market and "ETH" meaning all three.
█ LIMITATIONS
The pivots are very close to those shown in DAS Trader Pro. They are not to-the-cent exact, but within a few cents. The reasons are:
TradingView provides free real-time data from CBOE One, not full exchange data (you can pay for this though, and it's not expensive), and
the close/high/low are taken from the intraday timeframe you are currently viewing, not daily data—which are very close, but often not exactly the same. For example, the high on the daily timeframe may differ slightly from the daily high you'll see on an intraday timeframe.
Despite these caveats, occasionally large spikes will be seem in one platform and not the other (even with paid data), or the spikes will reach significantly difference prices. Where these spikes create the daily high or low, this can cause significantly different pivots levels. The more traded the stock is, the less the difference tends to be. Highly traded stocks are usually within a few cents (but even they occasionally have large differences in spikes). There is nothing that can be done about this.
The 6th Camarilla level does not have a standard definition and may not match the level shown on other platforms. It does match the definition used by DAS Trader Pro.
Replay mode for stocks does not work correctly. This is due to some important Pine Script variables provided by the TradingView platform and used by the script not being assigned correct values in replay mode. Futures do not use these variables, so they should work in replay mode.
The indicator is an intraday indicator (despite also being able to show weekly and monthly pivots on an intraday chart). It deactivates on a daily timeframe and higher. Sub-minute timeframes are also not supported.
The indicator was developed and tested for US/European stocks, US futures and EURUSD forex and BTCUSD. It should work as intended for stocks and futures in different countries, and for all forex and crypto, but this is tested as much as the security it was developed for.
█ DISCLAIMER
This indicator is provided for information only and should not be used in isolation without a good understand of the system and without considering other factors. You should not take trades using real money based solely on what this indicator says. Any trades you take are entirely at your own risk.
PG ATM Strike Line with Call & Put PremiumsPine Script: ATM Strike Line with Call & Put Premiums (Simplified)This Pine Script for TradingView displays the At-The-Money (ATM) strike price, futures price, call/put premiums (time value), and two ratios—Premium Ratio (PR) and Volume Ratio (VR)—for a user-selected underlying asset (e.g., NIFTY, BANKNIFTY, or stocks). It helps traders gauge near-term market direction using options data.How the Script WorksInputs:Expiry: Select year (e.g., '25), month (01–12), day (01–31) for option expiry (e.g., '251028').
Timeframe: Choose data timeframe (e.g., Daily, 15-min).
Symbol: Auto-detects chart symbol or select from Indian indices/stocks.
Strike: Auto-ATM (based on futures) or manual strike input.
Interval: Auto (e.g., 100 for NIFTY) or custom strike interval.
Colors: Customizable for ATM line, labels (Futures Price, CPR, PPR, VR, PR).
Calculations:Futures Price (FP): Fetches front-month futures price (e.g., NSE:NIFTY1!).
ATM Strike: Rounds futures price to nearest strike interval.
Option Data: Retrieves Last Traded Price (LTP) and volume for ATM call/put options (e.g., NSE:NIFTY251028C24200).
Call Premium (CPR): Call LTP minus intrinsic value (max(0, FP - Strike)).
Put Premium (PPR): Put LTP minus intrinsic value (max(0, Strike - FP)).
Premium Ratio (PR): PPR / CPR.
Volume Ratio (VR): Put Volume / Call Volume.
Visuals:Draws ATM strike line on chart.
Displays labels: FP (futures price), CPR (call premium), PPR (put premium), VR, PR.
VR/PR labels: Red (≥ 1.25, bearish), Green (≤ 0.75, bullish), Gray (0.75–1.25, neutral).
Updates on last confirmed bar to avoid redraws.
Using PR and VR for Market DirectionPremium Ratio (PR):PR ≥ 1.25 (Red): High put premiums suggest bearish sentiment (expect price drop).
PR ≤ 0.75 (Green): High call premiums suggest bullish sentiment (expect price rise).
0.75 < PR < 1.25 (Gray): Neutral, no clear direction.
Use: High PR favors bearish trades (e.g., buy puts); low PR favors bullish trades (e.g., buy calls).
Volume Ratio (VR):VR ≥ 1.25 (Red): High put volume indicates bearish activity.
VR ≤ 0.75 (Green): High call volume indicates bullish activity.
0.75 < VR < 1.25 (Gray): Neutral trading activity.
Use: High VR suggests bearish moves; low VR suggests bullish moves.
Combined Signals:High PR & VR: Strong bearish signal; consider put buying or call selling.
Low PR & VR: Strong bullish signal; consider call buying or put selling.
Mixed/Neutral: Use price action or support/resistance for confirmation.
Tips:Combine with technical analysis (e.g., trends, levels).
Match timeframe to trading horizon (e.g., 15-min for intraday).
Monitor FP for context; check volatility or news for accuracy.
ExampleNIFTY: FP = 24,237.50, ATM = 24,200, CPR = 120.25, PPR = 180.50, PR = 1.50 (Red), VR = 1.30 (Red).
Insight: High PR/VR suggests bearish bias; consider bearish trades if price nears resistance.
Action: Buy puts or exit longs, confirm with price action.
Conclusion: This script provides a concise tool for options traders, showing ATM strike, premiums, and PR/VR ratios. High PR/VR (≥ 1.25) signals bearish sentiment, low PR/VR (≤ 0.75) signals bullish sentiment, and neutral (0.75–1.25) suggests indecision. Combine with technical analysis for robust trading decisions in the Indian options market.
COT Index Indicator 1) One‑liner
My version of the OTC COT Index indicator: a 0–120 oscillator built from CFTC COT data that shows where Commercial, Noncommercial, and Nonreportable net positions sit relative to recent extremes.
2) Short paragraph
This is my version of the OTC COT Index indicator. It converts CFTC Commitments of Traders (COT) net positions into a normalized 0–120 oscillator for each trader group—Commercials, Noncommercials, and Nonreportables—so you can quickly see when positioning is near recent highs or lows. Data comes from TradingView’s official COT library and supports both “Futures Only” and “Futures and Options” reports.
3) Compact bullets
What: My version of the OTC COT Index indicator
Why: Quickly spot when trader groups are near positioning extremes
Data: CFTC COT via TradingView/LibraryCOT/2; Futures Only or Futures & Options
How: Index = 120 × (Current − Min) ÷ (Max − Min) over a configurable lookback
Plots: Commercials (blue), Noncommercials (orange), Nonreportables (red)
Lines: Overbought, Midline, Oversold, optional 0/100, upper/lower bounds
Note: Values are relative to the chosen window; not trading advice
4) Publication‑ready (sections)
Overview
My version of the OTC COT Index indicator. It turns CFTC COT positioning into a 0–120 oscillator per trader group (Commercials, Noncommercials, Nonreportables) to highlight relative extremes.
Data source
CFTC Commitments of Traders via TradingView’s official library (TradingView/LibraryCOT/2).
Supports “Futures Only” and “Futures and Options.”
Method
Net positions = Longs − Shorts.
Index = 120 × (Current Net − Min(Net, Lookback)) ÷ (Max(Net, Lookback) − Min(Net, Lookback)).
Inputs
Weeks Look Back (normalization window)
Weeks Look Back for Historical Hi/Los (longer reference)
Report Type selection
Visuals
Three indexes by trader group, plus reference levels (OB/OS, Midline, optional 0/100).
Notes
Some symbols map to specific CFTC codes for reliability.
If no relevant COT data exists for the symbol, the script reports it clearly.
If you want this adapted to a specific platform’s character limits (e.g., TradingView’s publish dialog), tell me the target length and I’ll trim it to fit.
VELA RANGO FUTURESNQ-@MRXAUFXRange candle plus Asian session, add EMAs 9 and 21 and VWAP for the strategy to work
ES Gap Trading Levels# ES Gap Trading Levels
## Overview
A professional gap trading indicator designed specifically for ES Futures traders. This indicator automatically captures the closing price at 3:59 PM ET (NYSE close) and immediately displays key gap levels for the evening trading session starting at 6:00 PM ET.
## Key Features
### ✅ **Automatic Gap Level Detection**
- Captures ES Futures closing price at 3:59-4:00 PM ET
- Instantly displays gap levels for immediate session planning
- Resets daily for fresh gap analysis
### ✅ **Six Critical Gap Levels**
- **±10 Points** (White lines) - Short-term gap targets
- **±20 Points** (Light Blue lines) - Medium gap targets
- **±30 Points** (Red lines) - Extended gap targets
### ✅ **Professional Display**
- Clean horizontal lines with customizable colors
- Clear labels showing point values (+30, +20, +10, -10, -20, -30)
- Gap levels table showing exact price targets
- Optional closing price reference line
### ✅ **Customizable Settings**
- Adjustable line colors, width, and extension
- Toggle labels and reference table on/off
- Manual closing price override for testing
- Debug mode for troubleshooting
### ✅ **Smart Management**
- Automatic cleanup of previous day's levels
- Lines appear immediately after market close
- Optimized for ES1!, MES1!, and other ES futures contracts
## How It Works
1. **Market Close Capture**: At 3:59 PM ET, the indicator captures the ES closing price
2. **Instant Display**: Gap levels immediately appear on your chart
3. **Evening Session Ready**: Lines are positioned for 6:00 PM ET session start
4. **Daily Reset**: Old levels are automatically cleared each new trading day
## Perfect For:
- Gap trading strategies
- Overnight futures trading
- ES futures scalping
- Session transition analysis
- Risk management levels
## Usage Tips:
- Best used on 1-15 minute ES futures charts
- Ensure chart timezone shows ET times
- Use manual mode for backtesting specific dates
- Combine with volume and momentum indicators
## Settings Guide:
- **Display Settings**: Control lines, labels, and table visibility
- **Colors**: Customize each gap level color scheme
- **Manual Settings**: Override closing price for testing
- **Debug**: View time detection and diagnostic information
*Designed by traders, for traders. Clean, professional, and reliable gap level detection for serious ES futures trading.*
ConeCastConeCast is a forward-looking projection indicator that visualizes a future price range (or "cone") based on recent trend momentum and adaptive volatility. Unlike lagging bands or reactive channels, this tool plots a predictive zone 3–50 bars ahead, allowing traders to anticipate potential price behavior rather than merely react to it.
How It Works
The core of ConeCast is a dynamic trend-slope engine derived from a Linear Regression line fitted over a user-defined lookback window. The slope of this trend is projected forward, and the cone’s width adapts based on real-time market volatility. In calm markets, the cone is narrow and focused. In volatile regimes, it expands proportionally, using an ATR-based % of price to scale.
Key Features
📈 Predictive Cone Zone: Visualizes a forward range using trend slope × volatility width.
🔄 Auto-Adaptive Volatility Scaling: Expands or contracts based on market quiet/chaotic states.
📊 Regime Detection: Identifies Bull, Bear, or Neutral states using a tunable slope threshold.
🧭 Multi-Timeframe Compatible: Slope and volatility can be calculated from higher timeframes.
🔔 Smart Alerts: Detects price entering the cone, and signals trend regime changes in real time.
🖼️ Clean Visual Output: Optionally includes outer cones, trend-trail marker, and dashboard label.
How to Use It
Use on 15m–4H charts for best forward visibility.
Look for price entering the cone as a potential trend continuation setup.
Monitor regime changes and volatility expansion to filter choppy market zones.
Tune the slope sensitivity and ATR multiplier to match your symbol's behavior.
Use outer cones to anticipate aggressive swings and wick traps.
What Makes It Unique
ConeCast doesn’t follow price — it predicts a possible future price envelope using trend + volatility math, without relying on lagging indicators or repainting logic. It's a hybrid of regression-based forecasting and dynamic risk zoning, designed for swing traders, scalpers, and algo developers alike.
Limitations
ConeCast projects based on current trend and volatility — it does not "know" future price. Like all projection tools, accuracy depends on trend persistence and market conditions. Use this in combination with confirmation signals and risk management.
Dskyz (DAFE) Quantum Sentiment Flux - Beginners Dskyz (DAFE) Quantum Sentiment Flux - Beginners:
Welcome to the Dskyz (DAFE) Quantum Sentiment Flux - Beginners , a strategy and concept that’s your ultimate wingman for trading futures like MNQ, NQ, MES, and ES. This gem combines lightning-fast momentum signals, market sentiment smarts, and bulletproof risk management into a system so intuitive, even newbies can trade like pros. With clean DAFE visuals, preset modes for every vibe, and a revamped dashboard that’s basically a market GPS, this strategy makes futures trading feel like a high-octane sci-fi mission.
Built on the Dskyz (DAFE) legacy of Aurora Divergence, the Quantum Sentiment Flux is designed to empower beginners while giving seasoned traders a lean, sentiment-driven edge. It uses fast/slow EMA crossovers for entries, filters trades with VIX, SPX trends, and sector breadth, and keeps your account safe with adaptive stops and cooldowns. Tuned for more action with faster signals and a slick bottom-left dashboard, this updated version is ready to light up your charts and outsmart institutional traps. Let’s dive into why this strat’s a must-have and break down its brilliance.
Why Traders Need This Strategy
Futures markets are a wild ride—fast moves, volatility spikes (like the April 28, 2025 NQ 1k-point drop), and institutional games that can wreck unprepared traders. Beginners often get lost in complex systems or burned by impulsive trades. The Quantum Sentiment Flux is the antidote, offering:
Dead-Simple Setup: Preset modes (Aggressive, Balanced, Conservative) auto-tune signals, risk, and sizing, so you can trade without a quant degree.
Sentiment Superpower: VIX filter, SPX trend, and sector breadth visuals keep you aligned with market health, dodging chop and riding trends.
Ironclad Safety: Tighter ATR-based stops, 2:1 take-profits, and preset cooldowns protect your capital, even in chaotic sessions.
Next-Level Visuals: Green/red entry triangles, vibrant EMAs, a sector breadth background, and a beefed-up dashboard make signals and context pop.
DAFE Swagger: The clean aesthetics, sleek dashboard—ties it to Dskyz’s elite brand, making your charts a work of art.
Traders need this because it’s a plug-and-play system that blends beginner-friendly simplicity with pro-level market awareness. Whether you’re just starting or scalping 5min MNQ, this strat’s your key to trading with confidence and style.
Strategy Components
1. Core Signal Logic (High-Speed Momentum)
The strategy’s engine is a momentum-based system using fast and slow Exponential Moving Averages (EMAs), now tuned for faster, more frequent trades.
How It Works:
Fast/Slow EMAs: Fast EMA (Aggressive: 5, Balanced: 7, Conservative: 9 bars) and slow EMA (12/14/18 bars) track short-term vs. longer-term momentum.
Crossover Signals:
Buy: Fast EMA crosses above slow EMA, and trend_dir = 1 (fast EMA > slow EMA + ATR * strength threshold).
Sell: Fast EMA crosses below slow EMA, and trend_dir = -1 (fast EMA < slow EMA - ATR * strength threshold).
Strength Filter: ma_strength = fast EMA - slow EMA must exceed an ATR-scaled threshold (Aggressive: 0.15, Balanced: 0.18, Conservative: 0.25) for robust signals.
Trend Direction: trend_dir confirms momentum, filtering out weak crossovers in choppy markets.
Evolution:
Faster EMAs (down from 7–10/21–50) catch short-term trends, perfect for active futures markets.
Lower strength thresholds (0.15–0.25 vs. 0.3–0.5) make signals more sensitive, boosting trade frequency without sacrificing quality.
Preset tuning ensures beginners get optimized settings, while pros can tweak via mode selection.
2. Market Sentiment Filters
The strategy leans hard into market sentiment with a VIX filter, SPX trend analysis, and sector breadth visuals, keeping trades aligned with the big picture.
VIX Filter:
Logic: Blocks long entries if VIX > threshold (default: 20, can_long = vix_close < vix_limit). Shorts are always allowed (can_short = true).
Impact: Prevents longs during high-fear markets (e.g., VIX spikes in crashes), while allowing shorts to capitalize on downturns.
SPX Trend Filter:
Logic: Compares S&P 500 (SPX) close to its SMA (Aggressive: 5, Balanced: 8, Conservative: 12 bars). spx_trend = 1 (UP) if close > SMA, -1 (DOWN) if < SMA, 0 (FLAT) if neutral.
Impact: Provides dashboard context, encouraging trades that align with market direction (e.g., longs in UP trend).
Sector Breadth (Visual):
Logic: Tracks 10 sector ETFs (XLK, XLF, XLE, etc.) vs. their SMAs (same lengths as SPX). Each sector scores +1 (bullish), -1 (bearish), or 0 (neutral), summed as breadth (-10 to +10).
Display: Green background if breadth > 4, red if breadth < -4, else neutral. Dashboard shows sector trends (↑/↓/-).
Impact: Faster SMA lengths make breadth more responsive, reflecting sector rotations (e.g., tech surging, energy lagging).
Why It’s Brilliant:
- VIX filter adds pro-level volatility awareness, saving beginners from panic-driven losses.
- SPX and sector breadth give a 360° view of market health, boosting signal confidence (e.g., green BG + buy signal = high-probability trade).
- Shorter SMAs make sentiment visuals react faster, perfect for 5min charts.
3. Risk Management
The risk controls are a fortress, now tighter and more dynamic to support frequent trading while keeping accounts safe.
Preset-Based Risk:
Aggressive: Fast EMAs (5/12), tight stops (1.1x ATR), 1-bar cooldown. High trade frequency, higher risk.
Balanced: EMAs (7/14), 1.2x ATR stops, 1-bar cooldown. Versatile for most traders.
Conservative: EMAs (9/18), 1.3x ATR stops, 2-bar cooldown. Safer, fewer trades.
Impact: Auto-scales risk to match style, making it foolproof for beginners.
Adaptive Stops and Take-Profits:
Logic: Stops = entry ± ATR * atr_mult (1.1–1.3x, down from 1.2–2.0x). Take-profits = entry ± ATR * take_mult (2x stop distance, 2:1 reward/risk). Longs: stop below entry, TP above; shorts: vice versa.
Impact: Tighter stops increase trade turnover while maintaining solid risk/reward, adapting to volatility.
Trade Cooldown:
Logic: Preset-driven (Aggressive/Balanced: 1 bar, Conservative: 2 bars vs. old user-input 2). Ensures bar_index - last_trade_bar >= cooldown.
Impact: Faster cooldowns (especially Aggressive/Balanced) allow more trades, balanced by VIX and strength filters.
Contract Sizing:
Logic: User sets contracts (default: 1, max: 10), no preset cap (unlike old 7/5/3 suggestion).
Impact: Flexible but risks over-leverage; beginners should stick to low contracts.
Built To Be Reliable and Consistent:
- Tighter stops and faster cooldowns make it a high-octane system without blowing up accounts.
- Preset-driven risk removes guesswork, letting newbies trade confidently.
- 2:1 TPs ensure profitable trades outweigh losses, even in volatile sessions like April 27, 2025 ES slippage.
4. Trade Entry and Exit Logic
The entry/exit rules are simple yet razor-sharp, now with VIX filtering and faster signals:
Entry Conditions:
Long Entry: buy_signal (fast EMA crosses above slow EMA, trend_dir = 1), no position (strategy.position_size = 0), cooldown passed (can_trade), and VIX < 20 (can_long). Enters with user-defined contracts.
Short Entry: sell_signal (fast EMA crosses below slow EMA, trend_dir = -1), no position, cooldown passed, can_short (always true).
Logic: Tracks last_entry_bar for visuals, last_trade_bar for cooldowns.
Exit Conditions:
Stop-Loss/Take-Profit: ATR-based stops (1.1–1.3x) and TPs (2x stop distance). Longs exit if price hits stop (below) or TP (above); shorts vice versa.
No Other Exits: Keeps it straightforward, relying on stops/TPs.
5. DAFE Visuals
The visuals are pure DAFE magic, blending clean function with informative metrics utilized by professionals, now enhanced by faster signals and a responsive breadth background:
EMA Plots:
Display: Fast EMA (blue, 2px), slow EMA (orange, 2px), using faster lengths (5–9/12–18).
Purpose: Highlights momentum shifts, with crossovers signaling entries.
Sector Breadth Background:
Display: Green (90% transparent) if breadth > 4, red (90%) if breadth < -4, else neutral.
Purpose: Faster breadth_sma_len (5–12 vs. 10–50) reflects sector shifts in real-time, reinforcing signal strength.
- Visuals are intuitive, turning complex signals into clear buy/sell cues.
- Faster breadth background reacts to market rotations (e.g., tech vs. energy), giving a pro-level edge.
6. Sector Breadth Dashboard
The new bottom-left dashboard is a game-changer, a 3x16 table (black/gray theme) that’s your market command center:
Metrics:
VIX: Current VIX (red if > 20, gray if not).
SPX: Trend as “UP” (green), “DOWN” (red), or “FLAT” (gray).
Trade Longs: “OK” (green) if VIX < 20, “BLOCK” (red) if not.
Sector Breadth: 10 sectors (Tech, Financial, etc.) with trend arrows (↑ green, ↓ red, - gray).
Placeholder Row: Empty for future metrics (e.g., ATR, breadth score).
Purpose: Consolidates regime, volatility, market trend, and sector data, making decisions a breeze.
- VIX and SPX metrics add context, helping beginners avoid bad trades (e.g., no longs if “BLOCK”).
Sector arrows show market health at a glance, like a cheat code for sentiment.
Key Features
Beginner-Ready: Preset modes and clear visuals make futures trading a breeze.
Sentiment-Driven: VIX filter, SPX trend, and sector breadth keep you in sync with the market.
High-Frequency: Faster EMAs, tighter stops, and short cooldowns boost trade volume.
Safe and Smart: Adaptive stops/TPs and cooldowns protect capital while maximizing wins.
Visual Mastery: DAFE’s clean flair, EMAs, dashboard—makes trading fun and clear.
Backtestable: Lean code and fixed qty ensure accurate historical testing.
How to Use
Add to Chart: Load on a 5min MNQ/ES chart in TradingView.
Pick Preset: Aggressive (scalping), Balanced (versatile), or Conservative (safe). Balanced is default.
Set Contracts: Default 1, max 10. Stick low for safety.
Check Dashboard: Bottom-left shows preset, VIX, SPX, and sectors. “OK” + green breadth = strong buy.
Backtest: Run in strategy tester to compare modes.
Live Trade: Connect to Tradovate or similar. Watch for slippage (e.g., April 27, 2025 ES issues).
Replay Test: Try April 28, 2025 NQ drop to see VIX filter and stops in action.
Why It’s Brilliant
The Dskyz (DAFE) Quantum Sentiment Flux - Beginners is a masterpiece of simplicity and power. It takes pro-level tools—momentum, VIX, sector breadth—and wraps them in a system anyone can run. Faster signals and tighter stops make it a trading machine, while the VIX filter and dashboard keep you ahead of market chaos. The DAFE visuals and bottom-left command center turn your chart into a futuristic cockpit, guiding you through every trade. For beginners, it’s a safe entry to futures; for pros, it’s a scalping beast with sentiment smarts. This strat doesn’t just trade—it transforms how you see the market.
Final Notes
This is more than a strategy—it’s your launchpad to mastering futures with Dskyz (DAFE) flair. The Quantum Sentiment Flux blends accessibility, speed, and market savvy to help you outsmart the game. Load it, watch those triangles glow, and let’s make the markets your canvas!
Official Statement from Pine Script Team
(see TradingView help docs and forums):
"This warning may appear when you call functions such as ta.sma inside a request.security in a loop. There is no runtime impact. If you need to loop through a dynamic list of tickers, this cannot be avoided in the present version... Values will still be correct. Ignore this warning in such contexts."
(This publishing will most likely be taken down do to some miscellaneous rule about properly displaying charting symbols, or whatever. Once I've identified what part of the publishing they want to pick on, I'll adjust and repost.)
Use it with discipline. Use it with clarity. Trade smarter.
**I will continue to release incredible strategies and indicators until I turn this into a brand or until someone offers me a contract.
Created by Dskyz, powered by DAFE Trading Systems. Trade fast, trade bold.
Quarterly Cycle Theory with DST time AdjustedThe Quarterly Theory removes ambiguity, as it gives specific time-based reference points to look for when entering trades. Before being able to apply this theory to trading, one must first understand that time is fractal:
Yearly Quarters = 4 quarters of three months each.
Monthly Quarters = 4 quarters of one week each.
Weekly Quarters = 4 quarters of one day each (Monday - Thursday). Friday has its own specific function.
Daily Quarters = 4 quarters of 6 hours each = 4 trading sessions of a trading day.
Sessions Quarters = 4 quarters of 90 minutes each.
90 Minute Quarters = 4 quarters of 22.5 minutes each.
Yearly Cycle: Analogously to financial quarters, the year is divided in four sections of three months each:
Q1 - January, February, March.
Q2 - April, May, June (True Open, April Open).
Q3 - July, August, September.
Q4 - October, November, December.
S&P 500 E-mini Futures (daily candles) — Monthly Cycle.
Monthly Cycle: Considering that we have four weeks in a month, we start the cycle on the first month’s Monday (regardless of the calendar Day):
Q1 - Week 1: first Monday of the month.
Q2 - Week 2: second Monday of the month (True Open, Daily Candle Open Price).
Q3 - Week 3: third Monday of the month.
Q4 - Week 4: fourth Monday of the month.
S&P 500 E-mini Futures (4 hour candles) — Weekly Cycle.
Weekly Cycle: Daye determined that although the trading week is composed by 5 trading days, we should ignore Friday, and the small portion of Sunday’s price action:
Q1 - Monday.
Q2 - Tuesday (True Open, Daily Candle Open Price).
Q3 - Wednesday.
Q4 - Thursday.
S&P 500 E-mini Futures (1 hour candles) — Daily Cycle.
Daily Cycle: The Day can be broken down into 6 hour quarters. These times roughly define the sessions of the trading day, reinforcing the theory’s validity:
Q1 - 18:00 - 00:00 Asia.
Q2 - 00:00 - 06:00 London (True Open).
Q3 - 06:00 - 12:00 NY AM.
Q4 - 12:00 - 18:00 NY PM.
S&P 500 E-mini Futures (15 minute candles) — 6 Hour Cycle.
6 Hour Quarters or 90 Minute Cycle / Sessions divided into four sections of 90 minutes each (EST/EDT):
Asian Session
Q1 - 18:00 - 19:30
Q2 - 19:30 - 21:00 (True Open)
Q3 - 21:00 - 22:30
Q4 - 22:30 - 00:00
London Session
Q1 - 00:00 - 01:30
Q2 - 01:30 - 03:00 (True Open)
Q3 - 03:00 - 04:30
Q4 - 04:30 - 06:00
NY AM Session
Q1 - 06:00 - 07:30
Q2 - 07:30 - 09:00 (True Open)
Q3 - 09:00 - 10:30
Q4 - 10:30 - 12:00
NY PM Session
Q1 - 12:00 - 13:30
Q2 - 13:30 - 15:00 (True Open)
Q3 - 15:00 - 16:30
Q4 - 16:30 - 18:00
S&P 500 E-mini Futures (5 minute candles) — 90 Minute Cycle.
Micro Cycles: Dividing the 90 Minute Cycle yields 22.5 Minute Quarters, also known as Micro Sessions or Micro Quarters:
Asian Session
Q1/1 18:00:00 - 18:22:30
Q2 18:22:30 - 18:45:00
Q3 18:45:00 - 19:07:30
Q4 19:07:30 - 19:30:00
Q2/1 19:30:00 - 19:52:30 (True Session Open)
Q2/2 19:52:30 - 20:15:00
Q2/3 20:15:00 - 20:37:30
Q2/4 20:37:30 - 21:00:00
Q3/1 21:00:00 - 21:23:30
etc. 21:23:30 - 21:45:00
London Session
00:00:00 - 00:22:30 (True Daily Open)
00:22:30 - 00:45:00
00:45:00 - 01:07:30
01:07:30 - 01:30:00
01:30:00 - 01:52:30 (True Session Open)
01:52:30 - 02:15:00
02:15:00 - 02:37:30
02:37:30 - 03:00:00
03:00:00 - 03:22:30
03:22:30 - 03:45:00
03:45:00 - 04:07:30
04:07:30 - 04:30:00
04:30:00 - 04:52:30
04:52:30 - 05:15:00
05:15:00 - 05:37:30
05:37:30 - 06:00:00
New York AM Session
06:00:00 - 06:22:30
06:22:30 - 06:45:00
06:45:00 - 07:07:30
07:07:30 - 07:30:00
07:30:00 - 07:52:30 (True Session Open)
07:52:30 - 08:15:00
08:15:00 - 08:37:30
08:37:30 - 09:00:00
09:00:00 - 09:22:30
09:22:30 - 09:45:00
09:45:00 - 10:07:30
10:07:30 - 10:30:00
10:30:00 - 10:52:30
10:52:30 - 11:15:00
11:15:00 - 11:37:30
11:37:30 - 12:00:00
New York PM Session
12:00:00 - 12:22:30
12:22:30 - 12:45:00
12:45:00 - 13:07:30
13:07:30 - 13:30:00
13:30:00 - 13:52:30 (True Session Open)
13:52:30 - 14:15:00
14:15:00 - 14:37:30
14:37:30 - 15:00:00
15:00:00 - 15:22:30
15:22:30 - 15:45:00
15:45:00 - 15:37:30
15:37:30 - 16:00:00
16:00:00 - 16:22:30
16:22:30 - 16:45:00
16:45:00 - 17:07:30
17:07:30 - 18:00:00
S&P 500 E-mini Futures (30 second candles) — 22.5 Minute Cycle.
Volatility Arbitrage Spread Oscillator Model (VASOM)The Volatility Arbitrage Spread Oscillator Model (VASOM) is a systematic approach to capitalizing on price inefficiencies in the VIX futures term structure. By analyzing the differential between front-month and second-month VIX futures contracts, we employ a momentum-based oscillator (Relative Strength Index, RSI) to signal potential market reversion opportunities. Our research builds upon existing financial literature on volatility risk premia and contango/backwardation dynamics in the volatility markets (Zhang & Zhu, 2006; Alexander & Korovilas, 2012).
Volatility derivatives have become essential tools for managing risk and engaging in speculative trades (Whaley, 2009). The Chicago Board Options Exchange (CBOE) Volatility Index (VIX) measures the market’s expectation of 30-day forward-looking volatility derived from S&P 500 option prices (CBOE, 2018). Term structures in VIX futures often exhibit contango or backwardation, depending on macroeconomic and market conditions (Alexander & Korovilas, 2012).
This strategy seeks to exploit the spread between the front-month and second-month VIX futures as a proxy for term structure dynamics. The spread’s momentum, quantified by the RSI, serves as a signal for entry and exit points, aligning with empirical findings on mean reversion in volatility markets (Zhang & Zhu, 2006).
• Entry Signal: When RSI_t falls below the user-defined threshold (e.g., 30), indicating a potential undervaluation in the spread.
• Exit Signal: When RSI_t exceeds a threshold (e.g., 70), suggesting mean reversion has occurred.
Empirical Justification
The strategy aligns with findings that suggest predictable patterns in volatility futures spreads (Alexander & Korovilas, 2012). Furthermore, the use of RSI leverages insights from momentum-based trading models, which have demonstrated efficacy in various asset classes, including commodities and derivatives (Jegadeesh & Titman, 1993).
References
• Alexander, C., & Korovilas, D. (2012). The Hazards of Volatility Investing. Journal of Alternative Investments, 15(2), 92-104.
• CBOE. (2018). The VIX White Paper. Chicago Board Options Exchange.
• Jegadeesh, N., & Titman, S. (1993). Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency. The Journal of Finance, 48(1), 65-91.
• Zhang, C., & Zhu, Y. (2006). Exploiting Predictability in Volatility Futures Spreads. Financial Analysts Journal, 62(6), 62-72.
• Whaley, R. E. (2009). Understanding the VIX. The Journal of Portfolio Management, 35(3), 98-105.
Codi's Perp-Spot Basis# Perp-Spot Basis Indicator
This indicator calculates the percentage basis between perpetual futures and spot prices for crypto assets. It is inspired by the original concept from **Krugermacro**, with the added improvement of **automatic detection of the asset pairs** based on the current chart symbol. This enhancement makes it faster and easier to apply across different assets without manual configuration.
## How It Works
The indicator compares the perpetual futures price (e.g., `BTCUSDT.P`) to the spot price (e.g., `BTCUSDT`) on Binance. The difference is expressed as a percentage: (Perp - Spot) / Spot * 100
The results are displayed in a color-coded graph:
- **Blue (Positive Basis):** Perpetual futures are trading at a premium, indicating **bullish sentiment** among derivatives traders.
- **Red (Negative Basis):** Perpetual futures are trading at a discount, indicating **bearish sentiment** among derivatives traders.
This percentage basis is a core component in understanding funding rates and derivatives market dynamics. It serves as a faster proxy for funding rates, which typically lag behind real-time price movements.
---
## How to Use It
### General Concept
- **Red (Negative Basis):** Ideal to execute **longs** when derivatives traders are overly bearish.
- **Blue (Positive Basis):** Ideal to execute **shorts** when derivatives traders are overly bullish.
### Pullback Sniping
1. During an **uptrend**:
- If the basis turns **red** temporarily, it can signal an opportunity to **buy the dip**.
2. During a **downtrend**:
- If the basis turns **blue** temporarily, it can signal an opportunity to **sell the rip**.
3. Wait for the basis to **pop back** (higher in uptrend, lower in downtrend) to time entries more effectively—this often coincides with **stop runs** or **liquidations**.
### Intraday Execution
- **When price is falling**:
- If the basis is **red**, the move is derivatives-led (**normal**).
- If the basis is **blue**, spot traders are leading, and perps are offside—wait for **price dumps** before longing.
- **When price is rising**:
- If the basis is **blue**, the move is derivatives-led (**normal**).
- If the basis is **red**, spot traders are leading, and perps are offside—wait for **price pops** before shorting.
### Larger Time Frames
- **Consistently Blue Basis:** Indicates a **bull market** as derivatives traders are bullish over the long term.
- **Consistently Red Basis:** Indicates a **bear market** as derivatives traders are bearish over the long term.
---
## Improvements Over the Original
This version of the Perp-Spot Basis indicator **automatically detects the Binance perpetual futures and spot pairs** based on the current chart symbol. For example:
- If you are viewing `ETHUSDT`, it automatically references `ETHUSDT.P` for the perpetual futures pair and `ETHUSDT` for the spot pair in BINANCE.
FCNC SpreadTitle: FCNC Spread Indicator
Description:
The FCNC Spread Indicator is designed to help traders analyze the price difference (spread) between two futures contracts: the front contract and the next contract. This type of analysis is commonly used in futures trading to identify market sentiment, arbitrage opportunities, and potential roll yield strategies.
How It Works:
Front Contract: The front contract represents the futures contract closest to expiration, often referred to as the near-month contract.
Next Contract: The next contract is the futures contract that follows the front contract in the expiration cycle, typically the next available month.
Spread Calculation: frontContract - nextContract represents the difference between the price of the front contract and the next contract.
Positive Spread: A positive value means that the front contract is more expensive than the next contract, indicating backwardation.
Negative Spread: A negative value means that the front contract is cheaper than the next contract, indicating contango.
How to Use:
Input Selection: Select your desired futures contracts for the front and next contract through the input settings. The script will fetch and calculate the closing prices of these contracts.
Spread Plotting: The calculated spread is plotted on the chart, with color-coding based on the spread's value (green for positive, red for negative).
Labeling: The spread value is dynamically labeled on the chart for quick reference.
Moving Average: A 20-period Simple Moving Average (SMA) of the spread is also plotted to help identify trends and smooth out fluctuations.
Applications:
Trend Identification: Analyze the spread to determine market sentiment and potential trend reversals.
Divergence Detection: Look for divergences between the spread and the underlying market to identify possible shifts in trend or market sentiment. Divergences can signal upcoming reversals or provide early warning signs of a change in market dynamics.
This indicator is particularly useful for futures traders who are looking to gain insights into the market structure and to exploit differences in contract pricing. By providing a clear visualization of the spread between two key futures contracts, traders can make more informed decisions about their trading strategies.
Commitment of Trader %RThis script is a TradingView Pine Script that creates a custom indicator to analyze Commitment of Traders (COT) data. It leverages the TradingView COT library to fetch data related to futures and options markets, processes this data, and then applies the Williams %R indicator to the COT data to assist in trading decisions. Here’s a detailed explanation of its components and functionality:
Importing and Configuration:
The script imports the COT library from TradingView and sets up tooltips to explain different input options to the user.
It allows the user to choose the mode for fetching COT data, which can be based on the root of the symbol, base currency, or quote currency.
Users can also input a specific CFTC code directly, instead of relying on automatic code generation.
Inputs and Parameters:
The script provides inputs to select the type of data (futures, options, or both), the type of COT data to display (long positions, short positions, etc.), and thresholds for the Williams %R indicator.
It also allows setting the period for the Williams %R calculation.
Data Request and Processing:
The dataRequest function fetches COT data for large traders, small traders, and commercial hedgers.
The script calculates the Williams %R for each type of trader, which measures overbought and oversold conditions.
Visualization:
The script uses background colors to highlight when the Williams %R crosses the specified thresholds for commercial hedgers.
It plots the COT data and Williams %R on the chart, with different colors representing large traders, small traders, and commercial hedgers.
Horizontal lines are drawn to indicate the upper and lower thresholds.
Display Information:
A table is displayed on the chart’s lower left corner showing the current COT data and CFTC code used.
Use of COT Report in Futures Trading
The COT report is a weekly publication by the Commodity Futures Trading Commission (CFTC) that provides insights into the positions held by different types of traders in the futures markets. This information is valuable for traders as it shows:
Market Sentiment: By analyzing the positions of commercial traders (often considered to be more informed), non-commercial traders (speculative traders), and small traders, traders can gauge market sentiment and potential future movements.
Contrarian Indicators: Large shifts in positions, especially when non-commercial traders hold extreme positions, can signal potential reversals or trends.
Research on COT Data and Price Movements
Several academic studies have examined the relationship between COT data and price movements in financial markets. Here are a few key works:
"The Predictive Power of the Commitment of Traders Report" by Jacob J. (2009):
This paper explores how changes in the positions of different types of traders in the COT report can predict future price movements in futures markets.
Citation: Jacob, J. (2009). The Predictive Power of the Commitment of Traders Report. Journal of Futures Markets.
"A New Look at the Commitment of Traders Report" by Mitchell, C. (2010):
Mitchell analyzes the efficacy of using COT data as a trading signal and its impact on trading strategies.
Citation: Mitchell, C. (2010). A New Look at the Commitment of Traders Report. Financial Analysts Journal.
"Market Timing Using the Commitment of Traders Report" by Kirkpatrick, C., & Dahlquist, J. (2011):
This study investigates the use of COT data for market timing and the effectiveness of various trading strategies based on the report.
Citation: Kirkpatrick, C., & Dahlquist, J. (2011). Market Timing Using the Commitment of Traders Report. Technical Analysis of Stocks & Commodities.
These studies provide insights into how COT data can be utilized for forecasting and trading decisions, reinforcing the utility of incorporating such data into trading strategies.
Volume Liqidations [EagleVSniper]The Volume Liquidations Indicator is designed for traders who want to spot significant liquidation events in the cryptocurrency markets, particularly between spot and futures volumes. This powerful tool auto-detects the trading asset and compares the volume data from both spot and futures markets to highlight potential high-volume liquidation points that can significantly impact price movement. Raw source code owner - tartigradia
Features:
Auto-Detect Functionality: Automatically identifies the current trading asset, providing an option for manual selection for both spot and futures symbols.
Volume Comparison: Calculates the difference between futures and spot volumes within a user-defined timeframe, helping to identify liquidation events.
Customizable Parameters: Offers customizable options for multipliers, lookback periods, and timeframe selection to tailor the indicator to your trading strategy.
Visual Indicators: Displays liquidation volumes as color-coded columns, with green indicating potential long liquidations and red for short liquidations. It also highlights bars that exceed the high-volume threshold, providing a clear visual cue for significant liquidation events.
Spot and Futures Volume MA: Includes optional moving average plots for both spot and futures volumes, allowing for a deeper analysis of market trends.
Highlighting High-Volatility Candles: The indicator uniquely colors candles that reach a predefined volatility threshold, determined by the user-set multiplier. This functionality aims to spotlight moments of significant market volatility, providing traders with immediate visual cues.
Dynamic Ticker Selection: Seamlessly switches between auto and manual ticker selection, providing flexibility for all types of traders.
How to Use:
Setup: Configure the indicator to your preferences. You can choose between automatic or manual ticker selection, set the multiplier for the high-volume threshold, and define the lookback period for the moving average calculation.
Analysis: The indicator plots differences in volume between futures and spot markets as columns on your chart, color-coded to indicate the direction of potential liquidations.
Decision Making: Use the indicator to identify potential liquidation events. High-volume thresholds are highlighted, suggesting significant market movements. Combine this information with other analysis tools to make informed trading decisions.
@tk · spectral█ OVERVIEW
This script is an indicator that helps traders to identify the price difference between spot and futures of the current crypto plotted into the chart. It works in both types of markets, when the chart is plotting the crypto in spot market, it will compare with its respective futures ticker and vice-versa. If the current asset isn't a crypt ticker, the indicator will not be plotted into the chart.
█ MOTIVATION
Since crypto's derivative market is based on spot market asset's price, to calculate the arbitrage mechanisms that attempts to balance the asset price, this indicator can help traders to identify some spot and futures price divergence that can create an anomaly of funding rate and can push it to an extreme negative — or positive — rate. So, easing to track the price difference between both markets will bring more evidences to identify an artificial price move, specially in crypto assets with low market cap.
█ CONCEPT
The trading concept to use this indicator is the concept of the arbitrage machamism created by exchanges that calculates the funding rate based on spot and futures price difference that will vary from exchange to exchange. This strategy don't works alone. It needs to be aligned together with others indicators like Exponential Moving Averages, Chart Patterns, Support and Resistance, and so on... Even more confluences that you have, bigger are your chances to increase the probability for a successful trade. So, don't use this indicator alone. Compose a trading strategy and use it to improve your analysis.
█ CUSTOMIZATION
This indicator allows the trader to customize the following settings:
GENERAL
Text size
Changes the font size of price difference table to improve accessibility.
Type: string
Options: `tiny`, `small`, `normal`, `large`.
Default: `small`
Position
Changes the position of price difference table.
Type: string
Options: `top_left`, `top_center`, `top_right`, `middle_left`, `middle_center`, `middle_right`, `bottom_left`, `bottom_center`, `bottom_right`.
Default: `bottom_right`
Pair Quote
The ticker quote symbol that will be used to base the ticker comparison from spot to futures (e.g. BTCUSDT which `USDT` is the quote. ETHBTC which `BTC` is the quote).
Type: string
Default: USDT
Spectrum Color
The color of the spectrum candles. Spectrum candles are the candles of the opposite market. If the current ticker is in the spot market, the spectrum candles will be the price of the futures market.
Type: color
Default: #434651
█ FUNCTIONS
The indicator contains the following functions:
stripStarts(src, str)
Strips a defined pattern from a string.
Parameters:
src: (string) Source string
str: (string) String pattern to be stripped from start of source string.
Returns: (string) Stripped string with matched regex pattern.
Open Interest Chart [LuxAlgo]The Open Interest Chart displays Commitments of Traders %change of futures open interest , with a unique circular plotting technique, inspired from this publication Periodic Ellipses .
🔶 USAGE
Open interest represents the total number of contracts that have been entered by market participants but have not yet been offset or delivered. This can be a direct indicator of market activity/liquidity, with higher open interest indicating a more active market.
Increasing open interest is highlighted in green on the circular plot, indicating money coming into the market, while decreasing open interests highlighted in red indicates money coming out of the market.
You can set up to 6 different Futures Open interest tickers for a quick follow up:
🔶 DETAILS
Circles are drawn, using plot() , with the functions createOuterCircle() (for the largest circle) and createInnerCircle() (for inner circles).
Following snippet will reload the chart, so the circles will remain at the right side of the chart:
if ta.change(chart.left_visible_bar_time ) or
ta.change(chart.right_visible_bar_time)
n := bar_index
Here is a snippet which will draw a 39-bars wide circle that will keep updating its position to the right.
//@version=5
indicator("")
n = bar_index
barsTillEnd = last_bar_index - n
if ta.change(chart.left_visible_bar_time ) or
ta.change(chart.right_visible_bar_time)
n := bar_index
createOuterCircle(radius) =>
var int end = na
var int start = na
var basis = 0.
barsFromNearestEdgeCircle = 0.
barsTillEndFromCircleStart = radius
startCylce = barsTillEnd % barsTillEndFromCircleStart == 0 // start circle
bars = ta.barssince(startCylce)
barsFromNearestEdgeCircle := barsTillEndFromCircleStart -1
basis := math.min(startCylce ? -1 : basis + 1 / barsFromNearestEdgeCircle * 2, 1) // 0 -> 1
shape = math.sqrt(1 - basis * basis)
rad = radius / 2
isOK = barsTillEnd <= barsTillEndFromCircleStart and barsTillEnd > 0
hi = isOK ? (rad + shape * radius) - rad : na
lo = isOK ? (rad - shape * radius) - rad : na
start := barsTillEnd == barsTillEndFromCircleStart ? n -1 : start
end := barsTillEnd == 0 ? start + radius : end
= createOuterCircle(40)
plot(h), plot(l)
🔶 LIMITATIONS
Due to the inability to draw between bars, from time to time, drawings can be slightly off.
Bar-replay can be demanding, since it has to reload on every bar progression. We don't recommend using this script on bar-replay. If you do, please choose the lowest speed and from time to time pause bar-replay for a second. You'll see the script gets reloaded.
🔶 SETTINGS
🔹 TICKERS
Toggle :
• Enabled -> uses the first column with a pre-filled list of Futures Open Interest tickers/symbols
• Disabled -> uses the empty field where you can enter your own ticker/symbol
Pre-filled list : the first column is filled with a list, so you can choose your open interest easily, otherwise you would see COT:088691_F_OI aka Gold Futures Open Interest for example.
If applicable, you will see 3 different COT data:
• COT: Legacy Commitments of Traders report data
• COT2: Disaggregated Commitments of Traders report data
• COT3: Traders in Financial Futures report data
Empty field : When needed, you can pick another ticker/symbol in the empty field at the right and disable the toggle.
Timeframe : Commitments of Traders (COT) data is tallied by the Commodity Futures Trading Commission (CFTC) and is published weekly. Therefore data won't change every day.
Default set TF is Daily
🔹 STYLE
From middle:
• Enabled (default): Drawings start from the middle circle -> towards outer circle is + %change , towards middle of the circle is - %change
• Disabled: Drawings start from the middle POINT of the circle, towards outer circle is + OR -
-> in both options, + %change will be coloured green , - %change will be coloured red .
-> 0 %change will be coloured blue , and when no data is available, this will be coloured gray .
Size circle : options tiny, small, normal, large, huge.
Angle : Only applicable if "From middle" is disabled!
-> sets the angle of the spike:
Show Ticker : Name of ticker, as seen in table, will be added to labels.
Text - fill
• Sets colour for +/- %change
Table
• Sets 2 text colours, size and position
Circles
• Sets the colour of circles, style can be changed in the Style section.
You can make it as crazy as you want:
NSDT Custom High and Low LinesFirst, the credit for the original script to plot a High and Low between a certain time goes to developer paaax.
I took that idea, converted it to Pinescript V5, cleaned up the code, and added a few more lines so you can plot different levels based on time of day.
Published open source like the original.
The example shown has:
Blue - plotting from the start of the Futures Asian session to the start of the Futures USA Session. (6:00PM - 9:30AM Eastern)
Yellow - plotting from the start of the Futures Europe session to the start of the Futures USA Session. (3:00AM - 9:30AM Eastern)
Green - plotting from the start of the Futures US Premarket session to the start of the Futures USA Session. (8:00AM - 9:30AM Eastern)
These are great levels to use for breakouts and/or support and resistance.
Combine these levels with the 5 min Open Range levels, as you have some good trades.
Each of the three sessions have individual start and end times that can be modified by the trader, so you can easily mark off important areas for your style of trading.






















