Adaptive Momentum Fusion [WillyAlgoTrader]

WillyAlgoTrader · study · 502 行 · 点赞 2,754 · TradingView 原页

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

Pine Script

//@version=6
// ══════════════════════════════════════════════════════════
// ADAPTIVE MOMENTUM FUSION [WillyAlgoTrader]
// ══════════════════════════════════════════════════════════
// Author:  Willy | WillyAlgoTrader
// Version: 1.0.0
// Date:    2025-06-01
 
 
indicator(
    title            = "Adaptive Momentum Fusion [WillyAlgoTrader]",
    shorttitle       = "AMF",
    overlay          = false,
    precision        = 2,
    max_labels_count = 500,
    max_lines_count  = 500)
 
// ══════════════════════════════════════
// CONSTANTS
// ══════════════════════════════════════
GRP_MAIN   = "⚙️ Main Settings"
GRP_VISUAL = "🎨 Visual Settings"
GRP_FILTER = "🔍 Filters"
GRP_DASH   = "📊 Dashboard"
GRP_ALERT  = "🔔 Alerts"
GRP_COLORS = "🎨 Colors"
GRP_ADV    = "🔧 Advanced"
 
INDICATOR_VERSION = "v1.0.0"
 
// ══════════════════════════════════════
// INPUTS
// ══════════════════════════════════════
 
// ── Main Settings ───────────────────
sourceInput = input.source(close, "Source", group = GRP_MAIN, tooltip = "Price source for calculation.\nTypically 'close'. Use 'hlc3' or 'ohlc4' for smoother readings")
engineInput = input.string("Efficiency", "Adaptation Engine", options = ["Efficiency", "Volatility", "Fractal", "Momentum", "Volume", "Composite"], group = GRP_MAIN, tooltip = "Core adaptation method:\n• Efficiency: Kaufman-style efficiency ratio — best all-around\n• Volatility: ATR-normalized responsiveness — great for ranging\n• Fractal: Hurst exponent estimation — detects trending vs mean-reverting\n• Momentum: Rate-of-change adaptive — fast reaction to breakouts\n• Volume: Volume-weighted adaptation — confirms with participation\n• Composite: Blends all engines — most robust but slightly slower")
fastLenInput = input.int(8, "Fast Length", minval = 2, maxval = 100, step = 1, group = GRP_MAIN, tooltip = "Fast adaptive MA period.\nLower = more responsive, more noise\nHigher = smoother, more lag\nRecommended: 5–15")
slowLenInput = input.int(21, "Slow Length", minval = 5, maxval = 200, step = 1, group = GRP_MAIN, tooltip = "Slow adaptive MA period.\nShould be 2–4x the fast length\nRecommended: 15–50")
signalLenInput = input.int(7, "Signal Length", minval = 2, maxval = 50, step = 1, group = GRP_MAIN, tooltip = "Signal line smoothing period.\nLower = faster crossovers, more whipsaws\nHigher = smoother, fewer false signals\nRecommended: 5–12")
modeInput = input.string("MACD", "Output Mode", options = ["MACD", "PPO"], group = GRP_MAIN, tooltip = "MACD = absolute difference (price-scaled)\nPPO = percentage difference (normalized, better for cross-market comparison)")
 
// ── Filters ─────────────────────────
useDivergenceInput = input.bool(true, "Detect Divergences", group = GRP_FILTER, tooltip = "Scan for regular and hidden divergences between price and momentum.\nRegular = potential reversal\nHidden = trend continuation")
divLookbackInput = input.int(30, "Divergence Lookback", minval = 10, maxval = 100, step = 5, group = GRP_FILTER, tooltip = "How far back to search for pivot points when detecting divergences.\nHigher = catches larger divergences but may lag\nRecommended: 20–50")
useZeroCrossInput = input.bool(true, "Zero Line Cross Signals", group = GRP_FILTER, tooltip = "Generate signals when the oscillator crosses the zero line.\nUseful as trend confirmation filter")
 
// ── Visual Settings ─────────────────
showSignalsInput = input.bool(false, "Show Buy/Sell Signals", group = GRP_VISUAL, tooltip = "Display signal arrows on crossovers")
labelSizeInput = input.string("Small", "Label Size", options = ["Auto", "Tiny", "Small", "Normal", "Large"], group = GRP_VISUAL, tooltip = "Size of signal and divergence labels.\n• Tiny: minimal footprint\n• Small: default, readable on most screens\n• Normal: larger, good for presentations\n• Large: maximum visibility\n• Auto: Small for signals, Tiny for secondary")
showHistInput = input.bool(true, "Show Histogram", group = GRP_VISUAL, tooltip = "Display momentum histogram bars")
showFillInput = input.bool(true, "Show Fill Between Lines", group = GRP_VISUAL, tooltip = "Shade area between oscillator and signal line")
showDivInput = input.bool(true, "Show Divergence Lines", group = GRP_VISUAL, tooltip = "Draw lines connecting divergence pivots")
showBgInput = input.bool(false, "Show Background Color", group = GRP_VISUAL, tooltip = "Tint background based on momentum direction")
showWatermarkInput = input.bool(true, "Show Watermark", group = GRP_VISUAL, tooltip = "Display 'WillyAlgoTrader - by Willy' watermark on chart")
 
// ── Dashboard ───────────────────────
showDashInput = input.bool(false, "Show Dashboard", group = GRP_DASH, tooltip = "Display info panel with trend, signal, and strength")
dashPosStr = input.string("Top Right", "Dashboard Position", options = ["Top Left", "Top Right", "Bottom Left", "Bottom Right"], group = GRP_DASH, tooltip = "Corner placement of the dashboard panel")
 
// ── Alerts ──────────────────────────
webhookInput = input.bool(false, "Webhook JSON Format", group = GRP_ALERT, tooltip = "Send alerts in JSON format for webhook integrations (3Commas, Autoview, etc.)")
 
// ── Colors ──────────────────────────
bullColorInput = input.color(#00E676, "Bull", inline = "col1", group = GRP_COLORS)
bearColorInput = input.color(#FF5252, "Bear", inline = "col1", group = GRP_COLORS)
neutralColorInput = input.color(#FFEB3B, "Neutral", inline = "col1", group = GRP_COLORS)
 
// ── Advanced ────────────────────────
themeInput = input.string("Auto", "Theme", options = ["Auto", "Dark", "Light"], group = GRP_ADV, tooltip = "Chart color theme.\n• Auto: detects from chart background\n• Dark: optimized for dark backgrounds\n• Light: optimized for light/white backgrounds")
smoothFactorInput = input.float(0.7, "Jitter Reduction", minval = 0.0, maxval = 1.0, step = 0.1, group = GRP_ADV, tooltip = "Additional smoothing to reduce signal line jitter.\n0.0 = no extra smoothing\n1.0 = maximum smoothing\nRecommended: 0.5–0.8")
 
// ══════════════════════════════════════
// THEME DETECTION & COLORS
// ══════════════════════════════════════
isDark = switch themeInput
    "Dark"  => true
    "Light" => false
    => color.r(chart.bg_color) < 128
 
TEXT_COLOR    = isDark ? #E0E0E0 : #1A1A1A
TEXT_MUTED    = isDark ? color.new(#9E9E9E, 0) : color.new(#757575, 0)
TEXT_BRIGHT   = isDark ? #FFFFFF : #000000
TABLE_BG     = isDark ? color.new(#131722, 5) : color.new(#FFFFFF, 5)
TABLE_BORDER = isDark ? color.new(#2A2E39, 0) : color.new(#D0D0D0, 0)
TABLE_ROW_ALT = isDark ? color.new(#1C2030, 0) : color.new(#F0F4F8, 0)
HEADER_BG    = color.new(#2962FF, 0)
HEADER_TEXT  = #FFFFFF
LABEL_TEXT   = #FFFFFF
LINE_SUBTLE  = isDark ? color.new(#555555, 0) : color.new(#AAAAAA, 0)
WM_COLOR     = isDark ? color.new(#FFFFFF, 80) : color.new(#000000, 80)
 
BULL_BG = color.new(bullColorInput, 85)
BEAR_BG = color.new(bearColorInput, 85)
 
// Label size resolution
LABEL_SIZE_MAIN = switch labelSizeInput
    "Tiny"   => size.tiny
    "Small"  => size.small
    "Normal" => size.normal
    "Large"  => size.large
    => size.small
 
LABEL_SIZE_SEC = switch labelSizeInput
    "Tiny"   => size.tiny
    "Small"  => size.tiny
    "Normal" => size.small
    "Large"  => size.normal
    => size.tiny
 
// ══════════════════════════════════════
// FUNCTIONS
// ══════════════════════════════════════
 
// Безопасное деление
safeDiv(float num, float den, float fallback = 0.0) =>
    den != 0 and not na(num) and not na(den) ? num / den : fallback
 
// ── Kaufman Efficiency Ratio ────────
efficiencyRatio(float src, int len) =>
    float direction = math.abs(src - nz(src[len], src))
    float volatility = math.sum(math.abs(src - nz(src[1], src)), len)
    safeDiv(direction, volatility, 0.5)
 
// ── Adaptive EMA core ───────────────
adaptiveEma(float src, float alpha) =>
    var float result = na
    float safeSrc = nz(src, 0.0)
    float safeAlpha = math.max(0.01, math.min(alpha, 1.0))
    result := na(result) ? safeSrc : safeAlpha * safeSrc + (1.0 - safeAlpha) * result
    result
 
// ── Engine: Efficiency (Kaufman AMA style) ──
engineEfficiency(float src, int len) =>
    float er = efficiencyRatio(src, len)
    float fastSc = 2.0 / (2.0 + 1.0)
    float slowSc = 2.0 / (30.0 + 1.0)
    float sc = math.pow(er * (fastSc - slowSc) + slowSc, 2)
    adaptiveEma(src, sc)
 
// ── Engine: Volatility (ATR-based) ──
engineVolatility(float src, int len) =>
    float atrVal = nz(ta.atr(len), 0.0)
    float atrSma = nz(ta.sma(ta.atr(len), len * 2), atrVal)
    float volRatio = safeDiv(atrVal, atrSma, 1.0)
    float baseAlpha = 2.0 / (len + 1.0)
    float alpha = math.max(0.01, math.min(baseAlpha * volRatio, 1.0))
    adaptiveEma(src, alpha)
 
// ── Engine: Fractal (Hurst-inspired) ──
engineFractal(float src, int len) =>
    int half = math.max(2, math.floor(len / 2))
    float rangeFull = nz(ta.highest(src, len), src) - nz(ta.lowest(src, len), src)
    float rangeH1 = nz(ta.highest(src, half), src) - nz(ta.lowest(src, half), src)
    float rangeH2 = nz(ta.highest(src[half], half), src) - nz(ta.lowest(src[half], half), src)
    float sumHalf = rangeH1 + rangeH2
    float fracDim = rangeFull > 0 and sumHalf > 0 ? 1.0 + safeDiv(math.log(sumHalf), math.log(2.0 * rangeFull > 0 ? 2.0 * rangeFull : 1.0), 0.5) : 1.5
    float alpha = math.max(0.01, math.min(math.exp(-4.6 * (fracDim - 1.0)), 1.0))
    adaptiveEma(src, alpha)
 
// ── Engine: Momentum (ROC-based) ────
engineMomentum(float src, int len) =>
    float roc = safeDiv(src - nz(src[len], src), nz(src[len], src), 0.0) * 100.0
    float rocAbs = math.abs(roc)
    float rocMax = nz(ta.highest(math.abs(safeDiv(src - nz(src[len], src), nz(src[len], src), 0.0) * 100.0), len * 2), rocAbs)
    float norm = rocMax > 0 ? math.min(rocAbs / rocMax, 1.0) : 0.5
    float baseAlpha = 2.0 / (len + 1.0)
    float alpha = math.max(0.01, math.min(baseAlpha + norm * (1.0 - baseAlpha) * 0.5, 1.0))
    adaptiveEma(src, alpha)
 
// ── Engine: Volume ──────────────────
engineVolume(float src, int len) =>
    bool hasVol = nz(volume, 0) > 0
    float volSma = hasVol ? nz(ta.sma(volume, len), 1.0) : 1.0
    float volRatio = hasVol ? safeDiv(volume, volSma, 1.0) : 1.0
    float baseAlpha = 2.0 / (len + 1.0)
    float alpha = math.max(0.01, math.min(baseAlpha * math.sqrt(math.max(volRatio, 0.01)), 1.0))
    adaptiveEma(src, alpha)
 
// ── Engine: Composite (blended) ─────
engineComposite(float src, int len) =>
    float e1 = engineEfficiency(src, len)
    float e2 = engineVolatility(src, len)
    float e3 = engineFractal(src, len)
    float e4 = engineMomentum(src, len)
    float e5 = engineVolume(src, len)
    bool hasVol = nz(volume, 0) > 0
    float result = hasVol ? (e1 * 0.30 + e2 * 0.20 + e3 * 0.20 + e4 * 0.15 + e5 * 0.15) : (e1 * 0.35 + e2 * 0.25 + e3 * 0.25 + e4 * 0.15)
    result
 
// ── Master dispatcher ───────────────
calcEngine(float src, int len) =>
    switch engineInput
        "Efficiency" => engineEfficiency(src, len)
        "Volatility" => engineVolatility(src, len)
        "Fractal"    => engineFractal(src, len)
        "Momentum"   => engineMomentum(src, len)
        "Volume"     => engineVolume(src, len)
        "Composite"  => engineComposite(src, len)
        => engineEfficiency(src, len)
 
// ── Jurik-style signal smoothing ────
jurikSmooth(float src, int len, float phase) =>
    float beta = 0.45 * (len - 1.0) / (0.45 * (len - 1.0) + 2.0)
    float alphaJ = math.pow(beta, 3)
    var float e0 = 0.0
    var float e1 = 0.0
    var float e2 = 0.0
    float safeSrc = nz(src, 0.0)
    e0 := (1.0 - alphaJ) * safeSrc + alphaJ * nz(e0[1], safeSrc)
    e1 := (safeSrc - e0) * (1.0 - beta) + beta * nz(e1[1], 0.0)
    e2 := (e0 + phase * e1 - nz(e2[1], e0 + phase * e1)) * math.pow(1.0 - alphaJ, 2) + math.pow(alphaJ, 2) * nz(e2[1], e0 + phase * e1)
    e2
 
// ── Pivot detection for divergence ──
pivotLow(float src, int lb, int rb) =>
    bool found = true
    float pivVal = nz(src[rb], 0.0)
    for i = 0 to lb + rb
        if i != rb
            if nz(src[i], pivVal) <= pivVal
                found := false
                break
    found ? pivVal : float(na)
 
pivotHigh(float src, int lb, int rb) =>
    bool found = true
    float pivVal = nz(src[rb], 0.0)
    for i = 0 to lb + rb
        if i != rb
            if nz(src[i], pivVal) >= pivVal
                found := false
                break
    found ? pivVal : float(na)
 
// ══════════════════════════════════════
// DASHBOARD POSITION
// ══════════════════════════════════════
dashPos = switch dashPosStr
    "Top Left"     => position.top_left
    "Top Right"    => position.top_right
    "Bottom Left"  => position.bottom_left
    "Bottom Right" => position.bottom_right
    => position.top_right
 
// ══════════════════════════════════════
// CALCULATIONS
// ══════════════════════════════════════
 
// Прогрев
int WARMUP_BARS = math.max(slowLenInput * 2, 50)
bool isWarmedUp = bar_index >= WARMUP_BARS
 
// Adaptive MAs
float fastMA = calcEngine(sourceInput, fastLenInput)
float slowMA = calcEngine(sourceInput, slowLenInput)
 
// Oscillator
float osc = modeInput == "PPO" ? safeDiv(fastMA - slowMA, slowMA, 0.0) * 100.0 : fastMA - slowMA
 
// Signal line — Jurik smooth for reduced lag
float signalLine = jurikSmooth(osc, signalLenInput, smoothFactorInput)
 
// Histogram
float hist = nz(osc, 0.0) - nz(signalLine, 0.0)
 
// Momentum acceleration (histogram slope)
float histPrev = nz(hist[1], 0.0)
bool histAccelUp = hist > 0 and hist > histPrev
bool histDecelUp = hist > 0 and hist <= histPrev
bool histAccelDn = hist < 0 and hist < histPrev
bool histDecelDn = hist < 0 and hist >= histPrev
 
// Trend state
int trendState = osc > signalLine ? 1 : osc < signalLine ? -1 : 0
 
// ══════════════════════════════════════
// SIGNAL LOGIC
// ══════════════════════════════════════
 
// Crossover signals
bool bullCross = ta.crossover(osc, signalLine)
bool bearCross = ta.crossunder(osc, signalLine)
 
// Zero line crosses
bool zeroBullCross = useZeroCrossInput and ta.crossover(osc, 0.0)
bool zeroBearCross = useZeroCrossInput and ta.crossunder(osc, 0.0)
 
// Confirmed signals
bool confirmedBuy = bullCross and barstate.isconfirmed and isWarmedUp
bool confirmedSell = bearCross and barstate.isconfirmed and isWarmedUp
bool confirmedZeroBuy = zeroBullCross and barstate.isconfirmed and isWarmedUp
bool confirmedZeroSell = zeroBearCross and barstate.isconfirmed and isWarmedUp
 
// ── Divergence Detection ────────────
int pivotRb = 5
int pivotLb = divLookbackInput
 
float oscPivLo = pivotLow(osc, pivotLb, pivotRb)
float oscPivHi = pivotHigh(osc, pivotLb, pivotRb)
float prcPivLo = pivotLow(low, pivotLb, pivotRb)
float prcPivHi = pivotHigh(high, pivotLb, pivotRb)
 
var float prevOscLo = na
var float prevPrcLo = na
var int   prevLoBar = na
var float prevOscHi = na
var float prevPrcHi = na
var int   prevHiBar = na
 
var string divSignalStr = "None"
var color  divSignalCol = color.gray
 
// Regular bullish divergence: price lower low, osc higher low
bool regBullDiv = false
if not na(oscPivLo) and not na(prcPivLo) and useDivergenceInput
    if not na(prevOscLo) and not na(prevPrcLo)
        if prcPivLo < prevPrcLo and oscPivLo > prevOscLo
            regBullDiv := true
    prevOscLo := oscPivLo
    prevPrcLo := prcPivLo
    prevLoBar := bar_index - pivotRb
 
// Regular bearish divergence: price higher high, osc lower high
bool regBearDiv = false
if not na(oscPivHi) and not na(prcPivHi) and useDivergenceInput
    if not na(prevOscHi) and not na(prevPrcHi)
        if prcPivHi > prevPrcHi and oscPivHi < prevOscHi
            regBearDiv := true
    prevOscHi := oscPivHi
    prevPrcHi := prcPivHi
    prevHiBar := bar_index - pivotRb
 
// Track divergence state for dashboard
if regBullDiv
    divSignalStr := "Bull Div"
    divSignalCol := bullColorInput
else if regBearDiv
    divSignalStr := "Bear Div"
    divSignalCol := bearColorInput
 
// Decay divergence label after 20 bars
if not regBullDiv and not regBearDiv
    if bar_index > nz(prevLoBar, 0) + 20 and bar_index > nz(prevHiBar, 0) + 20
        divSignalStr := "None"
        divSignalCol := color.gray
 
// Signal strength scoring (0–100)
float strengthScore = 0.0
float absHist = math.abs(hist)
float histMax = nz(ta.highest(math.abs(hist), 50), absHist)
float histNorm = histMax > 0 ? math.min(absHist / histMax * 100.0, 100.0) : 50.0
strengthScore := histNorm
 
// ══════════════════════════════════════
// PLOTS & VISUALS
// ══════════════════════════════════════
 
// Zero line
hline(0, "Zero", color = LINE_SUBTLE, linestyle = hline.style_dotted, linewidth = 1)
 
// Histogram colors
color histColor = histAccelUp ? color.new(bullColorInput, 15) : histDecelUp ? color.new(bullColorInput, 55) : histAccelDn ? color.new(bearColorInput, 15) : histDecelDn ? color.new(bearColorInput, 55) : color.new(color.gray, 50)
 
plot(showHistInput ? hist : na, "Histogram", color = histColor, style = plot.style_columns, linewidth = 1)
 
// Oscillator and signal
color oscColor = osc > signalLine ? bullColorInput : bearColorInput
plotOsc = plot(osc, "AMF Line", color = oscColor, linewidth = 2)
plotSig = plot(signalLine, "Signal", color = color.new(oscColor, 40), linewidth = 1)
 
// Fill
fill(plotOsc, plotSig, color = showFillInput ? color.new(oscColor, 88) : na, title = "Momentum Fill")
 
// Background
bgcolor(showBgInput ? (trendState == 1 ? BULL_BG : trendState == -1 ? BEAR_BG : na) : na, title = "Trend Background")
 
// ══════════════════════════════════════
// LABELS & SHAPES
// ══════════════════════════════════════
 
// Buy/Sell signals via label.new (supports dynamic size)
if showSignalsInput and confirmedBuy
    label.new(bar_index, osc, "▲", color = bullColorInput, textcolor = LABEL_TEXT, style = label.style_label_up, size = LABEL_SIZE_MAIN, tooltip = "BUY Signal\nEngine: " + engineInput + "\nPrice: " + str.tostring(close, format.mintick))
 
if showSignalsInput and confirmedSell
    label.new(bar_index, osc, "▼", color = bearColorInput, textcolor = LABEL_TEXT, style = label.style_label_down, size = LABEL_SIZE_MAIN, tooltip = "SELL Signal\nEngine: " + engineInput + "\nPrice: " + str.tostring(close, format.mintick))
 
// Zero line cross markers (secondary size)
if showSignalsInput and confirmedZeroBuy
    label.new(bar_index, 0.0, "●", color = color.new(bullColorInput, 30), textcolor = bullColorInput, style = label.style_none, size = LABEL_SIZE_SEC, tooltip = "Zero Line Bullish Cross")
 
if showSignalsInput and confirmedZeroSell
    label.new(bar_index, 0.0, "●", color = color.new(bearColorInput, 30), textcolor = bearColorInput, style = label.style_none, size = LABEL_SIZE_SEC, tooltip = "Zero Line Bearish Cross")
 
// Divergence labels
if regBullDiv and showDivInput and barstate.isconfirmed
    label.new(bar_index - pivotRb, nz(oscPivLo, 0.0), "Bull\nDiv", color = color.new(bullColorInput, 20), textcolor = LABEL_TEXT, style = label.style_label_up, size = LABEL_SIZE_MAIN, tooltip = "Regular Bullish Divergence\nPrice made lower low\nMomentum made higher low")
 
if regBearDiv and showDivInput and barstate.isconfirmed
    label.new(bar_index - pivotRb, nz(oscPivHi, 0.0), "Bear\nDiv", color = color.new(bearColorInput, 20), textcolor = LABEL_TEXT, style = label.style_label_down, size = LABEL_SIZE_MAIN, tooltip = "Regular Bearish Divergence\nPrice made higher high\nMomentum made lower high")
 
// Clean up old labels
if array.size(label.all) > 400
    label.delete(array.shift(label.all))
 
// ══════════════════════════════════════
// DASHBOARD
// ══════════════════════════════════════
string trendStr = trendState == 1 ? "Bullish" : trendState == -1 ? "Bearish" : "Neutral"
color trendCol = trendState == 1 ? bullColorInput : trendState == -1 ? bearColorInput : neutralColorInput
 
string signalStr = confirmedBuy ? "BUY" : confirmedSell ? "SELL" : "Wait"
color signalCol = confirmedBuy ? bullColorInput : confirmedSell ? bearColorInput : TEXT_MUTED
 
string strengthStr = strengthScore >= 70 ? "Strong" : strengthScore >= 40 ? "Medium" : "Weak"
color strengthCol = strengthScore >= 70 ? bullColorInput : strengthScore >= 40 ? neutralColorInput : TEXT_MUTED
 
if showDashInput and barstate.islast
    var dashTable = table.new(dashPos, 2, 8, TABLE_BG, TABLE_BORDER, 1, TABLE_BORDER, 1)
 
    // Header
    table.cell(dashTable, 0, 0, "WillyAlgoTrader — AMF", text_color = HEADER_TEXT, bgcolor = HEADER_BG, text_size = size.small, text_halign = text.align_center)
    table.merge_cells(dashTable, 0, 0, 1, 0)
 
    // Row 1: Trend
    table.cell(dashTable, 0, 1, "Trend", text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_BG)
    table.cell(dashTable, 1, 1, trendStr, text_color = trendCol, text_size = size.small, bgcolor = TABLE_BG)
 
    // Row 2: Signal
    table.cell(dashTable, 0, 2, "Signal", text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_ROW_ALT)
    table.cell(dashTable, 1, 2, signalStr, text_color = signalCol, text_size = size.small, bgcolor = TABLE_ROW_ALT)
 
    // Row 3: Strength
    table.cell(dashTable, 0, 3, "Strength", text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_BG)
    table.cell(dashTable, 1, 3, strengthStr + " (" + str.tostring(strengthScore, "#") + "%)", text_color = strengthCol, text_size = size.small, bgcolor = TABLE_BG)
 
    // Row 4: Momentum
    string momStr = hist > 0 ? (histAccelUp ? "Accel ▲" : "Decel ▽") : (histAccelDn ? "Accel ▼" : "Decel △")
    color momCol = hist > 0 ? bullColorInput : bearColorInput
    table.cell(dashTable, 0, 4, "Momentum", text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_ROW_ALT)
    table.cell(dashTable, 1, 4, momStr, text_color = momCol, text_size = size.small, bgcolor = TABLE_ROW_ALT)
 
    // Row 5: Divergence
    table.cell(dashTable, 0, 5, "Divergence", text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_BG)
    table.cell(dashTable, 1, 5, divSignalStr, text_color = divSignalCol, text_size = size.small, bgcolor = TABLE_BG)
 
    // Row 6: Engine + TF
    table.cell(dashTable, 0, 6, "Engine / TF", text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_ROW_ALT)
    table.cell(dashTable, 1, 6, engineInput + " / " + timeframe.period, text_color = TEXT_COLOR, text_size = size.small, bgcolor = TABLE_ROW_ALT)
 
    // Row 7: Version
    table.cell(dashTable, 0, 7, "Version", text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_BG)
    table.cell(dashTable, 1, 7, INDICATOR_VERSION, text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_BG)
 
// ══════════════════════════════════════
// WATERMARK — WillyAlgoTrader
// ══════════════════════════════════════
if barstate.islast and showWatermarkInput
    var wmTable = table.new(position = position.bottom_center, columns = 1, rows = 1, bgcolor = color.new(color.black, 100), border_color = color.new(color.black, 100), border_width = 0, frame_color = color.new(color.black, 100), frame_width = 0)
    table.cell(wmTable, 0, 0, "WillyAlgoTrader", text_color = WM_COLOR, text_size = size.normal, text_halign = text.align_center, bgcolor = color.new(color.black, 100))
 
// ══════════════════════════════════════
// ALERTS
// ══════════════════════════════════════
string tickerStr = syminfo.tickerid
string priceStr = str.tostring(close, format.mintick)
string tfStr = timeframe.period
 
// Buy alert
if confirmedBuy
    string jsonBuy = '{"action":"buy","ticker":"' + tickerStr + '","price":' + priceStr + ',"tf":"' + tfStr + '","engine":"' + engineInput + '"}'
    string textBuy = "🟢 BUY | " + tickerStr + " | TF: " + tfStr + " | Price: " + priceStr + " | Engine: " + engineInput
    alert(webhookInput ? jsonBuy : textBuy, alert.freq_once_per_bar_close)
 
// Sell alert
if confirmedSell
    string jsonSell = '{"action":"sell","ticker":"' + tickerStr + '","price":' + priceStr + ',"tf":"' + tfStr + '","engine":"' + engineInput + '"}'
    string textSell = "🔴 SELL | " + tickerStr + " | TF: " + tfStr + " | Price: " + priceStr + " | Engine: " + engineInput
    alert(webhookInput ? jsonSell : textSell, alert.freq_once_per_bar_close)
 
// Zero cross alert
if confirmedZeroBuy
    string jsonZB = '{"action":"zero_bull","ticker":"' + tickerStr + '","price":' + priceStr + ',"tf":"' + tfStr + '"}'
    string textZB = "🟡 ZERO BULL CROSS | " + tickerStr + " | TF: " + tfStr + " | Price: " + priceStr
    alert(webhookInput ? jsonZB : textZB, alert.freq_once_per_bar_close)
 
if confirmedZeroSell
    string jsonZS = '{"action":"zero_bear","ticker":"' + tickerStr + '","price":' + priceStr + ',"tf":"' + tfStr + '"}'
    string textZS = "🟡 ZERO BEAR CROSS | " + tickerStr + " | TF: " + tfStr + " | Price: " + priceStr
    alert(webhookInput ? jsonZS : textZS, alert.freq_once_per_bar_close)
 
// Divergence alerts
if regBullDiv and barstate.isconfirmed
    string jsonDB = '{"action":"bull_divergence","ticker":"' + tickerStr + '","price":' + priceStr + ',"tf":"' + tfStr + '"}'
    string textDB = "🔵 BULL DIVERGENCE | " + tickerStr + " | TF: " + tfStr + " | Price: " + priceStr
    alert(webhookInput ? jsonDB : textDB, alert.freq_once_per_bar_close)
 
if regBearDiv and barstate.isconfirmed
    string jsonDS = '{"action":"bear_divergence","ticker":"' + tickerStr + '","price":' + priceStr + ',"tf":"' + tfStr + '"}'
    string textDS = "🔵 BEAR DIVERGENCE | " + tickerStr + " | TF: " + tfStr + " | Price: " + priceStr
    alert(webhookInput ? jsonDS : textDS, alert.freq_once_per_bar_close)

← 返回列表