本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("ATK/DEF Quant Multi-Timeframe Causal Regime & Trend Rotation", "ATK/DEF Timeframe Causal Trend Regime ", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count=100)
// ============================================================
// UDT DEFINITION & FIFO MANAGER (Only for Boxes)
// ============================================================
type CollisionZone
int startTime
int endTime
float top
float bottom
color fillColor
box boxObj
var array<CollisionZone> zones = array.new<CollisionZone>()
const int MAX_ZONES = 50
removeOldestZone() =>
if array.size(zones) > 0
oldZone = array.shift(zones)
box.delete(oldZone.boxObj)
// ============================================================
// INPUTS - SWITCHES & SIZING
// ============================================================
grpSwitch = "🔧 Module Switches & Sizing"
showBiasTint = input.bool(true, "Show HTF Bias Background Tint", group=grpSwitch)
showCollisionBox = input.bool(true, "Show Collision Space (FIFO Boxes)", group=grpSwitch)
showDash = input.bool(true, "Show Dashboard Table", group=grpSwitch)
showStateBubble = input.bool(true, "Show Memory State Bubble", group=grpSwitch)
showStateBg = input.bool(true, "Show State Phase Background", group=grpSwitch)
showMALines = input.bool(true, "Show MA / Attack / Defense Lines", group=grpSwitch)
bubbleSize = input.string("small", "Bubble Size", options=["tiny", "small", "normal", "large", "huge"], group=grpSwitch)
dashTextSize = input.string("normal", "Dashboard Text Size", options=["tiny", "small", "normal", "large", "huge"], group=grpSwitch)
dashBorderWidth = input.int(1, "Dashboard Border Width", minval=0, maxval=5, group=grpSwitch)
// ============================================================
// INPUTS - PARAMETERS
// ============================================================
grpMTF = "MTF Hierarchy"
htf = input.timeframe("D", "HTF (Long Direction)", group=grpMTF)
mtf = input.timeframe("240", "MTF (Mid Direction)", group=grpMTF)
ltf = input.timeframe("60", "LTF (Short Direction)", group=grpMTF)
grpMA = "Markov Switching MA"
maLen = input.int(21, "MA Length", minval=5, group=grpMA)
regLen = input.int(50, "Regime Lookback", minval=20, group=grpMA)
smoothK = input.float(0.6, "Regime Smoothing (0-1)", step=0.05, group=grpMA)
grpRisk = "Rotation Risk"
volLen = input.int(14, "Volatility Len", group=grpRisk)
riskCap = input.float(2.5, "Risk Cap (ATR mult)", step=0.1, group=grpRisk)
grpLevel = "Attack / Defense Levels"
atrLen = input.int(14, "ATR Len", group=grpLevel)
defMult = input.float(1.5, "Defense ATR Mult", step=0.1, group=grpLevel)
atkMult = input.float(2.2, "Attack ATR Mult", step=0.1, group=grpLevel)
grpSqueeze = "Squeeze & Expansion"
sqzLen = input.int(20, "Squeeze Len", group=grpSqueeze)
sqzMult = input.float(2.0, "Squeeze BB Mult", group=grpSqueeze)
// ============================================================
// HTF / MTF / LTF DIRECTION
// ============================================================
f_dir(_tf) =>
c = request.security(syminfo.tickerid, _tf, close, lookahead=barmerge.lookahead_off)
m = request.security(syminfo.tickerid, _tf, ta.sma(close, maLen), lookahead=barmerge.lookahead_off)
c > m ? 1 : c < m ? -1 : 0
htfDir = f_dir(htf)
mtfDir = f_dir(mtf)
ltfDir = f_dir(ltf)
// ============================================================
// MARKOV SWITCHING MA
// ============================================================
maBase = ta.sma(close, maLen)
ret = close - maBase
retZ = (ret - ta.sma(ret, regLen)) / math.max(ta.stdev(ret, regLen), syminfo.mintick)
persist = 0.0
persist := ta.sma(retZ * retZ[1] > 0 ? 1.0 : 0.0, regLen)
pTrend = math.min(math.max((persist - 0.5) * 2, 0), 1)
pTrend := pTrend * smoothK + nz(pTrend[1]) * (1 - smoothK)
fastMA = ta.ema(close, maLen)
slowMA = ta.sma(close, maLen * 2)
msMA = pTrend * fastMA + (1 - pTrend) * slowMA
// ============================================================
// VOLATILITY ROTATION RISK & OSCILLATION
// ============================================================
atr = ta.atr(atrLen)
rotDist = math.abs(close - msMA) / math.max(atr, syminfo.mintick)
rotRisk = math.min(rotDist / riskCap, 1.0) * (pTrend > 0.5 ? 0.7 : 1.0)
msSlope = ta.change(msMA, 5) / math.max(atr, syminfo.mintick)
isOscUpDown = math.abs(msSlope) < 0.3 and pTrend < 0.45
isOscDown = msSlope < -0.5 and pTrend < 0.5
isOscUp = msSlope > 0.5 and pTrend < 0.5
isTrend = pTrend >= 0.5
// ============================================================
// CAUSAL INFLUENCE INDEX & LEVELS
// ============================================================
causalScore = htfDir != 0 and mtfDir != 0 and ltfDir != 0 ?
(htfDir == mtfDir ? (mtfDir == ltfDir ? 1.0 : 0.5) : 0.0) : 0.0
causalWeighted = causalScore * (0.4 + 0.6 * pTrend)
dirBias = causalWeighted > 0.5 ? (htfDir > 0 ? 1 : htfDir < 0 ? -1 : 0) : 0
defLevel = dirBias > 0 ? msMA - atr * defMult : dirBias < 0 ? msMA + atr * defMult : msMA
swingHi = ta.highest(high, 20)
swingLo = ta.lowest(low, 20)
atkLevel = dirBias > 0 ? swingHi + atr * atkMult * 0.3 : dirBias < 0 ? swingLo - atr * atkMult * 0.3 : msMA
collisionHi = math.max(defLevel, atkLevel)
collisionLo = math.min(defLevel, atkLevel)
fillColor = dirBias > 0 ? color.new(color.green, 80) : dirBias < 0 ? color.new(color.red, 80) : color.new(color.gray, 80)
rightTime = time + timeframe.in_seconds() * 1000
// ============================================================
// MEMORY STATE MACHINE
// ============================================================
bbBasis = ta.sma(close, sqzLen)
bbDev = sqzMult * ta.stdev(close, sqzLen)
bbWidth = (bbBasis + bbDev) - (bbBasis - bbDev)
squeezeRatio = bbWidth / math.max(atr, syminfo.mintick)
isExpanding = math.abs(msSlope) > 0.8 and rotDist > 1.2
var string statePhase = "Normal"
var int trendLevel = 1
if squeezeRatio < 1.5 and not isExpanding
statePhase := "Squeeze"
else if isExpanding
statePhase := "Expansion"
else if math.abs(msSlope) < 0.2 and rotDist < 0.5
statePhase := "Cooling"
else
statePhase := "Normal"
if statePhase == "Expansion" and causalWeighted >= 0.8
trendLevel := 5
else if statePhase == "Expansion" and causalWeighted >= 0.5
trendLevel := 4
else if statePhase == "Expansion" or causalWeighted >= 0.8
trendLevel := 3
else if statePhase == "Squeeze"
trendLevel := 2
else if statePhase == "Cooling"
trendLevel := 1
else
trendLevel := math.max(1, trendLevel - 1)
phaseTxt = statePhase + " Lv." + str.tostring(trendLevel)
getSize(sizeStr) =>
switch sizeStr
"tiny" => size.tiny
"small" => size.small
"normal" => size.normal
"large" => size.large
"huge" => size.huge
=> size.normal
// ============================================================
// SINGLE FLOATING BUBBLE
// ============================================================
var label singleBubble = na
if barstate.islast and showStateBubble
labelY = dirBias > 0 ? low - atr * 0.6 : high + atr * 0.6
labelStyle = dirBias > 0 ? label.style_label_up : label.style_label_down
stateColor = statePhase == "Expansion" ? color.new(color.lime, 20) : statePhase == "Squeeze" ? color.new(color.blue, 20) : statePhase == "Cooling" ? color.new(color.aqua, 20) : color.new(color.gray, 20)
if na(singleBubble)
singleBubble := label.new(x=time, y=labelY, text=phaseTxt, xloc=xloc.bar_time, style=labelStyle, color=stateColor, textcolor=color.black, size=getSize(bubbleSize))
else
label.set_x(singleBubble, time)
label.set_y(singleBubble, labelY)
label.set_text(singleBubble, phaseTxt)
label.set_style(singleBubble, labelStyle)
label.set_color(singleBubble, stateColor)
label.set_size(singleBubble, getSize(bubbleSize))
else if not showStateBubble and not na(singleBubble)
label.delete(singleBubble)
singleBubble := na
// ============================================================
// FIFO COLLISION SPACE
// ============================================================
if showCollisionBox and collisionHi > collisionLo
lastIdx = array.size(zones) - 1
if lastIdx >= 0
lastZone = array.get(zones, lastIdx)
if lastZone.fillColor == fillColor and lastZone.endTime == lastZone.startTime
box.set_right(lastZone.boxObj, rightTime)
box.set_top(lastZone.boxObj, collisionHi)
box.set_bottom(lastZone.boxObj, collisionLo)
else
newBox = box.new(left=time, top=collisionHi, right=rightTime, bottom=collisionLo, bgcolor=fillColor, border_color=color.new(color.gray, 100), xloc=xloc.bar_time)
newZone = CollisionZone.new(startTime=time, endTime=time, top=collisionHi, bottom=collisionLo, fillColor=fillColor, boxObj=newBox)
array.push(zones, newZone)
if array.size(zones) > MAX_ZONES
removeOldestZone()
else
newBox = box.new(left=time, top=collisionHi, right=rightTime, bottom=collisionLo, bgcolor=fillColor, border_color=color.new(color.gray, 100), xloc=xloc.bar_time)
newZone = CollisionZone.new(startTime=time, endTime=time, top=collisionHi, bottom=collisionLo, fillColor=fillColor, boxObj=newBox)
array.push(zones, newZone)
lastIdx := array.size(zones) - 1
if lastIdx >= 0
lastZone = array.get(zones, lastIdx)
lastZone.endTime := time
array.set(zones, lastIdx, lastZone)
else if not showCollisionBox and array.size(zones) > 0
while array.size(zones) > 0
removeOldestZone()
// ============================================================
// PLOTS
// ============================================================
plot(showMALines ? msMA : na, "MS MA", color=color.orange, linewidth=2)
plot(showMALines ? defLevel : na, "Defense", color=color.new(color.aqua, 30), style=plot.style_circles, linewidth=1)
plot(showMALines ? atkLevel : na, "Attack", color=color.new(color.fuchsia, 30), style=plot.style_circles, linewidth=1)
bgcolor(showBiasTint ? (dirBias > 0 ? color.new(color.green, 95) : dirBias < 0 ? color.new(color.red, 95) : na) : na, title="HTF Bias Tint")
bgcolor(showStateBg ? (statePhase == "Expansion" ? color.new(color.yellow, 90) : statePhase == "Squeeze" ? color.new(color.blue, 90) : na) : na, title="State Phase Bg")
// ============================================================
// DASHBOARD
// ============================================================
var table dash = table.new(position.top_right, 2, 10, border_width=1)
if barstate.islast and showDash
table.clear(dash, 0, 0, 1, 9)
tSize = getSize(dashTextSize)
dash := table.new(position.top_right, 2, 10, border_width=dashBorderWidth)
table.cell(dash, 0, 0, "HTF Dir", text_color=color.white, text_size=tSize)
table.cell(dash, 1, 0, str.tostring(htfDir), text_color=htfDir > 0 ? color.green : htfDir < 0 ? color.red : color.gray, text_size=tSize)
table.cell(dash, 0, 1, "MTF Dir", text_color=color.white, text_size=tSize)
table.cell(dash, 1, 1, str.tostring(mtfDir), text_color=mtfDir > 0 ? color.green : mtfDir < 0 ? color.red : color.gray, text_size=tSize)
table.cell(dash, 0, 2, "LTF Dir", text_color=color.white, text_size=tSize)
table.cell(dash, 1, 2, str.tostring(ltfDir), text_color=ltfDir > 0 ? color.green : ltfDir < 0 ? color.red : color.gray, text_size=tSize)
table.cell(dash, 0, 3, "Causal Score", text_color=color.white, text_size=tSize)
table.cell(dash, 1, 3, str.tostring(causalWeighted, "#.##"), text_color=causalWeighted > 0.5 ? color.lime : color.gray, text_size=tSize)
table.cell(dash, 0, 4, "Regime", text_color=color.white, text_size=tSize)
table.cell(dash, 1, 4, isTrend ? "Trend" : isOscDown ? "Osc Down" : isOscUp ? "Osc Up" : "Osc Mid", text_color=color.orange, text_size=tSize)
table.cell(dash, 0, 5, "pTrend", text_color=color.white, text_size=tSize)
table.cell(dash, 1, 5, str.tostring(pTrend, "#.##"), text_color=color.blue, text_size=tSize)
table.cell(dash, 0, 6, "Rot Risk", text_color=color.white, text_size=tSize)
table.cell(dash, 1, 6, str.tostring(rotRisk, "#.##"), text_color=rotRisk > 0.6 ? color.red : rotRisk > 0.3 ? color.orange : color.green, text_size=tSize)
table.cell(dash, 0, 7, "Memory State", text_color=color.white, text_size=tSize)
stateColor = statePhase == "Expansion" ? color.lime : statePhase == "Squeeze" ? color.blue : statePhase == "Cooling" ? color.aqua : color.gray
table.cell(dash, 1, 7, statePhase, text_color=stateColor, text_size=tSize)
table.cell(dash, 0, 8, "Trend Level (1-5)", text_color=color.white, text_size=tSize)
lvlColor = trendLevel == 5 ? color.lime : trendLevel == 4 ? color.green : trendLevel == 3 ? color.yellow : trendLevel == 2 ? color.orange : color.red
table.cell(dash, 1, 8, str.tostring(trendLevel), text_color=lvlColor, text_size=tSize)
table.cell(dash, 0, 9, "Bias", text_color=color.white, text_size=tSize)
table.cell(dash, 1, 9, dirBias > 0 ? "LONG" : dirBias < 0 ? "SHORT" : "NEUTRAL", text_color=dirBias > 0 ? color.green : dirBias < 0 ? color.red : color.gray, text_size=tSize)