0% found this document useful (0 votes)
18 views15 pages

Nuclear Multi-Layer Trading Framework

The document outlines a Pine Script for a trading framework called the 'Nuclear Multi-Layer Trading Framework'. It includes various modules for analyzing market conditions, such as volatility regimes, trend structures, demand pressure, and session microstructures, with configurable inputs for user preferences. The script is designed to assist traders in making informed decisions based on multiple timeframes and market dynamics.

Uploaded by

ozerolupa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views15 pages

Nuclear Multi-Layer Trading Framework

The document outlines a Pine Script for a trading framework called the 'Nuclear Multi-Layer Trading Framework'. It includes various modules for analyzing market conditions, such as volatility regimes, trend structures, demand pressure, and session microstructures, with configurable inputs for user preferences. The script is designed to assist traders in making informed decisions based on multiple timeframes and market dynamics.

Uploaded by

ozerolupa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

//@version=5

indicator("Nuclear Multi-Layer Trading Framework", overlay=true,


max_labels_count=60, max_lines_count=60, max_bars_back=500)

// ============================================================================
// INPUTS
// ============================================================================
htf_resolution = [Link]("240", "Higher Timeframe Resolution")
confidence_threshold = [Link](70.0, "Confidence Threshold", minval=0,
maxval=100, step=5)
signal_decay_bars = [Link](15, "Signal Decay Period (bars)", minval=5,
maxval=50)
enable_session_filter = [Link](true, "Enable Session Filter")
session_start_hour = [Link](9, "Session Start Hour (EST)", minval=0, maxval=23)
session_start_minute = [Link](30, "Session Start Minute", minval=0, maxval=59)
session_end_hour = [Link](16, "Session End Hour (EST)", minval=0, maxval=23)
enable_shorts = [Link](true, "Enable Short Signals")
liquidity_risk_threshold = [Link](65.0, "Liquidity Risk Threshold", minval=0,
maxval=100, step=5)

// ============================================================================
// GLOBAL STATE VARIABLES
// ============================================================================
var float htf_trend_cache = 0.0
var float htf_displacement_cache = 0.0
var float htf_structure_score_cache = 50.0
var int last_signal_bar_index = 0
var label[] signal_labels = array.new_label(0)
var line[] structure_lines = array.new_line(0)
var float session_open_price_cache = na
var int session_start_bar_cache = 0
var float first_hour_high_cache = na
var float first_hour_low_cache = na
var float last_swing_high_cache = na
var float last_swing_low_cache = na
// ============================================================================
// BATCHED HTF DATA PULL (valid Pine Script version)
// ============================================================================
htf_close = [Link]([Link], htf_resolution, close,
gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
htf_high = [Link]([Link], htf_resolution, high,
gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
htf_low = [Link]([Link], htf_resolution, low,
gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
htf_open = [Link]([Link], htf_resolution, open,
gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
htf_volume = [Link]([Link], htf_resolution, volume,
gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
htf_atr_50 = [Link]([Link], htf_resolution, [Link](50),
gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)

// ============================================================================
// DAILY DATA PULL (valid Pine Script version)
// ============================================================================

daily_prev_close = [Link]([Link], "D", close[1],


gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
daily_prev_high = [Link]([Link], "D", high[1],
gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
daily_prev_low = [Link]([Link], "D", low[1],
gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)

// -----------------------------------------------------------------------------
// SESSION CONTEXT ENGINE
// -----------------------------------------------------------------------------
f_context_engine() =>
hour_est = hour(time, "America/New_York")
minute_est = minute(time, "America/New_York")

// Check if within session hours


session_active = false
if enable_session_filter
start_minutes = session_start_hour * 60 + session_start_minute
end_minutes = session_end_hour * 60
current_minutes = hour_est * 60 + minute_est
session_active := current_minutes >= start_minutes and current_minutes <
end_minutes
else
session_active := true // 24/7 mode for crypto

// Session state: 0 = closed, 1 = pre, 2 = active, 3 = post


_session_state = session_active ? 2 : 0

// Volatility regime classification


atr_200 = [Link](200)
atr_50 = [Link](50)
atr_10 = [Link](10)
vol_ratio_long = nz(atr_50 / atr_200, 1.0)
_vol_regime = vol_ratio_long > 1.3 ? 2 : vol_ratio_long < 0.7 ? 0 : 1

// Context validation
_context_valid = session_active and not na(close) and not na(atr_10) and
bar_index > 100

[_session_state, _vol_regime, _context_valid]

[session_state, vol_regime, context_valid] = f_context_engine()

/// ============================================================================
// LAYER 1: VOLATILITY REGIME MODULE (VRM)
// ============================================================================

f_vrm() =>
_fast_atr = [Link](10)
_slow_atr = [Link](50)
// Safe division
_vol_ratio = nz(_slow_atr, 0.0) > 0.0 ? _fast_atr / _slow_atr : 1.0
// Cap extreme volatility spikes
_vol_ratio := [Link](0.3, [Link](_vol_ratio, 3.0))
// Adaptive multiplier for all downstream thresholds
_adaptive_multiplier = _vol_ratio
// Detect regime shifts (crossing key levels)
_regime_shift = [Link](_vol_ratio, 1.3) or [Link](_vol_ratio, 0.7)
// Volatility expansion/contraction flag
_vol_expanding = _vol_ratio > 1.2
_vol_contracting = _vol_ratio < 0.8

// Returning values as a tuple (array)


[_fast_atr, _slow_atr, _vol_ratio, _adaptive_multiplier, _regime_shift,
_vol_expanding, _vol_contracting]

// Assign outputs
[fast_atr, slow_atr, vol_ratio, adaptive_multiplier, regime_shift, vol_expanding,
vol_contracting] = f_vrm()

// ============================================================================
// LAYER 2: TREND STRUCTURE MODULE (TSM)
// ============================================================================

f_tsm() =>
base_lookback = 20
_lookback = int(base_lookback * adaptive_multiplier)
_lookback := [Link](10, [Link](_lookback, 50))
price_change = close - nz(close[_lookback], close)
_displacement = nz(fast_atr, 0.0) > 0.0 ? [Link](price_change) / fast_atr :
0.0
pivot_strength = 5
_swing_high = [Link](high, pivot_strength, pivot_strength)
_swing_low = [Link](low, pivot_strength, pivot_strength)
_last_swing_high_local = na(last_swing_high_cache) ? _swing_high :
last_swing_high_cache
_last_swing_low_local = na(last_swing_low_cache) ? _swing_low :
last_swing_low_cache
if not na(_swing_high)
_last_swing_high_local := _swing_high
if not na(_swing_low)
_last_swing_low_local := _swing_low
_structure_break_bull = not na(_swing_high) and not na(_last_swing_high_local)
and _swing_high > nz(_last_swing_high_local[pivot_strength], _swing_high)
_structure_break_bear = not na(_swing_low) and not na(_last_swing_low_local)
and _swing_low < nz(_last_swing_low_local[pivot_strength], _swing_low)
_structure_break = _structure_break_bull or _structure_break_bear
_is_impulse = _displacement > (2.2 * adaptive_multiplier) and
_structure_break
_is_correction = _displacement < (0.6 * adaptive_multiplier)
_trend_direction = 0.0
if not na(_last_swing_high_local) and not na(_last_swing_low_local)
if close > _last_swing_high_local
_trend_direction := 1.0
else if close < _last_swing_low_local
_trend_direction := -1.0
if _trend_direction == 0.0 and htf_trend_cache != 0.0
_trend_direction := htf_trend_cache

// Return semua termasuk cache update


[_displacement, _is_impulse, _is_correction, _trend_direction,
_structure_break, _swing_high, _swing_low, _last_swing_high_local,
_last_swing_low_local]

// Panggil fungsi
[ displacement, is_impulse, is_correction, trend_direction, structure_break,
swing_high, swing_low, _last_high_tmp, _last_low_tmp ] = f_tsm()
last_swing_high_cache := _last_high_tmp
last_swing_low_cache := _last_low_tmp

// ============================================================================
// LAYER 3: DEMAND/PRESSURE ENGINE (DPE)
// ============================================================================

last_swing_high_cache := _last_high_tmp
last_swing_low_cache := _last_low_tmp

// UNPACK RETURNED VALUES INCLUDING SWING CACHE UPDATES


[
displacement,
is_impulse,
is_correction,
trend_direction,
structure_break,
swing_high,
swing_low,
_last_high_tmp,
_last_low_tmp
] = f_tsm()

last_swing_high_cache := _last_high_tmp
last_swing_low_cache := _last_low_tmp

// ============================================================================
// LAYER 3: DEMAND/PRESSURE ENGINE (DPE)
// ============================================================================

last_swing_high_cache := _last_high_tmp
last_swing_low_cache := _last_low_tmp

// UNPACK RETURNED VALUES INCLUDING SWING CACHE UPDATES


[
displacement,
is_impulse,
is_correction,
trend_direction,
structure_break,
swing_high,
swing_low,
_last_high_tmp,
_last_low_tmp
] = f_tsm()

last_swing_high_cache := _last_high_tmp
last_swing_low_cache := _last_low_tmp

// ============================================================================
// LAYER 3: DEMAND/PRESSURE ENGINE (DPE)
// ============================================================================
f_dpe() =>
// Volume pressure analysis
vol_ma = [Link](volume, 20)
vol_threshold = vol_ma * adaptive_multiplier * 1.6
_volume_spike = volume > vol_threshold

// Body and wick analysis


body = [Link](close - open)
total_range = high - low

// Safe division
upper_wick_pct = total_range > 0.0 ? (high - [Link](open, close)) /
total_range : 0.0
lower_wick_pct = total_range > 0.0 ? ([Link](open, close) - low) /
total_range : 0.0
body_pct = total_range > 0.0 ? body / total_range : 0.0

// Absorption detection
large_wick_present = upper_wick_pct > 0.45 or lower_wick_pct > 0.45
small_body = body_pct < 0.25
_absorption = large_wick_present and small_body and _volume_spike

// Buying/selling pressure proxy


price_delta = close - open
_delta_volume = price_delta * volume

// Smooth delta to detect sustained pressure


delta_ma = [Link](_delta_volume, 5)
delta_threshold = [Link](delta_ma) * 1.4

// Pressure direction
_pressure_dir = 0.0
if _delta_volume > delta_threshold
_pressure_dir := 1.0
else if _delta_volume < -delta_threshold
_pressure_dir := -1.0

// Pressure strength normalized 0–100


vol_normalized = nz(vol_ma, 0.0) > 0.0 and total_range > 0.0 ?
[Link](_delta_volume) / (vol_ma * total_range) : 0.0
_pressure_strength = [Link](vol_normalized * 40.0, 100.0)

[_volume_spike, _absorption, _pressure_dir, _pressure_strength, upper_wick_pct,


lower_wick_pct]

[volume_spike, absorption_detected, pressure_direction, pressure_strength,


upper_wick_pct, lower_wick_pct] = f_dpe()

// ============================================================================
// LAYER 4: SESSION MICROSTRUCTURE MODULE (SMS)
// ============================================================================
f_sms() =>
// Gap analysis (open vs previous day close)
_open_gap = 0.0
_gap_significant = false

if not na(daily_prev_close) and nz(fast_atr, 0.0) > 0.0


_open_gap := (open - daily_prev_close) / fast_atr
_gap_significant := [Link](_open_gap) > (1.2 * adaptive_multiplier)

// Track session open price


if session_state == 2 and nz(session_state[1], 0) != 2
session_open_price_cache := open
session_start_bar_cache := bar_index

// First hour bias calculation


bars_since_session_open = bar_index - session_start_bar_cache
first_hour_bar_count = 12
_first_hour_bias = 0.0

if bars_since_session_open > 0 and bars_since_session_open <=


first_hour_bar_count and not na(session_open_price_cache)
net_displacement = close - session_open_price_cache
bias_threshold = fast_atr * 0.8

if net_displacement > bias_threshold


_first_hour_bias := 1.0
else if net_displacement < -bias_threshold
_first_hour_bias := -1.0

// Cache first hour range


if bars_since_session_open == first_hour_bar_count
first_hour_high_cache := [Link](high, first_hour_bar_count)
first_hour_low_cache := [Link](low, first_hour_bar_count)

// Mid-session breakout
_mid_session_breakout = false

if bars_since_session_open > first_hour_bar_count and not


na(first_hour_high_cache) and not na(first_hour_low_cache)
_mid_session_breakout := close > first_hour_high_cache or close <
first_hour_low_cache

// End-of-day detection (last 45 minutes)


hour_est = hour(time, "America/New_York")
minute_est = minute(time, "America/New_York")
minutes_from_start = hour_est * 60 + minute_est
minutes_to_close = (session_end_hour * 60) - minutes_from_start

_eod_period = enable_session_filter and minutes_to_close <= 45 and


minutes_to_close >= 0

[_open_gap, _gap_significant, _first_hour_bias, _mid_session_breakout,


_eod_period]

[open_gap, gap_significant, first_hour_bias, mid_session_breakout, eod_period] =


f_sms()

// ============================================================================
// LAYER 5: MTV (Multi-Timeframe Validator) - UPDATE HTF CACHE
// ============================================================================

// Function: Update HTF displacement, trend, structure score


f_update_htf_cache() =>
if [Link](htf_close)
htf_lookback = 20
htf_disp = nz(htf_atr_50, 0.0) > 0.0 ? (htf_close -
nz(htf_close[htf_lookback], htf_close)) / htf_atr_50 : 0.0

// HTF pivots → structure


htf_pivot_high = [Link](htf_high, 5, 5)
htf_pivot_low = [Link](htf_low, 5, 5)
has_structure = not na(htf_pivot_high) or not na(htf_pivot_low)

// Build return values


trend = htf_disp > 1.8 ? 1.0 : htf_disp < -1.8 ? -1.0 : 0.0
displ = htf_disp
score = has_structure ? 80.0 : 40.0

[trend, displ, score, true] // true = updated this bar


else
[htf_trend_cache, htf_displacement_cache, htf_structure_score_cache, false]

// Execute update + assign returned values


[htf_trend_cache, htf_displacement_cache, htf_structure_score_cache, _htf_flag] =
f_update_htf_cache()

// ============================================================================
// LAYER 6: EXECUTION QUALITY FILTER (EQF)
// ============================================================================
f_eqf() =>
// Spread proxy (bid-ask approximation)
_spread_proxy = nz(close, 0.0) > 0.0 ? (high - low) / close : 0.0

// Volume quality score


vol_ma = [Link](volume, 20)
vol_quality_ratio = nz(vol_ma, 0.0) > 0.0 ? volume / vol_ma : 1.0

// Execution risk components (0-100, lower is better)


spread_risk = [Link]((_spread_proxy / 0.005) * 25.0, 40.0) // 0.5% spread ≈
25 pts
volume_risk = vol_quality_ratio < 0.6 ? 35.0 :
vol_quality_ratio < 0.8 ? 20.0 : 5.0
session_risk = session_state != 2 ? 30.0 : 0.0

_execution_risk = spread_risk + volume_risk + session_risk


_execution_risk := [Link](_execution_risk, 100.0)

// Liquidity check
_liquidity_acceptable = _execution_risk < liquidity_risk_threshold

// Estimated slippage percentage


_estimated_slippage = _spread_proxy * adaptive_multiplier * 0.4

[_spread_proxy, _execution_risk, _liquidity_acceptable, _estimated_slippage]

[spread_proxy, execution_risk, liquidity_acceptable, estimated_slippage] = f_eqf()

// ============================================================================
// LAYER 7: CONFIDENCE AGGREGATOR (CAG)
// ============================================================================
f_cag() =>
// Initialize confidence score
_confidence = 0.0

// TIER 1: Critical foundation (40 points)


if context_valid
_confidence := _confidence + 10.0
if alignment or not htf_available
_confidence := _confidence + 20.0 // HTF alignment or graceful degradation
if liquidity_acceptable
_confidence := _confidence + 10.0

// TIER 2: Primary edge indicators (35 points)


if is_impulse
_confidence := _confidence + 20.0
if pressure_direction == trend_direction and pressure_direction != 0.0
_confidence := _confidence + 15.0

// TIER 3: Supporting confluence (20 points)


if absorption_detected and is_impulse
_confidence := _confidence + 8.0
if first_hour_bias == trend_direction and first_hour_bias != 0.0
_confidence := _confidence + 6.0
if fractal_valid
_confidence := _confidence + 3.0
if structure_break
_confidence := _confidence + 3.0

// TIER 4: Bonus factors (5 points)


if volume_spike and pressure_direction == trend_direction
_confidence := _confidence + 3.0
if gap_significant and [Link](open_gap) == trend_direction
_confidence := _confidence + 2.0

// Cap at 100
_confidence := [Link](_confidence, 100.0)

// Age-based decay (reduce confidence if too many bars since last signal)
bars_since_last = bar_index - last_signal_bar_index
if bars_since_last < signal_decay_bars
decay_factor = 1.0 - (bars_since_last / signal_decay_bars) * 0.3
_confidence := _confidence * decay_factor

_confidence

confidence_score = f_cag()

// ============================================================================
// REJECTION TREE (Hard No-Trade Filters)
// ============================================================================
f_rejection_tree() =>
_reject = false
_reason = ""

// Level 1: Fundamental validity


if not context_valid
_reject := true
_reason := "CONTEXT_INVALID"

// Level 2: Timeframe alignment


else if not alignment and htf_available
_reject := true
_reason := "HTF_MISALIGNMENT"

// Level 3: Execution quality


else if not liquidity_acceptable
_reject := true
_reason := "POOR_LIQUIDITY"
else if execution_risk > 80.0
_reject := true
_reason := "EXTREME_EXEC_RISK"

// Level 4: Timing filters


else if eod_period
_reject := true
_reason := "EOD_LOCKOUT"
else if regime_shift
_reject := true
_reason := "VOL_REGIME_SHIFT"

// Level 5: Confidence threshold


else if confidence_score < confidence_threshold
_reject := true
_reason := "LOW_CONFIDENCE"

// Level 6: Trend/impulse requirements


else if trend_direction == 0.0
_reject := true
_reason := "NO_TREND"
else if not is_impulse
_reject := true
_reason := "NO_IMPULSE"

[_reject, _reason]

[signal_rejected, rejection_reason] = f_rejection_tree()

// ============================================================================
// FINAL SIGNAL GENERATOR
// ============================================================================
f_generate_signals() =>
_signal_long = false
_signal_short = false

// Check decay period (avoid signal spam)


bars_since_last = bar_index - last_signal_bar_index
decay_elapsed = bars_since_last >= signal_decay_bars

if not signal_rejected and decay_elapsed


// Long signal conditions
if trend_direction == 1.0 and is_impulse and pressure_direction == 1.0
_signal_long := true
last_signal_bar_index := bar_index

// Short signal conditions


else if trend_direction == -1.0 and is_impulse and pressure_direction == -
1.0 and enable_shorts
_signal_short := true
last_signal_bar_index := bar_index

[_signal_long, _signal_short]

[signal_long, signal_short] = f_generate_signals()

// ============================================================================
// LAYER 8: VISUALIZATION & ALERTS (Pine-safe single-line labels)
// ============================================================================

// Ensure label variable was declared earlier (top of script):


// var label lbl = na
// Ensure arrays declared earlier: signal_labels, structure_lines

// Draw signal labels with confidence


if signal_long
lbl_text = "LONG\nConf: " + [Link]([Link](confidence_score))
// single-line with named args (safe)
lbl = [Link](x=bar_index, y=low, text=lbl_text, color=[Link]([Link],
0), style=label.style_label_up, textcolor=[Link], size=[Link],
xloc=xloc.bar_index, yloc=[Link])
[Link](signal_labels, lbl)

if signal_short
lbl_text = "SHORT\nConf: " + [Link]([Link](confidence_score))
lbl = [Link](x=bar_index, y=high, text=lbl_text, color=[Link]([Link],
0), style=label.style_label_down, textcolor=[Link], size=[Link],
xloc=xloc.bar_index, yloc=[Link])
[Link](signal_labels, lbl)

// Draw swing structure lines


if not na(swing_high) and not na(last_swing_high_cache)
ln = [Link](x1=bar_index - 5, y1=last_swing_high_cache, x2=bar_index,
y2=swing_high, color=[Link]([Link], 50), width=1)
[Link](structure_lines, ln)

if not na(swing_low) and not na(last_swing_low_cache)


ln = [Link](x1=bar_index - 5, y1=last_swing_low_cache, x2=bar_index,
y2=swing_low, color=[Link]([Link], 50), width=1)
[Link](structure_lines, ln)

// Garbage collection for labels


if [Link](signal_labels) > 60
old_label = [Link](signal_labels)
[Link](old_label)

// Garbage collection for lines


if [Link](structure_lines) > 60
old_line = [Link](structure_lines)
[Link](old_line)

// Background color for invalid context


bgcolor(context_valid ? na : [Link]([Link], 92), title="Invalid Context")

// Background color for HTF misalignment


bgcolor(not alignment and htf_available ? [Link]([Link], 95) : na, title="HTF
Misalignment")
//===========================END================================

// ============================================================================
// PLOTS (for alert message interpolation and debugging)
// ============================================================================
plot(confidence_score, title="Confidence", color=[Link], display=[Link])
plot(trend_direction, title="Trend Direction", color=[Link],
display=[Link])
plot(execution_risk, title="Execution Risk", color=[Link], display=[Link])

// ============================================================================
// ALERT CONDITIONS
// ============================================================================
alertcondition(signal_long, title="🟢 LONG Signal", message="HIGH-QUALITY LONG SETUP
| Confidence: {{plot_0}} | Trend: {{plot_1}} | Exec Risk: {{plot_2}}")
alertcondition(signal_short, title="🔴 SHORT Signal", message="HIGH-QUALITY SHORT
SETUP | Confidence: {{plot_0}} | Trend: {{plot_1}} | Exec Risk: {{plot_2}}")
alertcondition(signal_long or signal_short, title="⚡ ANY Signal", message="TRADE
SIGNAL DETECTED | Type: {{ticker}} | Confidence: {{plot_0}}")
//============================END======================================

// ============================================================================
// DIAGNOSTIC TABLE (optional visual feedback)
// ============================================================================
var table diagnostic_table = [Link](position.top_right, 3, 12, border_width=1)

if [Link]
// Header
[Link](diagnostic_table, 0, 0, "Layer", text_color=[Link],
bgcolor=[Link])
[Link](diagnostic_table, 1, 0, "Metric", text_color=[Link],
bgcolor=[Link])
[Link](diagnostic_table, 2, 0, "Value", text_color=[Link],
bgcolor=[Link])
// Context
[Link](diagnostic_table, 0, 1, "Context", text_color=[Link],
bgcolor=[Link]([Link], 70))
[Link](diagnostic_table, 1, 1, "Valid", text_color=[Link])
[Link](diagnostic_table, 2, 1, context_valid ? "✓" : "✗",
text_color=context_valid ? [Link] : [Link])
// VRM
[Link](diagnostic_table, 0, 2, "VRM", text_color=[Link],
bgcolor=[Link]([Link], 70))
[Link](diagnostic_table, 1, 2, "Vol Ratio", text_color=[Link])
[Link](diagnostic_table, 2, 2, [Link](vol_ratio, "#.##"),
text_color=[Link])
// TSM
[Link](diagnostic_table, 0, 3, "TSM", text_color=[Link],
bgcolor=[Link]([Link], 70))
[Link](diagnostic_table, 1, 3, "Trend", text_color=[Link])
trend_text = trend_direction == 1.0 ? "↑" : trend_direction == -1.0 ? "↓" : "→"
[Link](diagnostic_table, 2, 3, trend_text, text_color=[Link])
// DPE
[Link](diagnostic_table, 0, 4, "DPE", text_color=[Link],
bgcolor=[Link]([Link], 70))
[Link](diagnostic_table, 1, 4, "Pressure", text_color=[Link])
pressure_text = pressure_direction == 1.0 ? "BUY" : pressure_direction == -
1.0 ? "SELL" : "NEUT"
[Link](diagnostic_table, 2, 4, pressure_text, text_color=[Link])
// SMS
[Link](diagnostic_table, 0, 5, "SMS", text_color=[Link],
bgcolor=[Link]([Link], 70))
[Link](diagnostic_table, 1, 5, "Session", text_color=[Link])
[Link](diagnostic_table, 2, 5, session_state == 2 ? "OPEN" : "CLOSED",
text_color=[Link])
// MTV
[Link](diagnostic_table, 0, 6, "MTV", text_color=[Link],
bgcolor=[Link]([Link], 70))
[Link](diagnostic_table, 1, 6, "HTF Align", text_color=[Link])
[Link](diagnostic_table, 2, 6, alignment ? "✓" : "✗",
text_color=alignment ? [Link] : [Link])
// EQF
[Link](diagnostic_table, 0, 7, "EQF", text_color=[Link],
bgcolor=[Link]([Link], 70))
[Link](diagnostic_table, 1, 7, "Liquidity", text_color=[Link])
[Link](diagnostic_table, 2, 7, liquidity_acceptable ? "✓" : "✗",
text_color=liquidity_acceptable ? [Link] : [Link])
// CAG
[Link](diagnostic_table, 0, 8, "CAG", text_color=[Link],
bgcolor=[Link]([Link], 70))
[Link](diagnostic_table, 1, 8, "Confidence", text_color=[Link])
conf_color = confidence_score >= 80 ? [Link] : confidence_score >= 60 ?
[Link] : [Link]
[Link](diagnostic_table, 2, 8, [Link]([Link](confidence_score)),
text_color=conf_color)
// Signal Status
[Link](diagnostic_table, 0, 9, "Signal", text_color=[Link],
bgcolor=[Link]([Link], 70))
[Link](diagnostic_table, 1, 9, "Status", text_color=[Link])
signal_status = signal_long ? "LONG ↑" : signal_short ? "SHORT ↓" :
signal_rejected ? "BLOCKED" : "NONE"
signal_color = signal_long ? [Link] : signal_short ? [Link] :
[Link]
[Link](diagnostic_table, 2, 9, signal_status, text_color=signal_color)
// Rejection Reason
[Link](diagnostic_table, 0, 10, "Reject", text_color=[Link],
bgcolor=[Link]([Link], 70))
[Link](diagnostic_table, 1, 10, "Reason", text_color=[Link])
[Link](diagnostic_table, 2, 10, signal_rejected ? rejection_reason : "N/A",
text_color=[Link])
// Performance Stats
[Link](diagnostic_table, 0, 11, "Stats", text_color=[Link],
bgcolor=[Link]([Link], 70))
[Link](diagnostic_table, 1, 11, "Last Signal", text_color=[Link])
bars_ago = bar_index - last_signal_bar_index
[Link](diagnostic_table, 2, 11, [Link](bars_ago) + " bars",
text_color=[Link])

// ============================================================================
// ADDITIONAL VISUAL INDICATORS
// ============================================================================

// Plot displacement for reference (hidden)


plot(displacement, title="Displacement", color=[Link], display=[Link])
// Plot adaptive multiplier (hidden)
plot(adaptive_multiplier, title="Adaptive Multiplier", color=[Link],
display=[Link])

// Plot pressure strength (hidden)


plot(pressure_strength, title="Pressure Strength", color=[Link],
display=[Link])

// HTF trend line


plot(htf_trend_cache, title="HTF Trend", color=[Link]([Link], 0),
linewidth=2, style=plot.style_stepline)

// Mark impulse moves


plotshape(is_impulse and trend_direction == 1.0, title="Impulse Up",
location=[Link], color=[Link]([Link], 30),
style=[Link], size=[Link])
plotshape(is_impulse and trend_direction == -1.0, title="Impulse Down",
location=[Link], color=[Link]([Link], 30),
style=[Link], size=[Link])

// Mark absorption bars


plotshape(absorption_detected, title="Absorption", location=[Link],
color=[Link]([Link], 50), style=[Link], size=[Link], offset=0)

// Mark volume spikes


plotchar(volume_spike, title="Volume Spike", char="V", location=[Link],
color=[Link]([Link], 40), size=[Link])

// Mark structure breaks


plotshape(structure_break and trend_direction == 1.0, title="Structure Break Up",
location=[Link], color=[Link]([Link], 60), style=[Link],
size=[Link])
plotshape(structure_break and trend_direction == -1.0, title="Structure Break
Down", location=[Link], color=[Link]([Link], 60),
style=[Link], size=[Link])

// Session open marker


var line session_open_line = na
if session_state == 2 and nz(session_state[1], 0) != 2
// kalau ada line lama, padam dulu
if not na(session_open_line)
[Link](session_open_line)
session_open_line := [Link](bar_index, low, bar_index, high,
color=[Link]([Link], 60), width=2, style=line.style_dashed)

/// @version=5
indicator("Nuclear Multi-Layer Trading Framework", overlay=true,
max_labels_count=60, max_lines_count=60, max_bars_back=500)

// ... (rest of your code unchanged) ...

// @version=5
indicator("Nuclear Multi-Layer Trading Framework", overlay=true,
max_labels_count=60, max_lines_count=60, max_bars_back=500)

// ... (rest of your code unchanged) ...

// First hour range box (fully named args, line continuation safe)
var first_hour_box = na
if not na(first_hour_high_cache) and not na(first_hour_low_cache) and session_state
== 2
bars_since_session := bar_index - session_start_bar_cache
if bars_since_session == 12
if not na(first_hour_box)
[Link](first_hour_box)
first_hour_box := [Link](left=session_start_bar_cache,
top=first_hour_high_cache, right=bar_index, bottom=first_hour_low_cache,
border_color=[Link]([Link], 50), bgcolor=[Link]([Link], 90),
border_width=1)

// ======================= END ==========================================

// ============================================================================
// PERFORMANCE MONITORING
// ============================================================================

// Count total signals generated


var int total_long_signals = 0
var int total_short_signals = 0
var int total_rejections = 0

if signal_long
total_long_signals += 1

total_long_signals += 1

if signal_short
total_short_signals += 1

total_short_signals += 1

if signal_rejected and (trend_direction != 0.0 and is_impulse)


total_rejections += 1

total_rejections += 1

/// @version=5
indicator("Nuclear Multi-Layer Trading Framework", overlay=true,
max_labels_count=60, max_lines_count=60, max_bars_back=500)

// ... (rest of your code unchanged) ...

// Display cumulative stats in table on last bar


if [Link] and bar_index > 200
// Declare table outside of inline var usage
stats_table = [Link](position.bottom_right, 2, 4, border_width=1)
[Link](stats_table, 0, 0, "Metric", text_color=[Link],
bgcolor=[Link])
[Link](stats_table, 1, 0, "Count", text_color=[Link],
bgcolor=[Link])
[Link](stats_table, 0, 1, "Long Signals", text_color=[Link])
[Link](stats_table, 1, 1, [Link](total_long_signals),
text_color=[Link])
[Link](stats_table, 0, 2, "Short Signals", text_color=[Link])
[Link](stats_table, 1, 2, [Link](total_short_signals),
text_color=[Link])
[Link](stats_table, 0, 3, "Rejections", text_color=[Link])
[Link](stats_table, 1, 3, [Link](total_rejections),
text_color=[Link])

// ============================================================================
// DEBUGGING PLOTS (can be disabled in production)
// ============================================================================

// HTF data availability check


plot(htf_available ? 1 : 0, title="HTF Available", color=[Link],
display=[Link])

// Execution risk level


plot(execution_risk, title="Exec Risk Level", color=[Link],
display=[Link])

// Bars since last signal (for decay tracking)


plot(bar_index - last_signal_bar_index, title="Bars Since Signal",
color=[Link], display=[Link])

// Session state tracking


plot(session_state, title="Session State", color=[Link], display=[Link])

// Vol regime tracking


plot(vol_regime, title="Vol Regime", color=[Link], display=[Link])

// ============================================================================
// END OF NUCLEAR MULTI-LAYER TRADING FRAMEWORK
// ============================================================================

Common questions

Powered by AI

The Volatility Regime Module (VRM) is critical in detecting shifts in market volatility which indicates potential changes in trading conditions. It uses the average true range (ATR) over different periods to calculate a volatility ratio. This ratio helps in identifying regime shifts as it compares short-term volatility to a longer-term baseline. If the volatility ratio crosses key thresholds, it can signal an expansion or contraction in market volatility. The module uses these insights to adjust an adaptive multiplier, which modifies downstream parameters to better fit the current volatilities in the market. This dynamic adaptation helps traders align their strategies to either high or low volatility environments .

Diagnostic and performance monitoring tables track real-time metrics and historical performance, enhancing situational awareness and strategy refinement. These tables present layering modules, trend analysis, volatility ratios, and session states in organized rows, offering a concise summary of current trading contexts. Performance monitoring specifically logs signal counts, rejections, and execution metrics, aiding in the assessment of signal accuracy and strategy efficacy. By providing continuous feedback and allowing for historical review, traders can fine-tune their strategies to improve overall performance .

The framework maintains a balanced risk-to-reward ratio by dynamically adjusting adaptive multipliers and thresholds in response to volatility changes. The VRM identifies high volatility environments and modifies the thresholds for impulse and structure breaks throughout the modules to accommodate for expanded price ranges, thus maintaining profitability margins. This adaptive nature allows for maintaining conservative risk measures while capitalizing on potentially higher rewards during volatile periods, thereby controlling the overall risk exposure of trading activities .

The Demand/Pressure Engine (DPE) evaluates buying and selling pressures by analyzing volume and price movement combined with wick-to-body ratios on candlesticks. Key indicators include volume spikes, large wicks indicating potential absorption, and the direction of price-validated volume delta. The engine calculates a pressure direction by normalizing delta volume over smoothed averages and setting thresholds to trigger buying (positive volume delta) or selling (negative volume delta) pressures. This comprehensive analysis aids in the generation of trading signals by confirming the direction of market pressure and its intensity, which is crucial for executing high-confidence trades .

The Session Microstructure Module (SMS) detects potential breakout scenarios by analyzing session-based price movements and comparing them against volatility-adjusted metrics. Within the first hour after the session opens, it calculates an initial bias based on net displacement of prices from the open, comparing this against a threshold derived from average true range (ATR). Additionally, it monitors for mid-session breakouts by checking if price surpasses the established first hour high or low, indicating movement beyond this initial range. This approach allows traders to anticipate significant shifts during defined session windows, particularly when supported by other volatility and trend indicators .

The Trend Structure Module (TSM) identifies changes in market trends through analyzing price displacement and looking for structural breaks. It calculates displacement based on changes in the closing prices relative to average true ranges. Swing highs and lows are used as pivot points to detect breakouts or breakdowns, indicating a trend change. A structure break to the upside (bullish) is confirmed when a current swing high surpasses a previously identified swing high, and the opposite for a bearish trend. The TSM incorporates an impulse detection mechanism, marking significant movements when displacement exceeds an adaptive threshold. This method ensures changes in trend are recognized through objective structural conditions rather than purely price-based metrics .

Signal decay periods are critical in the strategy to prevent over-reactions to market noise and recent movements, ensuring signals are generated based on sustained conditions rather than fleeting anomalies. They impose a minimum time interval between signals, allowing the market time to evolve and reducing the likelihood of entering trades during erratic or temporary adjustments that align poorly with longer-term market conditions. This temporal buffer fosters more robust decision-making by emphasizing meaningful trends over short-lived volatility spikes .

The Execution Quality Filter (EQF) enhances signal reliability by evaluating the market conditions that affect trade execution, primarily through spread and volume analysis. It calculates a spread proxy, approximating bid-ask spreads in relation to current price levels, and assesses volume quality by comparing present volume to its moving average. This results in execution risk components being measured on a 0-100 scale, where lower values are preferable. These measures are crucial as they ensure that signals are executed under conditions that maximize profit potential and minimize trade slippage, ultimately leading to more consistent and reliable trading outputs .

The Multi-Timeframe Validator (MTV) refines trading signals by aligning them with higher timeframe trends and structures, ensuring that lower timeframe analyses don't contradict the broader market direction. It updates caches for displacement, trend, and structure scores from higher timeframe data, thus providing a holistic view of market conditions. By comparing current lower timeframe signals against these validated higher timeframe references, it helps in validating or rejecting signals based on their alignment with established longer-term trends, increasing the likelihood of successful trade outcomes .

The framework employs various visual indicators such as colored labels and plot shapes to communicate trading insights effectively. Long and short signals are illustrated using distinct color-coded labels placed at price bars, conveying confidence levels and direction. Swing structure and breakout points are marked with lines and shapes like circles or triangles, while background colors are used to signify context validity or higher timeframe misalignments. The integration of visual elements helps users quickly interpret complex data, providing situational awareness at a glance .

You might also like