Price Action Patterns | Sattam

S4tt4m · study · 820 行 · 点赞 251 · 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/
// © Sattam
//@version=6
indicator("Price Action Patterns | Sattam", shorttitle = "Price Action | Sattam", overlay = true, max_lines_count = 500, max_labels_count = 500, max_bars_back = 500)
 
// ───────────────────────── Inputs ─────────────────────────
G_DET = "Detection · الاكتشاف"
L        = input.int(5, "Swing length · طول القمة/القاع", minval = 2, maxval = 30, group = G_DET, tooltip = "Bars on each side that confirm a swing high/low.\nعدد الشموع على كل جانب لتأكيد القمة أو القاع.")
eqTol    = input.float(20, "Equal highs/lows tolerance % · سماحية التساوي %", minval = 1, maxval = 60, group = G_DET, tooltip = "How close tops/bottoms must be, as % of pattern height.\nمدى تقارب القمم أو القيعان كنسبة من ارتفاع النموذج.") / 100
shTol    = input.float(40, "Shoulder symmetry % · تماثل الكتفين %", minval = 1, maxval = 100, group = G_DET) / 100
touchTol = input.float(20, "Trendline touch tolerance % · سماحية لمس الخط %", minval = 1, maxval = 60, group = G_DET, tooltip = "A swing touches a line if within this % of the pattern height; candle bodies may not cut the lines by more.\nالنقطة تلمس الخط إن كانت ضمن هذه النسبة من الارتفاع، ولا تقطع أجسام الشموع الخطوط بأكثر منها.") / 100
flatTol  = input.float(20, "Flat line tolerance % · سماحية الخط الأفقي %", minval = 1, maxval = 60, group = G_DET) / 100
parTol   = input.float(25, "Parallel / converging % · التوازي والتقارب %", minval = 5, maxval = 60, group = G_DET) / 100
poleMult = input.float(1.5, "Flag/pennant pole ≥ x first pullback · السارية ≥ مضاعف أول ارتداد", minval = 0.5, step = 0.1, group = G_DET, tooltip = "The impulse before a flag or pennant must be at least this many times the first pullback inside it.\nالموجة الدافعة قبل العلم أو الراية يجب أن تكون على الأقل هذا المضاعف من أول ارتداد داخله.")
minH     = input.float(1.0, "Minimum height (ATR) · أدنى ارتفاع (ATR)", minval = 0, step = 0.1, group = G_DET)
maxWait  = input.int(30, "Bars to wait for breakout · مهلة الكسر (شموع)", minval = 1, group = G_DET)
maxSpan  = input.int(150, "Longest pattern (bars) · أطول نموذج (شموع)", minval = 20, maxval = 400, group = G_DET)
hsMode   = input.string("Head · الرأس", "H&S target from · هدف الرأس والكتفين من", options = ["Head · الرأس", "Shoulder · الكتف"], group = G_DET)
hsHead   = hsMode == "Head · الرأس"
 
G_PAT = "Patterns · النماذج"
onDouble = input.bool(true, "Double Top / Bottom · القمة والقاع المزدوج", group = G_PAT)
onTriple = input.bool(true, "Triple Top / Bottom · القمة والقاع الثلاثي", group = G_PAT)
onHS     = input.bool(true, "Head & Shoulders (+ inverse) · الرأس والكتفين", group = G_PAT)
onWedge  = input.bool(true, "Rising / Falling Wedge · الوتد الصاعد والهابط", group = G_PAT)
onRect   = input.bool(true, "Rectangle · المستطيل", group = G_PAT)
onTri    = input.bool(true, "Triangles · المثلثات", group = G_PAT)
onFlag   = input.bool(true, "Flags · الأعلام", group = G_PAT)
onPen    = input.bool(true, "Pennants · الرايات", group = G_PAT)
 
G_DRW = "Drawing · الرسم"
shMarks  = input.bool(true, "Circles & captions · الدوائر والتسميات", group = G_DRW)
shLvls   = input.bool(true, "Entry / SL / TP · الدخول والوقف والهدف", group = G_DRW)
shName   = input.bool(true, "Pattern name · اسم النموذج", group = G_DRW)
shForm   = input.bool(true, "Forming patterns · النماذج قيد التكوّن", group = G_DRW)
maxShow  = input.int(20, "Patterns kept on chart · عدد النماذج على الشارت", minval = 1, maxval = 35, group = G_DRW)
lvlLen   = input.int(20, "Level line length · طول خطوط المستويات", minval = 3, maxval = 200, group = G_DRW)
lw       = input.int(2, "Line width · سماكة الخط", minval = 1, maxval = 5, group = G_DRW)
txtMode  = input.string("Small · صغير", "Text size · حجم النص", options = ["Small · صغير", "Normal · متوسط", "Large · كبير"], group = G_DRW)
langMode = input.string("English + العربي", "Chart text language · لغة نصوص الشارت", options = ["English", "العربي", "English + العربي"], group = G_DRW)
szTxt    = txtMode == "Small · صغير" ? size.small : txtMode == "Large · كبير" ? size.large : size.normal
szBig    = txtMode == "Small · صغير" ? size.normal : txtMode == "Large · كبير" ? size.huge : size.large
szCirc   = txtMode == "Small · صغير" ? size.large : size.huge
 
G_COL = "Colors · الألوان"
cPat  = input.color(#E53935, "Pattern lines · خطوط النموذج", group = G_COL)
cTP   = input.color(#22A847, "Entry & TP · الدخول والهدف", group = G_COL)
cSL   = input.color(#E53935, "Stop loss · الوقف", group = G_COL)
cForm = input.color(#9E9E9E, "Forming · قيد التكوّن", group = G_COL)
 
// ───────────────────────── Types / constants ─────────────────────────
const int T_DT = 1
const int T_TT = 2
const int T_HS = 3
const int T_DB = 4
const int T_TB = 5
const int T_IHS = 6
const int T_RW = 7
const int T_FW = 8
const int T_RECT = 9
const int T_SYM = 10
const int T_ASC = 11
const int T_DESC = 12
const int T_BFLAG = 13
const int T_SFLAG = 14
const int T_BPEN = 15
const int T_SPEN = 16
 
type Pat
    int grp = 0
    int typ = 0
    int only = 0
    int start = 0
    int lastBar = 0
    int nx1 = 0
    float ny1 = na
    int nx2 = 0
    float ny2 = na
    float inv = na
    float height = na
    float shAvg = na
    int ux1 = 0
    float uy1 = na
    int ux2 = 0
    float uy2 = na
    int dx1 = 0
    float dy1 = na
    int dx2 = 0
    float dy2 = na
    float apex = na
    float lastHigh = na
    float lastLow = na
    float hhi = na
    float llo = na
    int preB = na
    float preP = na
    array<int> pb
    array<float> pp
    array<int> pt
 
f_name(int t) =>
    switch t
        T_DT    => "Double Top"
        T_TT    => "Triple Top"
        T_HS    => "Head & Shoulders"
        T_DB    => "Double Bottom"
        T_TB    => "Triple Bottom"
        T_IHS   => "Inverse Head & Shoulders"
        T_RW    => "Rising Wedge"
        T_FW    => "Falling Wedge"
        T_RECT  => "Rectangle"
        T_SYM   => "Symmetrical Triangle"
        T_ASC   => "Ascending Triangle"
        T_DESC  => "Descending Triangle"
        T_BFLAG => "Bull Flag"
        T_SFLAG => "Bear Flag"
        T_BPEN  => "Bull Pennant"
        T_SPEN  => "Bear Pennant"
        => ""
 
f_name_ar(int t) =>
    switch t
        T_DT    => "قمة مزدوجة"
        T_TT    => "قمة ثلاثية"
        T_HS    => "رأس وكتفين"
        T_DB    => "قاع مزدوج"
        T_TB    => "قاع ثلاثي"
        T_IHS   => "رأس وكتفين معكوس"
        T_RW    => "وتد صاعد"
        T_FW    => "وتد هابط"
        T_RECT  => "مستطيل"
        T_SYM   => "مثلث متماثل"
        T_ASC   => "مثلث صاعد"
        T_DESC  => "مثلث هابط"
        T_BFLAG => "علم صاعد"
        T_SFLAG => "علم هابط"
        T_BPEN  => "راية صاعدة"
        T_SPEN  => "راية هابطة"
        => ""
 
// chart text in the chosen language (both = English line + Arabic line)
f_t(string en, string ar) =>
    langMode == "English" ? en : langMode == "العربي" ? ar : en + "\n" + ar
 
f_enabled(int t) =>
    switch t
        T_DT    => onDouble
        T_DB    => onDouble
        T_TT    => onTriple
        T_TB    => onTriple
        T_HS    => onHS
        T_IHS   => onHS
        T_RW    => onWedge
        T_FW    => onWedge
        T_RECT  => onRect
        T_SYM   => onTri
        T_ASC   => onTri
        T_DESC  => onTri
        T_BFLAG => onFlag
        T_SFLAG => onFlag
        T_BPEN  => onPen
        T_SPEN  => onPen
        => false
 
// prices sit on a tick grid, so a tolerance can be hit exactly; TOL makes such ties decide the same way
// everywhere (exact ties pass a '<=' test and fail a strict one)
const float TOL = 1.000000001
 
// a close counts as beyond a level only when it clears it by more than float noise
f_above(float a, float b) =>
    a - b > 1e-9 * math.abs(b)
f_below(float a, float b) =>
    b - a > 1e-9 * math.abs(b)
 
f_line(int x1, float y1, int x2, float y2, int x) =>
    x2 == x1 ? y1 : y1 + (y2 - y1) * (x - x1) / (x2 - x1)
 
// ───────────────────────── State ─────────────────────────
var array<int>   sb = array.new<int>()
var array<float> sp = array.new<float>()
var array<int>   st = array.new<int>()
var array<Pat>   pend = array.new<Pat>(3, na)
var array<int>   lastEnd = array.from(-1, -1, -1)
var array<int>   recT = array.new<int>(3, na)
var array<int>   recDir = array.new<int>(3, na)
var array<int>   recStart = array.new<int>(3, na)
// drawings, grouped per pattern (oldest first)
var array<line>  gLines = array.new<line>()
var array<label> gLabels = array.new<label>()
var array<int>   cntL = array.new<int>()
var array<int>   cntX = array.new<int>()
// per-bar outputs (one slot per group) for alerts and verification
array<float> oCode  = array.new<float>(3, na)
array<float> oEntry = array.new<float>(3, na)
array<float> oSL    = array.new<float>(3, na)
array<float> oTP    = array.new<float>(3, na)
array<float> oXb    = array.new<float>(3, na)
array<float> oStart = array.new<float>(3, na)
array<int>   oCnt   = array.new<int>(1, 0)
 
atrv = ta.atr(14)
 
// ───────────────────────── Pattern evaluation ─────────────────────────
f_pts(int i1, int i2) =>
    array<int> b = array.new<int>()
    array<float> p = array.new<float>()
    array<int> t = array.new<int>()
    for i = i1 to i2
        b.push(sb.get(i))
        p.push(sp.get(i))
        t.push(st.get(i))
    [b, p, t]
 
f_tops(float atr, int lastE) =>
    Pat res = na
    int n = sb.size()
    if n >= 6 and onHS
        // Head & Shoulders
        float P0 = sp.get(n - 6), float LS = sp.get(n - 5), float T1 = sp.get(n - 4), float HD = sp.get(n - 3), float T2 = sp.get(n - 2), float RS = sp.get(n - 1)
        int bLS = sb.get(n - 5), int bT1 = sb.get(n - 4), int bHD = sb.get(n - 3), int bT2 = sb.get(n - 2), int bRS = sb.get(n - 1)
        float h = HD - f_line(bT1, T1, bT2, T2, bHD)
        bool ok = h > 0 and h >= minH * atr and HD - math.max(LS, RS) >= eqTol * h / TOL and math.abs(LS - RS) <= shTol * h * TOL and LS - f_line(bT1, T1, bT2, T2, bLS) >= eqTol * h / TOL and RS - f_line(bT1, T1, bT2, T2, bRS) >= eqTol * h / TOL and math.abs(T1 - T2) <= 0.5 * h * TOL and P0 < math.min(T1, T2)
        if ok and bLS >= lastE
            float hs = ((LS - f_line(bT1, T1, bT2, T2, bLS)) + (RS - f_line(bT1, T1, bT2, T2, bRS))) / 2
            [b, p, t] = f_pts(n - 6, n - 1)
            res := Pat.new(1, T_HS, -1, bLS, bRS, bT1, T1, bT2, T2, HD, hsHead ? h : hs, (LS + RS) / 2, hhi = HD, llo = math.min(T1, T2), pb = b, pp = p, pt = t)
    if na(res) and n >= 6 and onTriple
        // Triple Top
        float P0 = sp.get(n - 6), float H1 = sp.get(n - 5), float T1 = sp.get(n - 4), float H2 = sp.get(n - 3), float T2 = sp.get(n - 2), float H3 = sp.get(n - 1)
        int bH1 = sb.get(n - 5), int bT1 = sb.get(n - 4), int bT2 = sb.get(n - 2), int bH3 = sb.get(n - 1)
        float neck = math.min(T1, T2)
        float hi = math.max(H1, H2, H3)
        float lo = math.min(H1, H2, H3)
        float h = hi - neck
        bool ok = h > 0 and h >= minH * atr and hi - lo <= eqTol * h * TOL and math.abs(T1 - T2) <= 0.5 * h * TOL and P0 < neck - eqTol * h * TOL
        if ok and bH1 >= lastE
            [b, p, t] = f_pts(n - 6, n - 1)
            res := Pat.new(1, T_TT, -1, bH1, bH3, bT1, neck, bT2, neck, hi, h, hhi = hi, llo = neck, pb = b, pp = p, pt = t)
    if na(res) and n >= 4 and onDouble
        // Double Top
        float P0 = sp.get(n - 4), float H1 = sp.get(n - 3), float TR = sp.get(n - 2), float H2 = sp.get(n - 1)
        int bH1 = sb.get(n - 3), int bTR = sb.get(n - 2), int bH2 = sb.get(n - 1)
        float hi = math.max(H1, H2)
        float h = hi - TR
        bool ok = h > 0 and h >= minH * atr and math.abs(H1 - H2) <= eqTol * h * TOL and P0 < TR - eqTol * h * TOL
        if ok and bH1 >= lastE
            [b, p, t] = f_pts(n - 4, n - 1)
            res := Pat.new(1, T_DT, -1, bH1, bH2, bTR, TR, bH2, TR, hi, h, hhi = hi, llo = TR, pb = b, pp = p, pt = t)
    res
 
f_bottoms(float atr, int lastE) =>
    Pat res = na
    int n = sb.size()
    if n >= 6 and onHS
        // Inverse Head & Shoulders
        float P0 = sp.get(n - 6), float LS = sp.get(n - 5), float T1 = sp.get(n - 4), float HD = sp.get(n - 3), float T2 = sp.get(n - 2), float RS = sp.get(n - 1)
        int bLS = sb.get(n - 5), int bT1 = sb.get(n - 4), int bHD = sb.get(n - 3), int bT2 = sb.get(n - 2), int bRS = sb.get(n - 1)
        float h = f_line(bT1, T1, bT2, T2, bHD) - HD
        bool ok = h > 0 and h >= minH * atr and math.min(LS, RS) - HD >= eqTol * h / TOL and math.abs(LS - RS) <= shTol * h * TOL and f_line(bT1, T1, bT2, T2, bLS) - LS >= eqTol * h / TOL and f_line(bT1, T1, bT2, T2, bRS) - RS >= eqTol * h / TOL and math.abs(T1 - T2) <= 0.5 * h * TOL and P0 > math.max(T1, T2)
        if ok and bLS >= lastE
            float hs = ((f_line(bT1, T1, bT2, T2, bLS) - LS) + (f_line(bT1, T1, bT2, T2, bRS) - RS)) / 2
            [b, p, t] = f_pts(n - 6, n - 1)
            res := Pat.new(2, T_IHS, 1, bLS, bRS, bT1, T1, bT2, T2, HD, hsHead ? h : hs, (LS + RS) / 2, hhi = math.max(T1, T2), llo = HD, pb = b, pp = p, pt = t)
    if na(res) and n >= 6 and onTriple
        // Triple Bottom
        float P0 = sp.get(n - 6), float L1 = sp.get(n - 5), float T1 = sp.get(n - 4), float L2 = sp.get(n - 3), float T2 = sp.get(n - 2), float L3 = sp.get(n - 1)
        int bL1 = sb.get(n - 5), int bT1 = sb.get(n - 4), int bT2 = sb.get(n - 2), int bL3 = sb.get(n - 1)
        float neck = math.max(T1, T2)
        float lo = math.min(L1, L2, L3)
        float hi = math.max(L1, L2, L3)
        float h = neck - lo
        bool ok = h > 0 and h >= minH * atr and hi - lo <= eqTol * h * TOL and math.abs(T1 - T2) <= 0.5 * h * TOL and P0 > neck + eqTol * h * TOL
        if ok and bL1 >= lastE
            [b, p, t] = f_pts(n - 6, n - 1)
            res := Pat.new(2, T_TB, 1, bL1, bL3, bT1, neck, bT2, neck, lo, h, hhi = neck, llo = lo, pb = b, pp = p, pt = t)
    if na(res) and n >= 4 and onDouble
        // Double Bottom
        float P0 = sp.get(n - 4), float L1 = sp.get(n - 3), float TR = sp.get(n - 2), float L2 = sp.get(n - 1)
        int bL1 = sb.get(n - 3), int bTR = sb.get(n - 2), int bL2 = sb.get(n - 1)
        float lo = math.min(L1, L2)
        float h = TR - lo
        bool ok = h > 0 and h >= minH * atr and math.abs(L1 - L2) <= eqTol * h * TOL and P0 > TR + eqTol * h * TOL
        if ok and bL1 >= lastE
            [b, p, t] = f_pts(n - 4, n - 1)
            res := Pat.new(2, T_DB, 1, bL1, bL2, bTR, TR, bL2, TR, lo, h, hhi = TR, llo = lo, pb = b, pp = p, pt = t)
    res
 
f_window(float atr, int lastE, int w) =>
    Pat res = na
    int n = sb.size()
    for _k = 0 to 0
        if n < w + 1
            break
        int i0 = n - w
        int xs = sb.get(i0)
        int xe = sb.get(n - 1)
        if xe - xs > maxSpan
            break
        if xs < lastE
            break
        int iu1 = -1
        int iu2 = -1
        int id1 = -1
        int id2 = -1
        for i = i0 to n - 1
            if st.get(i) == 1
                if iu1 < 0
                    iu1 := i
                iu2 := i
            else
                if id1 < 0
                    id1 := i
                id2 := i
        int ux1 = sb.get(iu1), int ux2 = sb.get(iu2), int dx1 = sb.get(id1), int dx2 = sb.get(id2)
        float uy1 = sp.get(iu1), float uy2 = sp.get(iu2), float dy1 = sp.get(id1), float dy2 = sp.get(id2)
        float h0 = f_line(ux1, uy1, ux2, uy2, xs) - f_line(dx1, dy1, dx2, dy2, xs)
        float he = f_line(ux1, uy1, ux2, uy2, xe) - f_line(dx1, dy1, dx2, dy2, xe)
        if not (h0 > 0 and he > 0 and h0 >= minH * atr)
            break
        float tol = touchTol * h0
        bool ok = true
        for i = i0 to n - 1
            float d = st.get(i) == 1 ? math.abs(sp.get(i) - f_line(ux1, uy1, ux2, uy2, sb.get(i))) : math.abs(sp.get(i) - f_line(dx1, dy1, dx2, dy2, sb.get(i)))
            if d > tol
                ok := false
                break
        if not ok
            break
        for x = xs to xe
            int off = bar_index - x
            float top = math.max(open[off], close[off])
            float bot = math.min(open[off], close[off])
            if top > f_line(ux1, uy1, ux2, uy2, x) + tol or bot < f_line(dx1, dy1, dx2, dy2, x) - tol
                ok := false
                break
        if not ok
            break
        if he > (1 + parTol) * h0
            break
        float su = (f_line(ux1, uy1, ux2, uy2, xe) - f_line(ux1, uy1, ux2, uy2, xs)) / h0
        float sd = (f_line(dx1, dy1, dx2, dy2, xe) - f_line(dx1, dy1, dx2, dy2, xs)) / h0
        bool conv = he < (1 - parTol) * h0
        bool par = not conv
        bool fu = math.abs(su) <= flatTol
        bool fd = math.abs(sd) <= flatTol
        bool legUp = st.get(i0) == 1
        // impulse start: walk back while the move into the window keeps its trend
        int j = i0 - 1
        while j - 2 >= 0 and (legUp ? (sp.get(j - 1) < sp.get(i0) and sp.get(j - 2) < sp.get(j)) : (sp.get(j - 1) > sp.get(i0) and sp.get(j - 2) > sp.get(j)))
            j -= 2
        // pole vs the first pullback of the pattern
        bool pole = math.abs(sp.get(i0) - sp.get(j)) >= poleMult * math.abs(sp.get(i0) - sp.get(i0 + 1))
        int typ = 0
        if fu and fd
            typ := T_RECT
        else if fu and sd > flatTol
            typ := T_ASC
        else if fd and su < -flatTol
            typ := T_DESC
        else if su < -flatTol and sd > flatTol
            typ := pole ? (legUp ? T_BPEN : T_SPEN) : T_SYM
        else if su > flatTol and sd > flatTol
            typ := conv and sd > su ? T_RW : (par and pole and not legUp ? T_SFLAG : 0)
        else if su < -flatTol and sd < -flatTol
            typ := conv and su < sd ? T_FW : (par and pole and legUp ? T_BFLAG : 0)
        // rectangle: almost equal highs and equal lows -> horizontal box at their averages
        float rU = na
        float rD = na
        if typ == T_RECT
            float sh = 0.0
            int nh = 0
            float sl = 0.0
            int nl = 0
            float hMax = na
            float hMin = na
            float lMax = na
            float lMin = na
            for i = i0 to n - 1
                float q = sp.get(i)
                if st.get(i) == 1
                    sh += q
                    nh += 1
                    hMax := na(hMax) ? q : math.max(hMax, q)
                    hMin := na(hMin) ? q : math.min(hMin, q)
                else
                    sl += q
                    nl += 1
                    lMax := na(lMax) ? q : math.max(lMax, q)
                    lMin := na(lMin) ? q : math.min(lMin, q)
            rU := sh / nh
            rD := sl / nl
            float hR = rU - rD
            if not (hR > 0 and hMax - hMin <= eqTol * hR * TOL and lMax - lMin <= eqTol * hR * TOL)
                typ := 0
        if typ == 0 or not f_enabled(typ)
            break
        int only = (typ == T_RW or typ == T_SFLAG or typ == T_SPEN) ? -1 : (typ == T_FW or typ == T_BFLAG or typ == T_BPEN) ? 1 : 0
        float kU = (f_line(ux1, uy1, ux2, uy2, xe) - f_line(ux1, uy1, ux2, uy2, xs)) / (xe - xs)
        float kD = (f_line(dx1, dy1, dx2, dy2, xe) - f_line(dx1, dy1, dx2, dy2, xs)) / (xe - xs)
        bool converging = typ == T_SYM or typ == T_ASC or typ == T_DESC or typ == T_RW or typ == T_FW or typ == T_BPEN or typ == T_SPEN
        float apex = converging and kD > kU ? xs + h0 / (kD - kU) : na
        float lastHigh = na
        float lastLow = na
        float hhi = sp.get(i0)
        float llo = sp.get(i0)
        for i = i0 to n - 1
            if st.get(i) == 1
                lastHigh := sp.get(i)
            else
                lastLow := sp.get(i)
            hhi := math.max(hhi, sp.get(i))
            llo := math.min(llo, sp.get(i))
        [b, p, t] = f_pts(i0, n - 1)
        bool rect = typ == T_RECT
        res := Pat.new(3, typ, only, xs, xe, ux1 = ux1, uy1 = rect ? rU : uy1, ux2 = ux2, uy2 = rect ? rU : uy2, dx1 = dx1, dy1 = rect ? rD : dy1, dx2 = dx2, dy2 = rect ? rD : dy2, height = rect ? rU - rD : h0, apex = apex, lastHigh = lastHigh, lastLow = lastLow, hhi = hhi, llo = llo, preB = sb.get(j), preP = sp.get(j), pb = b, pp = p, pt = t)
        break
    res
 
// both windows; a flag/pennant in the 5-swing window wins (its pole stays outside the pattern,
// whereas the 6-swing window would swallow the pole as the pattern's first leg)
f_shapes(float atr, int lastE) =>
    Pat r6 = f_window(atr, lastE, 6)
    Pat r5 = f_window(atr, lastE, 5)
    bool pole5 = not na(r5) and (r5.typ == T_BFLAG or r5.typ == T_SFLAG or r5.typ == T_BPEN or r5.typ == T_SPEN)
    pole5 ? r5 : not na(r6) ? r6 : r5
 
// one bar of a pending pattern → [res, dir, entry]; res: 0 nothing, -1 drop, 1 breakout
f_step(Pat p, int x, float cl) =>
    int res = 0
    int dir = 0
    float entry = na
    if x - p.lastBar > maxWait
        res := -1
    else if not na(p.apex) and x > p.apex
        res := -1
    else if p.grp == 1
        float nk = f_line(p.nx1, p.ny1, p.nx2, p.ny2, x)
        if f_above(cl, p.inv)
            res := -1
        else if f_below(cl, nk)
            res := 1
            dir := -1
            entry := nk
    else if p.grp == 2
        float nk = f_line(p.nx1, p.ny1, p.nx2, p.ny2, x)
        if f_below(cl, p.inv)
            res := -1
        else if f_above(cl, nk)
            res := 1
            dir := 1
            entry := nk
    else
        float up = f_line(p.ux1, p.uy1, p.ux2, p.uy2, x)
        float dn = f_line(p.dx1, p.dy1, p.dx2, p.dy2, x)
        if p.only == -1
            if f_above(cl, up)
                res := -1
            else if f_below(cl, dn)
                res := 1
                dir := -1
                entry := dn
        else if p.only == 1
            if f_below(cl, dn)
                res := -1
            else if f_above(cl, up)
                res := 1
                dir := 1
                entry := up
        else
            if f_above(cl, up)
                res := 1
                dir := 1
                entry := up
            else if f_below(cl, dn)
                res := 1
                dir := -1
                entry := dn
    [res, dir, entry]
 
// ───────────────────────── Drawing ─────────────────────────
f_lbl(int x, float y, string txt, string sty, color col, string sz) =>
    gLabels.push(label.new(x, y, txt, style = sty, color = #00000000, textcolor = col, size = sz))
 
f_ln(int x1, float y1, int x2, float y2, color col, int w, string sty) =>
    gLines.push(line.new(x1, y1, x2, y2, color = col, width = w, style = sty))
 
f_caption_en(int t, int dir) =>
    switch t
        T_DT    => "price drops down!"
        T_TT    => "price drops down!"
        T_DB    => "price moves up!"
        T_TB    => "price moves up!"
        T_HS    => "KABOOM! Price dropped..."
        T_IHS   => "Price shoots up!"
        T_RW    => "price makes a nice move down..."
        T_FW    => "huge upside breakout!"
        T_RECT  => dir < 0 ? "price falls by the same height... and more!" : "price pops up by the same height... and more!"
        T_SYM   => dir > 0 ? "Whee, price surged up!" : "price drops by the same height!"
        T_ASC   => dir > 0 ? "price pops up by the same height!" : "price drops by almost the same height!"
        T_DESC  => dir > 0 ? "Whoa, price flew up!" : "price drops by the same height!"
        T_BFLAG => "price breaks, uptrend resumes"
        T_BPEN  => "price breaks, uptrend resumes"
        => "price broke down, downtrend resumes..."
 
f_caption_ar(int t, int dir) =>
    switch t
        T_DT    => "السعر يهبط!"
        T_TT    => "السعر يهبط!"
        T_DB    => "السعر يصعد!"
        T_TB    => "السعر يصعد!"
        T_HS    => "بوم! السعر هبط..."
        T_IHS   => "السعر ينطلق للأعلى!"
        T_RW    => "السعر يتحرك للأسفل بقوة..."
        T_FW    => "اختراق صاعد قوي!"
        T_RECT  => dir < 0 ? "السعر يهبط بنفس الارتفاع... وأكثر!" : "السعر يصعد بنفس الارتفاع... وأكثر!"
        T_SYM   => dir > 0 ? "السعر قفز للأعلى!" : "السعر يهبط بنفس الارتفاع!"
        T_ASC   => dir > 0 ? "السعر يصعد بنفس الارتفاع!" : "السعر يهبط بنفس الارتفاع تقريباً!"
        T_DESC  => dir > 0 ? "السعر طار للأعلى!" : "السعر يهبط بنفس الارتفاع!"
        T_BFLAG => "كسر، والاتجاه الصاعد يستمر"
        T_BPEN  => "كسر، والاتجاه الصاعد يستمر"
        => "كسر للأسفل، والاتجاه الهابط يستمر..."
 
f_caption(int t, int dir) =>
    f_t(f_caption_en(t, dir), f_caption_ar(t, dir))
 
// a price level label: the price follows the English word, the Arabic word goes last (keeps the number readable)
f_lvl(string en, string ar, float v) =>
    string pr = str.tostring(v, format.mintick)
    langMode == "English" ? en + " " + pr : langMode == "العربي" ? ar + " " + pr : en + " " + pr + " · " + ar
 
f_draw(Pat p, int xb, int dir, float entry, float sl, float tp) =>
    int l0 = gLines.size()
    int x0 = gLabels.size()
    color tc = chart.fg_color
    float H = p.hhi - p.llo
    int n = p.pb.size()
    // pattern geometry
    if p.grp != 3
        bool top = p.grp == 1
        string stA = top ? label.style_label_down : label.style_label_up
        float pad = (top ? 1 : -1) * 0.06 * H
        int nxA = p.pb.get(1)
        f_ln(nxA, f_line(p.nx1, p.ny1, p.nx2, p.ny2, nxA), xb, f_line(p.nx1, p.ny1, p.nx2, p.ny2, xb), cPat, lw, line.style_solid)
        if shMarks
            int xm = int(math.round((nxA + xb) / 2))
            f_lbl(xm, f_line(p.nx1, p.ny1, p.nx2, p.ny2, xm), f_t("neckline", "خط العنق"), top ? label.style_label_up : label.style_label_down, tc, szTxt)
            for i = 1 to n - 1 by 2
                f_lbl(p.pb.get(i), p.pp.get(i), "◯", label.style_label_center, cPat, szCirc)
                int k = int((i - 1) / 2)
                string txt = switch p.typ
                    T_DT => k == 0 ? f_t("one top...", "قمة أولى...") : f_t("two tops!", "قمتان!")
                    T_TT => k == 0 ? f_t("one top...", "قمة أولى...") : k == 1 ? f_t("two tops!", "قمتان!") : f_t("three tops!", "ثلاث قمم!")
                    T_DB => k == 0 ? f_t("first bottom", "القاع الأول") : f_t("second bottom", "القاع الثاني")
                    T_TB => k == 0 ? f_t("first bottom", "القاع الأول") : k == 1 ? f_t("second bottom", "القاع الثاني") : f_t("third bottom", "القاع الثالث")
                    => k == 1 ? f_t("head", "الرأس") : f_t("shoulder", "الكتف")
                f_lbl(p.pb.get(i), p.pp.get(i) + pad, txt, stA, tc, szTxt)
    else
        bool tri = p.typ == T_SYM or p.typ == T_ASC or p.typ == T_DESC or p.typ == T_BPEN or p.typ == T_SPEN
        int xEnd = tri and not na(p.apex) and p.apex - xb <= 2 * (p.lastBar - p.start) ? math.max(xb, int(math.round(p.apex))) : xb
        if p.typ == T_RECT
            float u0 = f_line(p.ux1, p.uy1, p.ux2, p.uy2, p.start)
            float d0 = f_line(p.dx1, p.dy1, p.dx2, p.dy2, p.start)
            float u1 = f_line(p.ux1, p.uy1, p.ux2, p.uy2, xb)
            float d1 = f_line(p.dx1, p.dy1, p.dx2, p.dy2, xb)
            f_ln(p.start, u0, xb, u1, cPat, lw, line.style_solid)
            f_ln(p.start, d0, xb, d1, cPat, lw, line.style_solid)
            f_ln(p.start, u0, p.start, d0, cPat, lw, line.style_solid)
            f_ln(xb, u1, xb, d1, cPat, lw, line.style_solid)
        else
            f_ln(p.ux1, p.uy1, xEnd, f_line(p.ux1, p.uy1, p.ux2, p.uy2, xEnd), cPat, lw, line.style_solid)
            f_ln(p.dx1, p.dy1, xEnd, f_line(p.dx1, p.dy1, p.dx2, p.dy2, xEnd), cPat, lw, line.style_solid)
        if shMarks
            string tU = switch p.typ
                T_RW   => f_t("higher highs", "قمم أعلى")
                T_FW   => f_t("lower highs", "قمم أدنى")
                T_SYM  => f_t("lower highs...", "قمم أدنى...")
                T_ASC  => f_t("resistance", "مقاومة")
                T_DESC => f_t("lower highs", "قمم أدنى")
                => ""
            string tD = switch p.typ
                T_RW   => f_t("...even higher lows!", "...وقيعان أعلى!")
                T_FW   => f_t("lower lows", "قيعان أدنى")
                T_SYM  => f_t("higher lows...", "قيعان أعلى...")
                T_ASC  => f_t("higher lows", "قيعان أعلى")
                T_DESC => f_t("support", "دعم")
                => ""
            int xm = int(math.round((p.start + p.lastBar) / 2))
            if p.typ == T_RECT
                // opposite side to the pattern name
                if dir < 0
                    f_lbl(xm, f_line(p.dx1, p.dy1, p.dx2, p.dy2, xm), f_t("stuck in a box", "عالق في صندوق"), label.style_label_up, tc, szTxt)
                else
                    f_lbl(xm, f_line(p.ux1, p.uy1, p.ux2, p.uy2, xm), f_t("stuck in a box", "عالق في صندوق"), label.style_label_down, tc, szTxt)
            if tU != ""
                f_lbl(xm, f_line(p.ux1, p.uy1, p.ux2, p.uy2, xm), tU, label.style_label_down, tc, szTxt)
            if tD != ""
                f_lbl(xm, f_line(p.dx1, p.dy1, p.dx2, p.dy2, xm), tD, label.style_label_up, tc, szTxt)
    // caption of the expected move, beside the breakout on the empty side
    if shMarks
        f_lbl(xb - 2, entry + (tp - entry) * 0.6, f_caption(p.typ, dir), label.style_label_right, tc, szTxt)
    if shName
        float yN = dir < 0 ? p.hhi + 0.12 * H : p.llo - 0.12 * H
        f_lbl(int(math.round((p.start + p.lastBar) / 2)), yN, f_t(f_name(p.typ), f_name_ar(p.typ)), dir < 0 ? label.style_label_down : label.style_label_up, cPat, szBig)
    // cheat-sheet levels
    if shLvls
        f_ln(xb, entry, xb + lvlLen, entry, cTP, 1, line.style_dashed)
        f_ln(xb, sl, xb + lvlLen, sl, cSL, 1, line.style_dashed)
        f_ln(xb, tp, xb + lvlLen, tp, cTP, 1, line.style_dashed)
        f_lbl(xb + lvlLen, entry, f_lvl("ENTRY", "دخول", entry), label.style_label_left, cTP, szTxt)
        f_lbl(xb + lvlLen, sl, f_lvl("SL", "وقف", sl), label.style_label_left, cSL, szTxt)
        f_lbl(xb + lvlLen, tp, f_lvl("TP", "هدف", tp), label.style_label_left, cTP, szTxt)
    cntL.push(gLines.size() - l0)
    cntX.push(gLabels.size() - x0)
    // keep only the newest patterns
    while cntL.size() > maxShow
        int cl = cntL.shift()
        int cx = cntX.shift()
        if cl > 0
            for i = 1 to cl
                gLines.shift().delete()
        if cx > 0
            for i = 1 to cx
                gLabels.shift().delete()
 
f_fire(Pat p, int t, int xb, int dir, float entry) =>
    int g = p.grp - 1
    lastEnd.set(g, p.lastBar)
    bool dup = false
    if p.typ == T_RECT
        Pat q = dir == -1 ? pend.get(0) : pend.get(1)
        if not na(q)
            if q.start >= p.start
                dup := true
    if p.grp == 3
        for k = 0 to 1
            if not na(recT.get(k))
                if recDir.get(k) == dir and t - recT.get(k) <= L and p.start <= recStart.get(k)
                    dup := true
    else
        if not na(recT.get(2))
            if recDir.get(2) == dir and t - recT.get(2) <= L and recStart.get(2) <= p.start
                dup := true
    if not dup
        recT.set(g, t)
        recDir.set(g, dir)
        recStart.set(g, p.start)
        float tp = na
        float sl = na
        if p.grp == 1
            tp := entry - p.height
            sl := p.typ == T_HS ? (p.shAvg + entry) / 2 : (p.inv + entry) / 2
        else if p.grp == 2
            tp := entry + p.height
            sl := p.typ == T_IHS ? (p.shAvg + entry) / 2 : (p.inv + entry) / 2
        else
            tp := entry + dir * p.height
            if p.typ == T_RECT
                sl := (f_line(p.ux1, p.uy1, p.ux2, p.uy2, xb) + f_line(p.dx1, p.dy1, p.dx2, p.dy2, xb)) / 2
            else
                sl := dir == 1 ? p.lastLow : p.lastHigh
        oCode.set(g, p.typ * dir)
        oEntry.set(g, entry)
        oSL.set(g, sl)
        oTP.set(g, tp)
        oXb.set(g, t - xb)
        oStart.set(g, t - p.start)
        oCnt.set(0, oCnt.get(0) + 1)
        f_draw(p, xb, dir, entry, sl, tp)
        alert(syminfo.ticker + " " + f_name(p.typ) + " · " + f_name_ar(p.typ) + (dir > 0 ? " breakout up" : " breakdown") + " | Entry " + str.tostring(entry, format.mintick) + " SL " + str.tostring(sl, format.mintick) + " TP " + str.tostring(tp, format.mintick), alert.freq_once_per_bar_close)
 
// ───────────────────────── Engine (one bar) ─────────────────────────
// runs on closed bars only: a breakout needs a candle close, so nothing appears or fires intrabar
if barstate.isconfirmed
    // 1) pending patterns on this bar
    for g = 0 to 2
        Pat p = pend.get(g)
        if not na(p)
            [res, dir, entry] = f_step(p, bar_index, close)
            if res == -1
                pend.set(g, na)
            else if res == 1
                f_fire(p, bar_index, bar_index, dir, entry)
                pend.set(g, na)
 
    // 2) swings
    bool changed = false
    if bar_index >= 2 * L
        bool ph = true
        bool pl = true
        for k = 1 to L
            if not (high[L] > high[L + k]) or not (high[L] >= high[L - k])
                ph := false
            if not (low[L] < low[L + k]) or not (low[L] <= low[L - k])
                pl := false
        int pB = bar_index - L
        if ph
            int n = sb.size()
            if n == 0
                sb.push(pB)
                sp.push(high[L])
                st.push(1)
                changed := true
            else if st.last() == 1
                if high[L] > sp.last()
                    sb.set(n - 1, pB)
                    sp.set(n - 1, high[L])
                    changed := true
            else if high[L] > sp.last()
                sb.push(pB)
                sp.push(high[L])
                st.push(1)
                changed := true
        if pl
            int n = sb.size()
            if n == 0
                sb.push(pB)
                sp.push(low[L])
                st.push(-1)
                changed := true
            else if st.last() == -1
                if low[L] < sp.last()
                    sb.set(n - 1, pB)
                    sp.set(n - 1, low[L])
                    changed := true
            else if low[L] < sp.last()
                sb.push(pB)
                sp.push(low[L])
                st.push(-1)
                changed := true
        while sb.size() > 12
            sb.shift()
            sp.shift()
            st.shift()
 
    // 3) evaluate groups and scan the bars since the last swing
    if changed
        int lastT = st.last()
        int gA = lastT == 1 ? 0 : 1
        if lastT == 1
            pend.set(0, f_tops(atrv, lastEnd.get(0)))
        else
            pend.set(1, f_bottoms(atrv, lastEnd.get(1)))
        pend.set(2, f_shapes(atrv, lastEnd.get(2)))
        Pat s3 = pend.get(2)
        if not na(s3)
            if s3.typ != T_RECT
                Pat q1 = pend.get(0)
                Pat q2 = pend.get(1)
                if not na(q1)
                    if s3.only != 1 and s3.start <= q1.start
                        pend.set(0, na)
                if not na(q2)
                    if s3.only != -1 and s3.start <= q2.start
                        pend.set(1, na)
        for j = 0 to 1
            int g = j == 0 ? gA : 2
            Pat p = pend.get(g)
            if not na(p)
                for x = p.lastBar + 1 to bar_index
                    [res, dir, entry] = f_step(p, x, close[bar_index - x])
                    if res == -1
                        pend.set(g, na)
                        break
                    if res == 1
                        f_fire(p, bar_index, x, dir, entry)
                        pend.set(g, na)
                        break
 
// ───────────────────────── Forming patterns (last bar) ─────────────────────────
var array<line>  fLines = array.new<line>()
var array<label> fLabels = array.new<label>()
if barstate.islast and shForm
    while fLines.size() > 0
        fLines.pop().delete()
    while fLabels.size() > 0
        fLabels.pop().delete()
    for g = 0 to 2
        Pat p = pend.get(g)
        if not na(p)
            int xr = bar_index + 5
            if p.grp != 3
                int xa = p.pb.get(1)
                fLines.push(line.new(xa, f_line(p.nx1, p.ny1, p.nx2, p.ny2, xa), xr, f_line(p.nx1, p.ny1, p.nx2, p.ny2, xr), color = cForm, width = 1, style = line.style_dashed))
                fLabels.push(label.new(xr, f_line(p.nx1, p.ny1, p.nx2, p.ny2, xr), f_t("forming: " + f_name(p.typ), "قيد التكوّن: " + f_name_ar(p.typ)), style = label.style_label_left, color = #00000000, textcolor = cForm, size = size.small))
            else
                fLines.push(line.new(p.ux1, p.uy1, xr, f_line(p.ux1, p.uy1, p.ux2, p.uy2, xr), color = cForm, width = 1, style = line.style_dashed))
                fLines.push(line.new(p.dx1, p.dy1, xr, f_line(p.dx1, p.dy1, p.dx2, p.dy2, xr), color = cForm, width = 1, style = line.style_dashed))
                fLabels.push(label.new(xr, f_line(p.ux1, p.uy1, p.ux2, p.uy2, xr), f_t("forming: " + f_name(p.typ), "قيد التكوّن: " + f_name_ar(p.typ)), style = label.style_label_left, color = #00000000, textcolor = cForm, size = size.small))
 
// ───────────────────────── Alerts & data ─────────────────────────
bool anyBull = false
bool anyBear = false
for g = 0 to 2
    float c = oCode.get(g)
    if not na(c)
        anyBull := anyBull or c > 0
        anyBear := anyBear or c < 0
alertcondition(anyBull, "Bullish pattern breakout · كسر صاعد", "Bullish chart-pattern breakout on {{ticker}}")
alertcondition(anyBear, "Bearish pattern breakdown · كسر هابط", "Bearish chart-pattern breakdown on {{ticker}}")
 
plot(oCode.get(0), "e1code", display = display.none)
plot(oEntry.get(0), "e1entry", display = display.none)
plot(oSL.get(0), "e1sl", display = display.none)
plot(oTP.get(0), "e1tp", display = display.none)
plot(oXb.get(0), "e1xb", display = display.none)
plot(oStart.get(0), "e1start", display = display.none)
plot(oCode.get(1), "e2code", display = display.none)
plot(oEntry.get(1), "e2entry", display = display.none)
plot(oSL.get(1), "e2sl", display = display.none)
plot(oTP.get(1), "e2tp", display = display.none)
plot(oXb.get(1), "e2xb", display = display.none)
plot(oStart.get(1), "e2start", display = display.none)
plot(oCode.get(2), "e3code", display = display.none)
plot(oEntry.get(2), "e3entry", display = display.none)
plot(oSL.get(2), "e3sl", display = display.none)
plot(oTP.get(2), "e3tp", display = display.none)
plot(oXb.get(2), "e3xb", display = display.none)
plot(oStart.get(2), "e3start", display = display.none)
plot(bar_index, "barIndex", display = display.none)
plot(oCnt.get(0), "eCount", display = display.none)

← 返回列表