Structure Hunter - Market Structure & Chart Patterns

Seckin_Tuncay · study · 747 行 · 点赞 139 · 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/
// © Seckin_Tuncay
// Structure Hunter - Market Structure & Chart Patterns  (v3, formerly "Yapı Avcısı")
// Zigzag market structure (HH / HL / LH / LL, BOS / CHoCH) plus classic chart patterns
// with neckline / trendline breaks and measured-move targets. Only the last N patterns stay on the chart.
// Works on the TradingView free (Basic) plan.
//@version=6
indicator("Structure Hunter - Market Structure & Chart Patterns", shorttitle="Structure Hunter", overlay=true, max_lines_count=500, max_labels_count=500, max_polylines_count=100)
 
// ═══════════════════════ SEÇENEK SABİTLERİ / OPTION CONSTANTS ═══════════════════════
LANG_TR = "Türkçe"
LANG_EN = "English"
O_CLOSE = "Kapanış / Close"
O_WICK  = "Fitil / Wick"
FT_4    = "4 nokta / 4 points"
FT_5    = "5 nokta / 5 points"
SZ_T    = "Çok küçük / Tiny"
SZ_S    = "Küçük / Small"
SZ_N    = "Normal"
PS_TR   = "Sağ üst / Top right"
PS_BR   = "Sağ alt / Bottom right"
PS_TL   = "Sol üst / Top left"
PS_BL   = "Sol alt / Bottom left"
 
// ═══════════════════════ AYARLAR / SETTINGS ═══════════════════════
G1 = "1 · Genel / General"
langIn     = input.string(LANG_TR, "Dil / Language", options=[LANG_TR, LANG_EN], group=G1, tooltip="TR: Grafikteki yazıların, tablonun ve alarm mesajlarının dili.\n\nEN: Language of chart texts, table and alert messages.")
waitClose  = input.bool(true, "Bar kapanışını bekle / Wait for bar close", group=G1, tooltip="TR: Swing, kırılım ve formasyonlar sadece kapanmış mumda kesinleşir (repaint yok). Kapatılırsa açık mumda görünür ama mum kapanınca kaybolabilir.\n\nEN: Swings, breaks and patterns are final only on a closed candle (no repaint). If off, they appear on the open candle but may disappear when it closes.")
pivLen     = input.int(5, "Swing uzunluğu / Swing length", minval=2, maxval=50, group=G1, tooltip="TR: Bir tepe/dibin geçerli olması için sağında ve solunda gereken bar sayısı. Swing bu kadar bar gecikmeyle onaylanır.\n\nEN: Bars needed on each side to confirm a swing. A swing is confirmed with this many bars of delay.")
 
G2 = "2 · Piyasa Yapısı / Market Structure"
showZZ     = input.bool(true, "Zigzag", group=G2, inline="zz")
zzCol      = input.color(color.new(color.gray, 35), "", group=G2, inline="zz")
showHL     = input.bool(true, "HH · HL · LH · LL", group=G2)
showBOS    = input.bool(true, "BOS · CHoCH", group=G2)
bosMode    = input.string(O_CLOSE, "Kırılım teyidi / Break confirmation", options=[O_CLOSE, O_WICK], group=G2)
structMax  = input.int(100, "Gösterilecek yapı etiketi / Structure labels shown", minval=10, maxval=200, group=G2, tooltip="TR: Grafikte kalan en fazla swing etiketi ve BOS/CHoCH sayısı. Formasyon çizimlerine yer kalması için sınırlıdır.\n\nEN: Max swing labels and BOS/CHoCH kept on the chart. Limited so pattern drawings keep their room.")
stAlert    = input.bool(true, "Yapı alarmları (BOS · CHoCH) / Structure alerts", group=G2)
bullCol    = input.color(#00E676, "Yükseliş / Bullish", group=G2, inline="sc")
bearCol    = input.color(#FF1744, "Düşüş / Bearish", group=G2, inline="sc")
 
G3 = "3 · Formasyonlar / Patterns"
fmOn       = input.bool(true, "Formasyonları göster / Show patterns", group=G3)
fmMax      = input.int(10, "Gösterilecek formasyon sayısı / Patterns shown", minval=1, maxval=30, group=G3, tooltip="TR: Grafikte sadece son N formasyon kalır (çizimi, kırılım etiketi ve hedefiyle birlikte); eskiler silinir.\n\nEN: Only the last N patterns stay on the chart (with their drawing, break label and target); older ones are deleted.")
fmPivIn    = input.int(0, "Formasyon swing uzunluğu (0 = yapı ile aynı) / Pattern swing length (0 = same as structure)", minval=0, maxval=50, group=G3, tooltip="TR: Büyük değer daha az ama daha büyük formasyon bulur.\n\nEN: Larger values find fewer but bigger patterns.")
fmHS       = input.bool(true, "OBO · TOBO / H&S", group=G3, inline="fp1")
fmTpl      = input.bool(true, "Üçlü / Triple", group=G3, inline="fp1")
fmDbl      = input.bool(true, "İkili / Double", group=G3, inline="fp2")
fmCup      = input.bool(true, "Fincan-Kulp / Cup", group=G3, inline="fp2")
fmTri      = input.bool(true, "Üçgen / Triangle", group=G3, inline="fp3")
fmWdg      = input.bool(true, "Takoz / Wedge", group=G3, inline="fp3")
fmRect     = input.bool(true, "Dikdörtgen / Rectangle", group=G3, inline="fp4")
fmChan     = input.bool(true, "Kanal / Channel", group=G3, inline="fp4")
fmFlag     = input.bool(true, "Bayrak-Flama / Flag-Pennant", group=G3, inline="fp5")
fmBroad    = input.bool(false, "Genişleyen / Broadening", group=G3, inline="fp5")
fmTolPct   = input.float(15.0, "Seviye toleransı (% boy) / Level tolerance (% height)", minval=1.0, maxval=50.0, step=1.0, group=G3, tooltip="TR: Omuzların / tepelerin / dokunuşların birbirine ne kadar yakın olması gerektiği. Küçük = daha az ama daha kusursuz formasyon.\n\nEN: How close shoulders / peaks / touches must be. Smaller = fewer but cleaner patterns.")
fmHeadPct  = input.float(10.0, "Baş farkı (% boy) / Head excess (% height)", minval=0.0, maxval=100.0, step=1.0, group=G3, tooltip="TR: OBO'da başın omuzlardan en az bu kadar uzun olması gerekir.\n\nEN: In H&S the head must exceed the shoulders by at least this much.")
fmMinAtr   = input.float(1.5, "Min. formasyon boyu (ATR) / Min pattern height (ATR)", minval=0.1, step=0.1, group=G3)
fmSym      = input.float(2.5, "Zaman simetrisi (maks. oran) / Time symmetry (max ratio)", minval=1.0, step=0.1, group=G3, tooltip="TR: Sol ve sağ yarının bar sayısı oranı en fazla bu kadar olabilir.\n\nEN: Max bar-count ratio between the left and right halves.")
fmTrend    = input.bool(true, "Öncesinde trend şartı / Require prior trend", group=G3, tooltip="TR: Tepe formasyonu için öncesinde yükseliş, dip formasyonu için düşüş aranır.\n\nEN: Top patterns need a prior uptrend, bottom patterns a prior downtrend.")
fmTouch    = input.string(FT_5, "Çizgi dokunuşu / Trendline touches", options=[FT_4, FT_5], group=G3, tooltip="TR: 5 nokta = çizgilerden biri 3 kez test edilmiş olmalı (daha temiz). 4 nokta = daha çok formasyon.\n\nEN: 5 points = one line must be tested 3 times (cleaner). 4 points = more patterns.")
fmFlat     = input.float(0.25, "Yatay eşiği / Flat threshold", minval=0.05, maxval=1.0, step=0.05, group=G3, tooltip="TR: Çizginin formasyon boyunca kat ettiği mesafe / formasyon yüksekliği bu değerin altındaysa çizgi yatay sayılır.\n\nEN: If a line's travel over the pattern divided by the pattern height is below this, the line counts as flat.")
fmPole     = input.float(2.0, "Bayrak direği (boy ×) / Flag pole (height ×)", minval=1.0, step=0.1, group=G3, tooltip="TR: Bayrak / flama için öncesindeki sert hareket formasyon yüksekliğinin en az bu katı olmalı.\n\nEN: For flags / pennants the prior impulse must be at least this multiple of the pattern height.")
fmWait     = input.int(60, "Kırılım için maks. bar / Max bars for break", minval=5, group=G3, tooltip="TR: Bu süre içinde kırılmayan formasyon geçersiz sayılır (gri, noktalı).\n\nEN: A pattern not broken within this many bars is invalidated (gray, dotted).")
fmTgt      = input.bool(true, "Hedef çiz (ölçülen hareket) / Draw target (measured move)", group=G3)
fmAlert    = input.bool(true, "Formasyon alarmları / Pattern alerts", group=G3)
fmTopCol   = input.color(#FF9100, "Düşüş formasyonu / Bearish pattern", group=G3, inline="fc")
fmBotCol   = input.color(#2979FF, "Yükseliş / Bullish", group=G3, inline="fc")
fmLinCol   = input.color(#E040FB, "Çizgi / Line", group=G3, inline="fc")
 
G4 = "4 · Görünüm / Display"
showTbl    = input.bool(true, "Bilgi tablosu / Info table", group=G4)
tblPosIn   = input.string(PS_TR, "Tablo konumu / Table position", options=[PS_TR, PS_BR, PS_TL, PS_BL], group=G4)
txtSizeIn  = input.string(SZ_S, "Yazı boyutu / Text size", options=[SZ_T, SZ_S, SZ_N], group=G4)
 
// ═══════════════════════ YARDIMCILAR / HELPERS ═══════════════════════
isEN = langIn == LANG_EN
L(string tr, string en) => isEN ? en : tr
f_p(float p) => str.tostring(p, format.mintick)
txtSize = txtSizeIn == SZ_T ? size.tiny : txtSizeIn == SZ_N ? size.normal : size.small
tblPos  = tblPosIn == PS_BR ? position.bottom_right : tblPosIn == PS_TL ? position.top_left : tblPosIn == PS_BL ? position.bottom_left : position.top_right
 
atr   = ta.atr(14)
barOk = not waitClose or barstate.isconfirmed
ph    = ta.pivothigh(high, pivLen, pivLen)
pl    = ta.pivotlow(low, pivLen, pivLen)
 
f_trimLines(array<line> a, int mx) =>
    while a.size() > mx
        a.shift().delete()
    a.size()
 
f_trimLabels(array<label> a, int mx) =>
    while a.size() > mx
        a.shift().delete()
    a.size()
 
// ═══════════════════════ PİYASA YAPISI / MARKET STRUCTURE ═══════════════════════
var array<float> sZP = array.new<float>()
var array<int>   sZB = array.new<int>()
var array<int>   sZT = array.new<int>()
var array<line>  zzLines  = array.new<line>()
var array<label> swLabels = array.new<label>()
var array<line>  bosLines = array.new<line>()
var array<label> bosLbls  = array.new<label>()
 
sP(int k) => sZP.get(sZP.size() - 1 - k)
sB(int k) => sZB.get(sZB.size() - 1 - k)
 
var line   lastZZ     = na
var label  lastSL     = na
var int    lastSLBar  = na
var string lastStruct = "—"
var string lastBreak  = "—"
var float  swHi       = na
var int    swHiBar    = na
var bool   swHiDone   = true
var float  swLo       = na
var int    swLoBar    = na
var bool   swLoDone   = true
var int    trend      = 0
 
bool aBosUp = false
bool aBosDn = false
bool aChUp  = false
bool aChDn  = false
 
if barOk
    for i = 0 to 1
        int   t  = i == 0 ? 1 : -1
        float pv = i == 0 ? ph : pl
        if not na(pv)
            int pb   = bar_index - pivLen
            int n    = sZP.size()
            int ev   = 0
            int oldB = n > 0 ? sZB.last() : na
            if n == 0 or sZT.last() != t
                sZP.push(pv)
                sZB.push(pb)
                sZT.push(t)
                ev := 1
            else if (t == 1 and pv > sZP.last()) or (t == -1 and pv < sZP.last())
                sZP.set(n - 1, pv)
                sZB.set(n - 1, pb)
                ev := 2
            if sZP.size() > 10
                sZP.shift()
                sZB.shift()
                sZT.shift()
 
            if ev > 0
                n := sZP.size()
                // zigzag
                if showZZ and n >= 2
                    if ev == 2 and not na(lastZZ)
                        lastZZ.set_xy2(pb, pv)
                    else if ev == 1
                        lastZZ := line.new(sB(1), sP(1), pb, pv, color=zzCol, width=1)
                        zzLines.push(lastZZ)
                        f_trimLines(zzLines, structMax * 2)
                // HH / HL / LH / LL
                if n >= 3
                    float  ps = sP(2)
                    string st = t == 1 ? (pv > ps ? "HH" : "LH") : (pv < ps ? "LL" : "HL")
                    color  sc = st == "HH" or st == "HL" ? bullCol : bearCol
                    lastStruct := st
                    if showHL
                        if ev == 2 and not na(lastSL) and lastSLBar == oldB
                            lastSL.set_xy(pb, pv)
                            lastSL.set_text(st)
                            lastSL.set_textcolor(sc)
                        else
                            lastSL := label.new(pb, pv, st, style=t == 1 ? label.style_label_down : label.style_label_up, color=color(na), textcolor=sc, size=size.tiny)
                            swLabels.push(lastSL)
                            f_trimLabels(swLabels, structMax)
                        lastSLBar := pb
                // BOS seviyeleri / BOS levels
                if t == 1
                    swHi     := pv
                    swHiBar  := pb
                    swHiDone := false
                else
                    swLo     := pv
                    swLoBar  := pb
                    swLoDone := false
 
float upS = bosMode == O_CLOSE ? close : high
float dnS = bosMode == O_CLOSE ? close : low
 
if barOk and not swHiDone and not na(swHi) and upS > swHi
    swHiDone := true
    bool ch = trend == -1
    trend := 1
    if ch
        aChUp := true
    else
        aBosUp := true
    string k = ch ? "CHoCH" : "BOS"
    lastBreak := k + " ↑"
    if showBOS
        bosLines.push(line.new(swHiBar, swHi, bar_index, swHi, color=bullCol, style=line.style_dashed, width=1))
        bosLbls.push(label.new(math.round((swHiBar + bar_index) / 2), swHi, k, style=label.style_label_down, color=color(na), textcolor=bullCol, size=size.tiny))
        f_trimLines(bosLines, structMax)
        f_trimLabels(bosLbls, structMax)
    if stAlert
        alert(syminfo.ticker + " " + timeframe.period + " · " + k + L(" yükseliş", " bullish") + " @ " + f_p(close), alert.freq_once_per_bar_close)
 
if barOk and not swLoDone and not na(swLo) and dnS < swLo
    swLoDone := true
    bool ch = trend == 1
    trend := -1
    if ch
        aChDn := true
    else
        aBosDn := true
    string k = ch ? "CHoCH" : "BOS"
    lastBreak := k + " ↓"
    if showBOS
        bosLines.push(line.new(swLoBar, swLo, bar_index, swLo, color=bearCol, style=line.style_dashed, width=1))
        bosLbls.push(label.new(math.round((swLoBar + bar_index) / 2), swLo, k, style=label.style_label_up, color=color(na), textcolor=bearCol, size=size.tiny))
        f_trimLines(bosLines, structMax)
        f_trimLabels(bosLbls, structMax)
    if stAlert
        alert(syminfo.ticker + " " + timeframe.period + " · " + k + L(" düşüş", " bearish") + " @ " + f_p(close), alert.freq_once_per_bar_close)
 
// ═══════════════════════ FORMASYONLAR / PATTERNS ═══════════════════════
fmPiv = fmPivIn == 0 ? pivLen : fmPivIn
float fmPH = ta.pivothigh(high, fmPiv, fmPiv)
float fmPL = ta.pivotlow(low, fmPiv, fmPiv)
 
// bir formasyonun tüm çizimleri (birlikte silinir) / all drawings of one pattern (deleted together)
type FmDraw
    int             id
    array<line>     ls
    array<label>    lbs
    array<polyline> pls
    array<linefill> lfs
 
// boyun kırılımı bekleyen dönüş formasyonu / reversal pattern waiting for its neckline break
type FmRev
    bool   act = false
    int    b1
    float  p1
    int    b2
    float  p2
    int    st
    float  hgt
    float  inv
    string nm
    line   ln
    int    id
 
// kırılım bekleyen çizgi formasyonu / line pattern waiting for a break
type FmLin
    bool     act = false
    int      uB1
    float    uP1
    int      uB2
    float    uP2
    int      dB1
    float    dP1
    int      dB2
    float    dP2
    int      st
    int      ptEnd
    int      apex
    int      dir
    float    hgt
    float    pole
    string   nm
    line     lu
    line     ld
    linefill lf
    int      id
 
var array<float>  fmZP     = array.new<float>()
var array<int>    fmZB     = array.new<int>()
var array<int>    fmZT     = array.new<int>()
var array<FmDraw> fmHist   = array.new<FmDraw>()
var array<FmRev>  fmRv     = array.from(FmRev.new(), FmRev.new())   // 0 = düşüş beklenen / bearish, 1 = yükseliş / bullish
var FmLin         fmLn     = FmLin.new()
var int           fmBlock  = 0
var int           fmRevEnd = 0
var int           fmBrkDir = 0
var int           fmBrkBar = na
var string        fmBrkNm  = ""
 
fmP(int k) => fmZP.get(fmZP.size() - 1 - k)
fmB(int k) => fmZB.get(fmZB.size() - 1 - k)
fmY(int b1, float p1, int b2, float p2, int x) => p1 + (p2 - p1) * float(x - b1) / float(b2 - b1)
 
fmNewDraw(int id) =>
    FmDraw.new(id, array.new<line>(), array.new<label>(), array.new<polyline>(), array.new<linefill>())
 
fmKill(FmDraw d) =>
    for x in d.lfs
        x.delete()
    for x in d.ls
        x.delete()
    for x in d.lbs
        x.delete()
    for x in d.pls
        x.delete()
    d.id
 
fmFind(int id) =>
    FmDraw r = na
    for d in fmHist
        if d.id == id
            r := d
            break
    r
 
// geçmişe ekle, son N'i tut / add to history, keep the last N
fmStore(FmDraw d) =>
    fmHist.push(d)
    while fmHist.size() > fmMax
        FmDraw o = fmHist.shift()
        fmKill(o)
        for r in fmRv
            if r.act and r.id == o.id
                r.act := false
        if fmLn.act and fmLn.id == o.id
            fmLn.act := false
    d.id
 
// güncellenen formasyonun eski çizimini kaldır / remove the old drawing of an updated pattern
fmDrop(int id) =>
    int n = fmHist.size()
    if n > 0
        for i = n - 1 to 0
            if fmHist.get(i).id == id
                fmKill(fmHist.get(i))
                fmHist.remove(i)
                break
    id
 
fmGray(line l) =>
    l.set_color(color.new(color.gray, 50))
    l.set_style(line.style_dotted)
 
fmTarget(FmDraw d, float from, float tg, color c) =>
    d.ls.push(line.new(bar_index, from, bar_index, tg, color=c, style=line.style_dotted, width=1))
    d.ls.push(line.new(bar_index, tg, bar_index + 20, tg, color=c, style=line.style_dashed, width=2))
    d.lbs.push(label.new(bar_index + 20, tg, L("Hedef ", "Target ") + f_p(tg), style=label.style_label_left, color=color(na), textcolor=c, size=txtSize))
    tg
 
fmName(int kind, int t) =>
    switch kind
        4 => t == 1 ? L("Ters Fincan-Kulp", "Inv. Cup & Handle") : L("Fincan-Kulp", "Cup & Handle")
        2 => t == 1 ? L("OBO", "H&S") : L("TOBO", "Inv. H&S")
        3 => t == 1 ? L("Üçlü Tepe", "Triple Top") : L("Üçlü Dip", "Triple Bottom")
        => t == 1 ? L("İkili Tepe", "Double Top") : L("İkili Dip", "Double Bottom")
 
bool   fmEvForm = false
bool   fmEvUp   = false
bool   fmEvDn   = false
string fmMsg    = ""
 
if fmOn and barOk
    for i = 0 to 1
        int   t  = i == 0 ? 1 : -1
        float pv = i == 0 ? fmPH : fmPL
        if not na(pv)
            int  pb    = bar_index - fmPiv
            int  zn    = fmZP.size()
            bool fresh = false
            if zn == 0 or fmZT.last() != t
                fmZP.push(pv)
                fmZB.push(pb)
                fmZT.push(t)
                fresh := true
            else if (t == 1 and pv > fmZP.last()) or (t == -1 and pv < fmZP.last())
                fmZP.set(zn - 1, pv)
                fmZB.set(zn - 1, pb)
            if fmZP.size() > 60
                fmZP.shift()
                fmZB.shift()
                fmZT.shift()
 
            if fresh
                zn := fmZP.size()
                int   kind = 0      // 4 fincan / cup, 3 üçlü / triple, 2 OBO / H&S, 1 ikili / double
                int   km   = 0
                int   nb1  = 0
                float np1  = 0.0
                int   nb2  = 1
                float np2  = 0.0
                float cHg  = na
                float cInv = na
                float tol  = fmTolPct / 100.0
                float minH = fmMinAtr * atr
 
                if zn >= 5 and (fmHS or fmTpl)
                    // t ile çarpınca dip formasyonları tepe gibi incelenir / multiplying by t mirrors bottoms into tops
                    float H3 = t * fmP(0)
                    float N2 = t * fmP(1)
                    float H2 = t * fmP(2)
                    float N1 = t * fmP(3)
                    float H1 = t * fmP(4)
                    bool  trOk    = not fmTrend or (zn >= 6 and t * fmP(5) < math.min(N1, N2))
                    int   d1      = fmB(2) - fmB(4)
                    int   d2      = fmB(0) - fmB(2)
                    bool  symOk   = math.max(d1, d2) <= fmSym * math.max(math.min(d1, d2), 1)
                    float nAvg    = math.avg(N1, N2)
                    bool  aboveOk = math.min(H1, H2, H3) > math.max(N1, N2)
                    float hT      = math.avg(H1, H2, H3) - nAvg
                    if fmTpl and trOk and symOk and aboveOk and hT >= minH and math.max(H1, H2, H3) - math.min(H1, H2, H3) <= tol * hT and math.abs(N1 - N2) <= 0.5 * hT
                        kind := 3
                        km   := H1 >= H2 and H1 >= H3 ? 4 : H2 >= H3 ? 2 : 0
                    float hH = H2 - nAvg
                    if kind == 0 and fmHS and trOk and symOk and aboveOk and hH >= minH and H2 - math.max(H1, H3) >= fmHeadPct / 100.0 * hH and math.abs(H1 - H3) <= tol * hH and math.abs(N1 - N2) <= 0.5 * hH
                        kind := 2
                        km   := 2
                    if kind > 0
                        nb1 := fmB(3)
                        np1 := fmP(3)
                        nb2 := fmB(1)
                        np2 := fmP(1)
 
                // Fincan-Kulp (son nokta = kulp) / cup & handle (last point = handle)
                if kind == 0 and fmCup and zn >= 4
                    float c    = -t
                    float hnd  = fmP(0)
                    float rR   = fmP(1)
                    float bot  = fmP(2)
                    float rL   = fmP(3)
                    float dep  = c * (math.avg(rL, rR) - bot)
                    float hDep = c * (rR - hnd)
                    int   cupW = fmB(1) - fmB(3)
                    int   hW   = fmB(0) - fmB(1)
                    if dep >= minH and math.abs(rL - rR) <= tol * dep and hDep > 0 and hDep <= 0.5 * dep and cupW >= 4 * fmPiv and hW <= 0.5 * cupW
                        kind := 4
                        km   := 2
                        nb1  := fmB(1)
                        np1  := rR
                        nb2  := fmB(1) + 1
                        np2  := rR
                        cHg  := dep
                        cInv := bot + c * dep * 0.5
 
                // İkili Tepe / Dip / double top / bottom
                if kind == 0 and fmDbl and zn >= 3
                    float B2    = t * fmP(0)
                    float NN    = t * fmP(1)
                    float B1    = t * fmP(2)
                    bool  trOk2 = not fmTrend or (zn >= 4 and t * fmP(3) < NN)
                    float hD    = math.max(B1, B2) - NN
                    if trOk2 and hD >= minH and math.abs(B1 - B2) <= tol * hD
                        kind := 1
                        km   := B1 >= B2 ? 2 : 0
                        nb1  := fmB(1)
                        np1  := fmP(1)
                        nb2  := fmB(1) + 1
                        np2  := fmP(1)
 
                // dönüş formasyonu çizimi / reversal pattern drawing
                if kind > 0
                    int    ix  = t == 1 ? 0 : 1
                    color  pc  = t == 1 ? fmTopCol : fmBotCol
                    string nm  = fmName(kind, t)
                    FmDraw dr  = fmNewDraw(bar_index * 2 + i)
                    float  off = t * atr * 0.9
                    if kind == 4
                        // yuvarlak fincan: uçlarda dik, dipte yatay; mumların dışına taşmaz / rounded cup: steep at the rims, flat at the bottom, no overshoot
                        array<chart.point> cps = array.new<chart.point>()
                        int   xL = fmB(3)
                        int   xM = fmB(2)
                        int   xR = fmB(1)
                        float yL = fmP(3)
                        float yM = fmP(2)
                        float yR = fmP(1)
                        for k = 0 to 8
                            float u = k / 8.0
                            cps.push(chart.point.from_index(int(math.round(xL + (xM - xL) * u)), yL + (yM - yL) * math.sin(math.pi / 2 * u)))
                        for k = 1 to 8
                            float u = k / 8.0
                            cps.push(chart.point.from_index(int(math.round(xM + (xR - xM) * u)), yM + (yR - yM) * (1 - math.cos(math.pi / 2 * u))))
                        dr.pls.push(polyline.new(cps, line_color=pc, line_width=2))
                        dr.ls.push(line.new(xR, yR, fmB(0), fmP(0), color=pc, width=2))
                        dr.lbs.push(label.new(fmB(0), fmP(0) + t * atr * 0.5, L("Kulp", "Handle"), style=t == 1 ? label.style_label_down : label.style_label_up, color=color(na), textcolor=pc, size=size.tiny))
                    else
                        int cnt = kind == 1 ? 3 : 5
                        array<chart.point> pts = array.new<chart.point>()
                        for k = cnt - 1 to 0
                            pts.push(chart.point.from_index(fmB(k), fmP(k)))
                        dr.pls.push(polyline.new(pts, line_color=pc, line_width=2))
                    dr.lbs.push(label.new(fmB(km), fmP(km) + off, nm, style=t == 1 ? label.style_label_down : label.style_label_up, color=pc, textcolor=color.white, size=txtSize))
                    if kind == 2
                        dr.lbs.push(label.new(fmB(4), fmP(4) + t * atr * 0.5, L("Sol Omuz", "L. Shoulder"), style=t == 1 ? label.style_label_down : label.style_label_up, color=color(na), textcolor=pc, size=size.tiny))
                        dr.lbs.push(label.new(fmB(0), fmP(0) + t * atr * 0.5, L("Sağ Omuz", "R. Shoulder"), style=t == 1 ? label.style_label_down : label.style_label_up, color=color(na), textcolor=pc, size=size.tiny))
 
                    FmRev old = fmRv.get(ix)
                    if old.act
                        fmGray(old.ln)
                    float nkNow = fmY(nb1, np1, nb2, np2, bar_index)
                    line  nl    = line.new(nb1, np1, bar_index, nkNow, color=pc, width=2)
                    dr.ls.push(nl)
                    float hg    = kind == 4 ? cHg : math.abs(fmP(km) - fmY(nb1, np1, nb2, np2, fmB(km)))
                    float inv   = kind == 4 ? cInv : fmP(km)
                    fmRv.set(ix, FmRev.new(true, nb1, np1, nb2, np2, bar_index, hg, inv, nm, nl, dr.id))
                    // bu noktalar çizgi formasyonunda tekrar kullanılmaz (çift sayım yok) / these points are not reused by line patterns (no double counting)
                    fmRevEnd := math.max(fmRevEnd, fmB(0))
                    fmStore(dr)
                    fmEvForm := true
                    fmMsg    += (fmMsg == "" ? "" : " | ") + syminfo.ticker + " " + timeframe.period + " · " + nm + L(" oluştu, boyun ", " formed, neckline ") + f_p(nkNow)
 
                // ════════ çizgi formasyonları / line patterns ════════
                int m = fmTouch == FT_5 ? 5 : 4
                if kind == 0 and zn >= m and fmB(m - 1) >= math.max(fmBlock, fmRevEnd)
                    int   kHn = t == 1 ? 0 : 1
                    int   kHo = t == 1 ? (m == 5 ? 4 : 2) : 3
                    int   kLn = t == 1 ? 1 : 0
                    int   kLo = t == 1 ? 3 : (m == 5 ? 4 : 2)
                    int   uB1 = fmB(kHo)
                    float uP1 = fmP(kHo)
                    int   uB2 = fmB(kHn)
                    float uP2 = fmP(kHn)
                    int   dB1 = fmB(kLo)
                    float dP1 = fmP(kLo)
                    int   dB2 = fmB(kLn)
                    float dP2 = fmP(kLn)
                    int   xs  = fmB(m - 1)
                    int   xe  = fmB(0)
                    int   W   = xe - xs
                    float Hs  = fmY(uB1, uP1, uB2, uP2, xs) - fmY(dB1, dP1, dB2, dP2, xs)
                    float He  = fmY(uB1, uP1, uB2, uP2, xe) - fmY(dB1, dP1, dB2, dP2, xe)
 
                    if W > 0 and Hs >= minH and He > 0
                        float slU = (uP2 - uP1) / float(uB2 - uB1)
                        float slL = (dP2 - dP1) / float(dB2 - dB1)
                        float su  = slU * W / Hs
                        float sd  = slL * W / Hs
                        float rat = He / Hs
                        bool midOk = true
                        if m == 5
                            float midL = t == 1 ? fmY(uB1, uP1, uB2, uP2, fmB(2)) : fmY(dB1, dP1, dB2, dP2, fmB(2))
                            midOk := math.abs(fmP(2) - midL) <= tol * Hs
 
                        if midOk
                            bool uF  = math.abs(su) < fmFlat
                            bool lF  = math.abs(sd) < fmFlat
                            bool uUp = su >= fmFlat
                            bool uDn = su <= -fmFlat
                            bool lUp = sd >= fmFlat
                            bool lDn = sd <= -fmFlat
                            string lnm = ""
                            int    cat = 0     // 1 üçgen, 2 takoz, 3 dikdörtgen, 4 kanal, 5 genişleyen, 6 bayrak-flama
                            int    ldr = 0
                            if uF and lF
                                lnm := L("Dikdörtgen", "Rectangle")
                                cat := 3
                            else if uF and lUp
                                lnm := L("Yükselen Üçgen", "Ascending Triangle")
                                cat := 1
                                ldr := 1
                            else if uDn and lF
                                lnm := L("Alçalan Üçgen", "Descending Triangle")
                                cat := 1
                                ldr := -1
                            else if uDn and lUp
                                lnm := L("Simetrik Üçgen", "Symmetrical Triangle")
                                cat := 1
                            else if uUp and lUp
                                if rat < 0.75
                                    lnm := L("Yükselen Takoz", "Rising Wedge")
                                    cat := 2
                                    ldr := -1
                                else if rat <= 1.33
                                    lnm := L("Yükselen Kanal", "Rising Channel")
                                    cat := 4
                                else
                                    lnm := L("Genişleyen Formasyon", "Broadening Pattern")
                                    cat := 5
                            else if uDn and lDn
                                if rat < 0.75
                                    lnm := L("Alçalan Takoz", "Falling Wedge")
                                    cat := 2
                                    ldr := 1
                                else if rat <= 1.33
                                    lnm := L("Düşen Kanal", "Falling Channel")
                                    cat := 4
                                else
                                    lnm := L("Genişleyen Formasyon", "Broadening Pattern")
                                    cat := 5
                            else
                                lnm := L("Genişleyen Formasyon", "Broadening Pattern")
                                cat := 5
 
                            // bayrak / flama: öncesinde sert direk / flag / pennant: sharp pole before
                            float pole = 0.0
                            if fmFlag and zn >= m + 1 and (cat == 1 or cat == 3 or cat == 4)
                                float poleLen  = math.abs(fmP(m - 1) - fmP(m))
                                int   poleBars = fmB(m - 1) - fmB(m)
                                bool  poleUp   = fmP(m - 1) > fmP(m)
                                bool  isTriS   = cat == 1 and ldr == 0
                                bool  isRect   = cat == 3
                                bool  isChDn   = cat == 4 and su < 0
                                bool  isChUp   = cat == 4 and su > 0
                                if poleLen >= fmPole * Hs and poleBars <= W
                                    if poleUp and (isChDn or isRect)
                                        lnm  := L("Boğa Bayrağı", "Bull Flag")
                                        cat  := 6
                                        ldr  := 1
                                        pole := poleLen
                                    else if poleUp and isTriS
                                        lnm  := L("Boğa Flaması", "Bull Pennant")
                                        cat  := 6
                                        ldr  := 1
                                        pole := poleLen
                                    else if not poleUp and (isChUp or isRect)
                                        lnm  := L("Ayı Bayrağı", "Bear Flag")
                                        cat  := 6
                                        ldr  := -1
                                        pole := poleLen
                                    else if not poleUp and isTriS
                                        lnm  := L("Ayı Flaması", "Bear Pennant")
                                        cat  := 6
                                        ldr  := -1
                                        pole := poleLen
 
                            bool catOn = cat == 1 ? fmTri : cat == 2 ? fmWdg : cat == 3 ? fmRect : cat == 4 ? fmChan : cat == 5 ? fmBroad : cat == 6 ? fmFlag : false
                            if catOn
                                // önceki aktif formasyon üst üste biniyorsa güncellenir, değilse pasifleşir / overlapping active pattern is replaced, otherwise grayed
                                if fmLn.act
                                    if xs < fmLn.ptEnd
                                        fmDrop(fmLn.id)
                                    else
                                        fmGray(fmLn.lu)
                                        fmGray(fmLn.ld)
                                        fmLn.lf.set_color(color.new(color.gray, 94))
                                FmDraw dr = fmNewDraw(bar_index * 2 + i)
                                // her çizgi kendi ilk dokunuşundan başlar (dolgu taşmaz) / each line starts at its own first touch (no oversized fill)
                                line lu = line.new(uB1, uP1, bar_index, fmY(uB1, uP1, uB2, uP2, bar_index), color=fmLinCol, width=2)
                                line ld = line.new(dB1, dP1, bar_index, fmY(dB1, dP1, dB2, dP2, bar_index), color=fmLinCol, width=2)
                                linefill lf = linefill.new(lu, ld, color.new(fmLinCol, 88))
                                dr.ls.push(lu)
                                dr.ls.push(ld)
                                dr.lfs.push(lf)
                                string arw = ldr == 1 ? " ↑" : ldr == -1 ? " ↓" : ""
                                int    lx  = math.min(uB1, dB1)
                                dr.lbs.push(label.new(lx, fmY(uB1, uP1, uB2, uP2, lx) + atr * 0.6, lnm + arw, style=label.style_label_down, color=fmLinCol, textcolor=color.white, size=txtSize))
                                int apx = slL > slU ? xs + int(math.round(Hs / (slL - slU))) : na
                                fmLn := FmLin.new(true, uB1, uP1, uB2, uP2, dB1, dP1, dB2, dP2, bar_index, xe, apx, ldr, Hs, pole, lnm, lu, ld, lf, dr.id)
                                fmStore(dr)
                                fmEvForm := true
                                fmMsg    += (fmMsg == "" ? "" : " | ") + syminfo.ticker + " " + timeframe.period + " · " + lnm + arw + L(" oluştu", " formed")
 
    // ── dönüş formasyonu boyun kırılımı / reversal pattern neckline break ──
    for ix = 0 to 1
        FmRev r = fmRv.get(ix)
        if r.act
            int   s  = ix == 0 ? 1 : -1      // 1 = aşağı kırılım beklenir / bearish break expected
            float nk = fmY(r.b1, r.p1, r.b2, r.p2, bar_index)
            r.ln.set_xy2(bar_index, nk)
            if (s == 1 and close < nk) or (s == -1 and close > nk)
                r.act := false
                float  tg = nk - s * r.hgt
                color  pc = s == 1 ? fmTopCol : fmBotCol
                FmDraw dr = fmFind(r.id)
                if not na(dr)
                    dr.lbs.push(label.new(bar_index, s == 1 ? low - atr * 0.3 : high + atr * 0.3, (s == 1 ? "▼ " : "▲ ") + r.nm + L(" kırıldı", " broke"), style=s == 1 ? label.style_label_up : label.style_label_down, color=pc, textcolor=color.white, size=txtSize))
                    if fmTgt
                        fmTarget(dr, nk, tg, pc)
                fmBrkDir := -s
                fmBrkBar := bar_index
                fmBrkNm  := r.nm
                if s == 1
                    fmEvDn := true
                else
                    fmEvUp := true
                fmMsg += (fmMsg == "" ? "" : " | ") + syminfo.ticker + " " + timeframe.period + " · " + r.nm + L(" boyun kırıldı, hedef ", " neckline broke, target ") + f_p(tg)
            else if (s == 1 and close > r.inv) or (s == -1 and close < r.inv) or bar_index - r.st > fmWait
                // geçersiz (baş / tepe aşıldı) veya süre doldu / invalid (head / peak exceeded) or timed out
                r.act := false
                fmGray(r.ln)
 
    // ── çizgi formasyonu kırılımı / line pattern break ──
    if fmLn.act
        float uN = fmY(fmLn.uB1, fmLn.uP1, fmLn.uB2, fmLn.uP2, bar_index)
        float dN = fmY(fmLn.dB1, fmLn.dP1, fmLn.dB2, fmLn.dP2, bar_index)
        fmLn.lu.set_xy2(bar_index, uN)
        fmLn.ld.set_xy2(bar_index, dN)
        int bd = close > uN ? 1 : close < dN ? -1 : 0
        if bd != 0
            fmLn.act := false
            fmBlock  := bar_index
            float  lv = bd == 1 ? uN : dN
            float  tg = lv + bd * (fmLn.pole > 0 ? fmLn.pole : fmLn.hgt)
            color  bc = bd == 1 ? bullCol : bearCol
            FmDraw dr = fmFind(fmLn.id)
            if not na(dr)
                dr.lbs.push(label.new(bar_index, bd == 1 ? high + atr * 0.3 : low - atr * 0.3, (bd == 1 ? "▲ " : "▼ ") + fmLn.nm + L(" kırılım", " breakout"), style=bd == 1 ? label.style_label_down : label.style_label_up, color=bc, textcolor=bd == 1 ? color.black : color.white, size=txtSize))
                if fmTgt
                    fmTarget(dr, lv, tg, bc)
            fmBrkDir := bd
            fmBrkBar := bar_index
            fmBrkNm  := fmLn.nm
            if bd == 1
                fmEvUp := true
            else
                fmEvDn := true
            fmMsg += (fmMsg == "" ? "" : " | ") + syminfo.ticker + " " + timeframe.period + " · " + fmLn.nm + (bd == 1 ? L(" yukarı kırıldı, hedef ", " broke up, target ") : L(" aşağı kırıldı, hedef ", " broke down, target ")) + f_p(tg)
        else if bar_index - fmLn.st > fmWait or (not na(fmLn.apex) and bar_index >= fmLn.apex)
            // süre doldu ya da üçgen / takoz tepe noktasına ulaştı / timed out or triangle / wedge reached its apex
            fmLn.act := false
            fmGray(fmLn.lu)
            fmGray(fmLn.ld)
            fmLn.lf.set_color(color.new(color.gray, 94))
 
if fmAlert and fmMsg != ""
    alert(fmMsg, alert.freq_once_per_bar_close)
 
// ═══════════════════════ BİLGİ TABLOSU / INFO TABLE ═══════════════════════
var table tb = table.new(tblPos, 2, 8, bgcolor=color.new(#0B0E14, 10), frame_color=color.new(#2A2E39, 0), frame_width=1, border_width=1, border_color=color.new(#2A2E39, 40))
 
f_row(int r, string k, string v, color c) =>
    table.cell(tb, 0, r, k, text_color=color.new(#B2B5BE, 0), text_size=txtSize, text_halign=text.align_left)
    table.cell(tb, 1, r, v, text_color=c, text_size=txtSize, text_halign=text.align_right)
 
if showTbl and barstate.islast
    FmRev  rDn    = fmRv.get(0)
    FmRev  rUp    = fmRv.get(1)
    string upTxt  = rUp.act ? rUp.nm + L(" · boyun ", " · neckline ") + f_p(fmY(rUp.b1, rUp.p1, rUp.b2, rUp.p2, bar_index)) : "—"
    string dnTxt  = rDn.act ? rDn.nm + L(" · boyun ", " · neckline ") + f_p(fmY(rDn.b1, rDn.p1, rDn.b2, rDn.p2, bar_index)) : "—"
    string linTxt = fmLn.act ? fmLn.nm + (fmLn.dir == 1 ? " ↑" : fmLn.dir == -1 ? " ↓" : "") : "—"
    string brkTxt = na(fmBrkBar) ? "—" : (fmBrkDir == 1 ? "▲ " : "▼ ") + fmBrkNm + " · " + str.tostring(bar_index - fmBrkBar) + L(" bar önce", " bars ago")
    color  stC    = lastStruct == "HH" or lastStruct == "HL" ? bullCol : lastStruct == "—" ? color.gray : bearCol
    color  hb     = trend == 1 ? color.new(bullCol, 72) : trend == -1 ? color.new(bearCol, 72) : color.new(#1E2230, 0)
    table.cell(tb, 0, 0, "STRUCTURE HUNTER", text_color=color.white, bgcolor=hb, text_size=txtSize, text_halign=text.align_left)
    table.cell(tb, 1, 0, syminfo.ticker, text_color=color.new(#D1D4DC, 0), bgcolor=hb, text_size=txtSize, text_halign=text.align_right)
    f_row(1, "Trend", trend == 1 ? L("Yükseliş ▲", "Bullish ▲") : trend == -1 ? L("Düşüş ▼", "Bearish ▼") : "—", trend == 1 ? bullCol : trend == -1 ? bearCol : color.gray)
    f_row(2, L("Son yapı", "Last structure"), lastStruct, stC)
    f_row(3, L("Son kırılım", "Last break"), lastBreak, color.white)
    f_row(4, L("Yükseliş formasyonu", "Bullish pattern"), upTxt, rUp.act ? fmBotCol : color.gray)
    f_row(5, L("Düşüş formasyonu", "Bearish pattern"), dnTxt, rDn.act ? fmTopCol : color.gray)
    f_row(6, L("Çizgi formasyonu", "Line pattern"), linTxt, fmLn.act ? fmLinCol : color.gray)
    f_row(7, L("Son formasyon kırılımı", "Last pattern break"), brkTxt, na(fmBrkBar) ? color.gray : fmBrkDir == 1 ? bullCol : bearCol)
 
// ═══════════════════════ ALARMLAR / ALERTS ═══════════════════════
alertcondition(aBosUp,   "BOS ↑",                                         "{{ticker}} {{interval}} @ {{close}} | BOS ↑")
alertcondition(aBosDn,   "BOS ↓",                                         "{{ticker}} {{interval}} @ {{close}} | BOS ↓")
alertcondition(aChUp,    "CHoCH ↑",                                       "{{ticker}} {{interval}} @ {{close}} | CHoCH ↑")
alertcondition(aChDn,    "CHoCH ↓",                                       "{{ticker}} {{interval}} @ {{close}} | CHoCH ↓")
alertcondition(fmEvForm, "Formasyon oluştu / Pattern formed",              "{{ticker}} {{interval}} @ {{close}} | Pattern formed")
alertcondition(fmEvUp,   "Formasyon yukarı kırıldı / Pattern broke up",    "{{ticker}} {{interval}} @ {{close}} | Pattern ↑")
alertcondition(fmEvDn,   "Formasyon aşağı kırıldı / Pattern broke down",   "{{ticker}} {{interval}} @ {{close}} | Pattern ↓")

← 返回列表