Weierstrass + Fractal Cycles

gogaz · study · 598 行 · 点赞 13 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © gogaz
 
//@version=6
indicator("Weierstrass Function ", " Weierstrass+Fractal Cycles", overlay=false, max_lines_count=500, max_labels_count=500, max_boxes_count=500)
 
// ═══════════════════════════════════════════════════════════════════════
//  INPUTS
// ═══════════════════════════════════════════════════════════════════════
invrt          = input.bool(true,  "Invert",  inline="mode")
anchorMode     = input.string("Bar Index", "Anchor", options=["Bar Index", "Swing Pivot", "Fixed Start"], inline="anc")
fixedStartTime = input.time(timestamp("2024-01-01T00:00:00"), "Fixed Start Time", inline="anc2")
pivotLen       = input.int(10, "Pivot Length", 1)
 
grpAuto      = "Auto Timeframe"
autoTF       = input.bool(true, "Auto-detect settings by Timeframe", group=grpAuto)
 
grpW         = "Weierstrass Parameters"
a            = input.float(0.5,  "Amplitude Factor a", 0.01, 1.0,  0.05, group=grpW)
b            = input.float(3.0,  "Frequency Factor b", 1.01, 10.0, 0.01, group=grpW)
autoBTune    = input.bool(false, "Auto-Tune b", group=grpW)
bMin         = input.float(1.5, "  b Min", 1.01, 9.0, 0.01, group=grpW)
bMax         = input.float(5.0, "  b Max", 1.02, 10.0, 0.01, group=grpW)
tuneEvery    = input.int(200, "  Tune Every N Bars", 20, group=grpW)
tuneSteps    = input.int(8, "  Auto-Tune Steps", 4, 16, group=grpW)
perfGuardMax = input.int(3000, "  Perf Guard: Max History Bars", 500, group=grpW)
scaleMode    = input.string("Manual", "Scale Mode", options=["Auto", "Manual"], group=grpW)
scale_factor = input.float(0.005, "Scale (manual)", 0.0000001, 1.0, 0.0001, group=grpW)
n_terms      = input.int(8, "Number of Terms", 1, 50, group=grpW)
normalize    = input.bool(true, "Normalize Amplitude", group=grpW)
smoothLen    = input.int(1, "Smoothing (SMA)", 1, 20, group=grpW)
 
grpT         = "Trend Filter"
useTrend     = input.bool(true, "Enable Trend Gate", group=grpT)
trendType    = input.string("EMA", "Trend Type", options=["EMA", "SMA", "Supertrend"], group=grpT)
trendLen     = input.int(50, "Trend Length", 1, group=grpT)
stMult       = input.float(3.0, "Supertrend Multiplier", 0.1, 10.0, 0.1, group=grpT)
allowCounter = input.bool(false, "Allow Counter-Trend Alerts", group=grpT)
showSTOsc    = input.bool(true, "Plot Supertrend on Oscillator Panel", group=grpT)
stMirrorLevel = input.float(0.40, "ST Mirror Level", 0.1, 1.0, 0.05, group=grpT)
 
grpA         = "Regime & Alerts"
showRegime   = input.bool(true, "Show Regime Background", group=grpA)
confirmBars  = input.int(2, "Zero-Cross Confirmation Bars", 1, 10, group=grpA)
alertOnCross = input.bool(true, "Enable Zero-Cross Alert", group=grpA)
alertOnReg   = input.bool(true, "Enable Regime-Change Alert", group=grpA)
alertOnDiv   = input.bool(true, "Enable Divergence Alert", group=grpA)
useJson      = input.bool(false, "Webhook JSON Payload", group=grpA)
 
grpD         = "Divergence Detection"
divLookback  = input.int(20, "Pivot Lookback", 2, group=grpD)
divRange     = input.int(80, "Max Bars Between Pivots", 5, group=grpD)
showDivLines = input.bool(true, "Draw Divergence Lines", group=grpD)
useHiddenDiv = input.bool(true, "Include Hidden Divergence", group=grpD)
 
grpP         = "Trade Plan (State Machine)"
usePlan      = input.bool(true, "Enable Trade Plan", group=grpP)
planDir      = input.string("Both", "Allowed Direction", options=["Long", "Short", "Both"], group=grpP)
atrLen       = input.int(14, "ATR Length", 1, group=grpP)
slAtr        = input.float(1.5, "SL × ATR", 0.1, 10.0, 0.1, group=grpP)
tpAtr        = input.float(3.0, "TP × ATR", 0.1, 20.0, 0.1, group=grpP)
requireDiv   = input.bool(false, "Require Divergence for Entry", group=grpP)
requireNoOpp = input.bool(true, "Reject Entry if Opposite Signal Same Bar", group=grpP)
showPlanBox  = input.bool(true, "Draw Entry/SL/TP Lines", group=grpP)
 
grpI         = "Info Table"
showInfo     = input.bool(true, "Show Info Table", group=grpI)
showInfoTips = input.bool(true, "Show Cell Tooltips", group=grpI)
infoPos      = input.string("Top Right", "Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left", "Middle Right", "Middle Left"], group=grpI)
infoLayout   = input.string("Vertical", "Layout", options=["Vertical", "Horizontal"], group=grpI)
infoTxtSize  = input.string("Small", "Text Size", options=["Tiny", "Small", "Normal", "Large", "Huge"], group=grpI)
infoBgColor  = input.color(#000000, "Background", group=grpI)
infoBgTransp = input.int(0, "Background Transparency", 0, 100, group=grpI)
infoBorderCol= input.color(color.new(color.gray, 50), "Border Color", group=grpI)
infoTextCol  = input.color(color.white, "Base Text Color", group=grpI)
infoHeaderBg = input.color(color.new(color.gray, 70), "Header Cell BG", group=grpI)
infoCellBg   = input.color(color.new(color.gray, 85), "Value Cell BG", group=grpI)
 
// ═══════════════════════════════════════════════════════════════════════
//  AUTO TIMEFRAME
// ═══════════════════════════════════════════════════════════════════════
tfMin = timeframe.multiplier * (timeframe.isseconds ? 1.0/60.0 : timeframe.isminutes ? 1.0 : timeframe.isdaily ? 1440.0 : timeframe.isweekly ? 10080.0 : 43200.0)
 
int    eff_n_terms   = n_terms
int    eff_pivotLen  = pivotLen
int    eff_divLook   = divLookback
int    eff_trendLen  = trendLen
int    eff_confirm   = confirmBars
float  scaleBoost    = 1.0
 
if autoTF
    if tfMin <= 15
        eff_n_terms  := 8
        eff_pivotLen := 5
        eff_divLook  := 8
        eff_trendLen := 20
        eff_confirm  := 1
        scaleBoost   := 4.0
    else if tfMin <= 240
        eff_n_terms  := 10
        eff_pivotLen := 8
        eff_divLook  := 12
        eff_trendLen := 34
        eff_confirm  := 2
        scaleBoost   := 2.0
    else if tfMin <= 1440
        eff_n_terms  := 12
        eff_pivotLen := 12
        eff_divLook  := 16
        eff_trendLen := 50
        eff_confirm  := 2
        scaleBoost   := 1.0
    else
        eff_n_terms  := 14
        eff_pivotLen := 15
        eff_divLook  := 25
        eff_trendLen := 80
        eff_confirm  := 3
        scaleBoost   := 0.6
 
int nUse = math.min(eff_n_terms, 12)
 
// ═══════════════════════════════════════════════════════════════════════
//  PERFORMANCE GUARD + AUTO-TUNE
// ═══════════════════════════════════════════════════════════════════════
perfOK   = bar_index <= perfGuardMax
autoOn   = autoBTune and perfOK
 
f_entropy(float bv, float av, int n_) =>
    int win = math.min(tuneEvery, bar_index + 1)
    float scl = math.pi / (math.pow(bv, n_ - 1) * 5000.0)
    array<float> powA = array.new<float>(n_)
    array.set(powA, 0, 1.0)
    for nn = 1 to n_ - 1
        array.set(powA, nn, array.get(powA, nn - 1) * av)
    float prevVal = na
    float sumDiffSq = 0.0
    float s = 0.0, s2 = 0.0
    int cnt = 0
    for i = 0 to win - 1 by 2
        int xi = bar_index - i
        float v = 0.0
        float bp = 1.0
        for nn = 0 to n_ - 1
            v += array.get(powA, nn) * math.cos(bp * xi * scl)
            bp *= bv
        float denom = av == 1.0 ? n_ : (1 - math.pow(av, n_)) / (1 - av)
        v := v / math.max(denom, 1e-10)
        if not na(prevVal)
            sumDiffSq += math.pow(v - prevVal, 2)
        prevVal := v
        s += v
        s2 += v * v
        cnt += 1
    float var_ = cnt > 1 ? s2 / cnt - math.pow(s / cnt, 2) : 0.0
    float diffVar = cnt > 1 ? sumDiffSq / (cnt - 1) : 0.0
    diffVar / math.max(var_, 1e-10)
 
var float tunedB = na
var int   lastTuneBar = na
if autoOn and (na(lastTuneBar) or bar_index - lastTuneBar >= tuneEvery)
    float bestB = b
    float bestScore = -1.0
    for k = 0 to tuneSteps
        float bv = bMin + (bMax - bMin) * k / tuneSteps
        float sc = f_entropy(bv, a, nUse)
        if sc > bestScore
            bestScore := sc
            bestB := bv
    tunedB := bestB
    lastTuneBar := bar_index
 
float bEff = autoOn and not na(tunedB) ? tunedB : b
 
// ═══════════════════════════════════════════════════════════════════════
//  REGIME
// ═══════════════════════════════════════════════════════════════════════
ab = a * bEff
tol = 0.05
isFractal = ab > 1 + tol and a < 1
isCritical = math.abs(ab - 1) <= tol and a < 1
isSmooth = ab < 1 - tol or a >= 1
regimeStr = isFractal ? "FRACTAL" : isCritical ? "CRITICAL" : "SMOOTH"
regimeCol = isFractal ? color.new(#00c3ff, 88) : isCritical ? color.new(#ff9800, 88) : color.new(#9e9e9e, 90)
 
// ═══════════════════════════════════════════════════════════════════════
//  SCALE + ANCHOR + SUM  (continuous phase for Swing Pivot)
// ═══════════════════════════════════════════════════════════════════════
maxBars = 2000
bTop = math.pow(bEff, nUse - 1)
baseScale = math.pi / (bTop * maxBars)
autoScale = baseScale * scaleBoost
scaleVal = scaleMode == "Auto" ? autoScale : scale_factor
 
var int anchorIdx = 0
var int fixedIdx = na
var float phaseNudge = 0.0          // compensates so argument stays continuous
 
ph = ta.pivothigh(eff_pivotLen, eff_pivotLen)
pl = ta.pivotlow(eff_pivotLen, eff_pivotLen)
 
if anchorMode == "Swing Pivot" and (not na(ph) or not na(pl))
    float oldRawX = float(bar_index - anchorIdx)
    anchorIdx := bar_index - eff_pivotLen
    float newRawX = float(bar_index - anchorIdx)
    phaseNudge += oldRawX - newRawX   // keep total x continuous
 
if anchorMode == "Fixed Start" and na(fixedIdx) and time >= fixedStartTime
    fixedIdx := bar_index
 
float rawX = anchorMode == "Fixed Start" ? (na(fixedIdx) ? na : float(bar_index - fixedIdx)) : float(bar_index - anchorIdx)
float x = na(rawX) ? na : rawX + (anchorMode == "Swing Pivot" ? phaseNudge : 0.0)
 
float normDenom = 1.0
if normalize
    normDenom := a == 1.0 ? nUse : (1 - math.pow(a, nUse)) / (1 - a)
    normDenom := math.max(normDenom, 1e-10)
 
float osc_raw = 0.0
for n = 0 to nUse - 1
    osc_raw += math.pow(a, n) * math.cos(math.pow(bEff, n) * x * scaleVal)
osc_raw := osc_raw / normDenom
 
float osc_sma = ta.sma(osc_raw, smoothLen)
float fractal_osc = (smoothLen > 1 ? osc_sma : osc_raw) * (invrt ? -1 : 1)
 
// ═══════════════════════════════════════════════════════════════════════
//  TREND FILTER
// ═══════════════════════════════════════════════════════════════════════
[stL, stD] = ta.supertrend(stMult, eff_trendLen)
float stLine = stL
int   stDir  = int(stD)
 
float emaT = ta.ema(close, eff_trendLen)
float smaT = ta.sma(close, eff_trendLen)
 
bool trendUp = false
bool trendDn = false
if useTrend
    if trendType == "EMA"
        trendUp := close > emaT
        trendDn := close < emaT
    else if trendType == "SMA"
        trendUp := close > smaT
        trendDn := close < smaT
    else
        trendUp := stDir < 0
        trendDn := stDir > 0
 
// ═══════════════════════════════════════════════════════════════════════
//  CONFIRMED ZERO-CROSS
// ═══════════════════════════════════════════════════════════════════════
var int crossSide  = 0
var int barsHeld   = 0
var int pendingDir = 0
 
sgn = fractal_osc > 0 ? 1 : fractal_osc < 0 ? -1 : 0
 
bool rawConfirmedBull = false
bool rawConfirmedBear = false
 
if sgn != 0
    if crossSide == 0
        crossSide := sgn
    else if sgn == crossSide
        pendingDir := 0
        barsHeld   := 0
    else
        if sgn == pendingDir
            barsHeld += 1
        else
            pendingDir := sgn
            barsHeld   := 1
        if barsHeld >= eff_confirm
            rawConfirmedBull := sgn == 1
            rawConfirmedBear := sgn == -1
            crossSide  := sgn
            pendingDir := 0
            barsHeld   := 0
 
gatedBull = rawConfirmedBull and (not useTrend or trendUp or allowCounter)
gatedBear = rawConfirmedBear and (not useTrend or trendDn or allowCounter)
 
plotshape(rawConfirmedBull, "Bull Cross", shape.triangleup,   location.bottom, color.new(#00c3ff, gatedBull ? 0 : 70), size=size.tiny, offset=-eff_confirm + 1)
plotshape(rawConfirmedBear, "Bear Cross", shape.triangledown, location.top,    color.new(#fbc02d, gatedBear ? 0 : 70), size=size.tiny, offset=-eff_confirm + 1)
 
// ═══════════════════════════════════════════════════════════════════════
//  DIVERGENCE
// ═══════════════════════════════════════════════════════════════════════
ph2 = ta.pivothigh(close, eff_divLook, eff_divLook)
pl2 = ta.pivotlow(close,  eff_divLook, eff_divLook)
 
var float prevPHprice = na
var int   prevPHbar   = na
var float prevPHosc   = na
var float prevPLprice = na
var int   prevPLbar   = na
var float prevPLosc   = na
 
bool bullDiv = false
bool bearDiv = false
bool bullHid = false
bool bearHid = false
 
int bullDivX1 = na, int bullDivX2 = na
int bearDivX1 = na, int bearDivX2 = na
int bullHidX1 = na, int bullHidX2 = na
int bearHidX1 = na, int bearHidX2 = na
 
float bullDivOsc1 = na, float bullDivOsc2 = na
float bearDivOsc1 = na, float bearDivOsc2 = na
float bullHidOsc1 = na, float bullHidOsc2 = na
float bearHidOsc1 = na, float bearHidOsc2 = na
 
oscAtPH = fractal_osc[eff_divLook]
oscAtPL = fractal_osc[eff_divLook]
 
if not na(ph2)
    if not na(prevPHprice) and bar_index - prevPHbar <= divRange
        if ph2 > prevPHprice and oscAtPH < prevPHosc
            bearDiv := true
            bearDivX1 := prevPHbar
            bearDivX2 := bar_index - eff_divLook
            bearDivOsc1 := prevPHosc
            bearDivOsc2 := oscAtPH
        if useHiddenDiv and ph2 < prevPHprice and oscAtPH > prevPHosc
            bearHid := true
            bearHidX1 := prevPHbar
            bearHidX2 := bar_index - eff_divLook
            bearHidOsc1 := prevPHosc
            bearHidOsc2 := oscAtPH
    prevPHprice := ph2
    prevPHbar := bar_index - eff_divLook
    prevPHosc := oscAtPH
 
if not na(pl2)
    if not na(prevPLprice) and bar_index - prevPLbar <= divRange
        if pl2 < prevPLprice and oscAtPL > prevPLosc
            bullDiv := true
            bullDivX1 := prevPLbar
            bullDivX2 := bar_index - eff_divLook
            bullDivOsc1 := prevPLosc
            bullDivOsc2 := oscAtPL
        if useHiddenDiv and pl2 > prevPLprice and oscAtPL < prevPLosc
            bullHid := true
            bullHidX1 := prevPLbar
            bullHidX2 := bar_index - eff_divLook
            bullHidOsc1 := prevPLosc
            bullHidOsc2 := oscAtPL
    prevPLprice := pl2
    prevPLbar := bar_index - eff_divLook
    prevPLosc := oscAtPL
 
plotshape(bullDiv, "Bull Divergence", shape.labelup,   location.bottom, color.new(#26a69a, 0),  size=size.tiny, text="DIV",   textcolor=color.white)
plotshape(bearDiv, "Bear Divergence", shape.labeldown, location.top,    color.new(#ef5350, 0),  size=size.tiny, text="DIV",   textcolor=color.white)
plotshape(bullHid, "Bull Hidden",     shape.labelup,   location.bottom, color.new(#26a69a, 40), size=size.tiny, text="hDIV", textcolor=color.white)
plotshape(bearHid, "Bear Hidden",     shape.labeldown, location.top,    color.new(#ef5350, 40), size=size.tiny, text="hDIV", textcolor=color.white)
 
if showDivLines and barstate.isconfirmed
    if bullDiv
        line.new(bullDivX1, bullDivOsc1, bullDivX2, bullDivOsc2, color=#26a69a, style=line.style_dashed, width=1)
    if bearDiv
        line.new(bearDivX1, bearDivOsc1, bearDivX2, bearDivOsc2, color=#ef5350, style=line.style_dashed, width=1)
    if bullHid
        line.new(bullHidX1, bullHidOsc1, bullHidX2, bullHidOsc2, color=color.new(#26a69a, 40), style=line.style_dotted, width=1)
    if bearHid
        line.new(bearHidX1, bearHidOsc1, bearHidX2, bearHidOsc2, color=color.new(#ef5350, 40), style=line.style_dotted, width=1)
 
// ═══════════════════════════════════════════════════════════════════════
//  REGIME CHANGE + ST MIRROR
// ═══════════════════════════════════════════════════════════════════════
var string prevRegime = na
regimeChanged = regimeStr != prevRegime
prevRegime := regimeStr
 
stMirror = showSTOsc ? (stDir < 0 ? stMirrorLevel : stDir > 0 ? -stMirrorLevel : na) : na
plot(stMirror, "ST Mirror", color=color.new(color.gray, 55), style=plot.style_circles, linewidth=1)
 
// ═══════════════════════════════════════════════════════════════════════
//  TRADE PLAN (force_overlay lines)
// ═══════════════════════════════════════════════════════════════════════
var int   posState  = 0
var float entryPx   = na
var float slPx      = na
var float tpPx      = na
var int   entryBar  = na
var line  slLine    = na
var line  tpLine    = na
var line  entryLine = na
var label entryLbl  = na
var label statusLbl = na
 
atr = ta.atr(atrLen)
 
bool canLong  = gatedBull and (planDir == "Long" or planDir == "Both") and (not requireDiv or bullDiv or bullHid)
bool canShort = gatedBear and (planDir == "Short" or planDir == "Both") and (not requireDiv or bearDiv or bearHid)
if requireNoOpp and gatedBull and gatedBear
    canLong  := false
    canShort := false
 
bool closeLong  = false
bool closeShort = false
 
if usePlan and barstate.isconfirmed
    if posState == 1 and (low <= slPx or high >= tpPx or gatedBear)
        closeLong := true
    if posState == -1 and (high >= slPx or low <= tpPx or gatedBull)
        closeShort := true
 
msg(string kind, string dir, float px, float sl, float tp, string reason) =>
    if useJson
        '{"type":"' + kind + '","dir":"' + dir + '","reason":"' + reason + '","px":' + str.tostring(px, "#.#####") + ',"sl":' + str.tostring(sl, "#.#####") + ',"tp":' + str.tostring(tp, "#.#####") + ',"regime":"' + regimeStr + '","ab":' + str.tostring(ab, "#.###") + ',"sym":"' + syminfo.ticker + '","tf":"' + timeframe.period + '","time":' + str.tostring(time) + '}'
    else
        "Weierstrass " + kind + " " + dir + " | " + reason + " px=" + str.tostring(px, "#.#####") + " sl=" + str.tostring(sl, "#.#####") + " tp=" + str.tostring(tp, "#.#####") + " | " + regimeStr + " a·b=" + str.tostring(ab, "#.###")
 
if usePlan and barstate.isconfirmed
    if closeLong or closeShort
        alert(msg("EXIT", closeLong ? "LONG" : "SHORT", close, slPx, tpPx, "SL/TP/Opp"), alert.freq_once_per_bar_close)
        posState := 0
        entryPx := na
        if not na(entryLine)
            line.delete(entryLine)
            entryLine := na
        if not na(slLine)
            line.delete(slLine)
            slLine := na
        if not na(tpLine)
            line.delete(tpLine)
            tpLine := na
        if not na(entryLbl)
            label.delete(entryLbl)
            entryLbl := na
        if not na(statusLbl)
            label.delete(statusLbl)
            statusLbl := na
 
    if posState == 0 and canLong
        entryPx  := close
        slPx     := close - slAtr * atr
        tpPx     := close + tpAtr * atr
        entryBar := bar_index
        posState := 1
        alert(msg("ENTRY", "LONG", close, slPx, tpPx, requireDiv ? "Cross+DIV" : "Cross"), alert.freq_once_per_bar_close)
    else if posState == 0 and canShort
        entryPx  := close
        slPx     := close + slAtr * atr
        tpPx     := close - tpAtr * atr
        entryBar := bar_index
        posState := -1
        alert(msg("ENTRY", "SHORT", close, slPx, tpPx, requireDiv ? "Cross+DIV" : "Cross"), alert.freq_once_per_bar_close)
 
if usePlan and showPlanBox and barstate.isconfirmed
    if posState == 0
        if not na(entryLine)
            line.delete(entryLine)
            entryLine := na
        if not na(slLine)
            line.delete(slLine)
            slLine := na
        if not na(tpLine)
            line.delete(tpLine)
            tpLine := na
        if not na(entryLbl)
            label.delete(entryLbl)
            entryLbl := na
        if not na(statusLbl)
            label.delete(statusLbl)
            statusLbl := na
    else
        int rightBar = bar_index + 30
        if na(entryLine)
            entryLine := line.new(entryBar, entryPx, rightBar, entryPx, color=#ffffff, style=line.style_solid, width=1, force_overlay=true)
            slLine    := line.new(entryBar, slPx,    rightBar, slPx,    color=#ef5350, style=line.style_dashed, width=1, force_overlay=true)
            tpLine    := line.new(entryBar, tpPx,    rightBar, tpPx,    color=#26a69a, style=line.style_dashed, width=1, force_overlay=true)
            entryLbl  := label.new(rightBar, entryPx, (posState == 1 ? "L " : "S ") + "Entry", style=label.style_label_left, color=color.new(color.gray, 70), textcolor=color.white, size=size.small, force_overlay=true)
        else
            line.set_x2(entryLine, rightBar)
            line.set_x2(slLine,    rightBar)
            line.set_x2(tpLine,    rightBar)
            label.set_x(entryLbl,  rightBar)
 
        string stTxtLbl = posState == 1 ? "LONG" : "SHORT"
        if na(statusLbl)
            statusLbl := label.new(bar_index, high, stTxtLbl, style=label.style_label_down, color=posState == 1 ? color.new(#26a69a, 40) : color.new(#ef5350, 40), textcolor=color.white, size=size.tiny, force_overlay=true)
        else
            label.set_x(statusLbl, bar_index)
            label.set_y(statusLbl, high)
            label.set_text(statusLbl, stTxtLbl)
 
// ═══════════════════════════════════════════════════════════════════════
//  NON-PLAN ALERTS
// ═══════════════════════════════════════════════════════════════════════
msgSimple(string kind, string dir) =>
    if useJson
        '{"type":"' + kind + '","dir":"' + dir + '","regime":"' + regimeStr + '","ab":' + str.tostring(ab, "#.###") + ',"osc":' + str.tostring(fractal_osc, "#.####") + ',"price":' + str.tostring(close, "#.#####") + ',"sym":"' + syminfo.ticker + '","tf":"' + timeframe.period + '","time":' + str.tostring(time) + '}'
    else
        "Weierstrass " + kind + " " + dir + " | regime=" + regimeStr + " a·b=" + str.tostring(ab, "#.###") + " osc=" + str.tostring(fractal_osc, "#.####") + " price=" + str.tostring(close, "#.#####")
 
if alertOnCross and gatedBull
    alert(msgSimple("CROSS", "BULL"), alert.freq_once_per_bar_close)
if alertOnCross and gatedBear
    alert(msgSimple("CROSS", "BEAR"), alert.freq_once_per_bar_close)
if alertOnReg and regimeChanged
    alert(msgSimple("REGIME", regimeStr), alert.freq_once_per_bar_close)
if alertOnDiv and bullDiv
    alert(msgSimple("DIVERGENCE", "BULL"), alert.freq_once_per_bar_close)
if alertOnDiv and bearDiv
    alert(msgSimple("DIVERGENCE", "BEAR"), alert.freq_once_per_bar_close)
if alertOnDiv and bullHid
    alert(msgSimple("HIDDEN_DIV", "BULL"), alert.freq_once_per_bar_close)
if alertOnDiv and bearHid
    alert(msgSimple("HIDDEN_DIV", "BEAR"), alert.freq_once_per_bar_close)
 
// ═══════════════════════════════════════════════════════════════════════
//  PLOTS
// ═══════════════════════════════════════════════════════════════════════
oscCol = ta.change(fractal_osc) > 0 ? #00c3ff : #fbc02d
plot(fractal_osc, "Weierstrass", color=oscCol, linewidth=2)
hline(0, "Zero", color=color.new(color.gray, 70))
bgcolor(showRegime ? regimeCol : na, title="Regime Background")
 
// ═══════════════════════════════════════════════════════════════════════
//  INFO TABLE
// ═══════════════════════════════════════════════════════════════════════
posFromStr(string s) =>
    s == "Top Left" ? position.top_left : s == "Top Right" ? position.top_right : s == "Bottom Left" ? position.bottom_left : s == "Bottom Right" ? position.bottom_right : s == "Middle Left" ? position.middle_left : position.middle_right
 
sizeFromStr(string s) =>
    s == "Tiny" ? size.tiny : s == "Small" ? size.small : s == "Normal" ? size.normal : s == "Large" ? size.large : size.huge
 
tt(string s) => showInfoTips ? s : ""
 
bgBase = color.new(infoBgColor, infoBgTransp)
bgHead = color.new(infoHeaderBg, math.max(0, infoBgTransp - 10))
bgCell = color.new(infoCellBg, math.max(0, infoBgTransp - 5))
bordCol = infoBorderCol
txtCol = infoTextCol
 
isHoriz = infoLayout == "Horizontal"
nCols = isHoriz ? 11 : 2
nRows = isHoriz ? 2 : 11
 
var table info = na
if showInfo and barstate.islast
    table.delete(info)
    info := table.new(posFromStr(infoPos), nCols, nRows, bgcolor=bgBase, border_width=1, border_color=bordCol, frame_width=1, frame_color=bordCol)
 
if showInfo and barstate.islast
    ts = sizeFromStr(infoTxtSize)
 
    regimeColTxt = isFractal ? #00c3ff : isCritical ? #ff9800 : #9e9e9e
    bValTxt = str.tostring(bEff, "#.####") + (autoOn ? " ★" : autoBTune and not perfOK ? " ⚠" : "")
    bValCol = autoOn and not na(tunedB) ? #26a69a : txtCol
    trendTxt = useTrend ? (trendUp ? "UP" : trendDn ? "DOWN" : "—") : "off"
    trendColTxt = trendUp ? #26a69a : trendDn ? #ef5350 : #9e9e9e
    stTxt = stDir < 0 ? "Bull" : stDir > 0 ? "Bear" : "—"
    stColTxt = stDir < 0 ? #26a69a : stDir > 0 ? #ef5350 : #9e9e9e
    divTxt = bullDiv ? "BULL" : bearDiv ? "BEAR" : bullHid ? "hBULL" : bearHid ? "hBEAR" : "—"
    divColTxt = str.contains(divTxt, "BULL") ? #26a69a : str.contains(divTxt, "BEAR") ? #ef5350 : #9e9e9e
    planTxt = usePlan ? (posState == 1 ? "LONG" : posState == -1 ? "SHORT" : "flat") : "off"
    planColTxt = posState == 1 ? #26a69a : posState == -1 ? #ef5350 : #9e9e9e
    pnl = posState != 0 ? (posState == 1 ? (close - entryPx) / atr : (entryPx - close) / atr) : na
    pnlTxt = na(pnl) ? "—" : str.tostring(pnl, "#.##") + "R"
    pnlColTxt = na(pnl) ? #9e9e9e : pnl > 0 ? #26a69a : #ef5350
    perfTxt = perfOK ? "ok" : "throttled"
    perfColTxt = perfOK ? #26a69a : #ff9800
 
    labels = array.from("Regime", "a·b", "b (eff)", "Scale", "Osc", "Trend", "ST Dir", "Last Div", "Plan", "P&L (ATR)", "Perf")
    vals = array.from(str.tostring(ab, "#.###"), bValTxt, str.tostring(scaleVal, "#.########"), str.tostring(fractal_osc, "#.####"), trendTxt, stTxt, divTxt, planTxt, pnlTxt, perfTxt)
    valCols = array.from(txtCol, bValCol, txtCol, txtCol, trendColTxt, stColTxt, divColTxt, planColTxt, pnlColTxt, perfColTxt)
 
    tips = array.from(
         "Product of a and effective b (drives FRACTAL / CRITICAL / SMOOTH)",
         "Effective frequency factor (★ = currently auto-tuned)",
         "Scaling applied to the phase argument",
         "Current normalized Weierstrass oscillator value",
         "Trend-filter state (UP / DOWN / off)",
         "Supertrend direction mirrored on the oscillator",
         "Most recent regular or hidden divergence",
         "Trade-plan state (LONG / SHORT / flat / off)",
         "Open trade P&L expressed in ATR multiples",
         "Auto-tune performance guard status"
         )
 
    if isHoriz
        table.cell(info, 0, 0, "Regime", text_color=txtCol, text_size=ts, bgcolor=bgHead, tooltip=tt("Current regime based on a·b product"))
        table.cell(info, 0, 1, regimeStr, text_color=regimeColTxt, text_size=ts, bgcolor=bgCell, tooltip=tt("FRACTAL (ab>1), CRITICAL (~1), or SMOOTH"))
        for i = 0 to array.size(vals) - 1
            int ci = i + 1
            table.cell(info, ci, 0, array.get(labels, i + 1), text_color=txtCol, text_size=ts, bgcolor=bgHead, tooltip=tt(array.get(tips, i)))
            table.cell(info, ci, 1, array.get(vals, i), text_color=array.get(valCols, i), text_size=ts, bgcolor=bgCell, tooltip=tt(array.get(tips, i)))
    else
        table.cell(info, 0, 0, "Regime", text_color=txtCol, text_size=ts, bgcolor=bgHead, tooltip=tt("Current regime based on a·b product"))
        table.cell(info, 1, 0, regimeStr, text_color=regimeColTxt, text_size=ts, bgcolor=bgHead, tooltip=tt("FRACTAL (ab>1), CRITICAL (~1), or SMOOTH"))
        for i = 0 to array.size(vals) - 1
            int ri = i + 1
            table.cell(info, 0, ri, array.get(labels, i + 1), text_color=txtCol, text_size=ts, bgcolor=bgCell, tooltip=tt(array.get(tips, i)))
            table.cell(info, 1, ri, array.get(vals, i), text_color=array.get(valCols, i), text_size=ts, bgcolor=bgCell, tooltip=tt(array.get(tips, i)))

← 返回列表