Key Level Confluence & Target Zones [PhenLabs]

PhenLabs · study · 690 行 · 点赞 1,638 · 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/
// © PhenLabs
//@version=6
indicator("Key Level Confluence & Target Zones [PhenLabs]", shorttitle = "KLCTZ [PhenLabs]", overlay = true, max_lines_count = 200, max_labels_count = 200, max_boxes_count = 200)
 
// ═════════════════════════════ ENUMS ═════════════════════════════
enum TMode
    mBoth = "Both (Hold + Breakout)"
    mHold = "Hold Reversals Only"
    mBrk  = "Confirmed Breakouts Only"
 
enum PSel
    pAuto   = "Auto (Best EV)"
    pBal    = "Balanced"
    pStrict = "Strict 3x+ Stack"
    pScalp  = "Scalp Fast"
    pSwing  = "Swing Wide"
 
enum PivT
    pvTrad = "Traditional"
    pvFib  = "Fibonacci"
    pvCam  = "Camarilla"
 
enum TSize
    tsTiny   = "Tiny"
    tsSmall  = "Small"
    tsNormal = "Normal"
 
// ═════════════════════════════ INPUTS ═════════════════════════════
const string G1 = "Signals"
const string G2 = "Confluence Zones"
const string G3 = "Trade Plan"
const string G4 = "Display"
 
TMode  iMode    = input.enum(TMode.mBoth, "Trade Mode", group = G1, tooltip = "HOLD = price rejects a confluence zone and closes back out of it. BREAKOUT = price closes decisively through a zone.")
PSel   iProf    = input.enum(PSel.pAuto, "Profile", group = G1, tooltip = "Auto plots the profile with the best average R so far (needs 3+ closed trades). It keeps its own live record separate from the fixed profiles.")
PivT   iPiv     = input.enum(PivT.pvTrad, "Pivot Formula", group = G2, tooltip = "Formula used for daily and weekly pivot levels.")
float  iTol     = input.float(0.35, "Merge Tolerance (ATR)", minval = 0.05, maxval = 1.5, step = 0.05, group = G2, tooltip = "Levels this close together (in ATR) are merged into one zone.")
int    iMinSrc  = input.int(2, "Min Sources per Zone", minval = 2, maxval = 6, group = G2, tooltip = "Each zone needs at least one high/low or swing level plus one pivot or round-number level.")
int    iSwing   = input.int(10, "Swing Length", minval = 3, maxval = 50, group = G2)
bool   iRound   = input.bool(true, "Include Round Numbers", group = G2)
float  iSlBuf   = input.float(0.25, "Stop Buffer (ATR)", minval = 0.0, maxval = 2.0, step = 0.05, group = G3, tooltip = "Extra room past the zone edge and the signal wick. Stop distance is limited to 0.5 to 3.0 ATR.")
float  iR1      = input.float(1.0, "Targets: TP1 / TP2 / TP3 (R)", minval = 0.3, step = 0.1, inline = "tp", group = G3)
float  iR2      = input.float(2.0, "", minval = 0.5, step = 0.1, inline = "tp", group = G3)
float  iR3      = input.float(3.0, "", minval = 0.8, step = 0.1, inline = "tp", group = G3, tooltip = "Balanced/Strict use these values. Scalp uses 0.75x and Swing uses 1.5x. Scale-out: 50% at TP1, 30% at TP2, 20% at TP3. Stop moves to break-even after TP1.")
bool   iMagnet  = input.bool(true, "Snap TP2 to Next Opposing Zone", group = G3)
int    iMaxBars = input.int(60, "Time Exit (bars)", minval = 5, maxval = 400, group = G3)
int    iHist    = input.int(4, "Past Plans Shown", minval = 1, maxval = 12, group = G4)
int    iZones   = input.int(4, "Zones Shown", minval = 1, maxval = 10, group = G4)
TSize  iTbl     = input.enum(TSize.tsSmall, "Table Size", group = G4)
color  bullC    = input.color(#00E5A8, "Bull / Bear / Zone", inline = "c", group = G4)
color  bearC    = input.color(#FF4D6D, "", inline = "c", group = G4)
color  zoneC    = input.color(#F5C542, "", inline = "c", group = G4)
 
// ═════════════════════════════ TYPES ═════════════════════════════
type Ledger
    bool  active   = false
    int   dir      = 0
    int   kind     = 0
    int   cnt      = 0
    float entry    = na
    float sl       = na
    float risk     = na
    float tp1      = na
    float tp2      = na
    float tp3      = na
    bool  hit1     = false
    bool  hit2     = false
    float rem      = 1.0
    float accR     = 0.0
    int   entryBar = 0
    int   trades   = 0
    int   wins     = 0
    float sumR     = 0.0
    float gWin     = 0.0
    float gLoss    = 0.0
    float lastR    = 0.0
 
type PlanDraw
    line  eL
    line  sL
    line  t1L
    line  t2L
    line  t3L
    box   riskB
    box   rewB
    label sigLb
    label eLb
    label sLb
    label t1Lb
    label t2Lb
    label t3Lb
    label resLb
 
method openPlan(Ledger this, int d, int k, int c, float e, float s, float t1, float t2, float t3) =>
    this.active   := true
    this.dir      := d
    this.kind     := k
    this.cnt      := c
    this.entry    := e
    this.sl       := s
    this.risk     := math.abs(e - s)
    this.tp1      := t1
    this.tp2      := t2
    this.tp3      := t3
    this.hit1     := false
    this.hit2     := false
    this.rem      := 1.0
    this.accR     := 0.0
    this.entryBar := bar_index
    true
 
// Returns 0 none, 1 TP1, 2 TP2, 3 TP3 final, 4 stop final, 5 time exit final
method step(Ledger this, float w1, float w2, int maxB) =>
    int ev = 0
    if this.active and bar_index > this.entryBar
        float r     = math.max(this.risk, syminfo.mintick)
        bool  done  = false
        bool  stopH = this.dir == 1 ? low <= this.sl : high >= this.sl
        if stopH
            this.accR := this.accR + this.rem * (this.sl - this.entry) * this.dir / r
            this.rem  := 0.0
            done      := true
            ev        := 4
        else
            bool h1 = this.dir == 1 ? high >= this.tp1 : low <= this.tp1
            bool h2 = this.dir == 1 ? high >= this.tp2 : low <= this.tp2
            bool h3 = this.dir == 1 ? high >= this.tp3 : low <= this.tp3
            if not this.hit1 and h1
                this.hit1 := true
                this.accR := this.accR + w1 * (this.tp1 - this.entry) * this.dir / r
                this.rem  := this.rem - w1
                this.sl   := this.entry
                ev        := 1
            if this.hit1 and not this.hit2 and h2
                this.hit2 := true
                this.accR := this.accR + w2 * (this.tp2 - this.entry) * this.dir / r
                this.rem  := this.rem - w2
                ev        := 2
            if this.hit2 and h3
                this.accR := this.accR + this.rem * (this.tp3 - this.entry) * this.dir / r
                this.rem  := 0.0
                done      := true
                ev        := 3
            if not done and bar_index - this.entryBar >= maxB
                this.accR := this.accR + this.rem * (close - this.entry) * this.dir / r
                this.rem  := 0.0
                done      := true
                ev        := 5
        if done
            this.active := false
            this.trades := this.trades + 1
            this.sumR   := this.sumR + this.accR
            this.lastR  := this.accR
            if this.accR > 0
                this.wins := this.wins + 1
                this.gWin := this.gWin + this.accR
            else
                this.gLoss := this.gLoss - this.accR
    ev
 
method del(PlanDraw this) =>
    line.delete(this.eL)
    line.delete(this.sL)
    line.delete(this.t1L)
    line.delete(this.t2L)
    line.delete(this.t3L)
    box.delete(this.riskB)
    box.delete(this.rewB)
    label.delete(this.sigLb)
    label.delete(this.eLb)
    label.delete(this.sLb)
    label.delete(this.t1Lb)
    label.delete(this.t2Lb)
    label.delete(this.t3Lb)
    label.delete(this.resLb)
    true
 
// ═════════════════════════════ HELPERS ═════════════════════════════
f_piv(int pt, float h, float l, float c) =>
    float p  = (h + l + c) / 3.0
    float rg = h - l
    float r1 = na
    float r2 = na
    float r3 = na
    float s1 = na
    float s2 = na
    float s3 = na
    if pt == 0
        r1 := 2.0 * p - l
        s1 := 2.0 * p - h
        r2 := p + rg
        s2 := p - rg
        r3 := h + 2.0 * (p - l)
        s3 := l - 2.0 * (h - p)
    else if pt == 1
        r1 := p + 0.382 * rg
        s1 := p - 0.382 * rg
        r2 := p + 0.618 * rg
        s2 := p - 0.618 * rg
        r3 := p + rg
        s3 := p - rg
    else
        r1 := c + rg * 1.1 / 12.0
        s1 := c - rg * 1.1 / 12.0
        r2 := c + rg * 1.1 / 6.0
        s2 := c - rg * 1.1 / 6.0
        r3 := c + rg * 1.1 / 4.0
        s3 := c - rg * 1.1 / 4.0
    [p, r1, r2, r3, s1, s2, s3]
 
// src: 0 = structure (high/low/swing), 1 = formula (pivot/round). tier: 2 weekly, 1 daily, 3 swing, 0 round
f_add(array<float> ap, array<int> aSrc, array<int> at, array<string> an, float v, int src, int tier, string nm) =>
    if not na(v)
        array.push(ap, v)
        array.push(aSrc, src)
        array.push(at, tier)
        array.push(an, nm)
    true
 
f_final(int cnt, bool hasS, bool hasF, bool wk, bool sw, float lo, float hi, int minSrc, float atrV) =>
    bool  ok    = cnt >= minSrc and hasS and hasF
    float mid   = (lo + hi) / 2.0
    float h     = math.max(hi - lo, 0.12 * atrV)
    float score = math.min(100.0, math.min(cnt, 5) * 18.0 + (wk ? 8.0 : 0.0) + (sw ? 6.0 : 0.0))
    [ok, mid + h / 2.0, mid - h / 2.0, score]
 
// minScore, wick, body, breakout buffer, activity, R scale, stop multiplier
f_params(int p) =>
    float minS = 36.0
    float wk   = 0.35
    float bd   = 0.50
    float buf  = 0.10
    float act  = 0.90
    float rs   = 1.0
    float slm  = 1.0
    if p == 1
        minS := 54.0
        wk   := 0.45
        bd   := 0.60
        buf  := 0.15
        act  := 1.10
    else if p == 2
        wk   := 0.30
        bd   := 0.45
        buf  := 0.05
        act  := 0.80
        rs   := 0.75
        slm  := 0.75
    else if p == 3
        wk   := 0.40
        bd   := 0.55
        buf  := 0.20
        act  := 1.00
        rs   := 1.5
        slm  := 1.5
    [minS, wk, bd, buf, act, rs, slm]
 
f_pname(int p) =>
    p == 0 ? "Balanced" : p == 1 ? "Strict 3x+" : p == 2 ? "Scalp Fast" : p == 3 ? "Swing Wide" : "Auto (live)"
 
// ═════════════════════════════ CORE SERIES ═════════════════════════════
float atrV  = ta.atr(14)
bool  hasVol = ta.cum(nz(volume)) > 0
float volMa  = ta.sma(volume, 20)
float actV   = hasVol ? nz(volume) / math.max(nz(volMa), 1e-9) : (high - low) / math.max(nz(atrV), 1e-9)
float prevC  = nz(close[1], close)
float tfms   = timeframe.in_seconds() * 1000.0
 
bool useD = timeframe.in_seconds() <= 86400
bool useW = timeframe.in_seconds() <= 604800
 
[pdh, pdl, pdc] = request.security(syminfo.tickerid, "D", [high[1], low[1], close[1]], lookahead = barmerge.lookahead_on)
[pwh, pwl, pwc] = request.security(syminfo.tickerid, "W", [high[1], low[1], close[1]], lookahead = barmerge.lookahead_on)
 
int pt = iPiv == PivT.pvTrad ? 0 : iPiv == PivT.pvFib ? 1 : 2
[dP, dR1, dR2, dR3, dS1, dS2, dS3] = f_piv(pt, pdh, pdl, pdc)
[wP, wR1, wR2, wR3, wS1, wS2, wS3] = f_piv(pt, pwh, pwl, pwc)
 
float ph = ta.pivothigh(high, iSwing, iSwing)
float pl = ta.pivotlow(low, iSwing, iSwing)
var float sh1 = na
var float sh2 = na
var float sl1 = na
var float sl2 = na
if not na(ph)
    sh2 := sh1
    sh1 := ph
if not na(pl)
    sl2 := sl1
    sl1 := pl
 
float rStep = close > 0 ? math.pow(10.0, math.floor(math.log10(close)) - 1.0) * 5.0 : na
float rnDn  = na(rStep) ? na : math.floor(close / rStep) * rStep
float rnUp  = na(rStep) ? na : rnDn + rStep
 
// ═════════════════════════════ LEVEL COLLECTION ═════════════════════════════
var array<float>  lvP = array.new<float>()
var array<int>    lvS = array.new<int>()
var array<int>    lvT = array.new<int>()
var array<string> lvN = array.new<string>()
array.clear(lvP)
array.clear(lvS)
array.clear(lvT)
array.clear(lvN)
 
if useD
    f_add(lvP, lvS, lvT, lvN, pdh, 0, 1, "PDH")
    f_add(lvP, lvS, lvT, lvN, pdl, 0, 1, "PDL")
    f_add(lvP, lvS, lvT, lvN, pdc, 0, 1, "PDC")
    f_add(lvP, lvS, lvT, lvN, dP,  1, 1, "P")
    f_add(lvP, lvS, lvT, lvN, dR1, 1, 1, "R1")
    f_add(lvP, lvS, lvT, lvN, dR2, 1, 1, "R2")
    f_add(lvP, lvS, lvT, lvN, dR3, 1, 1, "R3")
    f_add(lvP, lvS, lvT, lvN, dS1, 1, 1, "S1")
    f_add(lvP, lvS, lvT, lvN, dS2, 1, 1, "S2")
    f_add(lvP, lvS, lvT, lvN, dS3, 1, 1, "S3")
if useW
    f_add(lvP, lvS, lvT, lvN, pwh, 0, 2, "PWH")
    f_add(lvP, lvS, lvT, lvN, pwl, 0, 2, "PWL")
    f_add(lvP, lvS, lvT, lvN, wP,  1, 2, "WP")
    f_add(lvP, lvS, lvT, lvN, wR1, 1, 2, "WR1")
    f_add(lvP, lvS, lvT, lvN, wS1, 1, 2, "WS1")
f_add(lvP, lvS, lvT, lvN, sh1, 0, 3, "SWING H")
f_add(lvP, lvS, lvT, lvN, sh2, 0, 3, "SWING H2")
f_add(lvP, lvS, lvT, lvN, sl1, 0, 3, "SWING L")
f_add(lvP, lvS, lvT, lvN, sl2, 0, 3, "SWING L2")
if iRound
    f_add(lvP, lvS, lvT, lvN, rnDn, 1, 0, "ROUND")
    f_add(lvP, lvS, lvT, lvN, rnUp, 1, 0, "ROUND")
 
// ═════════════════════════════ CONFLUENCE CLUSTERING ═════════════════════════════
var array<float>  zTop   = array.new<float>()
var array<float>  zBot   = array.new<float>()
var array<float>  zScore = array.new<float>()
var array<int>    zCnt   = array.new<int>()
var array<string> zName  = array.new<string>()
array.clear(zTop)
array.clear(zBot)
array.clear(zScore)
array.clear(zCnt)
array.clear(zName)
 
int nLv = array.size(lvP)
if nLv >= 2 and not na(atrV)
    array<int> idx = array.sort_indices(lvP, order.ascending)
    float tol  = iTol * atrV
    int   gCnt = 0
    bool  gS   = false
    bool  gF   = false
    bool  gW   = false
    bool  gSw  = false
    float gLo  = na
    float gHi  = na
    string gNm = ""
    for k = 0 to nLv - 1
        int   j = array.get(idx, k)
        float v = array.get(lvP, j)
        bool newGrp = gCnt == 0 or v - gHi > tol or v - gLo > 2.0 * tol
        if newGrp and gCnt > 0
            [ok, zt, zb, sc] = f_final(gCnt, gS, gF, gW, gSw, gLo, gHi, iMinSrc, atrV)
            if ok
                array.push(zTop, zt)
                array.push(zBot, zb)
                array.push(zScore, sc)
                array.push(zCnt, gCnt)
                array.push(zName, gNm)
            gCnt := 0
            gS   := false
            gF   := false
            gW   := false
            gSw  := false
            gNm  := ""
        if gCnt == 0
            gLo := v
        gHi  := v
        gCnt := gCnt + 1
        int src  = array.get(lvS, j)
        int tier = array.get(lvT, j)
        gS  := gS or src == 0
        gF  := gF or src == 1
        gW  := gW or tier == 2
        gSw := gSw or tier == 3
        gNm := gNm == "" ? array.get(lvN, j) : gNm + " + " + array.get(lvN, j)
    if gCnt > 0
        [ok2, zt2, zb2, sc2] = f_final(gCnt, gS, gF, gW, gSw, gLo, gHi, iMinSrc, atrV)
        if ok2
            array.push(zTop, zt2)
            array.push(zBot, zb2)
            array.push(zScore, sc2)
            array.push(zCnt, gCnt)
            array.push(zName, gNm)
 
// ═════════════════════════════ SIGNAL & PLAN FUNCTIONS ═════════════════════════════
// mode: 0 both, 1 hold only, 2 breakout only. Returns [dir, kind(1 hold / 2 breakout), zone index]
f_signal(int p, int mode, float atrNow, float actNow, float pc) =>
    [minS, wk, bd, buf, actMin, rs, slm] = f_params(p)
    int   dir  = 0
    int   kind = 0
    int   zi   = -1
    float best = -1.0
    float rng   = math.max(high - low, syminfo.mintick)
    float lw    = (math.min(open, close) - low) / rng
    float uw    = (high - math.max(open, close)) / rng
    float bodyR = math.abs(close - open) / rng
    int n = array.size(zTop)
    if n > 0 and actNow >= actMin and not na(atrNow)
        for i = 0 to n - 1
            float t = array.get(zTop, i)
            float b = array.get(zBot, i)
            float s = array.get(zScore, i)
            if s >= minS and s > best
                int d = 0
                int k = 0
                if mode != 2
                    if low <= t and low >= b - 0.5 * atrNow and close > t and close > open and lw >= wk and pc > b
                        d := 1
                        k := 1
                    else if high >= b and high <= t + 0.5 * atrNow and close < b and close < open and uw >= wk and pc < t
                        d := -1
                        k := 1
                if d == 0 and mode != 1
                    if pc <= t and close > t + buf * atrNow and close > open and bodyR >= bd
                        d := 1
                        k := 2
                    else if pc >= b and close < b - buf * atrNow and close < open and bodyR >= bd
                        d := -1
                        k := 2
                if d != 0
                    dir  := d
                    kind := k
                    zi   := i
                    best := s
    [dir, kind, zi]
 
f_plan(int d, int zi, int p, float atrNow) =>
    [minS, wk, bd, buf, actMin, rs, slm] = f_params(p)
    float e  = close
    float t  = array.get(zTop, zi)
    float b  = array.get(zBot, zi)
    float s  = d == 1 ? math.min(b, low) - iSlBuf * slm * atrNow : math.max(t, high) + iSlBuf * slm * atrNow
    float rk = math.min(math.max(math.abs(e - s), 0.5 * atrNow), 3.0 * atrNow)
    s := e - d * rk
    float t1 = e + d * rk * iR1 * rs
    float t2 = e + d * rk * iR2 * rs
    float t3 = e + d * rk * iR3 * rs
    if iMagnet
        float bestEdge = na
        float bestDist = 1e18
        int n = array.size(zTop)
        if n > 0
            for i = 0 to n - 1
                float edge = d == 1 ? array.get(zBot, i) : array.get(zTop, i)
                bool inside = d == 1 ? edge > t1 and edge < t3 : edge < t1 and edge > t3
                if inside and math.abs(edge - e) < bestDist
                    bestDist := math.abs(edge - e)
                    bestEdge := edge
        if not na(bestEdge)
            float snap = bestEdge - d * 0.05 * atrNow
            t2 := d == 1 ? math.max(snap, t1 + syminfo.mintick) : math.min(snap, t1 - syminfo.mintick)
    [e, s, t1, t2, t3]
 
// ═════════════════════════════ PROFILE TOURNAMENT ═════════════════════════════
var array<Ledger> L = array.from(Ledger.new(), Ledger.new(), Ledger.new(), Ledger.new(), Ledger.new())
 
int modeI   = iMode == TMode.mBoth ? 0 : iMode == TMode.mHold ? 1 : 2
int dispIdx = iProf == PSel.pAuto ? 4 : iProf == PSel.pBal ? 0 : iProf == PSel.pStrict ? 1 : iProf == PSel.pScalp ? 2 : 3
 
int   bp     = 0
float bestEv = -1e9
for p = 0 to 3
    Ledger lg = array.get(L, p)
    if lg.trades >= 3
        float ev = lg.sumR / lg.trades
        if ev > bestEv
            bestEv := ev
            bp     := p
 
int   dOpenDir = 0
int   dOpenK   = 0
int   dOpenC   = 0
int   dEv      = 0
bool  dH1      = false
bool  dH2      = false
float dLastR   = 0.0
float dE  = na
float dS  = na
float dT1 = na
float dT2 = na
float dT3 = na
 
if barstate.isconfirmed and not na(atrV)
    for p = 0 to 4
        Ledger lg   = array.get(L, p)
        int    prof = p == 4 ? bp : p
        int    ev   = lg.step(0.5, 0.3, iMaxBars)
        if p == dispIdx
            dEv    := ev
            dH1    := lg.hit1
            dH2    := lg.hit2
            dLastR := lg.lastR
        if not lg.active
            [sd, sk, szi] = f_signal(prof, modeI, atrV, actV, prevC)
            if sd != 0
                [e, s, t1, t2, t3] = f_plan(sd, szi, prof, atrV)
                int c = array.get(zCnt, szi)
                lg.openPlan(sd, sk, c, e, s, t1, t2, t3)
                if p == dispIdx
                    dOpenDir := sd
                    dOpenK   := sk
                    dOpenC   := c
                    dE  := e
                    dS  := s
                    dT1 := t1
                    dT2 := t2
                    dT3 := t3
 
Ledger dl = array.get(L, dispIdx)
 
// ═════════════════════════════ NEAREST ZONES ═════════════════════════════
float supScore = 0.0
float resScore = 0.0
string supTxt  = "—"
string resTxt  = "—"
float supDist  = 1e18
float resDist  = 1e18
int nZ = array.size(zTop)
if nZ > 0
    for i = 0 to nZ - 1
        float t = array.get(zTop, i)
        float b = array.get(zBot, i)
        if t < close and close - t < supDist
            supDist  := close - t
            supScore := array.get(zScore, i)
            supTxt   := str.tostring(array.get(zCnt, i)) + "x · " + str.tostring(supScore, "#") + " @ " + str.tostring((t + b) / 2.0, format.mintick)
        if b > close and b - close < resDist
            resDist  := b - close
            resScore := array.get(zScore, i)
            resTxt   := str.tostring(array.get(zCnt, i)) + "x · " + str.tostring(resScore, "#") + " @ " + str.tostring((t + b) / 2.0, format.mintick)
 
// ═════════════════════════════ PINE SCREENER / DATA WINDOW (first plots) ═════════════════════════════
float dispEvR = dl.trades > 0 ? dl.sumR / dl.trades : 0.0
plot(dOpenDir, "Signal (+1 Buy / -1 Sell)", display = display.data_window + display.pine_screener)
plot(dl.active ? dl.dir : 0, "Active Plan Direction", display = display.data_window + display.pine_screener)
plot(supScore, "Nearest Support Score", display = display.data_window + display.pine_screener)
plot(resScore, "Nearest Resistance Score", display = display.data_window + display.pine_screener)
plot(nZ, "Active Zones", display = display.data_window + display.pine_screener)
plot(dispEvR, "Avg R per Trade", display = display.data_window + display.pine_screener)
 
// Invisible price anchors keep the overlay locked to the price scale
plot(high, "Anchor High", display = display.pane, color = color.new(color.white, 100), editable = false)
plot(low, "Anchor Low", display = display.pane, color = color.new(color.white, 100), editable = false)
 
// ═════════════════════════════ TRADE PLAN DRAWINGS ═════════════════════════════
var array<PlanDraw> plans = array.new<PlanDraw>()
var bool drawActive = false
color fgC = chart.fg_color
int   projBars = 25
 
// Update the existing plan with the events from this bar (before a new plan is drawn)
if dEv != 0 and drawActive and array.size(plans) > 0
    PlanDraw pd = array.last(plans)
    if dH1
        line.set_color(pd.t1L, bullC)
        line.set_width(pd.t1L, 2)
        label.set_text(pd.t1Lb, "TP1 ✓")
        line.set_style(pd.sL, line.style_dashed)
        label.set_text(pd.sLb, "SL → BE")
    if dH2
        line.set_color(pd.t2L, bullC)
        line.set_width(pd.t2L, 2)
        label.set_text(pd.t2Lb, "TP2 ✓")
    if dEv >= 3
        int tx = time
        line.set_x2(pd.eL, tx)
        line.set_x2(pd.sL, tx)
        line.set_x2(pd.t1L, tx)
        line.set_x2(pd.t2L, tx)
        line.set_x2(pd.t3L, tx)
        box.set_right(pd.riskB, tx)
        box.set_right(pd.rewB, tx)
        label.set_x(pd.eLb, tx)
        label.set_x(pd.sLb, tx)
        label.set_x(pd.t1Lb, tx)
        label.set_x(pd.t2Lb, tx)
        label.set_x(pd.t3Lb, tx)
        if dEv == 3
            line.set_color(pd.t3L, bullC)
            line.set_width(pd.t3L, 2)
            label.set_text(pd.t3Lb, "TP3 ✓")
        string tag = dEv == 3 ? "TP3" : dEv == 4 ? (dH1 ? "BE STOP" : "STOP") : "TIME EXIT"
        string rs  = (dLastR >= 0 ? "+" : "") + str.tostring(dLastR, "#.##") + "R"
        color  rc  = dLastR > 0 ? bullC : dLastR < 0 ? bearC : fgC
        pd.resLb := label.new(tx, close, rs + " · " + tag, xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(rc, 15), textcolor = color.white, size = size.small)
        drawActive := false
 
if dOpenDir != 0
    int   t0   = time
    int   tEnd = int(time + projBars * tfms)
    color dc   = dOpenDir == 1 ? bullC : bearC
    float rk   = math.max(math.abs(dE - dS), syminfo.mintick)
    PlanDraw pd = PlanDraw.new()
    pd.riskB := box.new(t0, math.max(dE, dS), tEnd, math.min(dE, dS), xloc = xloc.bar_time, bgcolor = color.new(bearC, 86), border_color = color.new(bearC, 100))
    pd.rewB  := box.new(t0, math.max(dE, dT3), tEnd, math.min(dE, dT3), xloc = xloc.bar_time, bgcolor = color.new(bullC, 90), border_color = color.new(bullC, 100))
    pd.eL    := line.new(t0, dE, tEnd, dE, xloc = xloc.bar_time, color = fgC, width = 2)
    pd.sL    := line.new(t0, dS, tEnd, dS, xloc = xloc.bar_time, color = bearC, width = 2)
    pd.t1L   := line.new(t0, dT1, tEnd, dT1, xloc = xloc.bar_time, color = color.new(bullC, 40), width = 1)
    pd.t2L   := line.new(t0, dT2, tEnd, dT2, xloc = xloc.bar_time, color = color.new(bullC, 40), width = 1)
    pd.t3L   := line.new(t0, dT3, tEnd, dT3, xloc = xloc.bar_time, color = color.new(bullC, 40), width = 1)
    pd.eLb   := label.new(tEnd, dE, "ENTRY " + str.tostring(dE, format.mintick), xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(color.black, 100), textcolor = fgC, size = size.small)
    pd.sLb   := label.new(tEnd, dS, "SL " + str.tostring(dS, format.mintick), xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(color.black, 100), textcolor = bearC, size = size.small)
    pd.t1Lb  := label.new(tEnd, dT1, "TP1 " + str.tostring((dT1 - dE) * dOpenDir / rk, "#.#") + "R", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(color.black, 100), textcolor = bullC, size = size.small)
    pd.t2Lb  := label.new(tEnd, dT2, "TP2 " + str.tostring((dT2 - dE) * dOpenDir / rk, "#.#") + "R", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(color.black, 100), textcolor = bullC, size = size.small)
    pd.t3Lb  := label.new(tEnd, dT3, "TP3 " + str.tostring((dT3 - dE) * dOpenDir / rk, "#.#") + "R", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(color.black, 100), textcolor = bullC, size = size.small)
    string sigTxt = (dOpenDir == 1 ? "BUY" : "SELL") + "\n" + (dOpenK == 1 ? "HOLD" : "BREAKOUT") + " · " + str.tostring(dOpenC) + "x"
    pd.sigLb := label.new(t0, dOpenDir == 1 ? low : high, sigTxt, xloc = xloc.bar_time, yloc = yloc.price, style = dOpenDir == 1 ? label.style_label_up : label.style_label_down, color = dc, textcolor = color.black, size = size.small)
    array.push(plans, pd)
    drawActive := true
    if array.size(plans) > iHist
        PlanDraw old = array.shift(plans)
        old.del()
 
// ═════════════════════════════ ZONE DRAWINGS (last bar) ═════════════════════════════
var array<box> zBoxes = array.new<box>()
if barstate.islast
    if array.size(zBoxes) > 0
        for i = array.size(zBoxes) - 1 to 0
            box.delete(array.get(zBoxes, i))
    array.clear(zBoxes)
    if nZ > 0
        array<float> dist = array.new<float>()
        for i = 0 to nZ - 1
            array.push(dist, math.abs((array.get(zTop, i) + array.get(zBot, i)) / 2.0 - close))
        array<int> order = array.sort_indices(dist, order.ascending)
        int shown = math.min(iZones, nZ)
        for k = 0 to shown - 1
            int   i  = array.get(order, k)
            float t  = array.get(zTop, i)
            float b  = array.get(zBot, i)
            float sc = array.get(zScore, i)
            color base = b > close ? bearC : t < close ? bullC : zoneC
            int   tr   = int(math.max(55.0, 88.0 - sc * 0.33))
            string txt = str.tostring(array.get(zCnt, i)) + "x CONFLUENCE [" + array.get(zName, i) + "] · " + str.tostring(sc, "#")
            box bx = box.new(int(time - 40 * tfms), t, int(time + 25 * tfms), b, xloc = xloc.bar_time, bgcolor = color.new(base, tr), border_color = color.new(base, 60), text = txt, text_size = size.tiny, text_color = color.new(fgC, 10), text_halign = text.align_right, text_valign = text.align_center)
            array.push(zBoxes, bx)
 
// ═════════════════════════════ DASHBOARD ═════════════════════════════
string tblSz = iTbl == TSize.tsTiny ? size.tiny : iTbl == TSize.tsSmall ? size.small : size.normal
var table dash = table.new(position.top_right, 4, 13, bgcolor = color.new(chart.bg_color, 10), border_color = color.new(chart.fg_color, 80), border_width = 1, frame_color = color.new(chart.fg_color, 70), frame_width = 1)
 
f_row(table tb, int r, string k, string v, color vc, string sz) =>
    table.cell(tb, 0, r, k, text_color = color.new(chart.fg_color, 30), text_size = sz, text_halign = text.align_left)
    table.cell(tb, 1, r, v, text_color = vc, text_size = sz, text_halign = text.align_left)
    table.merge_cells(tb, 1, r, 3, r)
    true
 
if barstate.islast
    table.clear(dash, 0, 0, 3, 12)
    table.cell(dash, 0, 0, "KEY LEVEL CONFLUENCE", text_color = zoneC, text_size = tblSz, text_formatting = text.format_bold)
    table.merge_cells(dash, 0, 0, 3, 0)
    f_row(dash, 1, "Mode", str.tostring(iMode), fgC, tblSz)
    string profTxt = dispIdx == 4 ? "Auto → " + f_pname(bp) : f_pname(dispIdx)
    f_row(dash, 2, "Profile", profTxt, fgC, tblSz)
    string actTxt = dl.active ? (dl.dir == 1 ? "LONG" : "SHORT") + " · " + (dl.kind == 1 ? "HOLD" : "BREAKOUT") + " · " + str.tostring(dl.cnt) + "x" + (dl.hit1 ? " · BE ON" : "") : "FLAT — waiting"
    f_row(dash, 3, "Signal", actTxt, dl.active ? (dl.dir == 1 ? bullC : bearC) : color.new(fgC, 40), tblSz)
    f_row(dash, 4, "Support", supTxt, bullC, tblSz)
    f_row(dash, 5, "Resistance", resTxt, bearC, tblSz)
    table.cell(dash, 0, 6, "Profile", text_color = color.new(fgC, 30), text_size = tblSz, text_formatting = text.format_bold)
    table.cell(dash, 1, 6, "Trades", text_color = color.new(fgC, 30), text_size = tblSz, text_formatting = text.format_bold)
    table.cell(dash, 2, 6, "Win %", text_color = color.new(fgC, 30), text_size = tblSz, text_formatting = text.format_bold)
    table.cell(dash, 3, 6, "Avg R", text_color = color.new(fgC, 30), text_size = tblSz, text_formatting = text.format_bold)
    for p = 0 to 4
        Ledger lg = array.get(L, p)
        float wr  = lg.trades > 0 ? 100.0 * lg.wins / lg.trades : 0.0
        float ar  = lg.trades > 0 ? lg.sumR / lg.trades : 0.0
        bool  sel = p == dispIdx or (dispIdx == 4 and p == bp)
        color nc  = sel ? zoneC : fgC
        table.cell(dash, 0, 7 + p, (sel ? "▶ " : "") + f_pname(p), text_color = nc, text_size = tblSz, text_halign = text.align_left)
        table.cell(dash, 1, 7 + p, str.tostring(lg.trades), text_color = fgC, text_size = tblSz)
        table.cell(dash, 2, 7 + p, lg.trades > 0 ? str.tostring(wr, "#") + "%" : "—", text_color = fgC, text_size = tblSz)
        table.cell(dash, 3, 7 + p, lg.trades > 0 ? (ar >= 0 ? "+" : "") + str.tostring(ar, "#.##") : "—", text_color = ar > 0 ? bullC : ar < 0 ? bearC : fgC, text_size = tblSz)
    f_row(dash, 12, "Data", hasVol ? "VOLUME" : "RANGE PROXY", color.new(fgC, 40), tblSz)
 
// ═════════════════════════════ ALERTS ═════════════════════════════
alertcondition(dOpenDir == 1, "KLCTZ Bullish Entry", "KLCTZ: BUY at key level confluence on {{ticker}} {{interval}} @ {{close}}")
alertcondition(dOpenDir == -1, "KLCTZ Bearish Entry", "KLCTZ: SELL at key level confluence on {{ticker}} {{interval}} @ {{close}}")
alertcondition(dOpenDir != 0, "KLCTZ Any Entry", "KLCTZ: new confluence trade plan on {{ticker}} {{interval}} @ {{close}}")
alertcondition(dEv == 1, "KLCTZ TP1 Hit", "KLCTZ: TP1 reached, stop moved to break-even on {{ticker}}")
alertcondition(dEv == 3, "KLCTZ TP3 Hit", "KLCTZ: TP3 reached, plan closed on {{ticker}}")
alertcondition(dEv == 4, "KLCTZ Stop Hit", "KLCTZ: stop reached, plan closed on {{ticker}}")

← 返回列表