Code: Select all
//@version=5
strategy("BOJ Risk Engine v2.0", overlay=true, calc_on_every_tick=true, initial_capital=100000, default_qty_type=strategy.percent_of_equity, default_qty_value=2)
// =========================================================================
// 1. INPUTS & RISK PARAMETERS
// =========================================================================
grp_anomaly = "1. Anomaly Detection (Z-Score)"
lookback = input.int(100, title="Rolling Window (Bars)", group=grp_anomaly)
zThreshold = input.float(4.5, title="Z-Score Trigger (Sigma)", group=grp_anomaly, tooltip="Fires if a candle's range is this many standard deviations above the mean. 4.0 to 5.0 is ideal for tape bombs.")
grp_timer = "2. The Stand-Aside Timer"
cooldownBars= input.int(12, title="Cooldown Lockout (Bars)", group=grp_timer, tooltip="If on a 5m chart, 12 bars = 60 minute lockout after a spike.")
grp_eom = "3. Month-End Dynamics"
eomDayStart = input.int(26, title="Month-End Lockout Start Day", group=grp_eom, minval=1, maxval=31)
eomActive = input.bool(true, title="Enable Month-End Lockout", group=grp_eom)
grp_sess = "4. Session Awareness"
asianSess = input.session("0000-0900", title="BOJ/Asian Danger Zone (UTC)", group=grp_sess)
// =========================================================================
// 2. CORE MATH & Z-SCORE DETECTION
// =========================================================================
// True Range includes price gaps, which ATR smooths over. We want the raw shock.
rawShock = ta.tr
meanShock = ta.sma(rawShock, lookback)
stdDevShock = ta.stdev(rawShock, lookback)
// Z-Score: (Current Value - Mean) / Standard Deviation
// Protect against division by zero in dead markets
currentZScore = stdDevShock > 0 ? (rawShock - meanShock) / stdDevShock : 0
// Check if we are in the high-risk Asian/early London session
inDangerZone = time(timeframe.period, asianSess, "UTC")
// Dynamic threshold: If we are in the BOJ danger time AND it's month-end,
// the engine becomes hyper-sensitive, lowering the Z-Score required to trip the alarm.
isHighRiskWindow = inDangerZone and (dayofmonth >= eomDayStart) and eomActive
triggerLevel = isHighRiskWindow ? (zThreshold * 0.8) : zThreshold
// Spike Boolean
isInterventionSpike = currentZScore > triggerLevel
// =========================================================================
// 3. THE STAND-ASIDE TIMER (STATE MACHINE)
// =========================================================================
// Track bars since the last recorded spike
barsSinceSpike = ta.barssince(isInterventionSpike)
// If the spike hasn't happened yet in the dataset, barssince returns 'na'.
// We use nz() to convert 'na' to a large number so the system starts in a "safe" state.
safeBars = nz(barsSinceSpike, 999999)
// We are in cooldown if the bars passed are less than our input setting
inCooldown = safeBars <= cooldownBars
// =========================================================================
// 4. MONTH-END FILTER
// =========================================================================
inMonthEndLockout = (dayofmonth >= eomDayStart) and eomActive
// =========================================================================
// 5. EXECUTION & KILL-SWITCH
// =========================================================================
// EJECT MECHANISM
if isInterventionSpike
strategy.close_all(comment="🚨 BOJ EJECT (Z:" + str.tostring(math.round(currentZScore,1)) + ")")
alert("CLOSE_ALL", alert.freq_once_per_bar_close)
// GLOBAL TRADE PERMISSION (The master switch for your entry logic)
engineGreenLight = not isInterventionSpike and not inCooldown and not inMonthEndLockout
// =========================================================================
// 6. VISUALS & HUD (HEADS-UP DISPLAY)
// =========================================================================
// Background alerts
bgcolor(isInterventionSpike ? color.new(color.red, 70) : na, title="Spike Alarm")
bgcolor(inCooldown and not isInterventionSpike ? color.new(color.orange, 85) : na, title="Cooldown Timer")
bgcolor(inMonthEndLockout and not inCooldown and not isInterventionSpike ? color.new(color.yellow, 90) : na, title="Month-End Lockout")
// HUD Table
var table hud = table.new(position.top_right, 2, 4, border_width=1, border_color=color.gray)
if barstate.islast
// Header
table.cell(hud, 0, 0, "RISK ENGINE", text_color=color.white, bgcolor=color.black)
table.cell(hud, 1, 0, "STATUS", text_color=color.white, bgcolor=color.black)
// Z-Score Row
table.cell(hud, 0, 1, "Shock Z-Score", text_color=color.white, bgcolor=color.gray)
table.cell(hud, 1, 1, str.tostring(math.round(currentZScore, 2)) + " / " + str.tostring(triggerLevel) + "σ", text_color=color.white, bgcolor=currentZScore > 2 ? color.orange : color.gray)
// System Status Row
string statusText = inMonthEndLockout ? "MONTH END LOCK" : (inCooldown ? "COOLDOWN (" + str.tostring(cooldownBars - safeBars) + ")" : "ARMED / GREEN")
color statusColor = inMonthEndLockout ? color.yellow : (inCooldown ? color.orange : color.green)
table.cell(hud, 0, 2, "System State", text_color=color.white, bgcolor=color.gray)
table.cell(hud, 1, 2, statusText, text_color=statusColor == color.yellow ? color.black : color.white, bgcolor=statusColor)
// =========================================================================
// 7. PLACEHOLDER ENTRY LOGIC
// =========================================================================
// Example logic: only allowed to trade if engineGreenLight is true.
// Wrap YOUR strategy inside the 'engineGreenLight' condition.
emaFast = ta.ema(close, 9)
emaSlow = ta.ema(close, 21)
if ta.crossover(emaFast, emaSlow) and engineGreenLight
strategy.entry("Long", strategy.long)
if ta.crossunder(emaFast, emaSlow) and engineGreenLight
strategy.entry("Short", strategy.short)