Return Sign Transition Matrix [Pineify]

Pineify · study · 210 行 · 点赞 6 · TradingView 原页

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

Pine Script

//@version=6
indicator("Return Sign Transition Matrix [Pineify]", shorttitle="Sign Transition [Pineify]", overlay=false, precision=1)
 
// Independent implementation. Conditional frequencies describe observed paths;
// overlapping adjacent pairs are not independent trials or next-bar forecasts.
string G_SAMPLE = "Sample and support"
int window = input.int(160, "Raw transition slots", minval=40, maxval=600, group=G_SAMPLE)
float toleranceBps = input.float(0.5, "Zero-return tolerance (log bps)", minval=0.0, maxval=100.0, step=0.1, group=G_SAMPLE)
float prior = input.float(1.0, "Symmetric pseudocount per cell", minval=0.1, maxval=10.0, step=0.1, group=G_SAMPLE)
int minRow = input.int(16, "Minimum pairs from EACH direction", minval=4, maxval=150, group=G_SAMPLE)
float minCoverage = input.float(0.5, "Minimum directional-pair fraction", minval=0.1, maxval=1.0, step=0.05, group=G_SAMPLE)
string G_STATE = "State confirmation"
float entry = input.float(18.0, "Bias entry (points)", minval=5.0, maxval=70.0, step=1.0, group=G_STATE)
float exitInput = input.float(10.0, "Bias exit (capped below entry)", minval=0.0, maxval=60.0, step=1.0, group=G_STATE)
float asymEntry = input.float(30.0, "Asymmetry entry (points)", minval=10.0, maxval=80.0, step=1.0, group=G_STATE)
float asymExitInput = input.float(18.0, "Asymmetry exit (capped below entry)", minval=0.0, maxval=70.0, step=1.0, group=G_STATE)
int confirmations = input.int(3, "Consecutive candidate closes", minval=1, maxval=10, group=G_STATE)
string G_VIEW = "Visual layers"
bool showCells = input.bool(false, "Four cell-intensity strips (+112,+104,-104,-112)", group=G_VIEW)
bool showThresholds = input.bool(false, "Bias entry guides", group=G_VIEW)
bool showBackground = input.bool(false, "Confirmed-state background", group=G_VIEW)
bool showMarks = input.bool(false, "State-change dots", group=G_VIEW)
bool showTable = input.bool(true, "Transition matrix and diagnostics", group=G_VIEW)
 
f_phase(int state) =>
    switch state
        -1 => "Unavailable"
        0 => "No resolved bias"
        1 => "Continuation"
        2 => "Reversal"
        3 => "Up-persistence skew"
        4 => "Down-persistence skew"
        => "Unavailable"
 
f_color(int state) =>
    switch state
        1 => #137B73
        2 => #8057B6
        3 => #9A6200
        4 => #B43E62
        => #64748B
 
f_number(float value) =>
    na(value) ? "n/a" : str.tostring(value, "#.0")
 
f_cell(int count, float probability) =>
    str.tostring(count) + " | " + f_number(100.0 * probability) + "%"
 
float seconds = timeframe.in_seconds()
bool supported = chart.is_standard and (timeframe.isintraday or timeframe.isdaily or timeframe.isweekly) and not na(seconds) and seconds >= 900 and seconds <= 604800
bool priceValid = supported and not na(close) and not na(close[1]) and close > 0 and close[1] > 0
float logReturn = priceValid ? math.log(close) - math.log(close[1]) : na
float tolerance = toleranceBps / 10000.0
int liveSign = not priceValid ? 0 : logReturn > tolerance ? 1 : logReturn < -tolerance ? -1 : 0
float exitLevel = math.min(exitInput, entry - 1.0)
float asymExit = math.min(asymExitInput, asymEntry - 1.0)
 
// One slot per observed chart bar. -2 = invalid price, -1 = broken/zero pair.
// Codes 0,1,2,3 = ++,+-,-+,--. Never bridge a zero or missing return.
var array<int> slots = array.new<int>()
var array<int> counts = array.new<int>(4, 0)
var int invalidSlots = 0
var int previousSign = 0
var bool previousValid = false
var bool ready = false
var int phase = -1
var int candidate = -1
var int candidateRun = 0
var float pUU = na
var float pDD = na
var float bias = na
var float asymmetry = na
var float upRail = na
var float downRail = na
var float coverage = 0.0
var float support = 0.0
var int rowUp = 0
var int rowDown = 0
var string gate = "Warm-up"
 
if barstate.isconfirmed
    int code = not priceValid ? -2 : previousValid and previousSign != 0 and liveSign != 0 ? (previousSign == 1 ? (liveSign == 1 ? 0 : 1) : (liveSign == 1 ? 2 : 3)) : -1
    array.push(slots, code)
    if code >= 0
        array.set(counts, code, array.get(counts, code) + 1)
    else if code == -2
        invalidSlots += 1
    if array.size(slots) > window
        int expired = array.shift(slots)
        if expired >= 0
            array.set(counts, expired, array.get(counts, expired) - 1)
        else if expired == -2
            invalidSlots -= 1
    previousSign := liveSign
    previousValid := priceValid
 
    rowUp := array.get(counts, 0) + array.get(counts, 1)
    rowDown := array.get(counts, 2) + array.get(counts, 3)
    int pairs = rowUp + rowDown
    coverage := float(pairs) / window
    support := math.min(coverage, math.min(1.0, float(math.min(rowUp, rowDown)) / (2.0 * minRow)))
    bool full = array.size(slots) == window
    // The oldest transition also needs its immediately preceding return valid.
    ready := supported and full and invalidSlots == 0 and coverage >= minCoverage and rowUp >= minRow and rowDown >= minRow
    gate := not supported ? "Use standard 15m-1W" : not full ? "Warm-up " + str.tostring(array.size(slots)) + "/" + str.tostring(window) : invalidSlots > 0 ? "Invalid price slots" : coverage < minCoverage ? "Too few adjacent pairs" : rowUp < minRow or rowDown < minRow ? "One row undersampled" : "Supported"
    pUU := ready ? (array.get(counts, 0) + prior) / (rowUp + 2.0 * prior) : na
    pDD := ready ? (array.get(counts, 3) + prior) / (rowDown + 2.0 * prior) : na
    upRail := ready ? 100.0 * (2.0 * pUU - 1.0) : na
    downRail := ready ? 100.0 * (2.0 * pDD - 1.0) : na
    bias := ready ? (upRail + downRail) / 2.0 : na
    asymmetry := ready ? (upRail - downRail) / 2.0 : na
 
    if not ready
        phase := -1
        candidate := -1
        candidateRun := 0
    else
        if phase == -1
            phase := 0
        // Asymmetry has priority so unequal directional persistence cannot
        // silently masquerade as a symmetric continuation/reversal regime.
        int desired = phase == 3 and asymmetry >= asymExit ? 3 : phase == 4 and asymmetry <= -asymExit ? 4 : asymmetry >= asymEntry ? 3 : asymmetry <= -asymEntry ? 4 : phase == 1 and bias >= exitLevel ? 1 : phase == 2 and bias <= -exitLevel ? 2 : bias >= entry ? 1 : bias <= -entry ? 2 : 0
        if desired == phase
            candidate := phase
            candidateRun := 0
        else
            candidateRun := desired == candidate ? candidateRun + 1 : 1
            candidate := desired
            if candidateRun >= confirmations
                phase := desired
                candidateRun := 0
 
bool restored = barstate.isconfirmed and ready and not ready[1]
bool lost = barstate.isconfirmed and not ready and ready[1]
bool changed = barstate.isconfirmed and ready and phase != phase[1]
bool continued = changed and phase == 1
bool reversed = changed and phase == 2
bool upSkew = changed and phase == 3
bool downSkew = changed and phase == 4
bool neutralized = changed and phase == 0 and phase[1] > 0
 
color stateColor = f_color(phase)
color upColor = #2764C5
color downColor = #AD6900
int ribbonAlpha = int(math.round(94.0 - 16.0 * support))
int lineAlpha = int(math.round(35.0 * (1.0 - support)))
zero = plot(0.0, "Zero reference", color=color.new(#64748B, 55))
upper = plot(ready ? upRail : na, "After UP: continuation minus reversal", color=color.new(upColor, 15), linewidth=1, style=plot.style_linebr)
lower = plot(ready ? downRail : na, "After DOWN: continuation minus reversal", color=color.new(downColor, 15), linewidth=1, style=plot.style_linebr)
fill(upper, lower, color=ready ? color.new(stateColor, ribbonAlpha) : na, title="Conditional disagreement ribbon", fillgaps=false)
main = plot(ready ? bias : na, "Balanced conditional bias", color=color.new(stateColor, lineAlpha), linewidth=3, style=plot.style_linebr)
fill(main, zero, color=ready ? color.new(stateColor, 91) : na, title="Bias field", fillgaps=false)
plot(showThresholds ? entry : na, "Continuation entry", color=color.new(#137B73, 65))
plot(showThresholds ? -entry : na, "Reversal entry", color=color.new(#8057B6, 65))
plot(showCells and ready ? 112.0 : na, "++ conditional intensity", color=color.new(upColor, int(95 - 75 * nz(pUU))), linewidth=4, style=plot.style_linebr)
plot(showCells and ready ? 104.0 : na, "+- conditional intensity", color=color.new(upColor, int(95 - 75 * (1.0 - nz(pUU)))), linewidth=4, style=plot.style_linebr)
plot(showCells and ready ? -104.0 : na, "-+ conditional intensity", color=color.new(downColor, int(95 - 75 * (1.0 - nz(pDD)))), linewidth=4, style=plot.style_linebr)
plot(showCells and ready ? -112.0 : na, "-- conditional intensity", color=color.new(downColor, int(95 - 75 * nz(pDD))), linewidth=4, style=plot.style_linebr)
bgcolor(showBackground and ready ? color.new(stateColor, 95) : na, title="Confirmed-state wash")
plot(showMarks and changed ? bias : na, "Confirmed state change", color=stateColor, linewidth=4, style=plot.style_circles)
plot(ready ? asymmetry : na, "Directional asymmetry", display=display.data_window)
plot(100.0 * coverage, "Directional-pair coverage (%)", display=display.data_window)
plot(100.0 * support, "Support score (not confidence %)", display=display.data_window)
plot(phase, "State code (-1 unavailable; 0 neutral; 1 continue; 2 reverse; 3 up skew; 4 down skew)", display=display.data_window)
plot(priceValid ? liveSign : na, "LIVE return sign (intrabar)", display=display.data_window)
 
var table panel = table.new(position.top_right, 3, 9, border_width=1)
if barstate.islast and showTable
    color bg = color.new(chart.bg_color, 4)
    color fg = chart.fg_color
    for r = 0 to 8
        for c = 0 to 2
            table.cell(panel, c, r, "", bgcolor=bg, text_color=fg, text_size=size.small)
    table.cell(panel, 0, 0, "From / To", bgcolor=bg, text_color=fg)
    table.cell(panel, 1, 0, "UP", bgcolor=color.new(upColor, 85), text_color=fg)
    table.cell(panel, 2, 0, "DOWN", bgcolor=color.new(downColor, 85), text_color=fg)
    table.cell(panel, 0, 1, "UP", bgcolor=color.new(upColor, 85), text_color=fg)
    table.cell(panel, 1, 1, f_cell(array.get(counts, 0), pUU), bgcolor=bg, text_color=fg)
    table.cell(panel, 2, 1, f_cell(array.get(counts, 1), 1.0 - pUU), bgcolor=bg, text_color=fg)
    table.cell(panel, 0, 2, "DOWN", bgcolor=color.new(downColor, 85), text_color=fg)
    table.cell(panel, 1, 2, f_cell(array.get(counts, 2), 1.0 - pDD), bgcolor=bg, text_color=fg)
    table.cell(panel, 2, 2, f_cell(array.get(counts, 3), pDD), bgcolor=bg, text_color=fg)
    table.cell(panel, 0, 3, "State", bgcolor=bg, text_color=fg)
    table.cell(panel, 1, 3, f_phase(phase), bgcolor=color.new(stateColor, 86), text_color=fg)
    table.cell(panel, 2, 3, candidateRun > 0 ? "Pending " + str.tostring(candidateRun) + "/" + str.tostring(confirmations) : "Confirmed", bgcolor=bg, text_color=fg)
    table.cell(panel, 0, 4, "Bias / asym", bgcolor=bg, text_color=fg)
    table.cell(panel, 1, 4, f_number(bias), bgcolor=bg, text_color=fg)
    table.cell(panel, 2, 4, f_number(asymmetry), bgcolor=bg, text_color=fg)
    table.cell(panel, 0, 5, "Pair % / support", bgcolor=bg, text_color=fg)
    table.cell(panel, 1, 5, f_number(100.0 * coverage) + "%", bgcolor=bg, text_color=fg)
    table.cell(panel, 2, 5, f_number(support), bgcolor=bg, text_color=fg)
    table.cell(panel, 0, 6, "Row counts", bgcolor=bg, text_color=fg)
    table.cell(panel, 1, 6, str.tostring(rowUp), bgcolor=bg, text_color=fg)
    table.cell(panel, 2, 6, str.tostring(rowDown), bgcolor=bg, text_color=fg)
    table.cell(panel, 0, 7, "Close gate", bgcolor=bg, text_color=fg)
    table.cell(panel, 1, 7, gate, bgcolor=bg, text_color=fg)
    table.cell(panel, 2, 7, str.tostring(invalidSlots) + " invalid", bgcolor=bg, text_color=fg)
    table.cell(panel, 0, 8, "Live sign", bgcolor=bg, text_color=fg)
    table.cell(panel, 1, 8, not priceValid ? "Invalid" : liveSign == 1 ? "+" : liveSign == -1 ? "-" : "Zero band", bgcolor=bg, text_color=fg)
    table.cell(panel, 2, 8, "Stats: last close", bgcolor=bg, text_color=fg)
else if barstate.islast
    table.clear(panel, 0, 0, 2, 8)
 
alertcondition(continued, "Continuation bias confirmed", "Balanced return-sign continuation bias confirmed at close.")
alertcondition(reversed, "Reversal bias confirmed", "Balanced return-sign reversal bias confirmed at close.")
alertcondition(upSkew, "Up-persistence skew confirmed", "Up-row persistence exceeds down-row persistence; directional asymmetry confirmed.")
alertcondition(downSkew, "Down-persistence skew confirmed", "Down-row persistence exceeds up-row persistence; directional asymmetry confirmed.")
alertcondition(neutralized, "No resolved bias", "Return-sign structure returned to no resolved bias after confirmation.")
alertcondition(lost, "Sample support lost", "Return-sign matrix unavailable: coverage, row support, or price gate failed.")
alertcondition(restored, "Sample support restored", "Return-sign matrix has full supported coverage; candidate confirmation restarts.")

← 返回列表