Manual Harmonic Pattern

handi45 · study · 900 行 · 点赞 65 · TradingView 原页

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

Pine Script

//@version=6
indicator("Manual Harmonic Pattern", "Manual HP", overlay = true, max_lines_count = 150, max_labels_count = 100, max_boxes_count = 10, max_polylines_count = 10)
// Adaptasi manual yang terinspirasi oleh referensi RP Harmonic Pattern Collection.
// Kredit referensi asli: Robert R. Payne; karya harmonic: Scott Carney.
// Enam keluarga pertama mengikuti referensi RP, termasuk rentang kelayakannya yang luas.
// Shark/5-0: sumber penulis Carney; Cypher: penyelesaian dari XC; Stingray: definisi pengguna.
// Tanpa detektor swing: X/A/B/C adalah pasangan input waktu-harga yang dapat digeser.
// v1.8: alternatif otomatis memakai PRZ terdekat yang seluruhnya lebih dalam, semua keluarga.
// Pola gagal disembunyikan; HOP mengikuti pengganti; D terkonfirmasi mendapat target AD.
// Break PRZ memerlukan penutupan candle terkonfirmasi melewati sisi jauh; sumbu hanya menyentuh.
// Pengganti menjadi aktif hanya SETELAH PRZ aktif ditembus penutupan candle, sampai Late semula.
// Early/Ideal/Late memakai B + pengali * (B-X), dihitung dalam jumlah candle chart.
const int PATTERN_COUNT = 10
const int ABCD_ID = 10
const int STINGRAY_ID = 9
const int LIFE_ACTIVE = 0
const int LIFE_TOUCHED = 1
const int LIFE_BROKEN = 2
const int LIFE_LATE = 3
 
const string G_POINTS = "1. Titik manual - klik X, A, B, C berurutan"
float px = input.price(0, "X harga", inline = "X", group = G_POINTS, confirm = true)
int tx = input.time(0, "X waktu", inline = "X", group = G_POINTS, confirm = true)
float pa = input.price(0, "A harga", inline = "A", group = G_POINTS, confirm = true)
int ta = input.time(0, "A waktu", inline = "A", group = G_POINTS, confirm = true)
float pb = input.price(0, "B harga", inline = "B", group = G_POINTS, confirm = true)
int tb = input.time(0, "B waktu", inline = "B", group = G_POINTS, confirm = true)
float pc = input.price(0, "C harga", inline = "C", group = G_POINTS, confirm = true)
int tc = input.time(0, "C waktu", inline = "C", group = G_POINTS, confirm = true)
 
const string G_MODEL = "2. Pola dan proyeksi"
string model = input.string("Otomatis", "Pola utama", options = ["Otomatis", "Gartley", "Bat", "Alternate Bat", "Butterfly", "Crab", "Deep Crab", "Shark", "Cypher", "5-0", "Stingray", "AB=CD"], group = G_MODEL, tooltip = "PRZ break memerlukan close candle selesai melewati sisi jauh zona. Setelah break, semua keluarga XABC yang cocok dan memiliki PRZ utuh lebih dalam dibandingkan; PRZ terdekat yang belum gagal menjadi pengganti. Rantai dapat berulang sampai Late semula. Mode Stingray memulai Bat/Gartley, lalu memakai aturan alternatif yang sama. Potensi dini dari reject 23.6 AD + engulfing diatur di 2C.")
float tolerance = input.float(0.03, "Toleransi rasio D (absolut)", minval = 0, maxval = 0.10, step = 0.005, group = G_MODEL, tooltip = "0.03 berarti +/-0.03 pada rasio titik D. Bukan 3% harga. Rentang utama Shark 0.886-1.13 XC dan Stingray 1.272-1.414 XA tetap dibatasi pada rentang tersebut.")
float abcdMultiplier = input.float(1.0, "Pengali D utama mode AB=CD", options = [1.0, 1.272, 1.618], group = G_MODEL)
int rightBars = input.int(15, "Panjang level ke kanan", minval = 1, maxval = 200, group = G_MODEL)
float cypherCMin = input.float(1.272, "Cypher: minimum XC/XA", options = [1.13, 1.272], group = G_MODEL, tooltip = "Default 1.272-1.414. Pilih 1.13 untuk rentang lebih luas seperti alat Cypher TradingView. Completion D tetap 0.786 XC.")
bool showShark50 = input.bool(true, "Proyeksi lanjutan 5-0 setelah Shark", group = G_MODEL, tooltip = "5-0 berikutnya memakai A-B-C-D Shark sebagai X-A-B-C baru. Titik E = D + 0.5*(C-D), arah berlawanan. Masih hipotesis selama D Shark belum nyata.")
string altMode = input.string("Setelah AB=CD terlewati", "Tampilkan ALT AB=CD", options = ["Setelah AB=CD terlewati", "Selalu tampil"], group = G_MODEL, tooltip = "Setelah harga bergerak melewati completion AB=CD sejak candle setelah C, tampilkan ALT 1.272 dan 1.618. Tidak menggeser titik D pola utama.")
 
const string G_TIME = "2B. Waktu D - Early / Ideal / Late"
int leadBars = input.int(1, "D di depan candle terbaru (bar)", minval = 1, maxval = 100, group = G_TIME, tooltip = "D bergerak ke kanan selama aktif. Posisi dibatasi Late dan berhenti pada candle sentuhan/break pertama. Harga D tetap dari XABC manual.")
float earlyFactor = input.float(0.382, "Early x XB", minval = 0, maxval = 20, step = 0.001, group = G_TIME)
float idealFactor = input.float(1.0, "Ideal x XB", minval = 0, maxval = 20, step = 0.001, group = G_TIME)
float lateFactor = input.float(1.618, "Late x XB", minval = 0, maxval = 20, step = 0.001, group = G_TIME, tooltip = "Rumus referensi: B + ceil(Late * jumlah candle X ke B). Sentuhan/break pada candle Late didahulukan; setelah Late tidak diproses.")
bool showTimingZones = input.bool(true, "Garis Early / Ideal / Late", group = G_TIME)
 
const string G_CONT = "2C. Potensi alternatif dari reaksi PRZ"
bool enableContinuation = input.bool(true, "Alternatif: reject 23.6 AD + engulfing", group = G_CONT, tooltip = "Sesudah candle sentuhan PRZ aktif selesai, harga mencapai 0.236 AD dari D lalu reject ke sisi D. Engulfing body dua candle selesai searah kelanjutan CD memunculkan potensi kandidat berikutnya yang PRZ-nya utuh lebih dalam dan paling dekat. Bullish harmonic: bearish engulfing; bearish harmonic: bullish engulfing. HOP dan TP pola aktif tetap berlaku sampai close-break.")
bool showReactionLevel = input.bool(true, "Level reaksi 23.6 AD", group = G_CONT)
 
const string G_VIEW = "3. Tampilan"
bool showPoints = input.bool(true, "Label X A B C D", group = G_VIEW)
bool showPointPrices = input.bool(false, "Harga pada label XABCD", group = G_VIEW, tooltip = "Matikan untuk menampilkan huruf X, A, B, C, D saja. Harga pada level proyeksi dan panel tetap tersedia.")
bool showRatios = input.bool(true, "Rasio di tengah garis bantu", group = G_VIEW, tooltip = "Seperti alat XABCD: AB/XA pada X-B, BC/AB pada A-C, CD/BC pada B-D, dan AD/XA pada X-D. Arahkan kursor ke angka untuk melihat nama rasionya.")
bool showFill = input.bool(true, "Arsir bentuk pola", group = G_VIEW)
bool showPrz = input.bool(true, "Zona konfluensi (PRZ)", group = G_VIEW)
bool showAbcd = input.bool(true, "Proyeksi AB=CD dan ALT AB=CD", group = G_VIEW)
bool showBc = input.bool(false, "Rentang proyeksi BC", group = G_VIEW)
bool showAlternatives = input.bool(false, "Level D kandidat pola lain", group = G_VIEW)
bool showHop = input.bool(false, "Level HOP dari referensi", group = G_VIEW, tooltip = "HOP mengikuti pola yang tampil. Stingray memakai 1.618 XA sesuai pilihan pengguna; HOP pola lama dihapus setelah gagal.")
bool showTargets = input.bool(true, "TP setelah D valid (AD)", group = G_VIEW, tooltip = "Setelah candle sentuhan PRZ selesai tanpa break: TP1 = D + (A-D)*0.382, TP2 = D + (A-D)*0.618, TP3 = D + (A-D)*1.13. TP mengikuti pola yang masih valid.")
bool showPanel = input.bool(true, "Panel rasio dan kandidat", group = G_VIEW)
string panelMode = input.string("Ringkas", "Mode panel", options = ["Ringkas", "Lengkap"], group = G_VIEW)
string panelFont = input.string("Sangat kecil", "Ukuran teks panel", options = ["Sangat kecil", "Kecil", "Normal"], group = G_VIEW)
string panelTextSize = panelFont == "Sangat kecil" ? size.tiny : panelFont == "Kecil" ? size.small : size.normal
color bullColor = input.color(color.aqua, "Bullish", inline = "col", group = G_VIEW)
color bearColor = input.color(color.orange, "Bearish", inline = "col", group = G_VIEW)
color abcdColor = input.color(color.yellow, "ABCD", inline = "col2", group = G_VIEW)
color przColor = input.color(color.lime, "PRZ", inline = "col2", group = G_VIEW)
color stingrayColor = input.color(color.rgb(156, 39, 176), "PRZ alternatif Stingray", group = G_VIEW)
color targetColor = input.color(color.teal, "Take profit", group = G_VIEW)
 
const string G_ALERT = "4. Alert"
bool enableAlerts = input.bool(true, "Aktifkan kondisi alert PRZ", group = G_ALERT)
bool closeOnly = input.bool(true, "Alert sentuhan setelah candle selesai", group = G_ALERT, tooltip = "Break PRZ dan alert close selalu menunggu candle selesai. Opsi ini hanya mengatur alert sentuhan; mematikannya tidak mengubah aturan break.")
 
patternName(int p) =>
    switch p
        0 => "Alternate Bat"
        1 => "Bat"
        2 => "Butterfly"
        3 => "Crab"
        4 => "Gartley"
        5 => "Deep Crab"
        6 => "Shark"
        7 => "Cypher"
        8 => "5-0"
        9 => "Stingray"
        => "AB=CD"
 
patternId(string name) =>
    switch name
        "Alternate Bat" => 0
        "Bat" => 1
        "Butterfly" => 2
        "Crab" => 3
        "Gartley" => 4
        "Deep Crab" => 5
        "Shark" => 6
        "Cypher" => 7
        "5-0" => 8
        "Stingray" => 9
        "AB=CD" => ABCD_ID
        => -1
 
completionRule(int p) =>
    switch p
        6 => "CD/XC 0.886-1.130 + CD/BC 1.618-2.240"
        7 => "CD/XC 0.786"
        8 => "CD/BC 0.500 + reciprocal AB=CD"
        9 => "AD/XA 1.272-1.414 | XABC Bat/Gartley"
        10 => "CD/AB sesuai pengali AB=CD"
        => "AD/XA + CD/BC"
 
nominalLabel(int p) =>
    switch p
        6 => "D 0.886 XC teoritis"
        7 => "D 0.786 XC teoritis"
        8 => "D 50% BC teoritis"
        9 => "D 1.272 XA teoritis"
        => "D XA teoritis"
 
parameters(int p) =>
    float cdLo = p == 0 ? 2.0 : p == 1 or p == 2 ? 1.618 : p == 3 ? 2.618 : p == 4 ? 1.13 : 2.0
    float cdHi = p == 1 ? 2.618 : p == 2 ? 2.24 : p == 4 ? 1.618 : 3.618
    float ad = p == 0 ? 1.13 : p == 1 ? 0.886 : p == 2 ? 1.27 : p == 4 ? 0.786 : 1.618
    float abLo = p == 0 ? 1.618 : p == 3 ? 1.272 : 1.0
    float abHi = p == 0 or p == 3 ? 1.618 : p == 4 ? 1.0 : 1.272
    float hop = p == 0 ? 1.270 : p == 1 ? 1.141 : p == 2 ? 1.420 : p == 3 ? 1.902 : p == 4 ? 1.046 : 2.050
    [cdLo, cdHi, ad, abLo, abHi, hop]
 
between(float value, float lo, float hi) =>
    value >= lo - 1e-10 and value <= hi + 1e-10
 
eligible(int p, float rAB, float rBC) =>
    // Pembulatan kelayakan sama dengan referensi. Toleransi D dihitung terpisah.
    float ab = math.round(rAB, 2)
    float bc = math.round(rBC, 2)
    bool bOK = switch p
        0 => between(ab, 0.35, 0.41)
        1 => between(ab, 0.35, 0.65)
        2 => between(ab, 0.76, 0.85)
        3 => between(ab, 0.35, 0.75)
        4 => between(ab, 0.59, 0.65)
        => between(ab, 0.86, 0.92)
    bOK and between(bc, 0.35, 0.92)
 
type Projection
    int kind
    bool fits
    bool confluence
    float d
    float lower
    float upper
    float bcLower
    float bcUpper
    float hop
    float score
 
projectLegacy(int p, float x, float a, float b, float c, float rAB, float rBC, bool bull) =>
    [cdLo, cdHi, ad, abLo, abHi, hp] = parameters(p)
    float xa = a - x
    float ab = a - b
    float bc = c - b
    float d = a - xa * ad
    float xaLo = d - math.abs(xa) * tolerance
    float xaHi = d + math.abs(xa) * tolerance
    float bc1 = c - bc * math.max(0.0, cdLo - tolerance)
    float bc2 = c - bc * (cdHi + tolerance)
    float bcLoPrice = math.min(bc1, bc2)
    float bcHiPrice = math.max(bc1, bc2)
    float lo = math.max(xaLo, bcLoPrice)
    float hi = math.min(xaHi, bcHiPrice)
    // D harus selesai melewati B pada kaki yang berlawanan arah dari C.
    lo := bull ? lo : math.max(lo, b + syminfo.mintick)
    hi := bull ? math.min(hi, b - syminfo.mintick) : hi
    bool fits = eligible(p, rAB, rBC)
    bool overlaps = lo <= hi + 1e-10
    float abcd1 = c - ab * abLo
    float abcd2 = c - ab * abHi
    float abcdGap = math.min(math.abs(d - abcd1), math.abs(d - abcd2)) / math.abs(xa)
    // Dahulukan irisan XA/BC, lalu titik akhir ABCD keluarga yang paling dekat.
    float rank = (overlaps ? 0.0 : 10.0 + math.max(0.0, lo - hi) / math.abs(xa)) + abcdGap
    Projection.new(p, fits, fits and overlaps, d, lo, hi, bcLoPrice, bcHiPrice, a - xa * hp, rank)
 
project(int p, float x, float a, float b, float c, float rAB, float rBC, bool bull) =>
    Projection result = na
    if p < 6
        result := projectLegacy(p, x, a, b, c, rAB, rBC, bull)
    else
        float xa = a - x
        float ab = a - b
        float bc = c - b
        float xc = c - x
        float rXC = xc / xa
        bool fits = false
        float d = na
        float lo = na
        float hi = na
        float confirmLo = na
        float confirmHi = na
        float rank = na
        if p == 6
            // Label asli Shark 0-X-A-B-C dipetakan menjadi X-A-B-C-D di sini.
            // OB asli ditampilkan sebagai XC; jangan menggantinya dengan XA yang lebih pendek.
            fits := between(rAB, 0.382, 0.618) and between(rBC, 1.13, 1.618)
            d := c - xc * 0.886
            float edge1 = c - xc * 0.886
            float edge2 = c - xc * 1.13
            float bc1 = c - bc * (1.618 - tolerance)
            float bc2 = c - bc * (2.24 + tolerance)
            confirmLo := math.min(bc1, bc2)
            confirmHi := math.max(bc1, bc2)
            lo := math.max(math.min(edge1, edge2), confirmLo)
            hi := math.min(math.max(edge1, edge2), confirmHi)
        else if p == 7
            fits := between(rAB, 0.382, 0.618) and between(rXC, cypherCMin, 1.414)
            d := c - xc * 0.786
            lo := d - math.abs(xc) * tolerance
            hi := d + math.abs(xc) * tolerance
        else if p == 8
            fits := between(rAB, 1.13, 1.618) and between(rBC, 1.618, 2.24)
            d := c - bc * 0.5
            // Pola 5-0 selesai DI DALAM BC, sehingga aturan lama D melewati B tidak berlaku.
            float reciprocal = c - ab
            confirmLo := reciprocal - math.abs(ab) * tolerance
            confirmHi := reciprocal + math.abs(ab) * tolerance
            lo := math.max(d - math.abs(bc) * tolerance, confirmLo)
            hi := math.min(d + math.abs(bc) * tolerance, confirmHi)
        else
            // Stingray memakai varian ekstensi XA dari pengguna, bukan standar yang dikarang.
            fits := eligible(1, rAB, rBC) or eligible(4, rAB, rBC)
            d := a - xa * 1.272
            float edge2 = a - xa * 1.414
            lo := math.min(d, edge2)
            hi := math.max(d, edge2)
        // Semua penyelesaian harus berlawanan arah dengan kaki C. Hanya 5-0 berada di dalam BC.
        if p == 8
            lo := bull ? math.max(lo, b + syminfo.mintick) : math.max(lo, c + syminfo.mintick)
            hi := bull ? math.min(hi, c - syminfo.mintick) : math.min(hi, b - syminfo.mintick)
        else
            lo := bull ? lo : math.max(lo, b + syminfo.mintick)
            hi := bull ? math.min(hi, b - syminfo.mintick) : hi
        bool overlaps = lo <= hi + 1e-10
        float distance = math.min(math.abs(d - (c - ab)), math.min(math.abs(d - (c - ab * 1.272)), math.abs(d - (c - ab * 1.618)))) / math.abs(xa)
        rank := (overlaps ? 0.0 : 10.0 + math.max(0.0, lo - hi) / math.abs(xa)) + distance
        float hp = p == STINGRAY_ID ? a - xa * 1.618 : na
        result := Projection.new(p, fits, fits and overlaps, d, lo, hi, confirmLo, confirmHi, hp, rank)
    result
 
priceText(float value) =>
    na(value) ? "-" : str.tostring(value, format.mintick)
 
ratioText(float value) =>
    na(value) ? "-" : str.tostring(value, "0.000")
 
midTime(int first, int second) =>
    first + int((second - first) / 2)
 
timeWindow(int xIndex, int bIndex, float early, float ideal, float late) =>
    int baseBars = bIndex - xIndex
    [bIndex + int(math.floor(early * baseBars)), bIndex + int(math.round(ideal * baseBars)), bIndex + int(math.ceil(late * baseBars))]
 
anchorInCurrentBar(int stamp) =>
    time == stamp or (time < stamp and not na(time_close) and stamp < time_close)
 
timeAtIndex(int targetIndex, int knownStamp, int intervalMs) =>
    // Waktu penanda lampau diambil dari candle sebenarnya; hanya waktu mendatang yang diperkirakan.
    not na(knownStamp) ? knownStamp : not na(targetIndex) and targetIndex >= bar_index ? time + (targetIndex - bar_index) * intervalMs : na
 
farSideBreak(bool bullish, float lower, float upper, float candleClose, bool candleConfirmed) =>
    candleConfirmed and (bullish ? candleClose < lower - 1e-10 : candleClose > upper + 1e-10)
 
activationContactRange(bool justActivated, float candleHigh, float candleLow, float candleClose) =>
    // Alternatif baru aktif saat penutupan candle menembus PRZ utama, setelah sumbu sebelumnya.
    [justActivated ? candleClose : candleHigh, justActivated ? candleClose : candleLow]
 
advanceLifecycle(int previousState, int frozenIndex, int currentIndex, int cIndex, int lateIndex, bool monitorZone, bool bullish, float lower, float upper, float candleHigh, float candleLow, float candleClose, bool candleConfirmed) =>
    int nextState = previousState
    int nextIndex = frozenIndex
    if previousState == LIFE_ACTIVE
        bool inWindow = currentIndex > cIndex and currentIndex <= lateIndex
        if monitorZone and inWindow
            bool broken = farSideBreak(bullish, lower, upper, candleClose, candleConfirmed)
            bool touched = candleHigh >= lower - 1e-10 and candleLow <= upper + 1e-10
            // Sumbu membekukan D sebagai tersentuh. Break hanya dicatat setelah candle ditutup.
            if broken or touched
                nextState := broken ? LIFE_BROKEN : LIFE_TOUCHED
                nextIndex := currentIndex
        if nextState == LIFE_ACTIVE and currentIndex >= lateIndex
            nextState := LIFE_LATE
            nextIndex := lateIndex
    [nextState, nextIndex]
 
movingDIndex(int currentIndex, int cIndex, int lateIndex, int ahead, int frozenIndex) =>
    lateIndex <= cIndex ? int(na) : not na(frozenIndex) ? frozenIndex : math.min(math.max(currentIndex + ahead, cIndex + 1), lateIndex)
 
timingPhase(int index, int earlyIndex, int idealIndex, int lateIndex) =>
    index < earlyIndex ? "Sebelum Early" : index < idealIndex ? "Early-Ideal" : index < lateIndex ? "Ideal-Late" : "Late"
 
patternVisible(bool hasD, bool broken, int state) =>
    hasD and not broken and state != LIFE_BROKEN and state != LIFE_LATE
 
completionValid(bool zoneValid, int state, bool broken, int frozenIndex, int currentIndex, bool currentConfirmed) =>
    zoneValid and state == LIFE_TOUCHED and not broken and not na(frozenIndex) and (currentIndex > frozenIndex or currentConfirmed)
 
targetBasisValid(bool bullish, float a, float d, float minimumLeg) =>
    not na(a) and not na(d) and (bullish ? a - d >= minimumLeg : d - a >= minimumLeg)
 
targetPrice(float a, float d, float ratio) =>
    d + (a - d) * ratio
 
monitorCompletedPattern(bool timingAvailable, bool afterAnchorC, int currentIndex, int lateIndex, int state) =>
    timingAvailable and afterAnchorC and (currentIndex <= lateIndex or state == LIFE_TOUCHED)
 
reactionDSide(bool bullish, float level, float candleClose) =>
    not na(level) and (bullish ? candleClose < level - 1e-10 : candleClose > level + 1e-10)
 
reactionReject(bool bullish, float level, float candleHigh, float candleLow, float candleClose, bool candleConfirmed) =>
    candleConfirmed and not na(level) and candleHigh >= level - 1e-10 and candleLow <= level + 1e-10 and reactionDSide(bullish, level, candleClose)
 
continuationEngulf(bool bullish, float candleOpen, float candleClose, float previousOpen, float previousClose, bool candleConfirmed) =>
    bool bearishBody = candleClose < candleOpen - 1e-10 and previousClose > previousOpen + 1e-10 and candleOpen >= previousClose - 1e-10 and candleClose <= previousOpen + 1e-10
    bool bullishBody = candleClose > candleOpen + 1e-10 and previousClose < previousOpen - 1e-10 and candleOpen <= previousClose + 1e-10 and candleClose >= previousOpen - 1e-10
    candleConfirmed and (bullish ? bearishBody : bullishBody)
 
reactionRejectionIndex(int previousIndex, int currentIndex, int contactIndex, int lateIndex, bool eligible, bool rejected) =>
    eligible and not na(contactIndex) and currentIndex > contactIndex and currentIndex <= lateIndex and rejected ? currentIndex : previousIndex
 
continuationAlternativeSignal(int currentIndex, int contactIndex, int rejectionIndex, int lateIndex, bool sourceValid, bool engulf, bool onDSide) =>
    sourceValid and not na(contactIndex) and not na(rejectionIndex) and currentIndex > contactIndex and currentIndex >= rejectionIndex and currentIndex <= lateIndex and engulf and onDSide
 
potentialAlternativeVisible(bool predicted, bool promoted, bool primaryBroken, bool sourceVisible, int state, int currentIndex, int lateIndex) =>
    predicted and not promoted and not primaryBroken and sourceVisible and patternVisible(true, false, state) and currentIndex <= lateIndex
 
// Satu keadaan aktual untuk semua keluarga. Riwayat sentuhan kandidat lain tidak
// pernah menjadi konfirmasi D aktual; setiap promosi memulai pencatatannya sendiri.
type ActivePattern
    int family
    int state
    int frozenIndex
    int frozenTime
    int activationIndex
    int activationTime
    bool broken
 
nextAlternativeId(array<Projection> options, array<bool> failed, int sourceId, bool bullish) =>
    int chosen = -1
    float nearestGap = na
    if sourceId >= 0 and sourceId < PATTERN_COUNT and sourceId < options.size()
        Projection source = options.get(sourceId)
        if source.fits and source.confluence
            for p = 0 to options.size() - 1
                Projection candidate = options.get(p)
                bool notFailed = p < failed.size() and not failed.get(p)
                bool deeper = bullish ? candidate.upper < source.lower - 1e-10 : candidate.lower > source.upper + 1e-10
                if p < PATTERN_COUNT and p != sourceId and candidate.fits and candidate.confluence and notFailed and deeper
                    float gap = bullish ? source.lower - candidate.upper : candidate.lower - source.upper
                    if na(nearestGap) or gap < nearestGap - 1e-10
                        nearestGap := gap
                        chosen := p
    chosen
 
advanceActivePattern(ActivePattern previous, array<Projection> options, array<bool> failed, int currentIndex, int cIndex, int lateIndex, int stamp, int lateStamp, bool bullish, float candleHigh, float candleLow, float candleClose, bool candleConfirmed) =>
    ActivePattern next = ActivePattern.new(previous.family, previous.state, previous.frozenIndex, previous.frozenTime, previous.activationIndex, previous.activationTime, previous.broken)
    bool afterAnchor = currentIndex > cIndex
    // Tandai close-break semua kandidat sebelum memilih alternatif. Gap yang
    // melampaui beberapa zona langsung melewati kandidat yang sudah gagal.
    if afterAnchor and currentIndex <= lateIndex and candleConfirmed and options.size() > 0
        for p = 0 to options.size() - 1
            Projection candidate = options.get(p)
            if p < PATTERN_COUNT and p < failed.size() and candidate.fits and candidate.confluence and farSideBreak(bullish, candidate.lower, candidate.upper, candleClose, true)
                failed.set(p, true)
    if next.family >= 0 and next.family < PATTERN_COUNT and next.family < options.size() and not previous.broken
        Projection source = options.get(next.family)
        bool monitor = source.fits and source.confluence
        bool stillMonitored = afterAnchor and (currentIndex <= lateIndex or previous.state == LIFE_TOUCHED)
        bool justBroken = monitor and stillMonitored and farSideBreak(bullish, source.lower, source.upper, candleClose, candleConfirmed)
        if justBroken
            next.broken := true
            next.state := LIFE_BROKEN
            if na(next.frozenIndex)
                next.frozenIndex := currentIndex
                next.frozenTime := stamp
            // Setelah Late pola tersentuh masih dapat gagal, tetapi tidak
            // memperoleh pengganti baru ataupun perpanjangan batas waktunya.
            int replacement = currentIndex <= lateIndex ? nextAlternativeId(options, failed, next.family, bullish) : -1
            if replacement >= 0
                next := ActivePattern.new(replacement, LIFE_ACTIVE, int(na), int(na), currentIndex, stamp, false)
                Projection promoted = options.get(replacement)
                // Zona baru belum berlaku pada sumbu yang lebih awal di bar
                // promosi. Hanya close promosi boleh menyentuh D aktual baru.
                [promotedState, promotedIndex] = advanceLifecycle(LIFE_ACTIVE, int(na), currentIndex, currentIndex - 1, lateIndex, true, bullish, promoted.lower, promoted.upper, candleClose, candleClose, candleClose, candleConfirmed)
                next.state := promotedState
                next.frozenIndex := promotedIndex
                if promotedState != LIFE_ACTIVE
                    next.frozenTime := promotedState == LIFE_LATE ? lateStamp : stamp
        else
            [advancedState, advancedIndex] = advanceLifecycle(previous.state, previous.frozenIndex, currentIndex, cIndex, lateIndex, monitor, bullish, source.lower, source.upper, candleHigh, candleLow, candleClose, candleConfirmed)
            next.state := advancedState
            next.frozenIndex := advancedIndex
            if previous.state == LIFE_ACTIVE and advancedState != LIFE_ACTIVE
                next.frozenTime := advancedState == LIFE_LATE ? lateStamp : stamp
    next
 
var array<line> drawnLines = array.new<line>()
var array<label> drawnLabels = array.new<label>()
var array<box> drawnBoxes = array.new<box>()
var array<polyline> drawnShapes = array.new<polyline>()
 
drawLine(int t1, float p1, int t2, float p2, color col, string style, int width) =>
    line id = line.new(t1, p1, t2, p2, xloc = xloc.bar_time, color = col, style = style, width = width)
    drawnLines.push(id)
    id
 
drawPoint(int t, float p, string letter, color col, bool above, string details) =>
    string txt = letter + (showPointPrices ? "\n" + priceText(p) : "")
    label id = label.new(t, p, txt, xloc = xloc.bar_time, yloc = yloc.price, style = above ? label.style_label_down : label.style_label_up, color = col, textcolor = color.white, size = size.small, tooltip = details + "\nHarga: " + priceText(p))
    drawnLabels.push(id)
    id
 
drawRatio(int t1, float p1, int t2, float p2, float ratio, string title, color col) =>
    // Pusatkan kotak angka tepat pada garis bantu, tanpa pergeseran ke atas atau bawah.
    label id = label.new(midTime(t1, t2), (p1 + p2) / 2, ratioText(ratio), xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_center, color = col, textcolor = color.white, textalign = text.align_center, size = size.small, tooltip = title + " = " + ratioText(ratio))
    drawnLabels.push(id)
    id
 
drawLevel(int start, int finish, float value, string txt, color col, string style) =>
    drawLine(start, value, finish, value, col, style, 1)
    // Label transparan berujung kiri menempatkan teks tepat di KANAN ujung garis.
    label id = label.new(finish, value, txt + "  " + priceText(value), xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(color.black, 100), textcolor = col, textalign = text.align_left, size = size.small)
    drawnLabels.push(id)
 
drawTimeGuide(int stamp, float lower, float upper, string txt, color col) =>
    drawLine(stamp, lower, stamp, upper, col, line.style_dotted, 1)
    label id = label.new(stamp, upper, txt, xloc = xloc.bar_time, yloc = yloc.price, style = label.style_none, color = color.new(color.black, 100), textcolor = col, size = size.small, tooltip = "Dihitung dari B dengan basis jumlah candle X ke B")
    drawnLabels.push(id)
 
drawTriangle(int t1, float p1, int t2, float p2, int t3, float p3, color col) =>
    array<chart.point> points = array.from(chart.point.from_time(t1, p1), chart.point.from_time(t2, p2), chart.point.from_time(t3, p3))
    polyline id = polyline.new(points, curved = false, closed = true, xloc = xloc.bar_time, line_color = color.new(col, 75), fill_color = color.new(col, 92))
    drawnShapes.push(id)
 
// Geometri sepenuhnya memakai koordinat manual, terlepas dari swing pasar.
float xa = pa - px
float ab = pa - pb
float bc = pc - pb
float absXA = math.abs(xa)
bool ready = tx > 0 and ta > 0 and tb > 0 and tc > 0
bool ordered = ready and tx < ta and ta < tb and tb < tc
bool legsNonzero = absXA >= syminfo.mintick and math.abs(ab) >= syminfo.mintick and math.abs(bc) >= syminfo.mintick
bool bull = xa > 0
bool zigzag = legsNonzero and (bull ? ab > 0 and bc > 0 : ab < 0 and bc < 0)
bool geometryOK = ordered and zigzag
float rAB = legsNonzero ? math.abs(ab / xa) : na
float rBC = legsNonzero ? math.abs(bc / ab) : na
 
// Petakan waktu input ke candle chart sebenarnya; tanpa perkiraan durasi kalender
// untuk jumlah candle XB maupun lokasi sentuhan dan batas waktu historis.
float chartSeconds = timeframe.in_seconds()
int intervalMs = int(nz(chartSeconds, 60.0) * 1000)
intervalMs := math.max(intervalMs, 1)
var int firstLoadedTime = time
var int xBar = na
var int aBar = na
var int bBar = na
var int cBar = na
if na(xBar) and anchorInCurrentBar(tx)
    xBar := bar_index
if na(aBar) and anchorInCurrentBar(ta)
    aBar := bar_index
if na(bBar) and anchorInCurrentBar(tb)
    bBar := bar_index
if na(cBar) and anchorInCurrentBar(tc)
    cBar := bar_index
bool anchorsMapped = not na(xBar) and not na(aBar) and not na(bBar) and not na(cBar)
bool anchorBarsOrdered = anchorsMapped and xBar < aBar and aBar < bBar and bBar < cBar
bool timingConfigOK = earlyFactor < idealFactor and idealFactor < lateFactor
bool basisReady = not na(xBar) and not na(bBar) and bBar > xBar and timingConfigOK
int earlyIndex = na
int idealIndex = na
int lateIndex = na
if basisReady
    [e, i, l] = timeWindow(xBar, bBar, earlyFactor, idealFactor, lateFactor)
    earlyIndex := e
    idealIndex := i
    lateIndex := l
var int earlyStamp = na
var int idealStamp = na
var int lateStamp = na
if basisReady
    if bar_index == earlyIndex
        earlyStamp := time
    if bar_index == idealIndex
        idealStamp := time
    if bar_index == lateIndex
        lateStamp := time
int earlyTime = timeAtIndex(earlyIndex, earlyStamp, intervalMs)
int idealTime = timeAtIndex(idealIndex, idealStamp, intervalMs)
int lateTime = timeAtIndex(lateIndex, lateStamp, intervalMs)
bool timingReady = geometryOK and anchorBarsOrdered and timingConfigOK
 
array<Projection> candidates = array.new<Projection>()
bool stingrayRequested = model == "Stingray"
int selected = stingrayRequested ? -1 : patternId(model)
float bestScore = na
if geometryOK
    for p = 0 to PATTERN_COUNT - 1
        Projection candidate = project(p, px, pa, pb, pc, rAB, rBC, bull)
        candidates.push(candidate)
        if candidate.fits and p != STINGRAY_ID
            bool canSelectPrimary = model == "Otomatis" or (stingrayRequested and (p == 1 or p == 4))
            if canSelectPrimary and (na(bestScore) or candidate.score < bestScore)
                bestScore := candidate.score
                selected := p
 
bool harmonicSelected = geometryOK and selected >= 0 and selected < PATTERN_COUNT
Projection primary = harmonicSelected ? candidates.get(selected) : na
bool abcdMode = geometryOK and selected == ABCD_ID
float dABCD = pc - ab
float d1272 = pc - ab * 1.272
float d1618 = pc - ab * 1.618
// Pertahankan titik proyeksi di dalam PRZ valid ketika pusat XA berada di luar.
float dMain = harmonicSelected ? (primary.confluence ? math.max(primary.lower, math.min(primary.upper, primary.d)) : primary.d) : abcdMode ? pc - ab * abcdMultiplier : na
bool mainFits = harmonicSelected ? primary.fits : abcdMode and between(rBC, 0.382, 0.886)
color mainColor = bull ? bullColor : bearColor
color drawColor = mainFits ? mainColor : color.gray
 
// Semua keluarga harmonic berbagi satu keadaan aktif dan satu daftar close-break.
// Kandidat gagal hanya dipakai untuk pemilihan; sentuhan sebelum promosi tidak
// pernah dipindahkan ke pencatatan D aktual keluarga yang baru.
bool afterC = geometryOK and not na(cBar) and bar_index > cBar
bool inMonitoringWindow = timingReady and afterC and bar_index <= lateIndex
var array<bool> candidateBroken = array.new<bool>(PATTERN_COUNT, false)
var ActivePattern activePattern = ActivePattern.new(selected, LIFE_ACTIVE, int(na), int(na), int(na), int(na), false)
int previousActiveFamily = activePattern.family
if timingReady and harmonicSelected
    activePattern := advanceActivePattern(activePattern, candidates, candidateBroken, bar_index, cBar, lateIndex, time, lateTime, bull, high, low, close, barstate.isconfirmed)
bool activeFamilyChanged = activePattern.family != previousActiveFamily
bool activeHarmonic = harmonicSelected and activePattern.family >= 0 and activePattern.family < PATTERN_COUNT
Projection activeProjection = activeHarmonic ? candidates.get(activePattern.family) : na
 
// AB=CD berdiri sendiri; ID-nya tidak pernah dipakai mengakses array keluarga.
var int abcdState = LIFE_ACTIVE
var int abcdFrozenIndex = na
var int abcdFrozenTime = na
var bool abcdBroken = false
if timingReady and abcdMode
    bool abcdMonitor = mainFits
    if monitorCompletedPattern(timingReady, afterC, bar_index, lateIndex, abcdState) and abcdMonitor and farSideBreak(bull, dMain, dMain, close, barstate.isconfirmed)
        abcdBroken := true
    [nextAbcdState, nextAbcdIndex] = advanceLifecycle(abcdState, abcdFrozenIndex, bar_index, cBar, lateIndex, abcdMonitor, bull, dMain, dMain, high, low, close, barstate.isconfirmed)
    if abcdState == LIFE_ACTIVE and nextAbcdState != LIFE_ACTIVE
        abcdFrozenTime := nextAbcdState == LIFE_LATE ? lateTime : time
    abcdState := nextAbcdState
    abcdFrozenIndex := nextAbcdIndex
 
int activeFamily = activeHarmonic ? activePattern.family : abcdMode ? ABCD_ID : -1
int lifecycleState = activeHarmonic ? activePattern.state : abcdMode ? abcdState : timingReady and bar_index >= lateIndex ? LIFE_LATE : LIFE_ACTIVE
int frozenIndex = activeHarmonic ? activePattern.frozenIndex : abcdFrozenIndex
int frozenTime = activeHarmonic ? activePattern.frozenTime : abcdFrozenTime
bool activeBroken = activeHarmonic ? activePattern.broken : abcdBroken
bool activeZoneValid = activeHarmonic and activeProjection.fits and activeProjection.confluence
bool monitorZone = activeZoneValid or (abcdMode and mainFits)
float activeD = activeHarmonic ? (activeProjection.confluence ? math.max(activeProjection.lower, math.min(activeProjection.upper, activeProjection.d)) : activeProjection.d) : abcdMode ? dMain : na
bool activeFits = activeHarmonic ? activeProjection.fits : mainFits
bool actualReplacement = activeHarmonic and not na(activePattern.activationIndex)
int activeZoneStart = actualReplacement ? activePattern.activationTime : tc
int dIndex = timingReady ? movingDIndex(bar_index, cBar, lateIndex, leadBars, frozenIndex) : na
int td = not na(dIndex) ? (not na(frozenTime) ? frozenTime : timeAtIndex(dIndex, int(na), intervalMs)) : na
int durationMs = math.max(intervalMs, tb - ta)
string timePhase = timingReady ? timingPhase(not na(frozenIndex) ? frozenIndex : bar_index, earlyIndex, idealIndex, lateIndex) : "Waktu belum tersedia"
string lifecycleText = not timingConfigOK ? "Early harus < Ideal < Late" : not anchorsMapped ? (time < tc ? "Menunggu candle XABC" : tx < firstLoadedTime ? "Riwayat XABC belum dimuat" : "Waktu titik tidak cocok dengan candle") : not anchorBarsOrdered ? "XABC harus di candle berbeda" : lateIndex <= cBar ? "Late sudah lewat saat C ditentukan" : activeBroken ? "PRZ aktif break | pola gagal" : lifecycleState == LIFE_BROKEN ? (activeZoneValid ? "Berhenti: PRZ break" : "Berhenti: target D dilewati") : lifecycleState == LIFE_TOUCHED ? (activeZoneValid ? "Berhenti: PRZ tersentuh" : "Berhenti: target D tersentuh") : lifecycleState == LIFE_LATE ? "Berhenti: batas Late" : monitorZone ? "D mengikuti candle | " + timePhase : "Tanpa PRZ valid | batas Late"
 
// Potensi dini selalu bersumber dari keluarga AKTIF saat ini dan memakai
// pemilih PRZ lebih dalam yang sama dengan penggantian aktual.
int nextFamily = activeHarmonic and not activeBroken ? nextAlternativeId(candidates, candidateBroken, activeFamily, bull) : -1
float reactionLevel = activeZoneValid ? targetPrice(pa, activeD, 0.236) : na
bool continuationSourceValid = enableContinuation and timingReady and nextFamily >= 0 and completionValid(activeZoneValid, lifecycleState, activeBroken, frozenIndex, bar_index, barstate.isconfirmed) and targetBasisValid(bull, pa, activeD, syminfo.mintick)
var int reactionRejectIndex = na
var int potentialSourceFamily = -1
var int potentialFamily = -1
var int potentialIndex = na
var int potentialTime = na
var float potentialMarkerPrice = na
var int potentialState = LIFE_ACTIVE
var int potentialFrozenIndex = na
var int potentialFrozenTime = na
if activeFamilyChanged
    reactionRejectIndex := na
    potentialSourceFamily := -1
    potentialFamily := -1
    potentialIndex := na
    potentialTime := na
    potentialMarkerPrice := na
    potentialState := LIFE_ACTIVE
    potentialFrozenIndex := na
    potentialFrozenTime := na
bool rejected236 = reactionReject(bull, reactionLevel, high, low, close, barstate.isconfirmed)
reactionRejectIndex := reactionRejectionIndex(reactionRejectIndex, bar_index, frozenIndex, lateIndex, continuationSourceValid, rejected236)
bool engulfContinuation = continuationEngulf(bull, open, close, open[1], close[1], barstate.isconfirmed)
bool earlyAlternativeSignal = continuationAlternativeSignal(bar_index, frozenIndex, reactionRejectIndex, lateIndex, continuationSourceValid, engulfContinuation, reactionDSide(bull, reactionLevel, close))
bool potentialJustStarted = na(potentialIndex) and earlyAlternativeSignal and nextFamily >= 0
if potentialJustStarted
    potentialSourceFamily := activeFamily
    potentialFamily := nextFamily
    potentialIndex := bar_index
    potentialTime := time
    potentialMarkerPrice := bull ? high : low
bool potentialPredicted = not na(potentialIndex) and potentialSourceFamily == activeFamily and potentialFamily >= 0
Projection potentialProjection = potentialPredicted ? candidates.get(potentialFamily) : na
if potentialPredicted and not activeBroken
    [previewHigh, previewLow] = activationContactRange(potentialJustStarted, high, low, close)
    [nextPreviewState, nextPreviewIndex] = advanceLifecycle(potentialState, potentialFrozenIndex, bar_index, potentialIndex - 1, lateIndex, true, bull, potentialProjection.lower, potentialProjection.upper, previewHigh, previewLow, close, barstate.isconfirmed)
    if potentialState == LIFE_ACTIVE and nextPreviewState != LIFE_ACTIVE
        potentialFrozenTime := nextPreviewState == LIFE_LATE ? lateTime : time
    potentialState := nextPreviewState
    potentialFrozenIndex := nextPreviewIndex
float potentialD = potentialPredicted ? math.max(potentialProjection.lower, math.min(potentialProjection.upper, potentialProjection.d)) : na
int potentialDIndex = potentialPredicted ? movingDIndex(bar_index, cBar, lateIndex, leadBars, potentialFrozenIndex) : na
int potentialDTime = not na(potentialDIndex) ? (not na(potentialFrozenTime) ? potentialFrozenTime : timeAtIndex(potentialDIndex, int(na), intervalMs)) : na
string potentialName = potentialPredicted ? patternName(potentialFamily) : "-"
 
// Render satu keluarga yang masih berlaku: tidak ada fallback ke keluarga gagal.
bool hasVisiblePattern = patternVisible(not na(activeD), activeBroken, lifecycleState)
bool potentialVisible = potentialAlternativeVisible(potentialPredicted, false, activeBroken, hasVisiblePattern, potentialState, bar_index, lateIndex)
int visibleFamily = hasVisiblePattern ? activeFamily : -1
float visibleD = hasVisiblePattern ? activeD : na
int visibleDTime = hasVisiblePattern ? td : na
int visibleFrozenIndex = hasVisiblePattern ? frozenIndex : na
int visibleState = lifecycleState
bool visibleZone = hasVisiblePattern and activeZoneValid
float visibleLower = visibleZone ? activeProjection.lower : na
float visibleUpper = visibleZone ? activeProjection.upper : na
float visibleHop = hasVisiblePattern and activeHarmonic ? activeProjection.hop : na
int visibleZoneStart = activeZoneStart
color visibleColor = activeFamily == STINGRAY_ID ? stingrayColor : activeFits ? mainColor : color.gray
color visibleZoneColor = activeFamily == STINGRAY_ID ? stingrayColor : przColor
bool visibleComplete = completionValid(hasVisiblePattern and monitorZone, visibleState, activeBroken, visibleFrozenIndex, bar_index, barstate.isconfirmed)
bool targetsReady = visibleComplete and targetBasisValid(bull, pa, visibleD, syminfo.mintick)
string visibleName = hasVisiblePattern ? patternName(visibleFamily) : "-"
string visiblePhase = timePhase
string visibleStatus = potentialVisible ? "Valid | Potensi " + potentialName : hasVisiblePattern ? (visibleComplete ? (targetsReady ? "Valid | D terkonfirmasi" : "Valid | AD tidak mendukung TP") : lifecycleText) : activeBroken or lifecycleState == LIFE_BROKEN ? "Pola gagal disembunyikan" : lifecycleState == LIFE_LATE ? "Berakhir: batas Late" : lifecycleText
 
// ABCD memakai XABC tetap. Pelampauan completion membuka ALT ABCD sesuai input.
var bool abcdExceeded = false
if afterC and (bull ? low < dABCD - syminfo.mintick / 2 : high > dABCD + syminfo.mintick / 2)
    abcdExceeded := true
bool altVisible = altMode == "Selalu tampil" or abcdExceeded or (abcdMode and abcdMultiplier > 1.0)
 
// Alert berganti ke zona keluarga aktif; sumbu sebelum promosi tidak dianggap kontak.
[alertHigh, alertLow] = activationContactRange(activeFamilyChanged, high, low, close)
bool overlapsPrz = visibleZone and inMonitoringWindow and alertHigh >= visibleLower and alertLow <= visibleUpper
bool closedInPrz = visibleZone and inMonitoringWindow and close >= visibleLower and close <= visibleUpper
bool firstTouch = overlapsPrz and (not overlapsPrz[1] or activeFamilyChanged)
bool firstClose = closedInPrz and (not closedInPrz[1] or activeFamilyChanged)
bool alertTiming = not closeOnly or barstate.isconfirmed
bool touchSignal = enableAlerts and alertTiming and firstTouch
bool closeSignal = enableAlerts and barstate.isconfirmed and firstClose
alertcondition(touchSignal, "Harga menyentuh PRZ manual", "{{ticker}} {{interval}}: harga menyentuh PRZ harmonic manual. Periksa reaksi harga pada chart.")
alertcondition(closeSignal, "Harga close di PRZ manual", "{{ticker}} {{interval}}: harga close di dalam PRZ harmonic manual.")
alertcondition(enableAlerts and potentialJustStarted and potentialVisible, "Potensi alternatif: reject 23.6 + engulfing", "{{ticker}} {{interval}}: reject 23.6 AD dan engulfing searah kelanjutan CD memproyeksikan kandidat harmonic berikutnya. PRZ pola aktif belum close-break.")
 
var table panel = table.new(position.top_right, panelMode == "Ringkas" ? 2 : 4, panelMode == "Ringkas" ? 6 : PATTERN_COUNT + 8, bgcolor = color.new(color.black, 15), border_width = 1, border_color = color.new(color.gray, 70))
if barstate.isfirst and panelMode == "Lengkap"
    table.merge_cells(panel, 1, 1, 3, 1)
    table.merge_cells(panel, 1, PATTERN_COUNT + 6, 3, PATTERN_COUNT + 6)
    table.merge_cells(panel, 1, PATTERN_COUNT + 7, 3, PATTERN_COUNT + 7)
 
cell(int col, int row, string txt, color foreground, color background) =>
    table.cell(panel, col, row, txt, text_color = foreground, bgcolor = background, text_size = panelTextSize)
 
compactCell(int col, int row, string txt, color foreground) =>
    table.cell(panel, col, row, txt, text_color = foreground, bgcolor = color.new(color.black, 15), text_size = panelTextSize)
 
if barstate.islast
    while drawnLines.size() > 0
        line.delete(drawnLines.pop())
    while drawnLabels.size() > 0
        label.delete(drawnLabels.pop())
    while drawnBoxes.size() > 0
        box.delete(drawnBoxes.pop())
    while drawnShapes.size() > 0
        polyline.delete(drawnShapes.pop())
    table.clear(panel, 0, 0, panelMode == "Ringkas" ? 1 : 3, panelMode == "Ringkas" ? 5 : PATTERN_COUNT + 7)
 
    // Rangka XABC bersama mengikuti keluarga yang masih berlaku, termasuk Stingray.
    if ordered and (hasVisiblePattern or not geometryOK)
        color trunkColor = hasVisiblePattern ? visibleColor : mainColor
        drawLine(tx, px, ta, pa, trunkColor, line.style_solid, 2)
        drawLine(ta, pa, tb, pb, trunkColor, line.style_solid, 2)
        drawLine(tb, pb, tc, pc, trunkColor, line.style_solid, 2)
        if showPoints
            drawPoint(tx, px, "X", trunkColor, not bull, "Titik X manual")
            drawPoint(ta, pa, "A", trunkColor, bull, "Titik A manual")
            drawPoint(tb, pb, "B", trunkColor, not bull, "Titik B manual")
            drawPoint(tc, pc, "C", trunkColor, bull, "Titik C manual")
 
    if geometryOK and hasVisiblePattern
        int visibleEnd = math.max(nz(visibleDTime, time), time) + intervalMs * rightBars
        bool canPlotD = timingReady and not na(visibleDTime)
        bool dAtUpper = visibleZone and math.abs(visibleD - visibleUpper) < syminfo.mintick / 2
        bool dAtLower = visibleZone and math.abs(visibleD - visibleLower) < syminfo.mintick / 2
        string dLevelTitle = "D " + visibleName + (showPrz ? (dAtUpper ? " / PRZ atas" : dAtLower ? " / PRZ bawah" : "") : "")
        if showFill
            drawTriangle(tx, px, ta, pa, tb, pb, visibleColor)
        if showRatios
            drawLine(tx, px, tb, pb, visibleColor, line.style_dotted, 1)
            drawLine(ta, pa, tc, pc, visibleColor, line.style_dotted, 1)
            drawRatio(tx, px, tb, pb, rAB, "AB/XA", visibleColor)
            drawRatio(ta, pa, tc, pc, rBC, "BC/AB", visibleColor)
 
        drawLevel(visibleZoneStart, visibleEnd, visibleD, dLevelTitle, visibleColor, line.style_solid)
        if activeHarmonic and math.abs(visibleD - activeProjection.d) >= syminfo.mintick / 2
            drawLevel(visibleZoneStart, visibleEnd, activeProjection.d, nominalLabel(visibleFamily), color.gray, line.style_dotted)
        if canPlotD
            drawLine(tc, pc, visibleDTime, visibleD, visibleColor, visibleState == LIFE_ACTIVE ? line.style_dashed : line.style_solid, 2)
            if showFill
                drawTriangle(tb, pb, tc, pc, visibleDTime, visibleD, visibleColor)
            if showPoints
                string dDetails = "D | " + visibleName + (visibleFamily != ABCD_ID ? "\n" + completionRule(visibleFamily) : "") + "\n" + visibleStatus + "\n" + visiblePhase
                if visibleComplete and not targetsReady
                    dDetails += "\nTP AD tidak tersedia: AD terlalu pendek atau arahnya berlawanan dengan pembalikan pola."
                drawPoint(visibleDTime, visibleD, "D", visibleColor, not bull, dDetails)
            if showRatios
                drawLine(tb, pb, visibleDTime, visibleD, visibleColor, line.style_dotted, 1)
                drawLine(tx, px, visibleDTime, visibleD, visibleColor, line.style_dotted, 1)
                drawRatio(tb, pb, visibleDTime, visibleD, math.abs((pc - visibleD) / bc), "CD/BC", visibleColor)
                float fourthRatio = visibleFamily == 6 or visibleFamily == 7 ? math.abs((pc - visibleD) / (pc - px)) : visibleFamily == 8 ? math.abs((pc - visibleD) / ab) : math.abs((pa - visibleD) / xa)
                string fourthTitle = visibleFamily == 6 or visibleFamily == 7 ? "CD/XC" : visibleFamily == 8 ? "CD/AB (reciprocal)" : "AD/XA"
                drawRatio(tx, px, visibleDTime, visibleD, fourthRatio, fourthTitle, visibleColor)
 
        if showPrz and visibleZone
            drawnBoxes.push(box.new(visibleZoneStart, visibleUpper, visibleEnd, visibleLower, xloc = xloc.bar_time, border_color = visibleZoneColor, bgcolor = color.new(visibleZoneColor, 87)))
            if not dAtUpper
                drawLevel(visibleZoneStart, visibleEnd, visibleUpper, "PRZ " + visibleName + " atas", visibleZoneColor, line.style_dotted)
            if not dAtLower
                drawLevel(visibleZoneStart, visibleEnd, visibleLower, "PRZ " + visibleName + " bawah", visibleZoneColor, line.style_dotted)
        if showHop and not na(visibleHop)
            string hopTitle = visibleFamily == STINGRAY_ID ? "HOP Stingray 1.618 XA" : "HOP " + visibleName
            drawLevel(visibleZoneStart, visibleEnd, visibleHop, hopTitle, color.red, line.style_dashed)
        if showTargets and targetsReady and canPlotD
            drawLevel(visibleDTime, visibleEnd, targetPrice(pa, visibleD, 0.382), "TP 1 | 0.382 AD", targetColor, line.style_dashed)
            drawLevel(visibleDTime, visibleEnd, targetPrice(pa, visibleD, 0.618), "TP 2 | 0.618 AD", targetColor, line.style_dashed)
            drawLevel(visibleDTime, visibleEnd, targetPrice(pa, visibleD, 1.13), "TP 3 | 1.130 AD", targetColor, line.style_dashed)
 
        if showTimingZones and basisReady
            float timingLow = math.min(math.min(px, pa), math.min(pb, math.min(pc, visibleD)))
            float timingHigh = math.max(math.max(px, pa), math.max(pb, math.max(pc, visibleD)))
            if visibleZone
                timingLow := math.min(timingLow, visibleLower)
                timingHigh := math.max(timingHigh, visibleUpper)
            float timingPad = math.max((timingHigh - timingLow) * 0.12, syminfo.mintick * 10)
            if not na(earlyTime)
                drawTimeGuide(earlyTime, timingLow - timingPad, timingHigh, "Early " + ratioText(earlyFactor), color.silver)
            if not na(idealTime)
                drawTimeGuide(idealTime, timingLow - timingPad, timingHigh, "Ideal " + ratioText(idealFactor), color.teal)
            if not na(lateTime)
                drawTimeGuide(lateTime, timingLow - timingPad, timingHigh, "Late " + ratioText(lateFactor), color.orange)
 
        // Level ABCD memakai XABC manual yang sama; garis proyeksinya mengikuti D yang masih berlaku.
        if showAbcd
            array<float> levels = array.from(dABCD, d1272, d1618)
            array<string> titles = array.from("AB=CD (1.000)", "ALT AB=CD 1.272", "ALT AB=CD 1.618")
            for j = 0 to 2
                if j == 0 or altVisible
                    float value = levels.get(j)
                    drawLevel(tc, visibleEnd, value, titles.get(j), abcdColor, line.style_dashed)
                    if canPlotD
                        drawLine(tc, pc, visibleDTime, value, color.new(abcdColor, 45), line.style_dotted, 1)
        if activeHarmonic
            if showBc and not na(activeProjection.bcUpper) and not na(activeProjection.bcLower)
                string confirmName = visibleFamily == 8 ? "Reciprocal AB=CD" : "BC"
                drawLevel(visibleZoneStart, visibleEnd, activeProjection.bcUpper, confirmName + " batas atas", color.silver, line.style_dotted)
                drawLevel(visibleZoneStart, visibleEnd, activeProjection.bcLower, confirmName + " batas bawah", color.silver, line.style_dotted)
            if visibleFamily == 8
                drawLevel(tc, visibleEnd, pc - ab, "5-0 reciprocal AB=CD", visibleColor, line.style_dotted)
            if visibleFamily == 6 and activeFits and showShark50 and canPlotD
                float shiftedAB = math.abs(bc / ab)
                float shiftedBC = math.abs((pc - visibleD) / bc)
                if between(shiftedAB, 1.13, 1.618) and between(shiftedBC, 1.618, 2.24)
                    int te = visibleDTime + durationMs
                    int chainEnd = math.max(te, time) + intervalMs * rightBars
                    float e50 = visibleD + (pc - visibleD) * 0.5
                    float eRec = visibleD + bc
                    color nextColor = bull ? bearColor : bullColor
                    drawLine(visibleDTime, visibleD, te, e50, nextColor, line.style_dashed, 2)
                    drawLevel(visibleDTime, chainEnd, e50, "5-0 lanjutan: 50% CD Shark", nextColor, line.style_dashed)
                    drawLevel(visibleDTime, chainEnd, eRec, "5-0 lanjutan: reciprocal", nextColor, line.style_dotted)
                    if showPoints
                        drawPoint(te, e50, "E", nextColor, bull, "D pola 5-0 lanjutan (label E pada Shark).\nHipotesis; D Shark masih proyeksi.")
        if showAlternatives and activeHarmonic and bar_index <= lateIndex
            for p = 0 to PATTERN_COUNT - 1
                Projection candidate = candidates.get(p)
                bool deeper = bull ? candidate.upper < activeProjection.lower - 1e-10 : candidate.lower > activeProjection.upper + 1e-10
                if candidate.fits and candidate.confluence and p != activeFamily and not candidateBroken.get(p) and deeper
                    float candidateD = math.max(candidate.lower, math.min(candidate.upper, candidate.d))
                    drawLevel(visibleZoneStart, visibleEnd, candidateD, "D kandidat " + patternName(p), color.new(visibleColor, 35), line.style_dotted)
 
        if showReactionLevel and continuationSourceValid and bar_index <= lateIndex
            drawLevel(nz(frozenTime, tc), visibleEnd, reactionLevel, "Reaksi 23.6 AD", color.new(visibleColor, 15), line.style_dotted)
        if potentialVisible and not na(potentialDTime)
            // Lapisan ini adalah proyeksi. Pola sumber mempertahankan HOP dan TP miliknya.
            int previewEnd = math.max(potentialDTime, time) + intervalMs * rightBars
            color previewColor = color.new(stingrayColor, 15)
            bool previewAtUpper = math.abs(potentialD - potentialProjection.upper) < syminfo.mintick / 2
            bool previewAtLower = math.abs(potentialD - potentialProjection.lower) < syminfo.mintick / 2
            string previewTitle = "Potensi D " + potentialName + (showPrz ? (previewAtUpper ? " / PRZ atas" : previewAtLower ? " / PRZ bawah" : "") : "")
            drawLine(tc, pc, potentialDTime, potentialD, previewColor, line.style_dashed, 1)
            drawLevel(potentialTime, previewEnd, potentialD, previewTitle, previewColor, line.style_dashed)
            if showPrz
                drawnBoxes.push(box.new(potentialTime, potentialProjection.upper, previewEnd, potentialProjection.lower, xloc = xloc.bar_time, border_color = previewColor, border_style = line.style_dashed, bgcolor = color.new(stingrayColor, 96)))
                if not previewAtUpper
                    drawLevel(potentialTime, previewEnd, potentialProjection.upper, "Potensi PRZ " + potentialName + " atas", previewColor, line.style_dashed)
                if not previewAtLower
                    drawLevel(potentialTime, previewEnd, potentialProjection.lower, "Potensi PRZ " + potentialName + " bawah", previewColor, line.style_dashed)
            if showPoints
                drawPoint(potentialDTime, potentialD, "D? Potensi " + potentialName, previewColor, not bull, "D? Potensi " + potentialName + " | reject 23.6 AD + engulfing searah CD\nPola " + visibleName + " masih berlaku. Pengganti aktual menunggu close-break PRZ aktif.\n" + (potentialState == LIFE_TOUCHED ? "Zona potensi sudah tersentuh" : "Proyeksi dibatasi Late semula"))
                drawPoint(potentialTime, potentialMarkerPrice, "23.6 + ENG", previewColor, bull, "Candle engulfing searah CD setelah reject 23.6 AD\nPRZ pola aktif belum close-break")
            if showRatios
                drawLine(tx, px, potentialDTime, potentialD, previewColor, line.style_dotted, 1)
                float previewRatio = potentialFamily == 6 or potentialFamily == 7 ? math.abs((pc - potentialD) / (pc - px)) : potentialFamily == 8 ? math.abs((pc - potentialD) / ab) : math.abs((pa - potentialD) / xa)
                string previewRatioTitle = potentialFamily == 6 or potentialFamily == 7 ? "CD/XC" : potentialFamily == 8 ? "CD/AB (reciprocal)" : "AD/XA"
                drawRatio(tx, px, potentialDTime, potentialD, previewRatio, "Potensi " + potentialName + " " + previewRatioTitle, previewColor)
 
    string panelStatus = not ready ? "Pilih XABC" : not ordered ? "Urutan waktu salah" : not zigzag ? "Cek kaki XABC" : not timingReady ? lifecycleText : hasVisiblePattern and not activeFits ? "XABC belum cocok" : visibleStatus
    color statusColor = not timingReady ? color.orange : hasVisiblePattern ? visibleColor : activeBroken ? color.red : color.orange
    string panelZone = visibleZone ? priceText(visibleLower) + " - " + priceText(visibleUpper) : "-"
    if showPanel and panelMode == "Ringkas"
        compactCell(0, 0, "MANUAL HP", color.white)
        compactCell(1, 0, visibleName + (hasVisiblePattern ? (bull ? " | Bull" : " | Bear") : ""), hasVisiblePattern ? visibleColor : color.silver)
        compactCell(0, 1, "Status", color.silver)
        compactCell(1, 1, panelStatus, statusColor)
        compactCell(0, 2, "D " + (hasVisiblePattern ? visibleName : "proyeksi"), color.silver)
        compactCell(1, 2, priceText(visibleD), hasVisiblePattern ? visibleColor : color.gray)
        compactCell(0, 3, "PRZ", color.silver)
        compactCell(1, 3, panelZone, visibleZone ? visibleZoneColor : color.gray)
        compactCell(0, 4, "AB/XA | BC/AB", color.silver)
        compactCell(1, 4, ratioText(rAB) + " | " + ratioText(rBC), color.white)
        compactCell(0, 5, "Mode / waktu", color.silver)
        compactCell(1, 5, (model == "Otomatis" ? "Auto" : "Manual") + " | " + (hasVisiblePattern ? visiblePhase : "-"), color.silver)
 
    if showPanel and panelMode == "Lengkap"
        color bg = color.new(color.black, 15)
        cell(0, 0, "MANUAL HP", color.white, bg)
        cell(1, 0, geometryOK ? (bull ? "BULLISH" : "BEARISH") : "CEK TITIK", hasVisiblePattern ? visibleColor : color.orange, bg)
        cell(2, 0, visibleName, color.white, bg)
        cell(3, 0, model == "Otomatis" ? "AUTO" : "MANUAL", color.silver, bg)
        cell(0, 1, "Status", color.silver, bg)
        cell(1, 1, panelStatus, statusColor, bg)
        cell(0, 2, "AB/XA", color.silver, bg)
        cell(1, 2, ratioText(rAB), color.white, bg)
        cell(2, 2, "BC/AB", color.silver, bg)
        cell(3, 2, ratioText(rBC), color.white, bg)
        cell(0, 3, "D aktif", color.silver, bg)
        cell(1, 3, priceText(visibleD), hasVisiblePattern ? visibleColor : color.gray, bg)
        cell(2, 3, "Zona D / PRZ", color.silver, bg)
        cell(3, 3, panelZone, visibleZone ? visibleZoneColor : color.gray, bg)
        cell(0, 4, "Pola kandidat", color.silver, bg)
        cell(1, 4, "D teoritis", color.silver, bg)
        cell(2, 4, "CD/BC di D", color.silver, bg)
        cell(3, 4, "Kecocokan", color.silver, bg)
        int candidateRow = 5
        int remainingCandidates = 0
        for p = 0 to PATTERN_COUNT - 1
            bool available = geometryOK
            Projection candidate = available ? candidates.get(p) : na
            bool fits = available and candidate.fits
            bool overlap = available and candidate.confluence
            bool currentRow = visibleFamily == p
            bool previewRow = potentialVisible and potentialFamily == p
            bool expired = timingReady and bar_index >= lateIndex and not currentRow
            bool omitRow = geometryOK and (candidateBroken.get(p) or expired or (p == activeFamily and activeBroken))
            if not omitRow
                color rowColor = fits ? (overlap ? visibleColor : color.orange) : color.gray
                string fitText = not available ? "-" : not fits ? "XABC tidak cocok" : overlap ? "XABC + zona D" : "XABC saja"
                if currentRow
                    rowColor := visibleColor
                    fitText := visibleStatus
                else if previewRow
                    rowColor := stingrayColor
                    fitText := "Potensi: 23.6 + engulfing"
                else if p == nextFamily and fits
                    rowColor := color.silver
                    fitText := "Alternatif berikutnya"
                cell(0, candidateRow, (visibleFamily == p ? "> " : "") + patternName(p), rowColor, bg)
                cell(1, candidateRow, available ? priceText(candidate.d) : "-", rowColor, bg)
                cell(2, candidateRow, available ? ratioText(math.abs((pc - candidate.d) / bc)) : "-", rowColor, bg)
                cell(3, candidateRow, fitText, rowColor, bg)
                candidateRow += 1
                if fits
                    remainingCandidates += 1
        cell(0, PATTERN_COUNT + 5, "AB=CD", abcdColor, bg)
        cell(1, PATTERN_COUNT + 5, geometryOK and hasVisiblePattern ? priceText(dABCD) : "-", abcdColor, bg)
        cell(2, PATTERN_COUNT + 5, "ALT 1.272 / 1.618", abcdColor, bg)
        cell(3, PATTERN_COUNT + 5, geometryOK and hasVisiblePattern and altVisible ? priceText(d1272) + " / " + priceText(d1618) : "-", abcdColor, bg)
        cell(0, PATTERN_COUNT + 6, "Dasar D", color.silver, bg)
        cell(1, PATTERN_COUNT + 6, hasVisiblePattern ? completionRule(visibleFamily) : "-", color.silver, bg)
        cell(0, PATTERN_COUNT + 7, "XABC / waktu", color.silver, bg)
        cell(1, PATTERN_COUNT + 7, str.tostring(remainingCandidates) + " kandidat | " + (hasVisiblePattern ? visiblePhase : "-"), color.silver, bg)

← 返回列表