Trend Consensus Engine [ML]

Market_Logic_India · study · 456 行 · 点赞 27 · 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/
// © Market_Logic_India
//@version=6
// =============================================================================
//  TREND CONSENSUS ENGINE [ML]                      shorttitle: TrendCore   v2.1
//  Research-aligned, measured, regime-gated trend consensus — 16 orthogonal
//  direction components + 4 gates, SELF-CONTAINED (no external feeds), with a
//  screen-fixed 8-gauge strip. Volatility is DERIVED (VixFix), since India VIX
//  is not live on the tape.
//
//  DESIGN (our own measurement + the leading-indicator research): momentum is the
//  one leading price signal; order flow confirms (near-coincident); basis, breadth
//  and intermarket are independent axes; regime & volatility read CONTEXT, not
//  direction; and confluence only helps when each component measurably ADDS. So
//  components are decorrelated by design, each is self-rated by measured directional
//  accuracy (shrunk toward equal), the ensemble is regime-gated, and it ABSTAINS
//  when there is no proven edge.
//
//  DIRECTION COMPONENTS (16, all computed internally)
//    Momentum σ 10/30/60 · Trend-state MA stack · Breakout · Structure (BOS) ·
//    LinReg slope · VWAP · Volume-pressure · Flow (CVD proxy) · Basis · Basis-
//    momentum · Relative strength · Breadth · Breadth-thrust · Intermarket
//  GATES (4, modulate conviction — never vote)
//    Regime persistence (variance-ratio + Hurst) · Regime strength (ADX) ·
//    Volatility stress (DERIVED — VixFix percentile) · Expiry-day de-risk
//
//  MEASUREMENT — per-component measured accuracy → shrinkage weights · effective-N ·
//  ensemble accuracy (Wilson) · abstention. Non-repaint. Honest edge ~52–55%.
//
//  CREDITS — momentum: Moskowitz-Ooi-Pedersen; variance-ratio: Lo-MacKinlay; Hurst
//  R/S: Hurst, Mandelbrot; ADX/ATR: Wilder; VWAP: market-profile practice; derived
//  fear gauge: L. Williams (VixFix); basis/carry: futures theory; CVD: order-flow
//  practice; accuracy-weighting: Freund-Schapire; Wilson: E. B. Wilson; shrinkage:
//  C. Stein. The measured orthogonal-consensus calibration is the author's own.
//
//  DISCLAIMER — study for analysis & education only. NOT a strategy, NOT advice.
// =============================================================================
indicator("Trend Consensus Engine [ML]", "TrendCore", overlay = true, max_bars_back = 320, max_lines_count = 20, max_labels_count = 20)
 
// ───────────────────────────── INPUTS ──────────────────────────────────────
gTF = "① Gauge timeframes"
tf1 = input.timeframe("1",  "TF 1", group = gTF)
tf2 = input.timeframe("2",  "TF 2", group = gTF)
tf3 = input.timeframe("3",  "TF 3", group = gTF)
tf4 = input.timeframe("5",  "TF 4", group = gTF)
tf5 = input.timeframe("15", "TF 5", group = gTF)
tf6 = input.timeframe("30", "TF 6", group = gTF)
tf7 = input.timeframe("60", "TF 7", group = gTF)
 
gE = "② Engine — momentum, structure, regime"
momThr = input.float(0.4, "Momentum threshold (σ)", minval = 0.0, maxval = 3.0, step = 0.1, group = gE)
lrLen  = input.int(25, "LinReg length", minval = 5, maxval = 200, group = gE)
pvL    = input.int(10, "Swing pivot length", minval = 2, maxval = 50, group = gE)
obvLen = input.int(20, "Volume-pressure MA", minval = 2, maxval = 200, group = gE)
flowLen= input.int(20, "Flow (CVD) MA", minval = 2, maxval = 200, group = gE)
vrLen  = input.int(120, "Regime sample length", minval = 20, maxval = 500, group = gE)
vrQ    = input.int(8, "Variance-ratio horizon q", minval = 2, maxval = 40, group = gE)
hurstLen=input.int(100, "Hurst window", minval = 20, maxval = 300, group = gE)
adxThr = input.float(18, "ADX trending ≥", minval = 5, maxval = 50, step = 1, group = gE)
fadeMR = input.bool(false, "Fade in a mean-revert regime", group = gE)
vsOn   = input.bool(true, "Derived-vol stress conviction cut", group = gE)
vsLen  = input.int(22, "VixFix length", minval = 5, maxval = 100, group = gE)
vsPct  = input.float(80, "Stress percentile", minval = 50, maxval = 99, step = 1, group = gE)
seasOn = input.bool(false, "Expiry-day de-risk (weekly)", group = gE)
 
gB = "③ Basis + Relative strength (self-fetched)"
enBasis = input.bool(true, "Basis + basis-momentum (spot–futures)", group = gB)
futSym  = input.symbol("NSE:NIFTY1!", "Futures symbol", group = gB)
spotSym = input.symbol("NSE:NIFTY", "Spot symbol", group = gB)
basisLen= input.int(20, "Basis window", minval = 5, maxval = 200, group = gB)
enRS    = input.bool(true, "Relative strength vs benchmark", group = gB)
benchSym= input.symbol("NSE:CNX500", "Benchmark symbol", group = gB)
rsLen   = input.int(50, "RS window", minval = 5, maxval = 400, group = gB)
 
gBr = "④ Breadth (self-fetched constituents)"
enBrd  = input.bool(true, "Breadth + thrust", group = gBr)
maBrd  = input.int(50, "Constituent MA length", minval = 5, maxval = 400, group = gBr)
thrustN= input.int(5, "Breadth-thrust window", minval = 1, maxval = 50, group = gBr)
cs1 = input.symbol("NSE:RELIANCE",  "Constituent 1", group = gBr)
cs2 = input.symbol("NSE:HDFCBANK",  "Constituent 2", group = gBr)
cs3 = input.symbol("NSE:ICICIBANK", "Constituent 3", group = gBr)
cs4 = input.symbol("NSE:INFY",      "Constituent 4", group = gBr)
cs5 = input.symbol("NSE:TCS",       "Constituent 5", group = gBr)
cs6 = input.symbol("NSE:ITC",       "Constituent 6", group = gBr)
cs7 = input.symbol("NSE:LT",        "Constituent 7", group = gBr)
cs8 = input.symbol("NSE:AXISBANK",  "Constituent 8", group = gBr)
cs9 = input.symbol("NSE:SBIN",      "Constituent 9", group = gBr)
cs10= input.symbol("NSE:BHARTIARTL","Constituent 10", group = gBr)
 
gXA = "⑤ Intermarket (self-fetched)"
enXA  = input.bool(true, "Intermarket risk appetite", group = gXA)
dxySym= input.symbol("TVC:DXY",        "Dollar index", group = gXA)
crdSym= input.symbol("TVC:USOIL",      "Crude", group = gXA)
inrSym= input.symbol("FX_IDC:USDINR",  "USDINR", group = gXA)
xaLen = input.int(50, "Intermarket window", minval = 5, maxval = 400, group = gXA)
 
gM = "⑥ Measurement"
accH   = input.int(10, "Accuracy horizon (bars)", minval = 1, maxval = 100, group = gM)
accWin = input.int(200, "Accuracy window (bars)", minval = 30, maxval = 2000, group = gM)
shrink = input.float(0.5, "Weight shrinkage → equal", minval = 0.0, maxval = 1.0, step = 0.05, group = gM)
minSamp= input.int(20, "Min samples to trust", minval = 5, maxval = 200, group = gM)
 
gD = "⑦ Gauge strip (screen-fixed)"
showGauge= input.bool(true, "Show gauges", group = gD)
gaugePos = input.string("Top Right", "Gauge position", options = ["Top Right","Top Center","Top Left","Middle Right","Middle Center","Middle Left","Bottom Right","Bottom Center","Bottom Left"], group = gD)
 
gV = "⑧ Panel & theme"
showTable= input.bool(true, "Show panel", group = gV)
dashMode = input.string("Compact", "Dashboard", options = ["Compact","Pro"], group = gV)
posStr   = input.string("Top Left", "Panel position", options = ["Top Right","Top Center","Top Left","Middle Right","Middle Center","Middle Left","Bottom Right","Bottom Center","Bottom Left"], group = gV)
themeMode= input.string("Auto (match chart)", "Theme", options = ["Auto (match chart)","Dark","Light"], group = gV)
showEXP  = input.bool(true, "Export EXP_* values", group = gV)
 
// ───────────────────────────── HELPERS ─────────────────────────────────────
f_pos(string s) =>
    switch s
        "Top Left"      => position.top_left
        "Top Center"    => position.top_center
        "Top Right"     => position.top_right
        "Middle Left"   => position.middle_left
        "Middle Center" => position.middle_center
        "Middle Right"  => position.middle_right
        "Bottom Left"   => position.bottom_left
        "Bottom Center" => position.bottom_center
        "Bottom Right"  => position.bottom_right
        => position.top_right
f_wilsonHalf(int w, int n, float z) =>
    float h = na
    if n >= 1
        float p = w / float(n)
        float den = 1.0 + z * z / n
        h := z * math.sqrt(p * (1.0 - p) / n + z * z / (4.0 * n * n)) / den
    h
f_acc(float s, int h, int w) =>
    int retS = close - close[h] > 0 ? 1 : close - close[h] < 0 ? -1 : 0
    int sp   = int(nz(s[h], 0))
    int corr = (sp != 0 and retS != 0 and sp == retS) ? 1 : 0
    int cnt  = (sp != 0 and retS != 0) ? 1 : 0
    float cn = ta.sma(corr, w)
    float dn = ta.sma(cnt, w)
    dn > 0 ? cn / dn : na
f_tfName(string t) => str.tostring(str.tonumber(t)) == t ? t + "m" : t
// one constituent's "above its MA" contribution (self-fetched)
f_above(string sym, bool on, int n) =>
    float c = request.security(on ? sym : syminfo.tickerid, timeframe.period, close, lookahead = barmerge.lookahead_off)
    float m = ta.ema(c, n)
    on and not na(c) and not na(m) ? (c > m ? 1 : 0) : 0
// price-core regime-gated score (per-TF dial)
f_core() =>
    float rt = na(close[1]) or close[1] <= 0 ? 0.0 : math.log(close / close[1])
    float v1 = ta.stdev(rt, 20)
    float zs = v1 > 0 and not na(close[10]) and close[10] > 0 ? math.log(close / close[10]) / (v1 * math.sqrt(10)) : 0.0
    float zm = v1 > 0 and not na(close[30]) and close[30] > 0 ? math.log(close / close[30]) / (v1 * math.sqrt(30)) : 0.0
    float zl = v1 > 0 and not na(close[60]) and close[60] > 0 ? math.log(close / close[60]) / (v1 * math.sqrt(60)) : 0.0
    int vm = (zs + zm + zl) / 3.0 > momThr ? 1 : (zs + zm + zl) / 3.0 < -momThr ? -1 : 0
    float a50 = ta.ema(close, 50)
    float a150 = ta.ema(close, 150)
    float a200 = ta.ema(close, 200)
    int vk = close > a50 and a50 > a150 and a150 > a200 ? 1 : close < a50 and a50 < a150 and a150 < a200 ? -1 : 0
    float md = (ta.highest(high, 20) + ta.lowest(low, 20)) / 2
    int vd = close > md ? 1 : close < md ? -1 : 0
    float h50 = ta.highest(high, 50)[1]
    float l50 = ta.lowest(low, 50)[1]
    int vt = not na(h50) and close > h50 ? 1 : not na(l50) and close < l50 ? -1 : 0
    float vwp = ta.vwap(hlc3)
    int vv = not na(vwp) and close > vwp ? 1 : not na(vwp) and close < vwp ? -1 : 0
    float raw = (vm + vk + vd + vt + vv) / 5.0
    float rq = not na(close[vrQ]) and close[vrQ] > 0 ? math.log(close / close[vrQ]) : 0.0
    float vr1 = ta.variance(rt, vrLen)
    float vrq = ta.variance(rq, vrLen)
    float vr = vr1 > 0 ? vrq / (vrQ * vr1) : 1.0
    [dpc, dmc, adxc] = ta.dmi(14, 14)
    bool trd = vr >= 1.05 and adxc >= adxThr
    bool mr = vr <= 0.95
    float cv = trd ? 1.0 : mr ? 0.3 : 0.6
    float sc = fadeMR and mr ? -raw * 0.4 : raw * cv
    math.max(-1.0, math.min(1.0, sc))
 
// ───────────────────────────── THEME ───────────────────────────────────────
f_luma(color c) => na(c) ? 0.0 : color.r(c) * 0.299 + color.g(c) * 0.587 + color.b(c) * 0.114
uiDark = themeMode == "Dark" ? true : themeMode == "Light" ? false : (na(chart.bg_color) or f_luma(chart.bg_color) < 140)
cPanel = uiDark ? color.rgb(10, 14, 26)    : color.rgb(244, 246, 248)
cSub   = uiDark ? color.rgb(22, 27, 34)    : color.rgb(233, 237, 242)
cAlt   = uiDark ? color.rgb(16, 20, 32)    : color.rgb(238, 241, 245)
cTxt   = uiDark ? color.rgb(226, 232, 240) : color.rgb(20, 26, 38)
cDim   = uiDark ? color.rgb(150, 160, 174) : color.rgb(96, 104, 116)
cFrame = uiDark ? color.rgb(42, 52, 88)    : color.rgb(196, 204, 212)
uiGold = uiDark ? color.rgb(255, 196, 0)   : color.rgb(176, 120, 0)
cSD = color.rgb(205, 40, 60)
cD  = color.rgb(240, 130, 40)
cN  = color.rgb(240, 200, 30)
cU  = color.rgb(120, 200, 90)
cSU = color.rgb(20, 170, 95)
cBull = cSU
cBear = cSD
 
// ───────────────── CHART-TF COMPONENTS (16 orthogonal, internal) ────────────
float ret = na(close[1]) or close[1] <= 0 ? 0.0 : math.log(close / close[1])
float vol1 = ta.stdev(ret, 20)
// 1–3 vol-scaled momentum
float zS = vol1 > 0 and not na(close[10]) and close[10] > 0 ? math.log(close / close[10]) / (vol1 * math.sqrt(10)) : 0.0
float zM = vol1 > 0 and not na(close[30]) and close[30] > 0 ? math.log(close / close[30]) / (vol1 * math.sqrt(30)) : 0.0
float zL = vol1 > 0 and not na(close[60]) and close[60] > 0 ? math.log(close / close[60]) / (vol1 * math.sqrt(60)) : 0.0
int c1 = zS > momThr ? 1 : zS < -momThr ? -1 : 0
int c2 = zM > momThr ? 1 : zM < -momThr ? -1 : 0
int c3 = zL > momThr ? 1 : zL < -momThr ? -1 : 0
// 4 trend-state MA stack
float e50 = ta.ema(close, 50)
float e150 = ta.ema(close, 150)
float e200 = ta.ema(close, 200)
int c4 = close > e50 and e50 > e150 and e150 > e200 ? 1 : close < e50 and e50 < e150 and e150 < e200 ? -1 : 0
// 5 breakout (confirmed state)
float hh20 = ta.highest(high, 20)[1]
float ll20 = ta.lowest(low, 20)[1]
var int c5 = 0
c5 := not na(hh20) and close > hh20 ? 1 : not na(ll20) and close < ll20 ? -1 : c5
// 6 structure BOS (confirmed swings)
float ph = ta.pivothigh(pvL, pvL)
float pl = ta.pivotlow(pvL, pvL)
var float lph = na
var float lpl = na
lph := not na(ph) ? ph : lph
lpl := not na(pl) ? pl : lpl
var int c6 = 0
c6 := not na(lph) and close > lph ? 1 : not na(lpl) and close < lpl ? -1 : c6
// 7 linreg slope (ATR-normalized)
float lr0 = ta.linreg(close, lrLen, 0)
float lr1 = ta.linreg(close, lrLen, 1)
float lrSlope = lr0 - lr1
float atr14 = ta.atr(14)
int c7 = atr14 > 0 ? (lrSlope > 0.05 * atr14 ? 1 : lrSlope < -0.05 * atr14 ? -1 : 0) : 0
// 8 VWAP acceptance
float vw = ta.vwap(hlc3)
int c8 = not na(vw) and close > vw ? 1 : not na(vw) and close < vw ? -1 : 0
// 9 volume-pressure (OBV slope)
float obv = ta.obv
float obe = ta.ema(obv, obvLen)
int c9 = obv > obe ? 1 : obv < obe ? -1 : 0
// 10 order-flow (CVD proxy — self-contained from price/volume)
float clv = (high - low) > 0 ? ((close - low) - (high - close)) / (high - low) : 0.0
float cvd = ta.cum(clv * nz(volume))
float cvdE = ta.ema(cvd, flowLen)
int c10 = cvd > cvdE ? 1 : cvd < cvdE ? -1 : 0
// 11–12 basis + basis-momentum (self-fetched, optional)
float futC = request.security(enBasis ? futSym : syminfo.tickerid, timeframe.period, close, lookahead = barmerge.lookahead_off)
float spotC = request.security(enBasis ? spotSym : syminfo.tickerid, timeframe.period, close, lookahead = barmerge.lookahead_off)
float basisPct = enBasis and not na(spotC) and spotC > 0 ? (futC - spotC) / spotC * 100.0 : na
float basisAbn = basisPct - ta.sma(basisPct, basisLen)
float basisMom = basisAbn - basisAbn[basisLen]
int c11 = enBasis and not na(basisAbn) ? (basisAbn > 0 ? 1 : basisAbn < 0 ? -1 : 0) : 0
int c12 = enBasis and not na(basisMom) ? (basisMom > 0 ? 1 : basisMom < 0 ? -1 : 0) : 0
// 13 relative strength (self-fetched, optional)
float benchC = request.security(enRS ? benchSym : syminfo.tickerid, timeframe.period, close, lookahead = barmerge.lookahead_off)
float rsv = enRS and not na(benchC) and benchC > 0 ? close / benchC : na
float rsMa = ta.sma(rsv, rsLen)
int c13 = enRS and not na(rsv) and not na(rsMa) ? (rsv > rsMa ? 1 : rsv < rsMa ? -1 : 0) : 0
// 14–15 breadth participation + thrust (self-fetched constituents, optional)
float part = (f_above(cs1, enBrd, maBrd) + f_above(cs2, enBrd, maBrd) + f_above(cs3, enBrd, maBrd) + f_above(cs4, enBrd, maBrd) + f_above(cs5, enBrd, maBrd) + f_above(cs6, enBrd, maBrd) + f_above(cs7, enBrd, maBrd) + f_above(cs8, enBrd, maBrd) + f_above(cs9, enBrd, maBrd) + f_above(cs10, enBrd, maBrd)) / 10.0 * 100.0
int c14 = enBrd ? (part > 55 ? 1 : part < 45 ? -1 : 0) : 0
float partChg = part - part[thrustN]
int c15 = enBrd ? (partChg > 0 ? 1 : partChg < 0 ? -1 : 0) : 0
// 16 intermarket risk appetite (self-fetched, optional)
float dxyC = request.security(enXA ? dxySym : syminfo.tickerid, timeframe.period, close, lookahead = barmerge.lookahead_off)
float crdC = request.security(enXA ? crdSym : syminfo.tickerid, timeframe.period, close, lookahead = barmerge.lookahead_off)
float inrC = request.security(enXA ? inrSym : syminfo.tickerid, timeframe.period, close, lookahead = barmerge.lookahead_off)
float dxyContrib = dxyC > ta.sma(dxyC, xaLen) ? -1.0 : 1.0
float inrContrib = inrC > ta.sma(inrC, xaLen) ? -1.0 : 1.0
float crdContrib = crdC > ta.sma(crdC, xaLen) ? -0.5 : 0.5
float xaScore = dxyContrib + inrContrib + crdContrib
int c16 = enXA ? (xaScore > 0 ? 1 : xaScore < 0 ? -1 : 0) : 0
 
// ───────────────── MEASUREMENT: accuracy → shrinkage weights ────────────────
float a1 = f_acc(c1, accH, accWin)
float a2 = f_acc(c2, accH, accWin)
float a3 = f_acc(c3, accH, accWin)
float a4 = f_acc(c4, accH, accWin)
float a5 = f_acc(c5, accH, accWin)
float a6 = f_acc(c6, accH, accWin)
float a7 = f_acc(c7, accH, accWin)
float a8 = f_acc(c8, accH, accWin)
float a9 = f_acc(c9, accH, accWin)
float a10 = f_acc(c10, accH, accWin)
float a11 = f_acc(c11, accH, accWin)
float a12 = f_acc(c12, accH, accWin)
float a13 = f_acc(c13, accH, accWin)
float a14 = f_acc(c14, accH, accWin)
float a15 = f_acc(c15, accH, accWin)
float a16 = f_acc(c16, accH, accWin)
 
array<float>  cArr = array.from(float(c1),float(c2),float(c3),float(c4),float(c5),float(c6),float(c7),float(c8),float(c9),float(c10),float(c11),float(c12),float(c13),float(c14),float(c15),float(c16))
array<float>  aArr = array.from(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16)
array<bool>   eArr = array.from(true,true,true,true,true,true,true,true,true,true,enBasis,enBasis,enRS,enBrd,enBrd,enXA)
array<string> nArr = array.from("Mom 10","Mom 30","Mom 60","Trend-state","Breakout","Structure","LinReg","VWAP","Vol-pressure","Flow (CVD)","Basis","Basis mom","Rel.strength","Breadth","Breadth thrust","Intermarket")
 
float num = 0.0
float den = 0.0
float sumW = 0.0
float sumW2 = 0.0
int nUp = 0
int nDn = 0
int nAct = 0
// axis-decorrelation weights: correlated costumes of one axis share its weight
// (momentum 10/30/60 + linreg = one momentum axis; basis pair; breadth pair)
array<float> axArr = array.from(0.25, 0.25, 0.25, 1.0, 1.0, 1.0, 0.25, 1.0, 1.0, 1.0, 0.5, 0.5, 1.0, 0.5, 0.5, 1.0)
for i = 0 to 15
    if eArr.get(i)
        float sv = cArr.get(i)
        float accW = math.max(0.0, nz(aArr.get(i), 0.5) - 0.5) * 2.0
        float w = (shrink * 1.0 + (1.0 - shrink) * accW) * axArr.get(i)
        num += w * sv
        den += w
        sumW += w
        sumW2 += w * w
        nAct += 1
        nUp += sv > 0 ? 1 : 0
        nDn += sv < 0 ? 1 : 0
float rawScore = den > 0 ? num / den : 0.0
float effN = sumW2 > 0 ? (sumW * sumW) / sumW2 : 0.0
 
// ───────────────── GATES: regime (VR+Hurst) · ADX · derived-vol · season ────
float retq = not na(close[vrQ]) and close[vrQ] > 0 ? math.log(close / close[vrQ]) : 0.0
float var1 = ta.variance(ret, vrLen)
float varq = ta.variance(retq, vrLen)
float vr = var1 > 0 ? varq / (vrQ * var1) : 1.0
float hMean = ta.sma(ret, hurstLen)
float hStd = ta.stdev(ret, hurstLen)
float hcum = 0.0
float hmn = 0.0
float hmx = 0.0
for i = 0 to hurstLen - 1
    hcum += nz(ret[hurstLen - 1 - i]) - hMean
    hmn := i == 0 ? hcum : math.min(hmn, hcum)
    hmx := i == 0 ? hcum : math.max(hmx, hcum)
float hR = hmx - hmn
float hRS = hStd > 0 and hR > 0 ? hR / hStd : na
float hurst = na(hRS) ? 0.5 : math.log(hRS) / math.log(hurstLen)
[dpx, dmx, adx] = ta.dmi(14, 14)
bool persist = vr >= 1.05 and hurst >= 0.5
bool trending = persist and adx >= adxThr
bool meanrev = vr <= 0.95 or hurst <= 0.45
float convict = trending ? 1.0 : meanrev ? 0.3 : 0.6
float hc = ta.highest(close, vsLen)
float vixfix = hc > 0 ? (hc - low) / hc * 100.0 : na
float vfPct = ta.percentrank(vixfix, 252)
bool stress = vsOn and not na(vfPct) and vfPct >= vsPct
float stressCut = stress ? 0.6 : 1.0
bool expiry = seasOn and dayofweek == dayofweek.thursday
float seasCut = expiry ? 0.6 : 1.0
float score = (fadeMR and meanrev ? -rawScore * 0.4 : rawScore * convict) * stressCut * seasCut
score := math.max(-1.0, math.min(1.0, score))
 
// ───────────────── ENSEMBLE ACCURACY + ABSTENTION ──────────────────────────
float ensSig = score > 0 ? 1.0 : score < 0 ? -1.0 : 0.0
float ensAcc = f_acc(ensSig, accH, accWin)
int ensN = int(nz(ta.sma((ensSig != 0 and (close - close[accH]) != 0) ? 1 : 0, accWin), 0) * accWin)
float ensWh = ensN >= minSamp ? f_wilsonHalf(int(nz(ensAcc, 0.5) * ensN), ensN, 1.96) : na
bool proven = not na(ensAcc) and not na(ensWh) and (ensAcc - ensWh) > 0.5
bool abstain = not trending or not proven
float upThr = 0.15
int ensDir = abstain ? 0 : score > upThr ? 1 : score < -upThr ? -1 : 0
string verdict = ensDir == 1 ? "UP" : ensDir == -1 ? "DOWN" : abstain ? "STAND ASIDE" : "NEUTRAL"
color vClr = ensDir == 1 ? cBull : ensDir == -1 ? cBear : uiGold
float strength = math.abs(score) * 100.0
 
// ───────────────── TF GAUGE SCORES ─────────────────────────────────────────
float m1 = request.security(syminfo.tickerid, tf1, f_core(), lookahead = barmerge.lookahead_off)
float m2 = request.security(syminfo.tickerid, tf2, f_core(), lookahead = barmerge.lookahead_off)
float m3 = request.security(syminfo.tickerid, tf3, f_core(), lookahead = barmerge.lookahead_off)
float m4 = request.security(syminfo.tickerid, tf4, f_core(), lookahead = barmerge.lookahead_off)
float m5 = request.security(syminfo.tickerid, tf5, f_core(), lookahead = barmerge.lookahead_off)
float m6 = request.security(syminfo.tickerid, tf6, f_core(), lookahead = barmerge.lookahead_off)
float m7 = request.security(syminfo.tickerid, tf7, f_core(), lookahead = barmerge.lookahead_off)
array<float>  vArr = array.from(m1, m2, m3, m4, m5, m6, m7)
array<string> tArr = array.from(tf1, tf2, tf3, tf4, tf5, tf6, tf7)
 
// ───────────────── GAUGE STRIP (screen-fixed table) ────────────────────────
var table G = table.new(f_pos(gaugePos), 8, 3, border_width = 1, frame_width = 1)
if barstate.islast and showGauge
    table.set_bgcolor(G, cPanel)
    table.set_frame_color(G, cFrame)
    table.set_border_color(G, cFrame)
    for i = 0 to 7
        bool big = i == 7
        float v = big ? score : nz(vArr.get(i), 0.0)
        string nm = big ? "ALL" : f_tfName(tArr.get(i))
        float strg = math.abs(v) * 100.0
        color zc = v < -0.6 ? cSD : v < -0.2 ? cD : v < 0.2 ? cN : v < 0.6 ? cU : cSU
        string arrow = v < -0.6 ? "▼" : v < -0.2 ? "↘" : v < 0.2 ? "●" : v < 0.6 ? "↗" : "▲"
        table.cell(G, i, 0, nm, text_color = big ? color.white : cDim, bgcolor = big ? color.new(zc, 0) : cFrame, text_size = size.small, text_halign = text.align_center)
        table.cell(G, i, 1, arrow, text_color = zc, bgcolor = color.new(zc, 86), text_size = big ? size.huge : size.large, text_halign = text.align_center)
        table.cell(G, i, 2, str.tostring(strg, "0"), text_color = zc, bgcolor = big ? color.new(zc, 75) : (i % 2 == 0 ? cSub : cAlt), text_size = big ? size.large : size.normal, text_halign = text.align_center)
 
// ───────────────────────────── PANEL ───────────────────────────────────────
var table T = table.new(f_pos(posStr), 3, 23, border_width = 1, frame_width = 1)
f_cell(int c, int r, string s, color tc, color bg, string ha) =>
    table.cell(T, c, r, s, text_color = tc, bgcolor = bg, text_size = size.small, text_halign = ha == "l" ? text.align_left : ha == "r" ? text.align_right : text.align_center)
bool pro = dashMode == "Pro"
string regTxt = trending ? "trending" : meanrev ? "mean-revert" : "random"
 
if barstate.islast and showTable
    table.set_bgcolor(T, cPanel)
    table.set_frame_color(T, cFrame)
    table.set_border_color(T, cFrame)
    f_cell(0, 0, "TREND CONSENSUS", color.white, color.new(vClr, 0), "l")
    f_cell(1, 0, verdict, color.white, color.new(vClr, 0), "c")
    f_cell(2, 0, str.tostring(strength, "0"), color.white, color.new(vClr, 0), "r")
    if not pro
        f_cell(0, 1, "Agreement", cDim, cSub, "l")
        f_cell(1, 1, str.tostring(nUp) + "▲", cBull, cSub, "c")
        f_cell(2, 1, str.tostring(nDn) + "▼", cBear, cSub, "r")
        f_cell(0, 2, "Regime", cDim, cAlt, "l")
        f_cell(1, 2, regTxt, trending ? cBull : meanrev ? cBear : cDim, cAlt, "c")
        f_cell(2, 2, "H " + str.tostring(hurst, "0.00"), cDim, cAlt, "r")
        f_cell(0, 3, "Ensemble accuracy", cDim, cSub, "l")
        f_cell(1, 3, na(ensAcc) ? "—" : str.tostring(ensAcc * 100, "0") + "%", na(ensAcc) ? cDim : proven ? cBull : cDim, cSub, "c")
        f_cell(2, 3, proven ? "★ proven" : "unproven", proven ? cBull : cDim, cSub, "r")
    else
        f_cell(0, 1, "— component", cDim, cFrame, "l")
        f_cell(1, 1, "dir", cDim, cFrame, "c")
        f_cell(2, 1, "acc", cDim, cFrame, "r")
        for i = 0 to 15
            int rr = 2 + i
            float sv = cArr.get(i)
            float av = aArr.get(i)
            bool en = eArr.get(i)
            color bg = i % 2 == 0 ? cSub : cAlt
            f_cell(0, rr, nArr.get(i), en ? cTxt : cDim, bg, "l")
            f_cell(1, rr, not en ? "off" : sv > 0 ? "▲" : sv < 0 ? "▼" : "–", not en ? cDim : sv > 0 ? cBull : sv < 0 ? cBear : cDim, bg, "c")
            f_cell(2, rr, not en or na(av) ? "—" : str.tostring(av * 100, "0") + "%", not en or na(av) ? cDim : av > 0.55 ? cBull : av < 0.45 ? cBear : cTxt, bg, "r")
        f_cell(0, 18, "Regime·Hurst·ADX", cDim, cSub, "l")
        f_cell(1, 18, regTxt, trending ? cBull : meanrev ? cBear : cDim, cSub, "c")
        f_cell(2, 18, str.tostring(hurst, "0.00") + "·" + str.tostring(adx, "0") + (stress ? "·stress" : "") + (expiry ? "·exp" : ""), stress or expiry ? cBear : cDim, cSub, "r")
        f_cell(0, 19, "Effective-N / active", cDim, cAlt, "l")
        f_cell(1, 19, str.tostring(effN, "0.0"), cTxt, cAlt, "c")
        f_cell(2, 19, str.tostring(nAct), cDim, cAlt, "r")
        f_cell(0, 20, "Agreement", cDim, cSub, "l")
        f_cell(1, 20, str.tostring(nUp) + "▲", cBull, cSub, "c")
        f_cell(2, 20, str.tostring(nDn) + "▼", cBear, cSub, "r")
        f_cell(0, 21, "Ensemble accuracy", cDim, cAlt, "l")
        f_cell(1, 21, na(ensAcc) ? "—" : str.tostring(ensAcc * 100, "0") + "%", na(ensAcc) ? cDim : proven ? cBull : cDim, cAlt, "c")
        f_cell(2, 21, proven ? "★ proven" : "unproven", proven ? cBull : cDim, cAlt, "r")
        f_cell(0, 22, "measured · shrink " + str.tostring(shrink, "0.0"), cDim, cSub, "l")
        f_cell(1, 22, "abstain if unproven", cDim, cSub, "c")
        f_cell(2, 22, "", cDim, cSub, "r")
 
// ───────────────────────────── ALERTS ──────────────────────────────────────
alertcondition(ensDir == 1 and ensDir[1] != 1,  "Consensus → UP",   "TrendCore: consensus UP on {{ticker}} {{interval}}")
alertcondition(ensDir == -1 and ensDir[1] != -1,"Consensus → DOWN", "TrendCore: consensus DOWN on {{ticker}} {{interval}}")
 
// ───────────────────────────── EXP EXPORTS ─────────────────────────────────
plot(showEXP ? score * 100 : na,        "EXP_TrendScore",   color = color.new(color.gray, 100), display = display.data_window)
plot(showEXP ? float(ensDir) : na,      "EXP_TrendDir",     color = color.new(color.gray, 100), display = display.data_window)
plot(showEXP ? strength : na,           "EXP_Strength",     color = color.new(color.gray, 100), display = display.data_window)
plot(showEXP ? nz(ensAcc * 100, -1) : na,"EXP_EnsAcc",      color = color.new(color.gray, 100), display = display.data_window)
plot(showEXP ? effN : na,               "EXP_EffN",         color = color.new(color.gray, 100), display = display.data_window)
plot(showEXP ? hurst : na,              "EXP_Hurst",        color = color.new(color.gray, 100), display = display.data_window)

← 返回列表