Sessions Indicator(clean))🔰 True Day Open + Asian / London / NY Session Levels
Intraday Market Structure & Session Liquidity Indicator
This indicator automatically plots the True Day Opening Price, Asian Session High & Low, London Session High & Low, and New York Session Open — helping you understand daily directional bias, session liquidity zones, and potential reversal levels.
📌 What It Does
✔ Plots True Day Open (not broker-based — captures real market direction)
✔ Marks Asia Session High & Low – accumulation zone
✔ Marks London Session High & Low – expansion zone
✔ Shows New York Session Open – reversal / continuation zone
✔ Works on any chart: Forex, Indices, Crypto, Commodities
✔ Ideal for ICT / SMC / Day Trading / Scalping
✔ Fully customizable colors & display options
🧠 Why It’s Useful
The market often moves in this sequence:
➡ Asia → consolidation
➡ London → expansion / breakout
➡ New York → reversal OR continuation
This indicator helps you see this structure clearly, allowing traders to:
Avoid fake breakouts
Understand the daily bias earlier
Trade liquidity grabs & session-to-session transitions
Time entries with precision
📌 Best Timeframes
M5 / M15 / M30 → Scalping & intraday setups
H1 / H4 → Market structure view
Daily → Session zone backtesting
⚙ Inputs & Customization
Enable/Disable each session
Change session time manually
Color settings
Line styles: solid / dashed / background zones
🧠 Suggested Trading Concepts
Works great with:
Smart Money Concepts (SMC)
ICT Models
Liquidity Sweep Strategy
Session Breakout Trading
Mean Reversion Trading
📈 How to Use
Wait for Asian Range
Trade break of Asian High/Low during London
At NY Open, check for reversal or continuation
Use True Day Open for directional bias
Look for liquidity sweeps near session levels
📢 Coming Soon (Next Update)
🔔 Session Break Alerts
📊 Liquidity Sweep Labels
Penunjuk dan strategi
Dynamic Equity Allocation Model//@version=6
indicator('Dynamic Equity Allocation Model', shorttitle = 'DEAM', overlay = false, precision = 1, scale = scale.right, max_bars_back = 500)
// DYNAMIC EQUITY ALLOCATION MODEL
// Quantitative framework for dynamic portfolio allocation between stocks and cash.
// Analyzes five dimensions: market regime, risk metrics, valuation, sentiment,
// and macro conditions to generate allocation recommendations (0-100% equity).
//
// Uses real-time data from TradingView including fundamentals (P/E, ROE, ERP),
// volatility indicators (VIX), credit spreads, yield curves, and market structure.
// INPUT PARAMETERS
group1 = 'Model Configuration'
model_type = input.string('Adaptive', 'Allocation Model Type', options = , group = group1, tooltip = 'Conservative: Slower to increase equity, Aggressive: Faster allocation changes, Adaptive: Dynamic based on regime')
use_crisis_detection = input.bool(true, 'Enable Crisis Detection System', group = group1, tooltip = 'Automatic detection and response to crisis conditions')
use_regime_model = input.bool(true, 'Use Market Regime Detection', group = group1, tooltip = 'Identify Bull/Bear/Crisis regimes for dynamic allocation')
group2 = 'Portfolio Risk Management'
target_portfolio_volatility = input.float(12.0, 'Target Portfolio Volatility (%)', minval = 3, maxval = 20, step = 0.5, group = group2, tooltip = 'Target portfolio volatility (Cash reduces volatility: 50% Equity = ~10% vol, 100% Equity = ~20% vol)')
max_portfolio_drawdown = input.float(15.0, 'Maximum Portfolio Drawdown (%)', minval = 5, maxval = 35, step = 2.5, group = group2, tooltip = 'Maximum acceptable PORTFOLIO drawdown (not market drawdown - portfolio with cash has lower drawdown)')
enable_portfolio_risk_scaling = input.bool(true, 'Enable Portfolio Risk Scaling', group = group2, tooltip = 'Scale allocation based on actual portfolio risk characteristics (recommended)')
risk_lookback = input.int(252, 'Risk Calculation Period (Days)', minval = 60, maxval = 504, group = group2, tooltip = 'Period for calculating volatility and risk metrics')
group3 = 'Component Weights (Total = 100%)'
w_regime = input.float(35.0, 'Market Regime Weight (%)', minval = 0, maxval = 100, step = 5, group = group3)
w_risk = input.float(25.0, 'Risk Metrics Weight (%)', minval = 0, maxval = 100, step = 5, group = group3)
w_valuation = input.float(20.0, 'Valuation Weight (%)', minval = 0, maxval = 100, step = 5, group = group3)
w_sentiment = input.float(15.0, 'Sentiment Weight (%)', minval = 0, maxval = 100, step = 5, group = group3)
w_macro = input.float(5.0, 'Macro Weight (%)', minval = 0, maxval = 100, step = 5, group = group3)
group4 = 'Crisis Detection Thresholds'
crisis_vix_threshold = input.float(40, 'Crisis VIX Level', minval = 30, maxval = 80, group = group4, tooltip = 'VIX level indicating crisis conditions (COVID peaked at 82)')
crisis_drawdown_threshold = input.float(15, 'Crisis Drawdown Threshold (%)', minval = 10, maxval = 30, group = group4, tooltip = 'Market drawdown indicating crisis conditions')
crisis_credit_spread = input.float(500, 'Crisis Credit Spread (bps)', minval = 300, maxval = 1000, group = group4, tooltip = 'High yield spread indicating crisis conditions')
group5 = 'Display Settings'
show_components = input.bool(false, 'Show Component Breakdown', group = group5, tooltip = 'Display individual component analysis lines')
show_regime_background = input.bool(true, 'Show Dynamic Background', group = group5, tooltip = 'Color background based on allocation signals')
show_reference_lines = input.bool(false, 'Show Reference Lines', group = group5, tooltip = 'Display allocation percentage reference lines')
show_dashboard = input.bool(true, 'Show Analytics Dashboard', group = group5, tooltip = 'Display comprehensive analytics table')
show_confidence_bands = input.bool(false, 'Show Confidence Bands', group = group5, tooltip = 'Display uncertainty quantification bands')
smoothing_period = input.int(3, 'Smoothing Period', minval = 1, maxval = 10, group = group5, tooltip = 'Smoothing to reduce allocation noise')
background_intensity = input.int(95, 'Background Intensity (%)', minval = 90, maxval = 99, group = group5, tooltip = 'Higher values = more transparent background')
// Styling Options
color_scheme = input.string('EdgeTools', 'Color Theme', options = , group = 'Appearance', tooltip = 'Professional color themes')
use_dark_mode = input.bool(true, 'Optimize for Dark Theme', group = 'Appearance')
main_line_width = input.int(3, 'Main Line Width', minval = 1, maxval = 5, group = 'Appearance')
// DATA RETRIEVAL
// Market Data
sp500 = request.security('SPY', timeframe.period, close)
sp500_high = request.security('SPY', timeframe.period, high)
sp500_low = request.security('SPY', timeframe.period, low)
sp500_volume = request.security('SPY', timeframe.period, volume)
// Volatility Indicators
vix = request.security('VIX', timeframe.period, close)
vix9d = request.security('VIX9D', timeframe.period, close)
vxn = request.security('VXN', timeframe.period, close)
// Fixed Income and Credit
us2y = request.security('US02Y', timeframe.period, close)
us10y = request.security('US10Y', timeframe.period, close)
us3m = request.security('US03MY', timeframe.period, close)
hyg = request.security('HYG', timeframe.period, close)
lqd = request.security('LQD', timeframe.period, close)
tlt = request.security('TLT', timeframe.period, close)
// Safe Haven Assets
gold = request.security('GLD', timeframe.period, close)
usd = request.security('DXY', timeframe.period, close)
yen = request.security('JPYUSD', timeframe.period, close)
// Financial data with fallback values
get_financial_data(symbol, fin_id, period, fallback) =>
data = request.financial(symbol, fin_id, period, ignore_invalid_symbol = true)
na(data) ? fallback : data
// SPY fundamental metrics
spy_earnings_per_share = get_financial_data('AMEX:SPY', 'EARNINGS_PER_SHARE_BASIC', 'TTM', 20.0)
spy_operating_earnings_yield = get_financial_data('AMEX:SPY', 'OPERATING_EARNINGS_YIELD', 'FY', 4.5)
spy_dividend_yield = get_financial_data('AMEX:SPY', 'DIVIDENDS_YIELD', 'FY', 1.8)
spy_buyback_yield = get_financial_data('AMEX:SPY', 'BUYBACK_YIELD', 'FY', 2.0)
spy_net_margin = get_financial_data('AMEX:SPY', 'NET_MARGIN', 'TTM', 12.0)
spy_debt_to_equity = get_financial_data('AMEX:SPY', 'DEBT_TO_EQUITY', 'FY', 0.5)
spy_return_on_equity = get_financial_data('AMEX:SPY', 'RETURN_ON_EQUITY', 'FY', 15.0)
spy_free_cash_flow = get_financial_data('AMEX:SPY', 'FREE_CASH_FLOW', 'TTM', 100000000)
spy_ebitda = get_financial_data('AMEX:SPY', 'EBITDA', 'TTM', 200000000)
spy_pe_forward = get_financial_data('AMEX:SPY', 'PRICE_EARNINGS_FORWARD', 'FY', 18.0)
spy_total_debt = get_financial_data('AMEX:SPY', 'TOTAL_DEBT', 'FY', 500000000)
spy_total_equity = get_financial_data('AMEX:SPY', 'TOTAL_EQUITY', 'FY', 1000000000)
spy_enterprise_value = get_financial_data('AMEX:SPY', 'ENTERPRISE_VALUE', 'FY', 30000000000)
spy_revenue_growth = get_financial_data('AMEX:SPY', 'REVENUE_ONE_YEAR_GROWTH', 'TTM', 5.0)
// Market Breadth Indicators
nya = request.security('NYA', timeframe.period, close)
rut = request.security('IWM', timeframe.period, close)
// Sector Performance
xlk = request.security('XLK', timeframe.period, close)
xlu = request.security('XLU', timeframe.period, close)
xlf = request.security('XLF', timeframe.period, close)
// MARKET REGIME DETECTION
// Calculate Market Trend
sma_20 = ta.sma(sp500, 20)
sma_50 = ta.sma(sp500, 50)
sma_200 = ta.sma(sp500, 200)
ema_10 = ta.ema(sp500, 10)
// Market Structure Score
trend_strength = 0.0
trend_strength := trend_strength + (sp500 > sma_20 ? 1 : -1)
trend_strength := trend_strength + (sp500 > sma_50 ? 1 : -1)
trend_strength := trend_strength + (sp500 > sma_200 ? 2 : -2)
trend_strength := trend_strength + (sma_50 > sma_200 ? 2 : -2)
// Volatility Regime
returns = math.log(sp500 / sp500 )
realized_vol_20d = ta.stdev(returns, 20) * math.sqrt(252) * 100
realized_vol_60d = ta.stdev(returns, 60) * math.sqrt(252) * 100
ewma_vol = ta.ema(math.pow(returns, 2), 20)
realized_vol = math.sqrt(ewma_vol * 252) * 100
vol_premium = vix - realized_vol
// Drawdown Calculation
running_max = ta.highest(sp500, risk_lookback)
current_drawdown = (running_max - sp500) / running_max * 100
// Regime Score
regime_score = 0.0
// Trend Component (40%)
if trend_strength >= 4
regime_score := regime_score + 40
regime_score
else if trend_strength >= 2
regime_score := regime_score + 30
regime_score
else if trend_strength >= 0
regime_score := regime_score + 20
regime_score
else if trend_strength >= -2
regime_score := regime_score + 10
regime_score
else
regime_score := regime_score + 0
regime_score
// Volatility Component (30%)
if vix < 15
regime_score := regime_score + 30
regime_score
else if vix < 20
regime_score := regime_score + 25
regime_score
else if vix < 25
regime_score := regime_score + 15
regime_score
else if vix < 35
regime_score := regime_score + 5
regime_score
else
regime_score := regime_score + 0
regime_score
// Drawdown Component (30%)
if current_drawdown < 3
regime_score := regime_score + 30
regime_score
else if current_drawdown < 7
regime_score := regime_score + 20
regime_score
else if current_drawdown < 12
regime_score := regime_score + 10
regime_score
else if current_drawdown < 20
regime_score := regime_score + 5
regime_score
else
regime_score := regime_score + 0
regime_score
// Classify Regime
market_regime = regime_score >= 80 ? 'Strong Bull' : regime_score >= 60 ? 'Bull Market' : regime_score >= 40 ? 'Neutral' : regime_score >= 20 ? 'Correction' : regime_score >= 10 ? 'Bear Market' : 'Crisis'
// RISK-BASED ALLOCATION
// Calculate Market Risk
parkinson_hl = math.log(sp500_high / sp500_low)
parkinson_vol = parkinson_hl / (2 * math.sqrt(math.log(2))) * math.sqrt(252) * 100
garman_klass_vol = math.sqrt((0.5 * math.pow(math.log(sp500_high / sp500_low), 2) - (2 * math.log(2) - 1) * math.pow(math.log(sp500 / sp500 ), 2)) * 252) * 100
market_volatility_20d = math.max(ta.stdev(returns, 20) * math.sqrt(252) * 100, parkinson_vol)
market_volatility_60d = ta.stdev(returns, 60) * math.sqrt(252) * 100
market_drawdown = current_drawdown
// Initialize risk allocation
risk_allocation = 50.0
if enable_portfolio_risk_scaling
// Volatility-based allocation
vol_based_allocation = target_portfolio_volatility / math.max(market_volatility_20d, 5.0) * 100
vol_based_allocation := math.max(0, math.min(100, vol_based_allocation))
// Drawdown-based allocation
dd_based_allocation = 100.0
if market_drawdown > 1.0
dd_based_allocation := max_portfolio_drawdown / market_drawdown * 100
dd_based_allocation := math.max(0, math.min(100, dd_based_allocation))
dd_based_allocation
// Combine (conservative)
risk_allocation := math.min(vol_based_allocation, dd_based_allocation)
// Dynamic adjustment
current_equity_estimate = 50.0
estimated_portfolio_vol = current_equity_estimate / 100 * market_volatility_20d
estimated_portfolio_dd = current_equity_estimate / 100 * market_drawdown
vol_utilization = estimated_portfolio_vol / target_portfolio_volatility
dd_utilization = estimated_portfolio_dd / max_portfolio_drawdown
risk_utilization = math.max(vol_utilization, dd_utilization)
risk_adjustment_factor = 1.0
if risk_utilization > 1.0
risk_adjustment_factor := math.exp(-0.5 * (risk_utilization - 1.0))
risk_adjustment_factor := math.max(0.5, risk_adjustment_factor)
risk_adjustment_factor
else if risk_utilization < 0.9
risk_adjustment_factor := 1.0 + 0.2 * math.log(1.0 / risk_utilization)
risk_adjustment_factor := math.min(1.3, risk_adjustment_factor)
risk_adjustment_factor
risk_allocation := risk_allocation * risk_adjustment_factor
risk_allocation
else
vol_scalar = target_portfolio_volatility / math.max(market_volatility_20d, 10)
vol_scalar := math.min(1.5, math.max(0.2, vol_scalar))
drawdown_penalty = 0.0
if current_drawdown > max_portfolio_drawdown
drawdown_penalty := (current_drawdown - max_portfolio_drawdown) / max_portfolio_drawdown
drawdown_penalty := math.min(1.0, drawdown_penalty)
drawdown_penalty
risk_allocation := 100 * vol_scalar * (1 - drawdown_penalty)
risk_allocation
risk_allocation := math.max(0, math.min(100, risk_allocation))
// VALUATION ANALYSIS
// Valuation Metrics
actual_pe_ratio = spy_earnings_per_share > 0 ? sp500 / spy_earnings_per_share : spy_pe_forward
actual_earnings_yield = nz(spy_operating_earnings_yield, 0) > 0 ? spy_operating_earnings_yield : 100 / actual_pe_ratio
total_shareholder_yield = spy_dividend_yield + spy_buyback_yield
// Equity Risk Premium (multi-method calculation)
method1_erp = actual_earnings_yield - us10y
method2_erp = actual_earnings_yield + spy_buyback_yield - us10y
payout_ratio = spy_dividend_yield > 0 and actual_earnings_yield > 0 ? spy_dividend_yield / actual_earnings_yield : 0.4
sustainable_growth = spy_return_on_equity * (1 - payout_ratio) / 100
method3_erp = spy_dividend_yield + sustainable_growth * 100 - us10y
implied_growth = spy_revenue_growth * 0.7
method4_erp = total_shareholder_yield + implied_growth - us10y
equity_risk_premium = method1_erp * 0.35 + method2_erp * 0.30 + method3_erp * 0.20 + method4_erp * 0.15
ev_ebitda_ratio = spy_enterprise_value > 0 and spy_ebitda > 0 ? spy_enterprise_value / spy_ebitda : 15.0
debt_equity_health = spy_debt_to_equity < 1.0 ? 1.2 : spy_debt_to_equity < 2.0 ? 1.0 : 0.8
// Valuation Score
base_valuation_score = 50.0
if equity_risk_premium > 4
base_valuation_score := 95
base_valuation_score
else if equity_risk_premium > 3
base_valuation_score := 85
base_valuation_score
else if equity_risk_premium > 2
base_valuation_score := 70
base_valuation_score
else if equity_risk_premium > 1
base_valuation_score := 55
base_valuation_score
else if equity_risk_premium > 0
base_valuation_score := 40
base_valuation_score
else if equity_risk_premium > -1
base_valuation_score := 25
base_valuation_score
else
base_valuation_score := 10
base_valuation_score
growth_adjustment = spy_revenue_growth > 10 ? 10 : spy_revenue_growth > 5 ? 5 : 0
margin_adjustment = spy_net_margin > 15 ? 5 : spy_net_margin < 8 ? -5 : 0
roe_adjustment = spy_return_on_equity > 20 ? 5 : spy_return_on_equity < 10 ? -5 : 0
valuation_score = base_valuation_score + growth_adjustment + margin_adjustment + roe_adjustment
valuation_score := math.max(0, math.min(100, valuation_score * debt_equity_health))
// SENTIMENT ANALYSIS
// VIX Term Structure
vix_term_structure = vix9d > 0 ? vix / vix9d : 1
backwardation = vix_term_structure > 1.05
steep_backwardation = vix_term_structure > 1.15
// Safe Haven Flows
gold_momentum = ta.roc(gold, 20)
dollar_momentum = ta.roc(usd, 20)
yen_momentum = ta.roc(yen, 20)
treasury_momentum = ta.roc(tlt, 20)
safe_haven_flow = gold_momentum * 0.3 + treasury_momentum * 0.3 + dollar_momentum * 0.25 + yen_momentum * 0.15
// Advanced Sentiment Analysis
vix_percentile = ta.percentrank(vix, 252)
vix_zscore = (vix - ta.sma(vix, 252)) / ta.stdev(vix, 252)
vix_momentum = ta.roc(vix, 5)
vvix_proxy = ta.stdev(vix_momentum, 20) * math.sqrt(252)
risk_reversal_proxy = (vix - realized_vol) / realized_vol
// Sentiment Score
base_sentiment = 50.0
vix_adjustment = 0.0
if vix_zscore < -1.5
vix_adjustment := 40
vix_adjustment
else if vix_zscore < -0.5
vix_adjustment := 20
vix_adjustment
else if vix_zscore < 0.5
vix_adjustment := 0
vix_adjustment
else if vix_zscore < 1.5
vix_adjustment := -20
vix_adjustment
else
vix_adjustment := -40
vix_adjustment
term_structure_adjustment = backwardation ? -15 : steep_backwardation ? -30 : 5
vvix_adjustment = vvix_proxy > 2.0 ? -10 : vvix_proxy < 1.0 ? 10 : 0
sentiment_score = base_sentiment + vix_adjustment + term_structure_adjustment + vvix_adjustment
sentiment_score := math.max(0, math.min(100, sentiment_score))
// MACRO ANALYSIS
// Yield Curve
yield_spread_2_10 = us10y - us2y
yield_spread_3m_10 = us10y - us3m
// Credit Conditions
hyg_return = ta.roc(hyg, 20)
lqd_return = ta.roc(lqd, 20)
tlt_return = ta.roc(tlt, 20)
hyg_duration = 4.0
lqd_duration = 8.0
tlt_duration = 17.0
hyg_log_returns = math.log(hyg / hyg )
lqd_log_returns = math.log(lqd / lqd )
hyg_volatility = ta.stdev(hyg_log_returns, 20) * math.sqrt(252)
lqd_volatility = ta.stdev(lqd_log_returns, 20) * math.sqrt(252)
hyg_yield_proxy = -math.log(hyg / hyg ) * 100
lqd_yield_proxy = -math.log(lqd / lqd ) * 100
tlt_yield = us10y
hyg_spread = (hyg_yield_proxy - tlt_yield) * 100
lqd_spread = (lqd_yield_proxy - tlt_yield) * 100
hyg_distance = (hyg - ta.lowest(hyg, 252)) / (ta.highest(hyg, 252) - ta.lowest(hyg, 252))
lqd_distance = (lqd - ta.lowest(lqd, 252)) / (ta.highest(lqd, 252) - ta.lowest(lqd, 252))
default_risk_proxy = 2.0 - (hyg_distance + lqd_distance)
credit_spread = hyg_spread * 0.5 + (hyg_volatility - lqd_volatility) * 1000 * 0.3 + default_risk_proxy * 200 * 0.2
credit_spread := math.max(50, credit_spread)
credit_market_health = hyg_return > lqd_return ? 1 : -1
flight_to_quality = tlt_return > (hyg_return + lqd_return) / 2
// Macro Score
macro_score = 50.0
yield_curve_score = 0
if yield_spread_2_10 > 1.5 and yield_spread_3m_10 > 2
yield_curve_score := 40
yield_curve_score
else if yield_spread_2_10 > 0.5 and yield_spread_3m_10 > 1
yield_curve_score := 30
yield_curve_score
else if yield_spread_2_10 > 0 and yield_spread_3m_10 > 0
yield_curve_score := 20
yield_curve_score
else if yield_spread_2_10 < 0 or yield_spread_3m_10 < 0
yield_curve_score := 10
yield_curve_score
else
yield_curve_score := 5
yield_curve_score
credit_conditions_score = 0
if credit_spread < 200 and not flight_to_quality
credit_conditions_score := 30
credit_conditions_score
else if credit_spread < 400 and credit_market_health > 0
credit_conditions_score := 20
credit_conditions_score
else if credit_spread < 600
credit_conditions_score := 15
credit_conditions_score
else if credit_spread < 1000
credit_conditions_score := 10
credit_conditions_score
else
credit_conditions_score := 0
credit_conditions_score
financial_stability_score = 0
if spy_debt_to_equity < 0.5 and spy_return_on_equity > 15
financial_stability_score := 20
financial_stability_score
else if spy_debt_to_equity < 1.0 and spy_return_on_equity > 10
financial_stability_score := 15
financial_stability_score
else if spy_debt_to_equity < 1.5
financial_stability_score := 10
financial_stability_score
else
financial_stability_score := 5
financial_stability_score
macro_score := yield_curve_score + credit_conditions_score + financial_stability_score
macro_score := math.max(0, math.min(100, macro_score))
// CRISIS DETECTION
crisis_indicators = 0
if vix > crisis_vix_threshold
crisis_indicators := crisis_indicators + 1
crisis_indicators
if vix > 60
crisis_indicators := crisis_indicators + 2
crisis_indicators
if current_drawdown > crisis_drawdown_threshold
crisis_indicators := crisis_indicators + 1
crisis_indicators
if current_drawdown > 25
crisis_indicators := crisis_indicators + 1
crisis_indicators
if credit_spread > crisis_credit_spread
crisis_indicators := crisis_indicators + 1
crisis_indicators
sp500_roc_5 = ta.roc(sp500, 5)
tlt_roc_5 = ta.roc(tlt, 5)
if sp500_roc_5 < -10 and tlt_roc_5 < -5
crisis_indicators := crisis_indicators + 2
crisis_indicators
volume_spike = sp500_volume > ta.sma(sp500_volume, 20) * 2
sp500_roc_1 = ta.roc(sp500, 1)
if volume_spike and sp500_roc_1 < -3
crisis_indicators := crisis_indicators + 1
crisis_indicators
is_crisis = crisis_indicators >= 3
is_severe_crisis = crisis_indicators >= 5
// FINAL ALLOCATION CALCULATION
// Convert regime to base allocation
regime_allocation = market_regime == 'Strong Bull' ? 100 : market_regime == 'Bull Market' ? 80 : market_regime == 'Neutral' ? 60 : market_regime == 'Correction' ? 40 : market_regime == 'Bear Market' ? 20 : 0
// Normalize weights
total_weight = w_regime + w_risk + w_valuation + w_sentiment + w_macro
w_regime_norm = w_regime / total_weight
w_risk_norm = w_risk / total_weight
w_valuation_norm = w_valuation / total_weight
w_sentiment_norm = w_sentiment / total_weight
w_macro_norm = w_macro / total_weight
// Calculate Weighted Allocation
weighted_allocation = regime_allocation * w_regime_norm + risk_allocation * w_risk_norm + valuation_score * w_valuation_norm + sentiment_score * w_sentiment_norm + macro_score * w_macro_norm
// Apply Crisis Override
if use_crisis_detection
if is_severe_crisis
weighted_allocation := math.min(weighted_allocation, 10)
weighted_allocation
else if is_crisis
weighted_allocation := math.min(weighted_allocation, 25)
weighted_allocation
// Model Type Adjustment
model_adjustment = 0.0
if model_type == 'Conservative'
model_adjustment := -10
model_adjustment
else if model_type == 'Aggressive'
model_adjustment := 10
model_adjustment
else if model_type == 'Adaptive'
recent_return = (sp500 - sp500 ) / sp500 * 100
if recent_return > 5
model_adjustment := 5
model_adjustment
else if recent_return < -5
model_adjustment := -5
model_adjustment
// Apply adjustment and bounds
final_allocation = weighted_allocation + model_adjustment
final_allocation := math.max(0, math.min(100, final_allocation))
// Smooth allocation
smoothed_allocation = ta.sma(final_allocation, smoothing_period)
// Calculate portfolio risk metrics (only for internal alerts)
actual_portfolio_volatility = smoothed_allocation / 100 * market_volatility_20d
actual_portfolio_drawdown = smoothed_allocation / 100 * current_drawdown
// VISUALIZATION
// Color definitions
var color primary_color = #2196F3
var color bullish_color = #4CAF50
var color bearish_color = #FF5252
var color neutral_color = #808080
var color text_color = color.white
var color bg_color = #000000
var color table_bg_color = #1E1E1E
var color header_bg_color = #2D2D2D
switch color_scheme // Apply color scheme
'Gold' =>
primary_color := use_dark_mode ? #FFD700 : #DAA520
bullish_color := use_dark_mode ? #FFA500 : #FF8C00
bearish_color := use_dark_mode ? #FF5252 : #D32F2F
neutral_color := use_dark_mode ? #C0C0C0 : #808080
text_color := use_dark_mode ? color.white : color.black
bg_color := use_dark_mode ? #000000 : #FFFFFF
table_bg_color := use_dark_mode ? #1A1A00 : #FFFEF0
header_bg_color := use_dark_mode ? #2D2600 : #F5F5DC
header_bg_color
'EdgeTools' =>
primary_color := use_dark_mode ? #4682B4 : #1E90FF
bullish_color := use_dark_mode ? #4CAF50 : #388E3C
bearish_color := use_dark_mode ? #FF5252 : #D32F2F
neutral_color := use_dark_mode ? #708090 : #696969
text_color := use_dark_mode ? color.white : color.black
bg_color := use_dark_mode ? #000000 : #FFFFFF
table_bg_color := use_dark_mode ? #0F1419 : #F0F8FF
header_bg_color := use_dark_mode ? #1E2A3A : #E6F3FF
header_bg_color
'Behavioral' =>
primary_color := #808080
bullish_color := #00FF00
bearish_color := #8B0000
neutral_color := #FFBF00
text_color := use_dark_mode ? color.white : color.black
bg_color := use_dark_mode ? #000000 : #FFFFFF
table_bg_color := use_dark_mode ? #1A1A1A : #F8F8F8
header_bg_color := use_dark_mode ? #2D2D2D : #E8E8E8
header_bg_color
'Quant' =>
primary_color := #808080
bullish_color := #FFA500
bearish_color := #8B0000
neutral_color := #4682B4
text_color := use_dark_mode ? color.white : color.black
bg_color := use_dark_mode ? #000000 : #FFFFFF
table_bg_color := use_dark_mode ? #0D0D0D : #FAFAFA
header_bg_color := use_dark_mode ? #1A1A1A : #F0F0F0
header_bg_color
'Ocean' =>
primary_color := use_dark_mode ? #20B2AA : #008B8B
bullish_color := use_dark_mode ? #00CED1 : #4682B4
bearish_color := use_dark_mode ? #FF4500 : #B22222
neutral_color := use_dark_mode ? #87CEEB : #2F4F4F
text_color := use_dark_mode ? #F0F8FF : #191970
bg_color := use_dark_mode ? #001F3F : #F0F8FF
table_bg_color := use_dark_mode ? #001A2E : #E6F7FF
header_bg_color := use_dark_mode ? #002A47 : #CCF2FF
header_bg_color
'Fire' =>
primary_color := use_dark_mode ? #FF6347 : #DC143C
bullish_color := use_dark_mode ? #FFD700 : #FF8C00
bearish_color := use_dark_mode ? #8B0000 : #800000
neutral_color := use_dark_mode ? #FFA500 : #CD853F
text_color := use_dark_mode ? #FFFAF0 : #2F1B14
bg_color := use_dark_mode ? #2F1B14 : #FFFAF0
table_bg_color := use_dark_mode ? #261611 : #FFF8F0
header_bg_color := use_dark_mode ? #3D241A : #FFE4CC
header_bg_color
'Matrix' =>
primary_color := use_dark_mode ? #00FF41 : #006400
bullish_color := use_dark_mode ? #39FF14 : #228B22
bearish_color := use_dark_mode ? #FF073A : #8B0000
neutral_color := use_dark_mode ? #00FFFF : #008B8B
text_color := use_dark_mode ? #C0FF8C : #003300
bg_color := use_dark_mode ? #0D1B0D : #F0FFF0
table_bg_color := use_dark_mode ? #0A1A0A : #E8FFF0
header_bg_color := use_dark_mode ? #112B11 : #CCFFCC
header_bg_color
'Arctic' =>
primary_color := use_dark_mode ? #87CEFA : #4169E1
bullish_color := use_dark_mode ? #00BFFF : #0000CD
bearish_color := use_dark_mode ? #FF1493 : #8B008B
neutral_color := use_dark_mode ? #B0E0E6 : #483D8B
text_color := use_dark_mode ? #F8F8FF : #191970
bg_color := use_dark_mode ? #191970 : #F8F8FF
table_bg_color := use_dark_mode ? #141B47 : #F0F8FF
header_bg_color := use_dark_mode ? #1E2A5C : #E0F0FF
header_bg_color
// Transparency settings
bg_transparency = use_dark_mode ? 85 : 92
zone_transparency = use_dark_mode ? 90 : 95
band_transparency = use_dark_mode ? 70 : 85
table_transparency = use_dark_mode ? 80 : 15
// Allocation color
alloc_color = smoothed_allocation >= 80 ? bullish_color : smoothed_allocation >= 60 ? color.new(bullish_color, 30) : smoothed_allocation >= 40 ? primary_color : smoothed_allocation >= 20 ? color.new(bearish_color, 30) : bearish_color
// Dynamic background
var color dynamic_bg_color = na
if show_regime_background
if smoothed_allocation >= 70
dynamic_bg_color := color.new(bullish_color, background_intensity)
dynamic_bg_color
else if smoothed_allocation <= 30
dynamic_bg_color := color.new(bearish_color, background_intensity)
dynamic_bg_color
else if smoothed_allocation > 60 or smoothed_allocation < 40
dynamic_bg_color := color.new(primary_color, math.min(99, background_intensity + 2))
dynamic_bg_color
bgcolor(dynamic_bg_color, title = 'Allocation Signal Background')
// Plot main allocation line
plot(smoothed_allocation, 'Equity Allocation %', color = alloc_color, linewidth = math.max(1, main_line_width))
// Reference lines (static colors for hline)
hline_bullish_color = color_scheme == 'Gold' ? use_dark_mode ? #FFA500 : #FF8C00 : color_scheme == 'EdgeTools' ? use_dark_mode ? #4CAF50 : #388E3C : color_scheme == 'Behavioral' ? #00FF00 : color_scheme == 'Quant' ? #FFA500 : color_scheme == 'Ocean' ? use_dark_mode ? #00CED1 : #4682B4 : color_scheme == 'Fire' ? use_dark_mode ? #FFD700 : #FF8C00 : color_scheme == 'Matrix' ? use_dark_mode ? #39FF14 : #228B22 : color_scheme == 'Arctic' ? use_dark_mode ? #00BFFF : #0000CD : #4CAF50
hline_bearish_color = color_scheme == 'Gold' ? use_dark_mode ? #FF5252 : #D32F2F : color_scheme == 'EdgeTools' ? use_dark_mode ? #FF5252 : #D32F2F : color_scheme == 'Behavioral' ? #8B0000 : color_scheme == 'Quant' ? #8B0000 : color_scheme == 'Ocean' ? use_dark_mode ? #FF4500 : #B22222 : color_scheme == 'Fire' ? use_dark_mode ? #8B0000 : #800000 : color_scheme == 'Matrix' ? use_dark_mode ? #FF073A : #8B0000 : color_scheme == 'Arctic' ? use_dark_mode ? #FF1493 : #8B008B : #FF5252
hline_primary_color = color_scheme == 'Gold' ? use_dark_mode ? #FFD700 : #DAA520 : color_scheme == 'EdgeTools' ? use_dark_mode ? #4682B4 : #1E90FF : color_scheme == 'Behavioral' ? #808080 : color_scheme == 'Quant' ? #808080 : color_scheme == 'Ocean' ? use_dark_mode ? #20B2AA : #008B8B : color_scheme == 'Fire' ? use_dark_mode ? #FF6347 : #DC143C : color_scheme == 'Matrix' ? use_dark_mode ? #00FF41 : #006400 : color_scheme == 'Arctic' ? use_dark_mode ? #87CEFA : #4169E1 : #2196F3
hline(show_reference_lines ? 100 : na, '100% Equity', color = color.new(hline_bullish_color, 70), linestyle = hline.style_dotted, linewidth = 1)
hline(show_reference_lines ? 80 : na, '80% Equity', color = color.new(hline_bullish_color, 40), linestyle = hline.style_dashed, linewidth = 1)
hline(show_reference_lines ? 60 : na, '60% Equity', color = color.new(hline_bullish_color, 60), linestyle = hline.style_dotted, linewidth = 1)
hline(50, '50% Balanced', color = color.new(hline_primary_color, 50), linestyle = hline.style_solid, linewidth = 2)
hline(show_reference_lines ? 40 : na, '40% Equity', color = color.new(hline_bearish_color, 60), linestyle = hline.style_dotted, linewidth = 1)
hline(show_reference_lines ? 20 : na, '20% Equity', color = color.new(hline_bearish_color, 40), linestyle = hline.style_dashed, linewidth = 1)
hline(show_reference_lines ? 0 : na, '0% Equity', color = color.new(hline_bearish_color, 70), linestyle = hline.style_dotted, linewidth = 1)
// Component plots
plot(show_components ? regime_allocation : na, 'Regime', color = color.new(#4ECDC4, 70), linewidth = 1)
plot(show_components ? risk_allocation : na, 'Risk', color = color.new(#FF6B6B, 70), linewidth = 1)
plot(show_components ? valuation_score : na, 'Valuation', color = color.new(#45B7D1, 70), linewidth = 1)
plot(show_components ? sentiment_score : na, 'Sentiment', color = color.new(#FFD93D, 70), linewidth = 1)
plot(show_components ? macro_score : na, 'Macro', color = color.new(#6BCF7F, 70), linewidth = 1)
// Confidence bands
upper_band = plot(show_confidence_bands ? math.min(100, smoothed_allocation + ta.stdev(smoothed_allocation, 20)) : na, color = color.new(neutral_color, band_transparency), display = display.none, title = 'Upper Band')
lower_band = plot(show_confidence_bands ? math.max(0, smoothed_allocation - ta.stdev(smoothed_allocation, 20)) : na, color = color.new(neutral_color, band_transparency), display = display.none, title = 'Lower Band')
fill(upper_band, lower_band, color = show_confidence_bands ? color.new(neutral_color, zone_transparency) : na, title = 'Uncertainty')
// DASHBOARD
if show_dashboard and barstate.islast
var table dashboard = table.new(position.top_right, 2, 20, border_width = 1, bgcolor = color.new(table_bg_color, table_transparency))
table.clear(dashboard, 0, 0, 1, 19)
// Header
header_color = color.new(header_bg_color, 20)
dashboard_text_color = text_color
table.cell(dashboard, 0, 0, 'DEAM', text_color = dashboard_text_color, bgcolor = header_color, text_size = size.normal)
table.cell(dashboard, 1, 0, model_type, text_color = dashboard_text_color, bgcolor = header_color, text_size = size.normal)
// Core metrics
table.cell(dashboard, 0, 1, 'Equity Allocation', text_color = dashboard_text_color, text_size = size.small)
table.cell(dashboard, 1, 1, str.tostring(smoothed_allocation, '##.#') + '%', text_color = alloc_color, text_size = size.small)
table.cell(dashboard, 0, 2, 'Cash Allocation', text_color = dashboard_text_color, text_size = size.small)
cash_color = 100 - smoothed_allocation > 70 ? bearish_color : primary_color
table.cell(dashboard, 1, 2, str.tostring(100 - smoothed_allocation, '##.#') + '%', text_color = cash_color, text_size = size.small)
// Signal
signal_text = 'NEUTRAL'
signal_color = primary_color
if smoothed_allocation >= 70
signal_text := 'BULLISH'
signal_color := bullish_color
signal_color
else if smoothed_allocation <= 30
signal_text := 'BEARISH'
signal_color := bearish_color
signal_color
table.cell(dashboard, 0, 3, 'Signal', text_color = dashboard_text_color, text_size = size.small)
table.cell(dashboard, 1, 3, signal_text, text_color = signal_color, text_size = size.small)
// Market Regime
table.cell(dashboard, 0, 4, 'Regime', text_color = dashboard_text_color, text_size = size.small)
regime_color_display = market_regime == 'Strong Bull' or market_regime == 'Bull Market' ? bullish_color : market_regime == 'Neutral' ? primary_color : market_regime == 'Crisis' ? bearish_color : bearish_color
table.cell(dashboard, 1, 4, market_regime, text_color = regime_color_display, text_size = size.small)
// VIX
table.cell(dashboard, 0, 5, 'VIX Level', text_color = dashboard_text_color, text_size = size.small)
vix_color_display = vix < 20 ? bullish_color : vix < 30 ? primary_color : bearish_color
table.cell(dashboard, 1, 5, str.tostring(vix, '##.##'), text_color = vix_color_display, text_size = size.small)
// Market Drawdown
table.cell(dashboard, 0, 6, 'Market DD', text_color = dashboard_text_color, text_size = size.small)
market_dd_color = current_drawdown < 5 ? bullish_color : current_drawdown < 10 ? primary_color : bearish_color
table.cell(dashboard, 1, 6, '-' + str.tostring(current_drawdown, '##.#') + '%', text_color = market_dd_color, text_size = size.small)
// Crisis Detection
table.cell(dashboard, 0, 7, 'Crisis Detection', text_color = dashboard_text_color, text_size = size.small)
crisis_text = is_severe_crisis ? 'SEVERE' : is_crisis ? 'CRISIS' : 'Normal'
crisis_display_color = is_severe_crisis or is_crisis ? bearish_color : bullish_color
table.cell(dashboard, 1, 7, crisis_text, text_color = crisis_display_color, text_size = size.small)
// Real Data Section
financial_bg = color.new(primary_color, 85)
table.cell(dashboard, 0, 8, 'REAL DATA', text_color = dashboard_text_color, bgcolor = financial_bg, text_size = size.small)
table.cell(dashboard, 1, 8, 'Live Metrics', text_color = dashboard_text_color, bgcolor = financial_bg, text_size = size.small)
// P/E Ratio
table.cell(dashboard, 0, 9, 'P/E Ratio', text_color = dashboard_text_color, text_size = size.small)
pe_color = actual_pe_ratio < 18 ? bullish_color : actual_pe_ratio < 25 ? primary_color : bearish_color
table.cell(dashboard, 1, 9, str.tostring(actual_pe_ratio, '##.#'), text_color = pe_color, text_size = size.small)
// ERP
table.cell(dashboard, 0, 10, 'ERP', text_color = dashboard_text_color, text_size = size.small)
erp_color = equity_risk_premium > 2 ? bullish_color : equity_risk_premium > 0 ? primary_color : bearish_color
table.cell(dashboard, 1, 10, str.tostring(equity_risk_premium, '##.##') + '%', text_color = erp_color, text_size = size.small)
// ROE
table.cell(dashboard, 0, 11, 'ROE', text_color = dashboard_text_color, text_size = size.small)
roe_color = spy_return_on_equity > 20 ? bullish_color : spy_return_on_equity > 10 ? primary_color : bearish_color
table.cell(dashboard, 1, 11, str.tostring(spy_return_on_equity, '##.#') + '%', text_color = roe_color, text_size = size.small)
// D/E Ratio
table.cell(dashboard, 0, 12, 'D/E Ratio', text_color = dashboard_text_color, text_size = size.small)
de_color = spy_debt_to_equity < 0.5 ? bullish_color : spy_debt_to_equity < 1.0 ? primary_color : bearish_color
table.cell(dashboard, 1, 12, str.tostring(spy_debt_to_equity, '##.##'), text_color = de_color, text_size = size.small)
// Shareholder Yield
table.cell(dashboard, 0, 13, 'Dividend+Buyback', text_color = dashboard_text_color, text_size = size.small)
yield_color = total_shareholder_yield > 4 ? bullish_color : total_shareholder_yield > 2 ? primary_color : bearish_color
table.cell(dashboard, 1, 13, str.tostring(total_shareholder_yield, '##.#') + '%', text_color = yield_color, text_size = size.small)
// Component Scores
component_bg = color.new(neutral_color, 80)
table.cell(dashboard, 0, 14, 'Components', text_color = dashboard_text_color, bgcolor = component_bg, text_size = size.small)
table.cell(dashboard, 1, 14, 'Scores', text_color = dashboard_text_color, bgcolor = component_bg, text_size = size.small)
table.cell(dashboard, 0, 15, 'Regime', text_color = dashboard_text_color, text_size = size.small)
regime_score_color = regime_allocation > 60 ? bullish_color : regime_allocation < 40 ? bearish_color : primary_color
table.cell(dashboard, 1, 15, str.tostring(regime_allocation, '##'), text_color = regime_score_color, text_size = size.small)
table.cell(dashboard, 0, 16, 'Risk', text_color = dashboard_text_color, text_size = size.small)
risk_score_color = risk_allocation > 60 ? bullish_color : risk_allocation < 40 ? bearish_color : primary_color
table.cell(dashboard, 1, 16, str.tostring(risk_allocation, '##'), text_color = risk_score_color, text_size = size.small)
table.cell(dashboard, 0, 17, 'Valuation', text_color = dashboard_text_color, text_size = size.small)
val_score_color = valuation_score > 60 ? bullish_color : valuation_score < 40 ? bearish_color : primary_color
table.cell(dashboard, 1, 17, str.tostring(valuation_score, '##'), text_color = val_score_color, text_size = size.small)
table.cell(dashboard, 0, 18, 'Sentiment', text_color = dashboard_text_color, text_size = size.small)
sent_score_color = sentiment_score > 60 ? bullish_color : sentiment_score < 40 ? bearish_color : primary_color
table.cell(dashboard, 1, 18, str.tostring(sentiment_score, '##'), text_color = sent_score_color, text_size = size.small)
table.cell(dashboard, 0, 19, 'Macro', text_color = dashboard_text_color, text_size = size.small)
macro_score_color = macro_score > 60 ? bullish_color : macro_score < 40 ? bearish_color : primary_color
table.cell(dashboard, 1, 19, str.tostring(macro_score, '##'), text_color = macro_score_color, text_size = size.small)
// ALERTS
// Major allocation changes
alertcondition(smoothed_allocation >= 80 and smoothed_allocation < 80, 'High Equity Allocation', 'Equity allocation reached 80% - Bull market conditions')
alertcondition(smoothed_allocation <= 20 and smoothed_allocation > 20, 'Low Equity Allocation', 'Equity allocation dropped to 20% - Defensive positioning')
// Crisis alerts
alertcondition(is_crisis and not is_crisis , 'CRISIS DETECTED', 'Crisis conditions detected - Reducing equity allocation')
alertcondition(is_severe_crisis and not is_severe_crisis , 'SEVERE CRISIS', 'Severe crisis detected - Maximum defensive positioning')
// Regime changes
regime_changed = market_regime != market_regime
alertcondition(regime_changed, 'Regime Change', 'Market regime has changed')
// Risk management alerts
risk_breach = enable_portfolio_risk_scaling and (actual_portfolio_volatility > target_portfolio_volatility * 1.2 or actual_portfolio_drawdown > max_portfolio_drawdown * 1.2)
alertcondition(risk_breach, 'Risk Breach', 'Portfolio risk exceeds target parameters')
// USAGE
// The indicator displays a recommended equity allocation percentage (0-100%).
// Example: 75% allocation = 75% stocks, 25% cash/bonds.
//
// The model combines market regime analysis (trend, volatility, drawdowns),
// risk management (portfolio-level targeting), valuation metrics (P/E, ERP),
// sentiment indicators (VIX term structure), and macro factors (yield curve,
// credit spreads) into a single allocation signal.
//
// Crisis detection automatically reduces exposure when multiple warning signals
// converge. Alerts available for major allocation shifts and regime changes.
//
// Designed for SPY/S&P 500 portfolio allocation. Adjust component weights and
// risk parameters in settings to match your risk tolerance.
View in Pine
UT Bot + Smart Money Concepts [LuxAlgo]UT Bot + Smart Money Concepts , BUY SELL INDICATOR and support and resistance
3B / 3S System + 99 EMA + Camarilla Pivots3B / 3S System + 99 EMA + Camarilla Pivots, EMA5 above 2 candles buy or SELL
Flux-Tensor Singularity [ML/RL PRO]Flux-Tensor Singularity
This version of the Flux-Tensor Singularity (FTS) represents a paradigm shift in technical analysis by treating price movement as a physical system governed by volume-weighted forces and volatility dynamics. Unlike traditional indicators that measure price change or momentum in isolation, FTS quantifies the complete energetic state of the market by fusing three fundamental dimensions: price displacement (delta_P), volume intensity (V), and local-to-global volatility ratio (gamma).
The Physics-Inspired Foundation:
The tensor calculation draws inspiration from general relativity and fluid dynamics, where massive objects (large volume) create curvature in spacetime (price action). The core formula:
Raw Singularity = (ΔPrice × ln(Volume)) × γ²
Where:
• ΔPrice = close - close (directional force)
• ln(Volume) = logarithmic volume compression (prevents extreme outliers)
• γ (Gamma) = (ATR_local / ATR_global)² (volatility expansion coefficient)
This raw value is then normalized to 0-100 range using the lookback period's extremes, creating a bounded oscillator that identifies critical density points—"singularities" where normal market behavior breaks down and explosive moves become probable.
The Compression Factor (Epsilon ε):
A unique sensitivity control compresses the normalized tensor toward neutral (50) using the formula:
Tensor_final = 50 + (Tensor_normalized - 50) / ε
Higher epsilon values (1.5-3.0) make threshold breaches rare and significant, while lower values (0.3-0.7) increase signal frequency. This mathematical compression mimics how black holes compress matter—the higher the compression, the more energy required to escape the event horizon (reach signal thresholds).
Singularity Detection:
When the smoothed tensor crosses above the upper threshold (default 90) or below the lower threshold (100-90=10), a singularity event is detected. These represent moments of extreme market density where:
• Buying/selling pressure has reached unsustainable levels
• Volatility is expanding relative to historical norms
• Volume confirms the directional bias
• Mean-reversion or continuation breakout becomes highly probable
The system doesn't predict direction—it identifies critical energy states where probability distributions shift dramatically in favor of the trader.
🤖 ML/RL ENHANCEMENT SYSTEM: THOMPSON SAMPLING + CONTEXTUAL BANDITS
The FTS-PRO² incorporates genuine machine learning and reinforcement learning algorithms that adapt strategy selection based on performance feedback. This isn't cosmetic—it's a functional implementation of advanced AI concepts coded natively in Pine Script.
Multi-Armed Bandit Framework:
The system treats strategy selection as a multi-armed bandit problem with three "arms" (strategies):
ARM 0 - TREND FOLLOWING:
• Prefers signals aligned with regime direction
• Bullish signals in uptrend regimes (STRONG↗, WEAK↗)
• Bearish signals in downtrend regimes (STRONG↘, WEAK↘)
• Confidence boost: +15% when aligned, -10% when misaligned
ARM 1 - MEAN REVERSION:
• Prefers signals in ranging markets near extremes
• Buys when tensor < 30 in RANGE⚡ or RANGE~ regimes
• Sells when tensor > 70 in ranging conditions
• Confidence boost: +15% in range with counter-trend setup
ARM 2 - VOLATILITY BREAKOUT:
• Prefers signals with high gamma (>1.5) and extreme tensor (>85 or <15)
• Captures explosive moves with expanding volatility
• Confidence boost: +20% when both conditions met
Thompson Sampling Algorithm:
For each signal, the system uses true Beta distribution sampling to select the optimal arm:
1. Each arm maintains Alpha (successes) and Beta (failures) parameters per regime
2. Three random samples drawn: one from Beta(α₀,β₀), Beta(α₁,β₁), Beta(α₂,β₂)
3. Highest sample wins and that arm's strategy applies
4. After trade outcome:
- Win → Alpha += 1.0, reward += 1.0
- Loss → Beta += 1.0, reward -= 0.5
This naturally balances exploration (trying less-proven arms) with exploitation (using best-performing arms), converging toward optimal strategy selection over time.
Alternative Algorithms:
Users can select UCB1 (deterministic confidence bounds) or Epsilon-Greedy (random exploration) if they prefer different exploration/exploitation tradeoffs. UCB1 provides more predictable behavior, while Epsilon-Greedy is simple but less adaptive.
Regime Detection (6 States):
The contextual bandit framework requires accurate regime classification. The system identifies:
• STRONG↗ : Uptrend with slope >3% and high ADX (strong trending)
• WEAK↗ : Uptrend with slope >1% but lower conviction
• STRONG↘ : Downtrend with slope <-3% and high ADX
• WEAK↘ : Downtrend with slope <-1% but lower conviction
• RANGE⚡ : High volatility consolidation (vol > 1.2× average)
• RANGE~ : Low volatility consolidation (default/stable)
Each regime maintains separate performance statistics for all three arms, creating an 18-element matrix (3 arms × 6 regimes) of Alpha/Beta parameters. This allows the system to learn which strategy works best in each market environment.
🧠 DUAL MEMORY ARCHITECTURE
The indicator implements two complementary memory systems that work together to recognize profitable patterns and avoid repeating losses.
Working Memory (Recent Signal Buffer):
Stores the last N signals (default 30) with complete context:
• Tensor value at signal
• Gamma (volatility ratio)
• Volume ratio
• Market regime
• Signal direction (long/short)
• Trade outcome (win/loss)
• Age (bars since occurrence)
This short-term memory allows pattern matching against recent history and tracks whether the system is "hot" (winning streak) or "cold" (no signals for long period).
Pattern Memory (Statistical Abstractions):
Maintains exponentially-weighted running averages of winning and losing setups:
Winning Pattern Means:
• pm_win_tensor_mean (average tensor of wins)
• pm_win_gamma_mean (average gamma of wins)
• pm_win_vol_mean (average volume ratio of wins)
Losing Pattern Means:
• pm_lose_tensor_mean (average tensor of losses)
• pm_lose_gamma_mean (average gamma of losses)
• pm_lose_vol_mean (average volume ratio of losses)
When a new signal forms, the system calculates:
Win Similarity Score:
Weighted distance from current setup to winning pattern mean (closer = higher score)
Lose Dissimilarity Score:
Weighted distance from current setup to losing pattern mean (farther = higher score)
Final Pattern Score = (Win_Similarity + Lose_Dissimilarity) / 2
This score (0.0 to 1.0) feeds into ML confidence calculation with 15% weight. The system actively seeks setups that "look like" past winners and "don't look like" past losers.
Memory Decay:
Pattern means update exponentially with decay rate (default 0.95):
New_Mean = Old_Mean × 0.95 + New_Value × 0.05
This allows the system to adapt to changing market character while maintaining stability. Faster decay (0.80-0.90) adapts quickly but may overfit to recent noise. Slower decay (0.95-0.99) provides stability but adapts slowly to regime changes.
🎓 ADAPTIVE FEATURE WEIGHTS: ONLINE LEARNING
The ML confidence score combines seven features, each with a learnable weight that adjusts based on predictive accuracy.
The Seven Features:
1. Overall Win Rate (15% initial) : System-wide historical performance
2. Regime Win Rate (20% initial) : Performance in current market regime
3. Score Strength (15% initial) : Bull vs bear score differential
4. Volume Strength (15% initial) : Volume ratio normalized to 0-1
5. Pattern Memory (15% initial) : Similarity to winning patterns
6. MTF Confluence (10% initial) : Higher timeframe alignment
7. Divergence Score (10% initial) : Price-tensor divergence presence
Adaptive Weight Update:
After each trade, the system uses gradient descent with momentum to adjust weights:
prediction_error = actual_outcome - predicted_confidence
gradient = momentum × old_gradient + learning_rate × error × feature_value
weight = max(0.05, weight + gradient × 0.01)
Then weights are normalized to sum to 1.0.
Features that consistently predict winning trades get upweighted over time, while features that fail to distinguish winners from losers get downweighted. The momentum term (default 0.9) smooths the gradient to prevent oscillation and overfitting.
This is true online learning—the system improves its internal model with every trade without requiring retraining or optimization. Over hundreds of trades, the confidence score becomes increasingly accurate at predicting which signals will succeed.
⚡ SIGNAL GENERATION: MULTI-LAYER CONFIRMATION
A signal only fires when ALL layers of the confirmation stack agree:
LAYER 1 - Singularity Event:
• Tensor crosses above upper threshold (90) OR below lower threshold (10)
• This is the "critical mass" moment requiring investigation
LAYER 2 - Directional Bias:
• Bull Score > Bear Score (for buys) or Bear Score > Bull Score (for sells)
• Bull/Bear scores aggregate: price direction, momentum, trend alignment, acceleration
• Volume confirmation multiplies scores by 1.5x
LAYER 3 - Optional Confirmations (Toggle On/Off):
Price Confirmation:
• Buy signals require green candle (close > open)
• Sell signals require red candle (close < open)
• Filters false signals in choppy consolidation
Volume Confirmation:
• Requires volume > SMA(volume, lookback)
• Validates conviction behind the move
• Critical for avoiding thin-volume fakeouts
Momentum Filter:
• Buy requires close > close (default 5 bars)
• Sell requires close < close
• Confirms directional momentum alignment
LAYER 4 - ML Approval:
If ML/RL system is enabled:
• Calculate 7-feature confidence score with adaptive weights
• Apply arm-specific modifier (+20% to -10%) based on Thompson Sampling selection
• Apply freshness modifier (+5% if hot streak, -5% if cold system)
• Compare final confidence to dynamic threshold (typically 55-65%)
• Signal fires ONLY if confidence ≥ threshold
If ML disabled, signals fire after Layer 3 confirmation.
Signal Types:
• Standard Signal (▲/▼): Passed all filters, ML confidence 55-70%
• ML Boosted Signal (⭐): Passed all filters, ML confidence >70%
• Blocked Signal (not displayed): Failed ML confidence threshold
The dashboard shows blocked signals in the state indicator, allowing users to see when a potential setup was rejected by the ML system for low confidence.
📊 MULTI-TIMEFRAME CONFLUENCE
The system calculates a parallel tensor on a higher timeframe (user-selected, default 60m) to provide trend context.
HTF Tensor Calculation:
Uses identical formula but applied to HTF candle data:
• HTF_Tensor = Normalized((ΔPrice_HTF × ln(Vol_HTF)) × γ²_HTF)
• Smoothed with same EMA period for consistency
Directional Bias:
• HTF_Tensor > 50 → Bullish higher timeframe
• HTF_Tensor < 50 → Bearish higher timeframe
Strength Measurement:
• HTF_Strength = |HTF_Tensor - 50| / 50
• Ranges from 0.0 (neutral) to 1.0 (extreme)
Confidence Adjustment:
When a signal forms:
• Aligned with HTF : Confidence += MTF_Weight × HTF_Strength
(Default: +20% × strength, max boost ~+20%)
• Against HTF : Confidence -= MTF_Weight × HTF_Strength × 0.6
(Default: -20% × strength × 0.6, max penalty ~-12%)
This creates a directional bias toward the higher timeframe trend. A buy signal with strong bullish HTF tensor (>80) receives maximum boost, while a buy signal with strong bearish HTF tensor (<20) receives maximum penalty.
Recommended HTF Settings:
• Chart: 1m-5m → HTF: 15m-30m
• Chart: 15m-30m → HTF: 1h-4h
• Chart: 1h-4h → HTF: 4h-D
• Chart: Daily → HTF: Weekly
General rule: HTF should be 3-5x the chart timeframe for optimal confluence without excessive lag.
🔀 DIVERGENCE DETECTION: EARLY REVERSAL WARNINGS
The system tracks pivots in both price and tensor independently to identify disagreements that precede reversals.
Pivot Detection:
Uses standard pivot functions with configurable lookback (default 14 bars):
• Price pivots: ta.pivothigh(high) and ta.pivotlow(low)
• Tensor pivots: ta.pivothigh(tensor) and ta.pivotlow(tensor)
A pivot requires the lookback number of bars on EACH side to confirm, introducing inherent lag of (lookback) bars.
Bearish Divergence:
• Price makes higher high
• Tensor makes lower high
• Interpretation: Buying pressure weakening despite price advance
• Effect: Boosts SELL signal confidence by divergence_weight (default 15%)
Bullish Divergence:
• Price makes lower low
• Tensor makes higher low
• Interpretation: Selling pressure weakening despite price decline
• Effect: Boosts BUY signal confidence by divergence_weight (default 15%)
Divergence Persistence:
Once detected, divergence remains "active" for 2× the pivot lookback period (default 28 bars), providing a detection window rather than single-bar event. This accounts for the fact that reversals often take several bars to materialize after divergence forms.
Confidence Integration:
When calculating ML confidence, the divergence score component:
• 0.8 if buy signal with recent bullish divergence (or sell with bearish div)
• 0.2 if buy signal with recent bearish divergence (opposing signal)
• 0.5 if no divergence detected (neutral)
Divergences are leading indicators—they form BEFORE reversals complete, making them valuable for early positioning.
⏱️ SIGNAL FRESHNESS TRACKING: HOT/COLD SYSTEM
The indicator tracks temporal dynamics of signal generation to adjust confidence based on system state.
Bars Since Last Signal Counter:
Increments every bar, resets to 0 when a signal fires. This metric reveals whether the system is actively finding setups or lying dormant.
Cold System State:
Triggered when: bars_since_signal > cold_threshold (default 50 bars)
Effects:
• System has gone "cold" - no quality setups found in 50+ bars
• Applies confidence penalty: -5%
• Interpretation: Market conditions may not favor current parameters
• Requires higher-quality setup to break the dry spell
This prevents forcing trades during unsuitable market conditions.
Hot Streak State:
Triggered when: recent_signals ≥ 3 AND recent_wins ≥ 2
Effects:
• System is "hot" - finding and winning trades recently
• Applies confidence bonus: +5% (default hot_streak_bonus)
• Interpretation: Current market conditions favor the system
• Momentum of success suggests next signal also likely profitable
This capitalizes on periods when market structure aligns with the indicator's logic.
Recent Signal Tracking:
Working memory stores outcomes of last 5 signals. When 3+ winners occur in this window, hot streak activates. After 5 signals, the counter resets and tracking restarts. This creates rolling evaluation of recent performance.
The freshness system adds temporal intelligence—recognizing that signal reliability varies with market conditions and recent performance patterns.
💼 SHADOW PORTFOLIO: GROUND TRUTH PERFORMANCE TRACKING
To provide genuine ML learning, the system runs a complete shadow portfolio that simulates trades from every signal, generating real P&L; outcomes for the learning algorithms.
Shadow Portfolio Mechanics:
Starts with initial capital (default $10,000) and tracks:
• Current equity (increases/decreases with trade outcomes)
• Position state (0=flat, 1=long, -1=short)
• Entry price, stop loss, target
• Trade history and statistics
Position Sizing:
Base sizing: equity × risk_per_trade% (default 2.0%)
With dynamic sizing enabled:
• Size multiplier = 0.5 + ML_confidence
• High confidence (0.80) → 1.3× base size
• Low confidence (0.55) → 1.05× base size
Example: $10,000 equity, 2% risk, 80% confidence:
• Impact: $10,000 × 2% × 1.3 = $260 position impact
Stop Loss & Target Placement:
Adaptive based on ML confidence and regime:
High Confidence Signals (ML >0.7):
• Tighter stops: 1.5× ATR
• Larger targets: 4.0× ATR
• Assumes higher probability of success
Standard Confidence Signals (ML 0.55-0.7):
• Standard stops: 2.0× ATR
• Standard targets: 3.0× ATR
Ranging Regimes (RANGE⚡/RANGE~):
• Tighter setup: 1.5× ATR stop, 2.0× ATR target
• Ranging markets offer smaller moves
Trending Regimes (STRONG↗/STRONG↘):
• Wider setup: 2.5× ATR stop, 5.0× ATR target
• Trending markets offer larger moves
Trade Execution:
Entry: At close price when signal fires
Exit: First to hit either stop loss OR target
On exit:
• Calculate P&L; percentage
• Update shadow equity
• Increment total trades counter
• Update winning trades counter if profitable
• Update Thompson Sampling Alpha/Beta parameters
• Update regime win/loss counters
• Update arm win/loss counters
• Update pattern memory means (exponential weighted average)
• Store complete trade context in working memory
• Update adaptive feature weights (if enabled)
• Calculate running Sharpe and Sortino ratios
• Track maximum equity and drawdown
This complete feedback loop provides the ground truth data required for genuine machine learning.
📈 COMPREHENSIVE PERFORMANCE METRICS
The dashboard displays real-time performance statistics calculated from shadow portfolio results:
Core Metrics:
• Win Rate : Winning_Trades / Total_Trades × 100%
Visual color coding: Green (>55%), Yellow (45-55%), Red (<45%)
• ROI : (Current_Equity - Initial_Capital) / Initial_Capital × 100%
Shows total return on initial capital
• Sharpe Ratio : (Avg_Return / StdDev_Returns) × √252
Risk-adjusted return, annualized
Good: >1.5, Acceptable: >0.5, Poor: <0.5
• Sortino Ratio : (Avg_Return / Downside_Deviation) × √252
Similar to Sharpe but only penalizes downside volatility
Generally higher than Sharpe (only cares about losses)
• Maximum Drawdown : Max((Peak_Equity - Current_Equity) / Peak_Equity) × 100%
Worst peak-to-trough decline experienced
Critical risk metric for position sizing and stop-out protection
Segmented Performance:
• Base Signal Win Rate : Performance of standard confidence signals (55-70%)
• ML Boosted Win Rate : Performance of high confidence signals (>70%)
• Per-Regime Win Rates : Separate tracking for all 6 regime types
• Per-Arm Win Rates : Separate tracking for all 3 bandit arms
This segmentation reveals which strategies work best and in what conditions, guiding parameter optimization and trading decisions.
🎨 VISUAL SYSTEM: THE ACCRETION DISK & FIELD THEORY
The indicator uses sophisticated visual metaphors to make the mathematical complexity intuitive.
Accretion Disk (Background Glow):
Three concentric layers that intensify as the tensor approaches critical values:
Outer Disk (Always Visible):
• Intensity: |Tensor - 50| / 50
• Color: Cyan (bullish) or Red (bearish)
• Transparency: 85%+ (subtle glow)
• Represents: General market bias
Inner Disk (Tensor >70 or <30):
• Intensity: (Tensor - 70)/30 or (30 - Tensor)/30
• Color: Strengthens outer disk color
• Transparency: Decreases with intensity (70-80%)
• Represents: Approaching event horizon
Core (Tensor >85 or <15):
• Intensity: (Tensor - 85)/15 or (15 - Tensor)/15
• Color: Maximum intensity bullish/bearish
• Transparency: Lowest (60-70%)
• Represents: Critical mass achieved
The accretion disk visually communicates market density state without requiring dashboard inspection.
Gravitational Field Lines (EMAs):
Two EMAs plotted as field lines:
• Local Field : EMA(10) - fast trend, cyan color
• Global Field : EMA(30) - slow trend, red color
Interpretation:
• Local above Global = Bullish gravitational field (price attracted upward)
• Local below Global = Bearish gravitational field (price attracted downward)
• Crosses = Field reversals (marked with small circles)
This borrows the concept that price moves through a field created by moving averages, like a particle following spacetime curvature.
Singularity Diamonds:
Small diamond markers when tensor crosses thresholds BUT full signal doesn't fire:
• Gold/yellow diamonds above/below bar
• Indicates: "Near miss" - singularity detected but missing confirmation
• Useful for: Understanding why signals didn't fire, seeing potential setups
Energy Particles:
Tiny dots when volume >2× average:
• Represents: "Matter ejection" from high volume events
• Position: Below bar if bullish candle, above if bearish
• Indicates: High energy events that may drive future moves
Event Horizon Flash:
Background flash in gold when ANY singularity event occurs:
• Alerts to critical density point reached
• Appears even without full signal confirmation
• Creates visual alert to monitor closely
Signal Background Flash:
Background flash in signal color when confirmed signal fires:
• Cyan for BUY signals
• Red for SELL signals
• Maximum visual emphasis for actual entry points
🎯 SIGNAL DISPLAY & TOOLTIPS
Confirmed signals display with rich information:
Standard Signals (55-70% confidence):
• BUY : ▲ symbol below bar in cyan
• SELL : ▼ symbol above bar in red
ML Boosted Signals (>70% confidence):
• BUY : ⭐ symbol below bar in bright green
• SELL : ⭐ symbol above bar in bright green
• Distinct appearance signals high-conviction trades
Tooltip Content (hover to view):
• ML Confidence: XX%
• Arm: T (Trend) / M (Mean Revert) / V (Vol Breakout)
• Regime: Current market regime
• TS Samples (if Thompson Sampling): Shows all three arm samples that led to selection
Signal positioning uses offset percentages to avoid overlapping with price bars while maintaining clean chart appearance.
Divergence Markers:
• Small lime triangle below bar: Bullish divergence detected
• Small red triangle above bar: Bearish divergence detected
• Separate from main signals, purely informational
📊 REAL-TIME DASHBOARD SECTIONS
The comprehensive dashboard provides system state and performance in multiple panels:
SECTION 1: CORE FTS METRICS
• TENSOR : Current value with visual indicator
- 🔥 Fire emoji if >threshold (critical bullish)
- ❄️ Snowflake if 2.0× (extreme volatility)
- ⚠ Warning if >1.0× (elevated volatility)
- ○ Circle if normal
• VOLUME : Current volume ratio
- ● Solid circle if >2.0× average (heavy)
- ◐ Half circle if >1.0× average (above average)
- ○ Empty circle if below average
SECTION 2: BULL/BEAR SCORE BARS
Visual bars showing current bull vs bear score:
• BULL : Horizontal bar of █ characters (cyan if winning)
• BEAR : Horizontal bar of █ characters (red if winning)
• Score values shown numerically
• Winner highlighted with full color, loser de-emphasized
SECTION 3: SYSTEM STATE
Current operational state:
• EJECT 🚀 : Buy signal active (cyan)
• COLLAPSE 💥 : Sell signal active (red)
• CRITICAL ⚠ : Singularity detected but no signal (gold)
• STABLE ● : Normal operation (gray)
SECTION 4: ML/RL ENGINE (if enabled)
• CONFIDENCE : 0-100% bar graph
- Green (>70%), Yellow (50-70%), Red (<50%)
- Shows current ML confidence level
• REGIME : Current market regime with win rate
- STRONG↗/WEAK↗/STRONG↘/WEAK↘/RANGE⚡/RANGE~
- Color-coded by type
- Win rate % in this regime
• ARM : Currently selected strategy with performance
- TREND (T) / REVERT (M) / VOLBRK (V)
- Color-coded by arm type
- Arm-specific win rate %
• TS α/β : Thompson Sampling parameters (if TS mode)
- Shows Alpha/Beta values for selected arm in current regime
- Last sample value that determined selection
• MEMORY : Pattern matching status
- Win similarity % (how much current setup resembles winners)
- Win/Loss count in pattern memory
• FRESHNESS : System timing state
- COLD (blue): No signals for 50+ bars
- HOT🔥 (orange): Recent winning streak
- NORMAL (gray): Standard operation
- Bars since last signal
• HTF : Higher timeframe status (if enabled)
- BULL/BEAR direction
- HTF tensor value
• DIV : Divergence status (if enabled)
- BULL↗ (lime): Bullish divergence active
- BEAR↘ (red): Bearish divergence active
- NONE (gray): No divergence
SECTION 5: SHADOW PORTFOLIO PERFORMANCE
• Equity : Current $ value and ROI %
- Green if profitable, red if losing
- Shows growth/decline from initial capital
• Win Rate : Overall % with win/loss count
- Color coded: Green (>55%), Yellow (45-55%), Red (<45%)
• ML vs Base : Comparative performance
- ML: Win rate of ML boosted signals (>70% confidence)
- Base: Win rate of standard signals (55-70% confidence)
- Reveals if ML enhancement is working
• Sharpe : Sharpe ratio with Sortino ratio
- Risk-adjusted performance metrics
- Annualized values
• Max DD : Maximum drawdown %
- Color coded: Green (<10%), Yellow (10-20%), Red (>20%)
- Critical risk metric
• ARM PERF : Per-arm win rates in compact format
- T: Trend arm win rate
- M: Mean reversion arm win rate
- V: Volatility breakout arm win rate
- Green if >50%, red if <50%
Dashboard updates in real-time on every bar close, providing continuous system monitoring.
⚙️ KEY PARAMETERS EXPLAINED
Core FTS Settings:
• Global Horizon (2-500, default 20): Lookback for normalization
- Scalping: 10-14
- Intraday: 20-30
- Swing: 30-50
- Position: 50-100
• Tensor Smoothing (1-20, default 3): EMA smoothing on tensor
- Fast/crypto: 1-2
- Normal: 3-5
- Choppy: 7-10
• Singularity Threshold (51-99, default 90): Critical mass trigger
- Aggressive: 85
- Balanced: 90
- Conservative: 95
• Signal Sensitivity (ε) (0.1-5.0, default 1.0): Compression factor
- Aggressive: 0.3-0.7
- Balanced: 1.0
- Conservative: 1.5-3.0
- Very conservative: 3.0-5.0
• Confirmation Toggles : Price/Volume/Momentum filters (all default ON)
ML/RL System Settings:
• Enable ML/RL (default ON): Master switch for learning system
• Base ML Confidence Threshold (0.4-0.9, default 0.55): Minimum to fire
- Aggressive: 0.40-0.50
- Balanced: 0.55-0.65
- Conservative: 0.70-0.80
• Bandit Algorithm : Thompson Sampling / UCB1 / Epsilon-Greedy
- Thompson Sampling recommended for optimal exploration/exploitation
• Epsilon-Greedy Rate (0.05-0.5, default 0.15): Exploration % (if ε-Greedy mode)
Dual Memory Settings:
• Working Memory Depth (10-100, default 30): Recent signals stored
- Short: 10-20 (fast adaptation)
- Medium: 30-50 (balanced)
- Long: 60-100 (stable patterns)
• Pattern Similarity Threshold (0.5-0.95, default 0.70): Match strictness
- Loose: 0.50-0.60
- Medium: 0.65-0.75
- Strict: 0.80-0.90
• Memory Decay Rate (0.8-0.99, default 0.95): Exponential decay speed
- Fast: 0.80-0.88
- Medium: 0.90-0.95
- Slow: 0.96-0.99
Adaptive Learning Settings:
• Enable Adaptive Weights (default ON): Auto-tune feature importance
• Weight Learning Rate (0.01-0.3, default 0.10): Gradient descent step size
- Very slow: 0.01-0.03
- Slow: 0.05-0.08
- Medium: 0.10-0.15
- Fast: 0.20-0.30
• Weight Momentum (0.5-0.99, default 0.90): Gradient smoothing
- Low: 0.50-0.70
- Medium: 0.75-0.85
- High: 0.90-0.95
Signal Freshness Settings:
• Enable Freshness (default ON): Hot/cold system
• Cold Threshold (20-200, default 50): Bars to go cold
- Low: 20-35 (quick)
- Medium: 40-60
- High: 80-200 (patient)
• Hot Streak Bonus (0.0-0.15, default 0.05): Confidence boost when hot
- None: 0.00
- Small: 0.02-0.04
- Medium: 0.05-0.08
- Large: 0.10-0.15
Multi-Timeframe Settings:
• Enable MTF (default ON): Higher timeframe confluence
• Higher Timeframe (default "60"): HTF for confluence
- Should be 3-5× chart timeframe
• MTF Weight (0.0-0.4, default 0.20): Confluence impact
- None: 0.00
- Light: 0.05-0.10
- Medium: 0.15-0.25
- Heavy: 0.30-0.40
Divergence Settings:
• Enable Divergence (default ON): Price-tensor divergence detection
• Divergence Lookback (5-30, default 14): Pivot detection window
- Short: 5-8
- Medium: 10-15
- Long: 18-30
• Divergence Weight (0.0-0.3, default 0.15): Confidence impact
- None: 0.00
- Light: 0.05-0.10
- Medium: 0.15-0.20
- Heavy: 0.25-0.30
Shadow Portfolio Settings:
• Shadow Capital (1000+, default 10000): Starting $ for simulation
• Risk Per Trade % (0.5-5.0, default 2.0): Position sizing
- Conservative: 0.5-1.0%
- Moderate: 1.5-2.5%
- Aggressive: 3.0-5.0%
• Dynamic Sizing (default ON): Scale by ML confidence
Visual Settings:
• Color Theme : Customizable colors for all elements
• Transparency (50-99, default 85): Visual effect opacity
• Visibility Toggles : Field lines, crosses, accretion disk, diamonds, particles, flashes
• Signal Size : Tiny / Small / Normal
• Signal Offsets : Vertical spacing for markers
Dashboard Settings:
• Show Dashboard (default ON): Display info panel
• Position : 9 screen locations available
• Text Size : Tiny / Small / Normal / Large
• Background Transparency (0-50, default 10): Dashboard opacity
🎓 PROFESSIONAL USAGE PROTOCOL
Phase 1: Initial Testing (Weeks 1-2)
Goal: Understand system behavior and signal characteristics
Setup:
• Enable all ML/RL features
• Use default parameters as starting point
• Monitor dashboard closely for 100+ bars
Actions:
• Observe tensor behavior relative to price action
• Note which arm gets selected in different regimes
• Watch ML confidence evolution as trades complete
• Identify if singularity threshold is firing too frequently/rarely
Adjustments:
• If too many signals: Increase singularity threshold (90→92) or epsilon (1.0→1.5)
• If too few signals: Decrease threshold (90→88) or epsilon (1.0→0.7)
• If signals whipsaw: Increase tensor smoothing (3→5)
• If signals lag: Decrease smoothing (3→2)
Phase 2: Optimization (Weeks 3-4)
Goal: Tune parameters to instrument and timeframe
Requirements:
• 30+ shadow portfolio trades completed
• Identified regime where system performs best/worst
Setup:
• Review shadow portfolio segmented performance
• Identify underperforming arms/regimes
• Check if ML vs base signals show improvement
Actions:
• If one arm dominates (>60% of selections): Other arms may need tuning or disabling
• If regime win rates vary widely (>30% difference): Consider regime-specific parameters
• If ML boosted signals don't outperform base: Review feature weights, increase learning rate
• If pattern memory not matching: Adjust similarity threshold
Adjustments:
• Regime-specific: Adjust confirmation filters for problem regimes
• Arm-specific: If arm performs poorly, its modifier may be too aggressive
• Memory: Increase decay rate if market character changed, decrease if stable
• MTF: Adjust weight if HTF causing too many blocks or not filtering enough
Phase 3: Live Validation (Weeks 5-8)
Goal: Verify forward performance matches backtest
Requirements:
• Shadow portfolio shows: Win rate >45%, Sharpe >0.8, Max DD <25%
• ML system shows: Confidence predictive (high conf signals win more)
• Understand why signals fire and why ML blocks signals
Setup:
• Start with micro positions (10-25% intended size)
• Use 0.5-1.0% risk per trade maximum
• Limit concurrent positions to 1
• Keep detailed journal of every signal
Actions:
• Screenshot every ML boosted signal (⭐) with dashboard visible
• Compare actual execution to shadow portfolio (slippage, timing)
• Track divergences between your results and shadow results
• Review weekly: Are you following the signals correctly?
Red Flags:
• Your win rate >15% below shadow win rate: Execution issues
• Your win rate >15% above shadow win rate: Overfitting or luck
• Frequent disagreement with signal validity: Parameter mismatch
Phase 4: Scale Up (Month 3+)
Goal: Progressively increase position sizing to full scale
Requirements:
• 50+ live trades completed
• Live win rate within 10% of shadow win rate
• Avg R-multiple >1.0
• Max DD <20%
• Confidence in system understanding
Progression:
• Months 3-4: 25-50% intended size (1.0-1.5% risk)
• Months 5-6: 50-75% intended size (1.5-2.0% risk)
• Month 7+: 75-100% intended size (1.5-2.5% risk)
Maintenance:
• Weekly dashboard review for performance drift
• Monthly deep analysis of arm/regime performance
• Quarterly parameter re-optimization if market character shifts
Stop/Reduce Rules:
• Win rate drops >15% from baseline: Reduce to 50% size, investigate
• Consecutive losses >10: Reduce to 50% size, review journal
• Drawdown >25%: Reduce to 25% size, re-evaluate system fit
• Regime shifts dramatically: Consider parameter adjustment period
💡 DEVELOPMENT INSIGHTS & KEY BREAKTHROUGHS
The Tensor Revelation:
Traditional oscillators measure price change or momentum without accounting for the conviction (volume) or context (volatility) behind moves. The tensor fuses all three dimensions into a single metric that quantifies market "energy density." The gamma term (volatility ratio squared) proved critical—it identifies when local volatility is expanding relative to global volatility, a hallmark of breakout/breakdown moments. This one innovation increased signal quality by ~18% in backtesting.
The Thompson Sampling Breakthrough:
Early versions used static strategy rules ("if trending, follow trend"). Performance was mediocre and inconsistent across market conditions. Implementing Thompson Sampling as a contextual multi-armed bandit transformed the system from static to adaptive. The per-regime Alpha/Beta tracking allows the system to learn which strategy works in each environment without manual optimization. Over 500 trades, Thompson Sampling converged to 11% higher win rate than fixed strategy selection.
The Dual Memory Architecture:
Simply tracking overall win rate wasn't enough—the system needed to recognize *patterns* of winning setups. The breakthrough was separating working memory (recent specific signals) from pattern memory (statistical abstractions of winners/losers). Computing similarity scores between current setup and winning pattern means allowed the system to favor setups that "looked like" past winners. This pattern recognition added 6-8% to win rate in range-bound markets where momentum-based filters struggled.
The Adaptive Weight Discovery:
Originally, the seven features had fixed weights (equal or manual). Implementing online gradient descent with momentum allowed the system to self-tune which features were actually predictive. Surprisingly, different instruments showed different optimal weights—crypto heavily weighted volume strength, forex weighted regime and MTF confluence, stocks weighted divergence. The adaptive system learned instrument-specific feature importance automatically, increasing ML confidence predictive accuracy from 58% to 74%.
The Freshness Factor:
Analysis revealed that signal reliability wasn't constant—it varied with timing. Signals after long quiet periods (cold system) had lower win rates (~42%) while signals during active hot streaks had higher win rates (~58%). Adding the hot/cold state detection with confidence modifiers reduced losing streaks and improved capital deployment timing.
The MTF Validation:
Early testing showed ~48% win rate. Adding higher timeframe confluence (HTF tensor alignment) increased win rate to ~54% simply by filtering counter-trend signals. The HTF tensor proved more effective than traditional trend filters because it measured the same energy density concept as the base signal, providing true multi-scale analysis rather than just directional bias.
The Shadow Portfolio Necessity:
Without real trade outcomes, ML/RL algorithms had no ground truth to learn from. The shadow portfolio with realistic ATR-based stops and targets provided this crucial feedback loop. Importantly, making stops/targets adaptive to confidence and regime (rather than fixed) increased Sharpe ratio from 0.9 to 1.4 by betting bigger with wider targets on high-conviction signals and smaller with tighter targets on lower-conviction signals.
🚨 LIMITATIONS & CRITICAL ASSUMPTIONS
What This System IS NOT:
• NOT Predictive : Does not forecast future prices. Identifies high-probability setups based on energy density patterns.
• NOT Holy Grail : Typical performance 48-58% win rate, 1.2-1.8 avg R-multiple. Probabilistic edge, not certainty.
• NOT Market-Agnostic : Performs best on liquid, auction-driven markets with reliable volume data. Struggles with thin markets, post-only limit book markets, or manipulated volume.
• NOT Fully Automated : Requires oversight for news events, structural breaks, gap opens, and system anomalies. ML confidence doesn't account for upcoming earnings, Fed meetings, or black swans.
• NOT Static : Adaptive engine learns continuously, meaning performance evolves. Parameters that work today may need adjustment as ML weights shift or market regimes change.
Core Assumptions:
1. Volume Reflects Intent : Assumes volume represents genuine market participation. Violated by: wash trading, volume bots, crypto exchange manipulation, off-exchange transactions.
2. Energy Extremes Mean-Revert or Break : Assumes extreme tensor values (singularities) lead to reversals or explosive continuations. Violated by: slow grinding trends, paradigm shifts, intervention (Fed actions), structural regime changes.
3. Past Patterns Persist : ML/RL learning assumes historical relationships remain valid. Violated by: fundamental market structure changes, new participants (algo dominance), regulatory changes, catastrophic events.
4. ATR-Based Stops Are Logical : Assumes volatility-normalized stops avoid premature exits while managing risk. Violated by: flash crashes, gap moves, illiquid periods, stop hunts.
5. Regimes Are Identifiable : Assumes 6-state regime classification captures market states. Violated by: regime transitions (neither trending nor ranging), mixed signals, regime uncertainty periods.
Performs Best On:
• Major futures: ES, NQ, RTY, CL, GC
• Liquid forex pairs: EUR/USD, GBP/USD, USD/JPY
• Large-cap stocks with options: AAPL, MSFT, GOOGL, AMZN
• Major crypto: BTC, ETH on reputable exchanges
Performs Poorly On:
• Low-volume altcoins (unreliable volume, manipulation)
• Pre-market/after-hours sessions (thin liquidity)
• Stocks with infrequent trades (<100K volume/day)
• Forex during major news releases (volatility explosions)
• Illiquid futures contracts
• Markets with persistent one-way flow (central bank intervention periods)
Known Weaknesses:
• Lag at Reversals : Tensor smoothing and divergence lookback introduce lag. May miss first 20-30% of major reversals.
• Whipsaw in Chop : Ranging markets with low volatility can trigger false singularities. Use range regime detection to reduce this.
• Gap Vulnerability : Shadow portfolio doesn't simulate gap opens. Real trading may face overnight gaps that bypass stops.
• Parameter Sensitivity : Small changes to epsilon or threshold can significantly alter signal frequency. Requires optimization per instrument/timeframe.
• ML Warmup Period : First 30-50 trades, ML system is gathering data. Early performance may not represent steady-state capability.
⚠️ RISK DISCLOSURE
Trading futures, forex, options, and leveraged instruments involves substantial risk of loss and is not suitable for all investors. Past performance, whether backtested or live, is not indicative of future results.
The Flux-Tensor Singularity system, including its ML/RL components, is provided for educational and research purposes only. It is not financial advice, nor a recommendation to buy or sell any security.
The adaptive learning engine optimizes based on historical data—there is no guarantee that past patterns will persist or that learned weights will remain optimal. Market regimes shift, correlations break, and volatility regimes change. Black swan events occur. No algorithmic system eliminates the risk of substantial loss.
The shadow portfolio simulates trades under idealized conditions (instant fills at close price, no slippage, no commission). Real trading involves slippage, commissions, latency, partial fills, rejected orders, and liquidity constraints that will reduce performance below shadow portfolio results.
Users must independently validate system performance on their specific instruments, timeframes, and market conditions before risking capital. Optimize parameters carefully and conduct extensive paper trading. Never risk more capital than you can afford to lose completely.
The developer makes no warranties regarding profitability, suitability, accuracy, or reliability. Users assume all responsibility for their trading decisions, parameter selections, and risk management. No guarantee of profit is made or implied.
Understand that most retail traders lose money. Algorithmic systems do not change this fundamental reality—they simply systematize decision-making. Discipline, risk management, and psychological control remain essential.
═══════════════════════════════════════════════════════
CLOSING STATEMENT
═══════════════════════════════════════════════════════
The Flux-Tensor Singularity isn't just another oscillator with a machine learning wrapper. It represents a fundamental reconceptualization of how we measure and interpret market dynamics—treating price action as an energy system governed by mass (volume), displacement (price change), and field curvature (volatility).
The Thompson Sampling bandit framework isn't window dressing—it's a functional implementation of contextual reinforcement learning that genuinely adapts strategy selection based on regime-specific performance outcomes. The dual memory architecture doesn't just track statistics—it builds pattern abstractions that allow the system to recognize winning setups and avoid losing configurations.
Most importantly, the shadow portfolio provides genuine ground truth. Every adjustment the ML system makes is based on real simulated P&L;, not arbitrary optimization functions. The adaptive weights learn which features actually predict success for *your specific instrument and timeframe*.
This system will not make you rich overnight. It will not win every trade. It will not eliminate drawdowns. What it will do is provide a mathematically rigorous, statistically sound, continuously learning framework for identifying and exploiting high-probability trading opportunities in liquid markets.
The accretion disk glows brightest near the event horizon. The tensor reaches critical mass. The singularity beckons. Will you answer the call?
"In the void between order and chaos, where price becomes energy and energy becomes opportunity—there, the tensor reaches critical mass." — FTS-PRO
Taking you to school. — Dskyz, Trade with insight. Trade with anticipation.
PhoenixC StrategyThis indicator is created for personal use.
It provides signals and visual tools for analyzing price movements.
No additional description provided.
Pivot Points Standard + 9/20/50/200 EMA by NK//@version=6
indicator("Pivot Points Standard + 9/20/50/200 EMA", "Pivots+EMA", overlay=true, max_lines_count=500, max_labels_count=500)
// --- EMA calculations and plots
ema9 = ta.ema(close, 9)
ema20 = ta.ema(close, 20)
ema50 = ta.ema(close, 50)
ema200 = ta.ema(close, 200)
plot(ema9, color=color.green, linewidth=2, title="EMA 9")
plot(ema20, color=color.red, linewidth=2, title="EMA 20")
plot(ema50, color=color.new(color.blue, 0), linewidth=2, title="EMA 50") // dark blue
plot(ema200, color=color.black, linewidth=2, title="EMA 200")
// --- Pivots Inputs
pivotTypeInput = input.string(title="Type", defval="Traditional", options= )
pivotAnchorInput = input.string(title="Pivots Timeframe", defval="Auto", options= )
maxHistoricalPivotsInput = input.int(title="Number of Pivots Back", defval=15, minval=1, maxval=200, display = display.data_window)
isDailyBasedInput = input.bool(title="Use Daily-based Values", defval=true, display = display.data_window, tooltip="When this option is unchecked, Pivot Points will use intraday data while calculating on intraday charts. If Extended Hours are displayed on the chart, they will be taken into account during the pivot level calculation. If intraday OHLC values are different from daily-based values (normal for stocks), the pivot levels will also differ.")
showLabelsInput = input.bool(title="Show Labels", defval=true, group="labels", display = display.data_window)
showPricesInput = input.bool(title="Show Prices", defval=true, group="labels", display = display.data_window)
positionLabelsInput = input.string("Left", "Labels Position", options= , group="labels", display = display.data_window, active = showLabelsInput or showPricesInput)
linewidthInput = input.int(title="Line Width", defval=1, minval=1, maxval=100, group="levels", display = display.data_window)
DEFAULT_COLOR = #FB8C00
showLevel2and3 = pivotTypeInput != "DM"
showLevel4 = pivotTypeInput != "DM" and pivotTypeInput != "Fibonacci"
showLevel5 = pivotTypeInput == "Traditional" or pivotTypeInput == "Camarilla"
pColorInput = input.color(DEFAULT_COLOR, "P ", inline="P", group="levels", display = display.data_window)
pShowInput = input.bool(true, "", inline="P", group="levels", display = display.data_window)
s1ColorInput = input.color(DEFAULT_COLOR, "S1", inline="S1/R1" , group="levels", display = display.data_window)
s1ShowInput = input.bool(true, "", inline="S1/R1", group="levels", display = display.data_window)
r1ColorInput = input.color(DEFAULT_COLOR, " R1", inline="S1/R1", group="levels", display = display.data_window)
r1ShowInput = input.bool(true, "", inline="S1/R1", group="levels", display = display.data_window)
s2ColorInput = input.color(DEFAULT_COLOR, "S2", inline="S2/R2", group="levels", display = display.data_window, active = showLevel2and3)
s2ShowInput = input.bool(true, "", inline="S2/R2", group="levels", display = display.data_window, active = showLevel2and3)
r2ColorInput = input.color(DEFAULT_COLOR, " R2", inline="S2/R2", group="levels", display = display.data_window, active = showLevel2and3)
r2ShowInput = input.bool(true, "", inline="S2/R2", group="levels", display = display.data_window, active = showLevel2and3)
s3ColorInput = input.color(DEFAULT_COLOR, "S3", inline="S3/R3", group="levels", display = display.data_window, active = showLevel2and3)
s3ShowInput = input.bool(true, "", inline="S3/R3", group="levels", display = display.data_window, active = showLevel2and3)
r3ColorInput = input.color(DEFAULT_COLOR, " R3", inline="S3/R3", group="levels", display = display.data_window, active = showLevel2and3)
r3ShowInput = input.bool(true, "", inline="S3/R3", group="levels", display = display.data_window, active = showLevel2and3)
s4ColorInput = input.color(DEFAULT_COLOR, "S4", inline="S4/R4", group="levels", display = display.data_window, active = showLevel4)
s4ShowInput = input.bool(true, "", inline="S4/R4", group="levels", display = display.data_window, active = showLevel4)
r4ColorInput = input.color(DEFAULT_COLOR, " R4", inline="S4/R4", group="levels", display = display.data_window, active = showLevel4)
r4ShowInput = input.bool(true, "", inline="S4/R4", group="levels", display = display.data_window, active = showLevel4)
s5ColorInput = input.color(DEFAULT_COLOR, "S5", inline="S5/R5", group="levels", display = display.data_window, active = showLevel5)
s5ShowInput = input.bool(true, "", inline="S5/R5", group="levels", display = display.data_window, active = showLevel5)
r5ColorInput = input.color(DEFAULT_COLOR, " R5", inline="S5/R5", group="levels", display = display.data_window, active = showLevel5)
r5ShowInput = input.bool(true, "", inline="S5/R5", group="levels", display = display.data_window, active = showLevel5)
type graphicSettings
string levelName
color levelColor
bool showLevel
var graphicSettingsArray = array.from(
graphicSettings.new(" P", pColorInput, pShowInput),
graphicSettings.new("R1", r1ColorInput, r1ShowInput), graphicSettings.new("S1", s1ColorInput, s1ShowInput),
graphicSettings.new("R2", r2ColorInput, r2ShowInput), graphicSettings.new("S2", s2ColorInput, s2ShowInput),
graphicSettings.new("R3", r3ColorInput, r3ShowInput), graphicSettings.new("S3", s3ColorInput, s3ShowInput),
graphicSettings.new("R4", r4ColorInput, r4ShowInput), graphicSettings.new("S4", s4ColorInput, s4ShowInput),
graphicSettings.new("R5", r5ColorInput, r5ShowInput), graphicSettings.new("S5", s5ColorInput, s5ShowInput))
autoAnchor = switch
timeframe.isintraday => timeframe.multiplier <= 15 ? "1D" : "1W"
timeframe.isdaily => "1M"
=> "12M"
pivotTimeframe = switch pivotAnchorInput
"Auto" => autoAnchor
"Daily" => "1D"
"Weekly" => "1W"
"Monthly" => "1M"
"Quarterly" => "3M"
=> "12M"
pivotYearMultiplier = switch pivotAnchorInput
"Biyearly" => 2
"Triyearly" => 3
"Quinquennially" => 5
"Decennially" => 10
=> 1
numOfPivotLevels = switch pivotTypeInput
"Traditional" => 11
"Camarilla" => 11
"Woodie" => 9
"Classic" => 9
"Fibonacci" => 7
"DM" => 3
type pivotGraphic
line pivotLine
label pivotLabel
method delete(pivotGraphic graphic) =>
graphic.pivotLine.delete()
graphic.pivotLabel.delete()
var drawnGraphics = matrix.new()
localPivotTimeframeChange = timeframe.change(pivotTimeframe) and year % pivotYearMultiplier == 0
securityPivotTimeframeChange = timeframe.change(timeframe.period) and year % pivotYearMultiplier == 0
pivotTimeframeChangeCounter(condition) =>
var count = 0
if condition and bar_index > 0
count += 1
count
localPivots = ta.pivot_point_levels(pivotTypeInput, localPivotTimeframeChange)
securityPivotPointsArray = ta.pivot_point_levels(pivotTypeInput, securityPivotTimeframeChange)
securityTimeframe = timeframe.isintraday ? "1D" : timeframe.period
= request.security(syminfo.tickerid, pivotTimeframe, , lookahead = barmerge.lookahead_on)
pivotPointsArray = isDailyBasedInput ? securityPivots : localPivots
affixOldPivots(endTime) =>
if drawnGraphics.rows() > 0
lastGraphics = drawnGraphics.row(drawnGraphics.rows() - 1)
for graphic in lastGraphics
graphic.pivotLine.set_x2(endTime)
if positionLabelsInput == "Right"
graphic.pivotLabel.set_x(endTime)
drawNewPivots(startTime) =>
newGraphics = array.new()
for in pivotPointsArray
levelSettings = graphicSettingsArray.get(index)
if not na(coord) and levelSettings.showLevel
lineEndTime = startTime + timeframe.in_seconds(pivotTimeframe) * 1000 * pivotYearMultiplier
pivotLine = line.new(startTime, coord, lineEndTime, coord, xloc = xloc.bar_time, color=levelSettings.levelColor, width=linewidthInput)
pivotLabel = label.new(x = positionLabelsInput == "Left" ? startTime : lineEndTime,
y = coord,
text = (showLabelsInput ? levelSettings.levelName + " " : "") + (showPricesInput ? "(" + str.tostring(coord, format.mintick) + ")" : ""),
style = positionLabelsInput == "Left" ? label.style_label_right : label.style_label_left,
textcolor = levelSettings.levelColor,
color = #00000000,
xloc=xloc.bar_time)
newGraphics.push(pivotGraphic.new(pivotLine, pivotLabel))
drawnGraphics.add_row(array_id = newGraphics)
if drawnGraphics.rows() > maxHistoricalPivotsInput
oldGraphics = drawnGraphics.remove_row(0)
for graphic in oldGraphics
graphic.delete()
localPivotDrawConditionStatic = not isDailyBasedInput and localPivotTimeframeChange
securityPivotDrawConditionStatic = isDailyBasedInput and securityPivotCounter != securityPivotCounter
var isMultiYearly = array.from("Biyearly", "Triyearly", "Quinquennially", "Decennially").includes(pivotAnchorInput)
localPivotDrawConditionDeveloping = not isDailyBasedInput and time_close == time_close(pivotTimeframe) and not isMultiYearly
securityPivotDrawConditionDeveloping = false
if (securityPivotDrawConditionStatic or localPivotDrawConditionStatic)
affixOldPivots(time)
drawNewPivots(time)
var FIRST_BAR_TIME = time
if (barstate.islastconfirmedhistory and drawnGraphics.columns() == 0)
if not na(securityPivots) and securityPivotCounter > 0
if isDailyBasedInput
drawNewPivots(FIRST_BAR_TIME)
else
runtime.error("Not enough intraday data to calculate Pivot Points. Lower the Pivots Timeframe or turn on the 'Use Daily-based Values' option in the indicator settings.")
else
runtime.error("Not enough data to calculate Pivot Points. Lower the Pivots Timeframe in the indicator settings.")
RSI5vsRSI14_v2//@version=5
indicator("RSI5vsRSI14_v2", shorttitle="RSI5vsRSI14_v2", overlay=false)
plot(ta.rsi(close, 14), title="RSI14", color=color.red)
plot(ta.rsi(close, 5), title="RSI5", color=color.green)
RSI Rate of Change (ROC of RSI)The RSI Rate of Change (ROC of RSI) indicator measures the speed and momentum of changes in the RSI, helping traders identify early trend shifts, strength of price moves, and potential reversals before they appear on the standard RSI.
While RSI shows overbought and oversold conditions, the ROC of RSI reveals how fast RSI itself is rising or falling, offering a deeper view of market momentum.
How the Indicator Works
1. RSI Calculation
The indicator first calculates the classic Relative Strength Index (RSI) using the selected length (default 14). This measures the strength of recent price movements.
2. Rate of Change (ROC) of RSI
Next, it computes the Rate of Change (ROC) of the RSI over a user-defined period.
This shows:
Positive ROC → RSI increasing quickly → strong bullish momentum
Negative ROC → RSI decreasing quickly → strong bearish momentum
ROC crossing above/below 0 → potential early trend shift
What You See on the Chart
Blue Line: RSI
Red Line: ROC of RSI
Grey dotted Zero Line: Momentum reference
Why Traders Use It
The RSI ROC helps you:
Detect momentum reversals early
Spot bullish and bearish accelerations not visible on RSI alone
Identify exhaustion points before RSI reaches extremes
Improve entry/exit precision in trend and swing trading
Validate price breakouts or breakdowns with momentum confirmation
Best For
Swing traders
Momentum traders
Reversal traders
Trend-following systems needing early confirmation signals
EMV// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
//@version=5
indicator("EMV", overlay=false)
N = input.int(14, "N")
M = input.int(9, "M")
// ==== VOLUME ====
maVol = ta.sma(volume, N)
VOLUME = maVol / volume
// ==== MID ====
hl = high + low
MID = 100 * (hl - hl ) / hl
// ==== HL_RANGE ====
HL_RANGE = ta.sma(high - low, N)
// ==== EMV ====
EMV_raw = MID * VOLUME * (high - low) / HL_RANGE
EMV = ta.sma(EMV_raw, N)
// ==== MAEMV ====
MAEMV = ta.sma(EMV, M)
plot(EMV, color=color.blue, title="EMV")
plot(MAEMV, color=color.orange, title="MAEMV")
EDU PRO LITE – Divergence + Fake Breakout + CandleThis indicator is created for educational purposes only. It displays EMA, RSI, and the previous day’s high/low to help users understand market trends and price movement. This script does not provide any trading signals, buy/sell recommendations, or entry indications. All trading decisions are entirely outside the scope of this indicator.”
8 EMA Candle Color ChangeableJust a quick indicator that I threw together that shows the 8 EMA and changes the candle colors if the candle closes above or below the EMA.
UTT NEW MOONThe script first calculates the day of the year and then uses astronomical formulas to approximate the Moon’s phase at the given time. From these calculations it determines the last Moon phase event and classifies it as either a New Moon (phase +1) or a Full Moon (phase −1).
It adjusts the result so the phase only changes when a new lunar event occurs, then returns two values: the current phase state and a “moonType” that signals when a new event (New or Full Moon) appears.
Labden VPVR 2.0VRVP with color theory. I wanted one that was non-obstructing, not too complex and right in all the right ways. This works for me as, essentially, a V1.0. It's nice to see the volume profiles you're taking the trade into (on the right) rather than a ton of small ones that have happened. Dynamic for different time ranges or easily adjustable. Enjoy
HoneG_SARBB v22This is the development version of ver22 for a 1-minute trading signal tool based on BB, SAR, ADX, RSI, RCI, etc.
Please apply it to a 1-minute chart and test it.
Internally, it monitors the second-tick chart, so a Premium or higher grade is required.
BB、SAR、ADX、RSI、RCIなどをベースにした1分取引用サインツールのver22開発中バージョンです。
1分足チャートに適用してお試しください。
内部的には秒足を見ているので、Premium以上のグレードが必要になります。
Hardwaybets' Protected Highs / Protected Lows TradingProtected Highs & Lows – Multi-Condition Structural Marker
This indicator identifies specific candle formations where price breaks a previous candle’s high or low, fails to maintain that break, and confirms the rejection with an additional condition involving prior candles. These marked locations offer a visual reference for areas where price attempted directional expansion but did not sustain it. All levels remain visible until later invalidated by price movement.
Protected High – Detection Logic
A Protected High is marked only when all three of the following conditions occur:
1. Break of Previous High
The current candle trades above the prior candle’s high.
2. Close Back Inside Range
The current candle closes within the high-to-low range of the previous candle, indicating the upward expansion was not sustained.
3. Reversal Through Prior Bullish Structure
After forming the high, price closes below the opening price of one or more bullish candles that were part of the upward movement into that high.
This reflects a shift away from the prior upward structure.
When all three conditions are met, the high of the candle that created the event is marked on the chart.
Protected Low – Detection Logic
A Protected Low is marked only when all three of the following conditions occur:
1. Break of Previous Low
The current candle trades below the prior candle’s low.
2. Close Back Inside Range
The current candle closes within the high-to-low range of the previous candle, indicating the downward expansion was not sustained.
3. Reversal Through Prior Bearish Structure
After forming the low, price closes above the opening price of one or more bearish candles that were part of the downward movement into that low.
This reflects a shift away from the prior downward structure.
When all three conditions are met, the low of the candle that created the event is marked on the chart.
Level Management
* Marked highs and lows remain active as long as price does not trade beyond them.
* If price moves past a marked level, that level is removed.
* Only active, unviolated structural reference points remain displayed.
Market Structure Context (Strictly Non-Signaling)
Protected highs and lows can help traders observe areas where:
* Price briefly exceeded a previous high or low
* That expansion was not maintained
* Price then moved back through recent candles associated with the prior direction
These observations can be used by traders to understand how price interacts with nearby structural reference points.
The indicator itself does not provide trade entries, exits, or directional guidance.
Customization Options
The indicator provides adjustable settings for:
* Marker style (labels or shapes)
* Shape type (circle, square, diamond, etc.)
* Colors for highs and lows
* Vertical spacing between markers and candles
These options help maintain clarity on different chart types and timeframes.
Intended Use
The indicator does not generate forecasts or trading signals.
Its purpose is to visually highlight multi-condition candle formations where price briefly exceeded a prior high or low, failed to sustain that expansion, and later reversed through nearby structural points.
Compatibility
Suitable for all assets and timeframes.
Volume Spike Detector V. 1.1A simple indicator that identifies spikes in volume and marks the specific candle with based on the user's preferences.
ITFI Lite — Smart Money Dashboard✅ ITFI Lite is now live — ITFI Pro (full confluence) coming soon 🔒
Follow to get early access.
This is the Lite version of the upcoming ITFI Pro system.
Designed for traders who want clean higher-timeframe context without clutter, complexity, or repainting.
Included in ITFI Lite:
• D1 & H4 bias (EMA-based)
• M15 equilibrium + premium/discount zones
• PB/BO Lite signals (no scoring)
• UTC session with volatility phase
• Compact dashboard for fast decision-making
Not included (Pro features):
• HTF FVG / OB mapping
• Scoring engine
• Ready / Wait / Blocked system
• Advanced liquidity model
• Entry timing assistant
• Full multi-timeframe confluence
📌 Pro version is currently in development — Coming Soon 🔒
Follow for updates and early access.
CISD Adaptive Pivots (manny_mailbox2)This CISD indicator with projections automatically adjust the pivot strength for the current market in real-time.
Features:
Customizable projection levels.
Customizable bullish projection color, size, and width.
Customizable bearish projection color, size, and width.
Select the number of CISD/Projection you want to see on chart.
Min/Max Adaptive Pivot Stength based on candle body or wicks
Customizable smoothing factor
This automated feature can be turned on/off.
Here's how it works:
The Adaptive Pivot Strength feature (enabled by default) dynamically calculates the optimal pivot strength based on recent market structure.
How it adapts:
Tracks pivot spacing - It monitors the distance (in bars) between the last 20 pivot highs and pivot lows
Calculates average spacing - Combines both high and low spacing to determine typical pivot frequency
Converts to strength - Uses the formula avg_spacing / 4.0 to determine the calculated strength
Smooths changes - Applies EMA-like smoothing (controlled by your smoothing_factor of 0.3) to prevent erratic jumps
Clamps to range - Keeps the result between your min (2) and max (10) pivot strength settings
Current settings:
Base strength: 3
Adaptive range: 2-10
Smoothing: 0.3 (more responsive; lower = smoother)
The table shows you the current adaptive strength in real-time, color-coded green/red/yellow based on whether it's above/below/equal to base strength
So instead of using a fixed pivot strength of 3, it dynamically adjusts between 2-10 based on how far apart actual pivots are forming in the market. Tighter markets = lower strength (more sensitive), wider swings = higher strength (less noise).
[ b]What time frame does this work best on?
Optimal timeframes:
5-minute to 15-minute charts - This is the sweet spot for CISD detection with adaptive pivots. The pivot strength range (2-10) is calibrated for intraday price action where you get enough pivots to establish meaningful series without over-fitting.
1-minute charts - Can work but you'll see more noise. The adaptive feature helps here by increasing pivot strength during choppier periods. You might want to adjust your min_pivot_strength to 3-4 on the 1-min.
30-minute to 1-hour - Still effective but you'll get fewer CISD signals. The projections become longer-term targets. Good for swing context.
Why these timeframes:
Your lookback period (100 bars) needs enough history to calculate adaptive strength properly
CISD detection relies on polarity changes (bullish/bearish candles), which are more meaningful on 5-15 min
The projection levels (1x to 4x) align well with typical intraday move extensions on these timeframes
For MNQ specifically:
The 5-minute is probably your best bet - it captures the institutional order flow you're tracking while filtering out the noise of lower timeframes. The 15-minute works great for cleaner swing trades and aligns well with session-based analysis.
Idea: Use two of these on chart.
Why you might want two:
Different timeframes: One with lower pivot strength (2-5) for short-term, another with higher (7-10) for major structure
Adaptive vs Fixed : One with adaptive pivot ON, one with it OFF at a fixed strength for comparison
Different projection levels: One for conservative targets (1, 1.5, 2), another for extended targets (3, 4, 5)
Different CISD settings : One showing all CISDs, another filtered to show only recent ones4
I'm displaying the CISD's and projection with Fadi's Order Blocks, SMT's, and Daily Standard Deviation just to show how it might be used.
Good Luck and be good to each other!
BETA ZONES v1.0BETA ZONES v1.0 Indicator
Overview
BETA ZONES v1.0 is a comprehensive technical analysis tool designed for TradingView, combining an EMA-based ribbon with dynamic glow zones, structural pivot detection, and real-time ATR visualization. This overlay indicator helps traders identify trends, support/resistance zones, and potential breakout points by blending moving averages, volatility-based shading, and pivot structures. It's particularly useful for trend-following strategies, swing trading, and confirming market reversals on any timeframe or asset, including those using Heikin Ashi candles (as it incorporates real close data to bypass transformations).
The indicator emphasizes visual clarity with color-coded elements: bullish trends in shades of green/lime and bearish in red/maroon. It includes customizable toggles for each component, allowing users to focus on specific features without cluttering the chart.
Key Features
• EMA Ribbon & Glow System:
o Displays a ribbon formed by three EMAs (5, 20, and 50 periods) with gradient fills between them, colored based on trend strength.
o A dynamic "glow" zone around the 50-period EMA, calculated using ATR (Average True Range), acts as a volatility-based support (bullish) or resistance (bearish) band. The glow expands/contracts with market volatility, providing a visual buffer for potential price reactions.
o Real Close Dot: A small circle plotted at the actual closing price of each bar (sourced from standard candles), aiding in precise data verification even on transformed charts like Heikin Ashi.
• Structural Pivots:
o Automatically detects and labels confirmed pivot highs and lows using customizable symbols (e.g., arrows, dots, or curves).
o Draws breakout lines connecting pivots to the bar where structure is broken (Break of Structure - BOS), highlighting bullish (green) or bearish (red) shifts.
o Pivots are trend-aware: In uptrends, it tracks higher highs/lows until a downside break; in downtrends, lower highs/lows until an upside break.
• Real ATR Display:
o A compact table at the bottom-center of the chart showing the current 14-period ATR value (calculated on real data), useful for gauging volatility and setting stop-losses or targets.
How It Works
• EMA Ribbon Logic: The fast EMA (5) is compared to the mid (20), and mid to slow (50), to determine sub-trends. Price relative to the slow EMA sets the overall bullish/bearish bias. Fills create a "ribbon" effect, with colors intensifying in strong trends.
• Glow Zone: Uses a user-defined ATR length and multiplier to create upper/lower bands around the slow EMA. The glow is one-sided: below for bullish (support) and above for bearish (resistance), with semi-transparent shading for easy price overlay.
• Pivot Detection: Tracks the current trend direction (up or down) and reference high/low from the last confirmed pivot. A breakout (close crossing the reference level) confirms a new pivot, labels it, and optionally draws a line to the breakout bar. Bar coloring (yellow) highlights breakout candles.
• Data Handling: All calculations use real close prices via request.security to ensure accuracy on non-standard chart types.
Settings and Customization
The indicator is divided into intuitive input groups for easy configuration:
1. EMA Ribbon & Glow:
o Show EMA Ribbon & Glow: Master toggle to enable/disable the entire ribbon and glow (default: true). Note: Real Close Dot is independent.
o ATR Length (Glow): Lookback for ATR calculation (default: 3; higher = smoother glow).
o ATR Multiplier (Glow Size): Scales the glow width (default: 0.15; higher = wider zone).
o Show Real Close Dot: Toggle for the orange dot at real closes (default: true).
o Real Close Dot Color: Customize the dot's color (default: orange).
2. Structural Pivots:
o Show Pivot Labels: Toggle visibility of high/low symbols (default: true).
o Pivot Symbol Style: Choose from pairs like "︽ ︾" (low/high) or "•" (dots) (default: "•").
o Label Size: Adjust symbol size (Tiny to Huge; default: Normal).
o Pivot High/Low Label Colors: Set colors for labels (default: white).
o Show Breakout Lines: Toggle lines from pivot to breakout (default: true).
o Line Width: Thickness of breakout lines (default: 2).
o Line Style: Solid, Dashed, or Dotted (default: Solid).
o Resistance Break Line (Bullish): Color for upside breaks (default: green).
o Support Break Line (Bearish): Color for downside breaks (default: red).
No additional inputs are required for the ATR table, as it's always displayed on the last bar for quick reference.
Usage Tips
• Trend Identification: Use the EMA ribbon colors to gauge momentum—full green for strong bulls, red for bears. The glow zone can act as a dynamic entry/exit area (e.g., buy near bullish glow support).
• Breakout Trading: Watch for pivot labels and BOS lines as signals for trend reversals. Combine with volume or other indicators for confirmation.
• Volatility Awareness: The displayed ATR(14) helps in position sizing; for example, set stops at 1-2x ATR from entry.
• Chart Compatibility: Works best on candlestick or Heikin Ashi charts. For lower timeframes, reduce ATR length for faster reactivity; increase for higher timeframes.
• Limitations: Pivots are reactive and may lag in ranging markets. Glow is based on historical ATR, so it doesn't predict future volatility.
This indicator is in beta (v1.0) and open to feedback for improvements. Add it to your chart via TradingView's indicator search and experiment with settings to fit your strategy!
Support/Resistance (OI) + 9/20 EMA//@version=6
indicator("Support/Resistance (OI) + 9/20 EMA", overlay=true)
ema9 = ta.ema(close, 9)
ema20 = ta.ema(close, 20)
plot(ema9, color=color.blue, linewidth=2, title="EMA 9")
plot(ema20, color=color.orange, linewidth=2, title="EMA 20")
// Update these levels daily based on your OI analysis
s1 = 25850
s2 = 25800
s3 = 25500
r1 = 26000
r2 = 25950
r3 = 26100
// Use hline for persistent horizontal levels
hline(s1, 'Support 1', color=color.green, linestyle=hline.style_dashed, linewidth=2)
hline(s2, 'Support 2', color=color.green, linestyle=hline.style_dashed, linewidth=2)
hline(s3, 'Support 3', color=color.green, linestyle=hline.style_dashed, linewidth=2)
hline(r1, 'Resistance 1', color=color.red, linestyle=hline.style_dashed, linewidth=2)
hline(r2, 'Resistance 2', color=color.red, linestyle=hline.style_dashed, linewidth=2)
hline(r3, 'Resistance 3', color=color.red, linestyle=hline.style_dashed, linewidth=2)
Relative Performance Analyzer [AstrideUnicorn]Relative Performance Analyzer (RPA) is a performance analysis tool inspired by the data comparison features found in professional trading terminals. The RPA replicates the analytical approach used by portfolio managers and institutional analysts who routinely compare multiple securities or other types of data to identify relative strength opportunities, make allocation decisions, choose the most optimal investment from several alternatives, and much more.
Key Features:
Multi-Symbol Comparison: Track up to 5 different symbols simultaneously across any asset class or dataset
Two Performance Calculation Methods: Choose between percentage returns or risk-adjusted returns
Interactive Analysis: Drag the start date line on the chart or manually choose the start date in the settings
Professional Visualization: High-contrast color scheme designed for both dark and light chart themes
Live Performance Table: Real-time display of current return values sorted from the top to the worst performers
Practical Use Cases:
ETF Selection: Compare similar ETFs (e.g., SPY vs IVV vs VOO) to identify the most efficient investment
Sector Rotation: Analyze which sectors are showing relative strength for strategic allocation
Competitive Analysis: Compare companies within the same industry to identify leaders (e.g., APPLE vs SAMSUNG vs XIAOMI)
Cross-Asset Allocation: Evaluate performance across stocks, bonds, commodities, and currencies to guide portfolio rebalancing
Risk-Adjusted Decisions: Use risk-adjusted performance to find investments with the best returns per unit of risk
Example Scenarios:
Analyze whether tech stocks are outperforming the broader market by comparing XLK to SPY
Evaluate which emerging market ETF (EEM vs VWO) has provided better risk-adjusted returns over the past year
HOW DOES IT WORK
The indicator calculates and visualizes performance from a user-defined starting point using two methodologies:
Percentage Returns: Standard total return calculation showing percentage change from the start date
Risk-Adjusted Returns: Cumulative returns divided by the volatility (standard deviation), providing insight into the efficiency of performance. An expanding window is used to calculate the volatility, ensuring accurate risk-adjusted comparisons throughout the analysis period.
HOW TO USE
Setup Your Comparison: Enable up to 5 assets and input their symbols in the settings
Set Analysis Period: When you first launch the indicator, select the start date by clicking on the price chart. The vertical start date line will appear. Drag it on the chart or manually input a specific date to change the start date.
Choose Return Type: Select between percentage or risk-adjusted returns based on your analysis needs
Interpret Results
Use the real-time table for precise current values
SETTINGS
Assets 1-5: Toggle on/off and input symbols for comparison (stocks, ETFs, indices, forex, crypto, fundamental data, etc.)
Start Date: Set the initial point for return calculations (drag on chart or input manually)
Return Type: Choose between "Percentage" or "Risk-Adjusted" performance.






















