Edo Candle Context

EdoLab-Markets · study · 812 行 · 点赞 27 · TradingView 原页

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

Pine Script

// ─────────────────────────────────────────────────────────────────
// ███████╗██████╗  ██████╗ ██╗      █████╗ ██████╗
// ██╔════╝██╔══██╗██╔═══██╗██║     ██╔══██╗██╔══██╗
// █████╗  ██║  ██║██║   ██║██║     ███████║██████╔╝
// ██╔══╝  ██║  ██║██║   ██║██║     ██╔══██║██╔══██╗
// ███████╗██████╔╝╚██████╔╝███████╗██║  ██║██████╔╝
// ╚══════╝╚═════╝  ╚═════╝ ╚══════╝╚═╝  ╚═╝╚═════╝
// ─────────────────────────────────────────────────────────────────
// ███╗   ███╗ █████╗ ██████╗ ██╗  ██╗███████╗████████╗███████╗
// ████╗ ████║██╔══██╗██╔══██╗██║ ██╔╝██╔════╝╚══██╔══╝██╔════╝
// ██╔████╔██║███████║██████╔╝█████╔╝ █████╗     ██║   ███████╗
// ██║╚██╔╝██║██╔══██║██╔══██╗██╔═██╗ ██╔══╝     ██║   ╚════██║
// ██║ ╚═╝ ██║██║  ██║██║  ██║██║  ██╗███████╗   ██║   ███████║
// ╚═╝     ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝   ╚═╝   ╚══════╝
// ─────────────────────────────────────────────────────────────────
// © Edolab Markets
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0.
 
//@version=6
indicator("Edo Candle Context", overlay = true, max_labels_count = 500, max_lines_count = 300)
 
// What changes when a new bar arrives (read before judging the drawing):
// 1. Patterns are read only on the CLOSE of a candle. A label never appears on the live candle and never moves
//    or disappears afterwards. Its score, its context and the hit rate printed on it are frozen at that close.
// 2. Life of a pattern = an event. After the label it is "Pending" for up to Hit Window bars. It is CONFIRMED when a
//    candle closes beyond the pattern in its direction (above the signal candle high for a bullish one, below its low
//    for a bearish one) and INVALIDATED when a candle closes beyond the other end of the whole pattern first. If
//    neither happens in time it is "Expired". Only the label text and tint of that earlier candle change, once, on
//    the close that decides it. Dojis have no direction and are not tracked.
// 3. HIT RATE (closed definition): hit = Confirmed. Rate = Confirmed / (Confirmed + Invalidated + Expired) over the
//    events already decided at that close of the symbol and timeframe you are looking at, with n shown next to it.
//    Pending events are not counted. It is measured with closed bars only, so it never repaints, but it depends on
//    the history loaded in the chart (more bars, more n). It is statistics of this chart, not a promise.
// 4. Score 0-100 = candle size in ATR (25) + close strength in the pattern direction (20) + closeness to the level
//    or extension that gave the context (30) + relative volume against its 20-bar average (25; a neutral 12 when the
//    symbol has no volume). Only one pattern per candle: the one with more candles wins, then the more specific.
// 5. The right-edge level labels and the panel corner follow the visible part of the chart, so they can change when
//    you scroll or zoom. The patterns, the statistics and the alerts do not.
 
// ================== CONSTANTS ==================
 
const float SIDE_SHARE = 0.35  // part of the visible chart, at each side, that a panel can cover
const float LOGO_PCT   = 9.0   // bottom-left: empty row under the panel so the TradingView logo does not cover its last row
const float ICON_PCT   = 6.0   // bottom-right: the same for the round TradingView button in that corner
const float LEGEND_PCT = 10.0  // top-left: empty row above the panel so the TradingView legend does not cover it
const float ROW_SHARE  = 0.035 // height of one panel row as a share of the visible price span (Medium); Small = 0.028
const int   MAX_BODY   = 7     // body rows in Full; with title, footer and one spacer the table never passes 10 rows
const int   MAX_BODY_C = 4     // body rows in Compact
const int   ZOOM_BARS  = 250   // above this many visible candles the labels on screen shrink to their score
const int   STACK_BARS = 6     // labels closer than this many bars on the same side are stacked vertically
 
gPat = "Patterns"
gCtx = "Context"
gSco = "Score and Statistics"
gDsp = "Display"
gSty = "Style"
gPan = "Panel"
 
// ================== SETTINGS - PATTERNS ==================
 
usEngulf   = input.bool(true,  "Engulfing",       inline = "p1", group = gPat, tooltip = "Two-candle reversal: the second body swallows the first one. On by default: the most classic reversal.")
usHarami   = input.bool(true,  "Harami",          inline = "p1", group = gPat, tooltip = "Two-candle reversals. Harami Cross when the second candle is a doji.")
usPierce   = input.bool(true,  "Piercing / Dark Cloud", inline = "p1", group = gPat, tooltip = "Two-candle reversal that closes beyond the middle of the previous body without swallowing it.")
usTweezer  = input.bool(true,  "Tweezer",         inline = "p1", group = gPat, tooltip = "Tweezer Bottom / Top: two candles with matching lows / highs (0.1 ATR tolerance) and opposite colour.")
usPin      = input.bool(true,  "Pin Bars",        inline = "p2", group = gPat, tooltip = "Hammer and Inverted Hammer after a decline; Hanging Man and Shooting Star after a rise. Same candle shape, opposite leg.")
usDoji     = input.bool(true,  "Doji",            inline = "p2", group = gPat, tooltip = "Doji, Dragonfly, Gravestone and Long-legged. Neutral: only shown right on a swing level.")
usMaru     = input.bool(true,  "Marubozu",        inline = "p2", group = gPat, tooltip = "Full-body candle with no wicks: a strength candle. Shown as a continuation at a level or extension, no reversal gate.")
usStar     = input.bool(true,  "Morning / Evening Star", inline = "p3", group = gPat, tooltip = "Three-candle reversals; the doji versions get their own label.")
usThree    = input.bool(true,  "Soldiers / Crows", inline = "p3", group = gPat, tooltip = "Three White Soldiers / Three Black Crows: continuation, no reversal gate.")
usThreeIn  = input.bool(true,  "Three Inside",    inline = "p3", group = gPat, tooltip = "Three Inside Up / Down: a harami confirmed by the third candle.")
usInside   = input.bool(true,  "Inside Bar Breakout", inline = "p3", group = gPat, tooltip = "A candle fully inside the previous range, in context, confirmed only when a later close breaks the mother bar high (bullish) or low (bearish).")
bodyLen    = input.int(14,  "Average Body Length",         minval = 5,   maxval = 50,  group = gPat, tooltip = "EMA of the candle body used to decide what a long body is (default 14).")
wickMult   = input.float(2.0, "Pin Wick / Body Ratio",    minval = 1.0, maxval = 5.0, step = 0.5, group = gPat, tooltip = "The long wick of a pin bar must be at least this many times the body (default 2).")
dojiPct    = input.float(5.0, "Doji Body % of Range",     minval = 1.0, maxval = 20.0, step = 1.0, group = gPat, tooltip = "A candle is a doji when its body is at most this percentage of its full range (default 5).")
maruMult   = input.float(1.5, "Marubozu Body x Average",  minval = 1.0, maxval = 4.0, step = 0.5, group = gPat, tooltip = "A marubozu body must be at least this many times the average body, with wicks under 5 % of the range (default 1.5).")
insideWait = input.int(5,   "Inside Bar Breakout Window", minval = 1,   maxval = 20,  group = gPat, tooltip = "Bars allowed for the breakout of the mother bar before the inside bar expires.")
 
// ================== SETTINGS - CONTEXT ==================
 
useCtx     = input.bool(true, "Require Context",           group = gCtx, tooltip = "On (default): a pattern is labelled only when it reacts to a swing level, the last swing or an extension from the EMA 20. Off: every detected pattern is labelled, classic scanner mode.")
cooldown   = input.int(3,   "Signal Silence (bars)",      minval = 0,  maxval = 50,   group = gCtx, tooltip = "Minimum bars between two labels, whatever the direction. After any pattern is shown the chart stays quiet for this many bars. Lower it for more labels, raise it for a cleaner chart; 0 shows every pattern that passes the filters (default 3).")
pivotLen   = input.int(10,  "Pivot Length",               minval = 3,  maxval = 50,   group = gCtx, tooltip = "Bars on each side needed to confirm a swing high / low. Confirmed swings become the levels a pattern must react to.")
lvlLife    = input.int(300, "Level Lifetime (bars)",      minval = 50, maxval = 2000, group = gCtx, tooltip = "A swing level is forgotten once it has not been touched for this many bars.")
minTouch   = input.int(2,   "Min Level Touches",          minval = 1,  maxval = 5,    group = gCtx, tooltip = "A clustered level counts as context once this many confirmed swings have built it. The most recent swing high and swing low always count, whatever their touches.")
ctxMult    = input.float(0.5, "Max Distance to Level (x ATR)", minval = 0.1, maxval = 3.0, step = 0.1, group = gCtx, tooltip = "The pattern extreme (low for bullish, high for bearish) must be within this many ATR(14) of a level, or overlap it.")
useExt     = input.bool(true, "Accept Extension as Context", group = gCtx, tooltip = "Also accept a pattern when price is stretched far from its 20 EMA, even without a level nearby.")
extMult    = input.float(2.0, "Extension (x ATR from EMA 20)", minval = 0.5, maxval = 5.0, step = 0.5, group = gCtx, tooltip = "How many ATR(14) the close must be away from the EMA 20 to count as an extension (default 2).")
trendLen   = input.int(5,   "Trend Lookback (bars)",      minval = 2,  maxval = 30,   group = gCtx, tooltip = "A bullish reversal must come from a decline over this many bars before the pattern started (close vs close N bars earlier); bearish the opposite. Continuation patterns, dojis and inside bars skip this check.")
showUnfilt = input.bool(false, "Show Unfiltered Patterns", group = gCtx, tooltip = "Draws the patterns that failed the context or score filter as faded dots, to see what was discarded. Off by default to keep the chart clean.")
 
// ================== SETTINGS - SCORE AND STATISTICS ==================
 
minScore   = input.int(30, "Min Pattern Score", minval = 0, maxval = 100, group = gSco, tooltip = "Patterns scoring below this value are discarded like the ones that fail the context. 0 shows everything that passes the context (default 30: drops tiny, weak-close patterns with no volume).")
confirmBars = input.int(5, "Hit Window (bars)", minval = 1, maxval = 20, group = gSco, tooltip = "Bars a pattern has to be CONFIRMED (a close beyond it in its direction) before it expires. It is the definition of a hit in the hit rate, so changing it changes the statistics (default 5).")
alertScore = input.int(70, "High Score Alert Level", minval = 1, maxval = 100, group = gSco, tooltip = "The High score pattern alert fires only for patterns scoring at least this value (default 70).")
 
// ================== SETTINGS - DISPLAY ==================
 
maxLbls    = input.int(100, "Max Labels", minval = 10, maxval = 400, group = gDsp, tooltip = "Pattern labels, level links and dots kept on the chart; the oldest are deleted beyond this number. Keeps a far zoom readable and fast (default 100).")
showLevels = input.bool(true, "Show Right-Edge Labels", group = gDsp, tooltip = "Labels at the right edge with the last swing high and swing low, the levels a pattern reacts to, and their distance from the close.")
extR       = input.int(10, "Projection (bars)", minval = 0, maxval = 50, group = gDsp, tooltip = "Length of the level lines to the right of the last candle. The labels end where the lines end and grow to the left, so nothing passes the right edge.")
labelSep   = input.float(1.0, "Label Spacing (ATR)", minval = 0.2, maxval = 5.0, step = 0.1, group = gDsp, tooltip = "Minimum vertical gap between the right-edge labels, in 14-bar ATR. It also grows when the chart is zoomed out, so the labels never overlap. A label moved off its line is joined to it by a dotted connector.")
labelSize  = input.string("Medium", "Label Size", options = ["Small", "Medium", "Large"], group = gDsp, tooltip = "Text size of the pattern labels and of the right-edge labels.")
showLevel  = input.bool(false, "Draw Level Link", group = gDsp, tooltip = "Optional, off by default: dashed line from the swing level to the candle that reacted to it, to show why the pattern was kept. The context is already in the label tooltip and in the panel.")
paintBar   = input.bool(true, "Highlight Pattern Candle", group = gDsp, tooltip = "Paints the candle of a labelled pattern with the pattern colour.")
 
// ================== SETTINGS - STYLE ==================
 
bullCol    = input.color(#26a69a, "Bullish", inline = "c1", group = gSty)
bearCol    = input.color(#ef5350, "Bearish", inline = "c1", group = gSty)
neutCol    = input.color(#6e7280, "Neutral", inline = "c1", group = gSty)
 
// ================== SETTINGS - PANEL ==================
 
showPanel    = input.bool(true, "Show Panel", group = gPan, tooltip = "Small table with the last pattern, its score and life, and the hit rate of the symbol.")
panelDetail  = input.string("Full", "Panel Detail", options = ["Full", "Compact"], group = gPan, tooltip = "Compact keeps only the last pattern, its score, its status and the hit rate.")
panelPos     = input.string("Top Right", "Panel Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = gPan, tooltip = "Preferred corner. With Keep Panel Off the Drawing on, the panel moves when this corner would cover the latest candles or the labels.")
panelAvoid   = input.bool(true, "Keep Panel Off the Drawing", group = gPan, tooltip = "The panel stays in the corner chosen while it has room; otherwise it moves to the other corner of the same side, then to the other side (left corners cover the oldest candles). Off = the panel never moves.")
panelSize    = input.string("Medium", "Panel Size", options = ["Small", "Medium"], group = gPan, tooltip = "Text size of the panel.")
themeMode    = input.string("Dark", "Theme Mode", options = ["Dark", "Light"], group = gPan, tooltip = "Match your TradingView background theme.")
panelOpacity = input.int(70, "Panel Opacity (%)", minval = 0, maxval = 100, group = gPan, tooltip = "100 = solid background, 0 = transparent.")
 
// ================== THEME ==================
 
isDark      = themeMode == "Dark"
textCol     = isDark ? #ffffff : #131722
headerBg    = isDark ? #2a2e39 : #d1d4dc
subHeaderBg = isDark ? #363a45 : #e0e3eb
cellBg      = isDark ? #1e222d : #f0f3fa
cellTxt     = isDark ? #d1d4dc : #363a45
numTxt      = isDark ? #b2b5be : #555a67
panelTransp = 100 - panelOpacity
lblTr       = isDark ? 10 : 0    // drawings are stronger on a light chart
lnTr        = isDark ? 30 : 5
 
lblSz = labelSize == "Small" ? size.small : labelSize == "Large" ? size.large : size.normal
panSz = panelSize == "Small" ? size.tiny : size.small
 
// ================== TYPES ==================
 
// A swing level built from confirmed pivots (highs and lows share the same pool)
type Level
    float price
    int   touches
    int   lastBar
 
var levels = array.new<Level>()
 
// Mutable state shared with the drawing helpers (Pine functions cannot assign globals, but can edit object fields)
type State
    string lastName
    string lastCtx
    int    lastBar
    int    lastDir
    int    shown
    int    filtered
    float  motherHigh
    float  motherLow
    int    motherBar
    float  motherLvl
    int    motherLvlBar
    string motherCtx
    int    lastScore
    string lastStatus
    int    hits
    int    total
    int    lastBelowBar
    int    belowLvl
    int    lastAboveBar
    int    aboveLvl
 
var S = State.new("—", "—", na, 0, 0, 0, na, na, na, na, na, "", 0, "-", 0, 0, na, 0, na, 0)
 
// The single pattern candidate chosen for this bar.
// tier: candles in the pattern (3 > 2 > 1). kind: 0 = reversal, 1 = continuation, 2 = doji (level only).
// grp: alert group — 1 engulfing, 2 harami, 3 star, 4 pin bar, 5 three-candle, 6 inside bar, 7 marubozu, 8 doji, 9 piercing / dark cloud, 10 tweezer
type Cand
    string name
    int    dir
    int    tier
    int    kind
    int    grp
 
// A labelled pattern waiting for its outcome (life as an event). trig = close beyond it confirms, inval = close beyond it invalidates
type Ev
    label  lbl
    string txt
    int    dir
    int    grp
    int    born
    float  trig
    float  inval
    color  col
 
var events = array.new<Ev>()
 
// Closed hit-rate statistics per pattern family (index = grp)
var grpHit = array.new<int>(11, 0)
var grpTot = array.new<int>(11, 0)
 
// Drawings kept on the chart, capped by Max Labels
var lblArr = array.new<label>()
var lnArr  = array.new<line>()
var dotArr = array.new<label>()
 
// Most recent confirmed swings: always valid context, even with a single touch
var float lastSwingHi = na
var float lastSwingLo = na
var int   lastSwingHiBar = na
var int   lastSwingLoBar = na
 
// ================== CALCULATIONS ==================
 
atrRef   = ta.atr(14)
ema20    = ta.ema(close, 20)
body     = math.abs(close - open)
rng      = high - low
bodyAvg  = ta.ema(body, bodyLen)
bodyHi   = math.max(open, close)
bodyLo   = math.min(open, close)
upWick   = high - bodyHi
dnWick   = bodyLo - low
lvlTol   = atrRef * 0.5
volAvg   = ta.sma(volume, 20)
volRel   = volume > 0 and volAvg > 0 ? volume / volAvg : na
 
bull     = close > open
bear     = close < open
longBody = body > bodyAvg
isDoji   = rng > 0 and body <= rng * dojiPct / 100
bigDoji  = isDoji and rng >= atrRef * 0.5   // a doji only matters when the candle itself has some range
 
ph = ta.pivothigh(pivotLen, pivotLen)
pl = ta.pivotlow(pivotLen, pivotLen)
 
// ================== HELPERS ==================
 
fmt(float v) => na(v) ? "-" : str.tostring(v, format.mintick)
 
plural(int n, string one, string many) => str.tostring(n) + " " + (n == 1 ? one : many)
 
agoTxt(int b) => b == bar_index ? "this bar" : plural(bar_index - b, "bar", "bars") + " ago"
 
pctShort(float lvl) =>
    float p = math.round((lvl - close) / close * 100, 1)
    (p > 0 ? "+" : p < 0 ? "-" : "") + str.tostring(math.abs(p), "0.0") + " %"
 
addRow(array<string> ks, array<string> vs, array<color> cs, string k, string v, color c) =>
    ks.push(k)
    vs.push(v)
    cs.push(c)
 
panelRow(table t, int r, string k, string v, color vc, color bg) =>
    table.cell(t, 0, r, k, text_color = cellTxt, bgcolor = bg, text_size = panSz, text_halign = text.align_left)
    table.cell(t, 1, r, v, text_color = vc, bgcolor = bg, text_size = panSz, text_halign = text.align_left)
 
dirColor(int dir) =>
    dir > 0 ? bullCol : dir < 0 ? bearCol : neutCol
 
// Text colour that reads on a given label background
txtOn(color c) =>
    (color.r(c) * 0.299 + color.g(c) * 0.587 + color.b(c) * 0.114) > 160 ? #131722 : #ffffff
 
rateText(int h, int t) =>
    t > 0 ? str.tostring(h * 100.0 / t, "#") + "% (n=" + str.tostring(t) + ")" : "no events yet (n=0)"
 
// ================== LEVELS (confirmed pivots, clustered) ==================
 
addLevel(float price) =>
    int found = -1
    float bestDist = na
    if levels.size() > 0
        for i = 0 to levels.size() - 1
            d = math.abs(levels.get(i).price - price)
            if d <= lvlTol and (na(bestDist) or d < bestDist)
                bestDist := d
                found    := i
    if found >= 0
        lv = levels.get(found)
        lv.price   := (lv.price * lv.touches + price) / (lv.touches + 1)
        lv.touches := lv.touches + 1
        lv.lastBar := bar_index - pivotLen
    else
        levels.push(Level.new(price, 1, bar_index - pivotLen))
    found >= 0
 
if not na(ph) and not na(atrRef)
    addLevel(ph)
    lastSwingHi    := ph
    lastSwingHiBar := bar_index - pivotLen
if not na(pl) and not na(atrRef)
    addLevel(pl)
    lastSwingLo    := pl
    lastSwingLoBar := bar_index - pivotLen
 
// Retire levels price has ignored for too long, and cap the pool. Runs only when a pivot is confirmed (a level older than its lifetime is also skipped when read)
if (not na(ph) or not na(pl)) and levels.size() > 0
    for i = levels.size() - 1 to 0
        if bar_index - levels.get(i).lastBar > lvlLife
            levels.remove(i)
while levels.size() > 40
    levels.remove(0)
 
// Nearest level to a price within the context distance; returns [price, touches, lastBar] or na
nearestLevel(float ref, float lo, float hi) =>
    float bestPrice = na
    int   bestTouch = 0
    int   bestBar   = na
    float bestDist  = na
    if levels.size() > 0
        for i = 0 to levels.size() - 1
            lv = levels.get(i)
            inside = lv.price >= lo and lv.price <= hi
            d = inside ? 0.0 : math.abs(ref - lv.price)
            if lv.touches >= minTouch and bar_index - lv.lastBar <= lvlLife and d <= atrRef * ctxMult and (na(bestDist) or d < bestDist)
                bestDist  := d
                bestPrice := lv.price
                bestTouch := lv.touches
                bestBar   := lv.lastBar
    [bestPrice, bestTouch, bestBar]
 
// Is the reacting extreme within context distance of the most recent swing (or does the range overlap it)?
nearSwing(float ref, float lo, float hi, float sw) =>
    not na(sw) and (sw >= lo and sw <= hi or math.abs(ref - sw) <= atrRef * ctxMult)
 
// Context of a price range [lo, hi]: bullish side (levels / swing low under it) and bearish side (levels / swing high over it).
// Returns [bullCtx, bullTxt, bLvl, bBar, bearCtx, bearTxt, sLvl, sBar, anyLevel]
contextOf(float lo, float hi) =>
    [bLvl0, bTouch, bBar0] = nearestLevel(lo, lo, hi)
    [sLvl0, sTouch, sBar0] = nearestLevel(hi, lo, hi)
    float bLvl = bLvl0
    int   bBar = bBar0
    float sLvl = sLvl0
    int   sBar = sBar0
    extDown = useExt and (ema20 - close) >= atrRef * extMult
    extUp   = useExt and (close - ema20) >= atrRef * extMult
    swLo = na(bLvl) and nearSwing(lo, lo, hi, lastSwingLo)
    swHi = na(sLvl) and nearSwing(hi, lo, hi, lastSwingHi)
    if swLo
        bLvl := lastSwingLo
        bBar := lastSwingLoBar
    if swHi
        sLvl := lastSwingHi
        sBar := lastSwingHiBar
    bullCtx = not na(bLvl) or extDown
    bearCtx = not na(sLvl) or extUp
    bullTxt = swLo ? "Swing low " + fmt(bLvl) : not na(bLvl) ? "Level " + fmt(bLvl) + " · " + str.tostring(bTouch) + " touches" : extDown ? "Extended " + str.tostring((ema20 - close) / atrRef, "#.#") + " ATR below EMA 20" : ""
    bearTxt = swHi ? "Swing high " + fmt(sLvl) : not na(sLvl) ? "Level " + fmt(sLvl) + " · " + str.tostring(sTouch) + " touches" : extUp ? "Extended " + str.tostring((close - ema20) / atrRef, "#.#") + " ATR above EMA 20" : ""
    [bullCtx, bullTxt, bLvl, bBar, bearCtx, bearTxt, sLvl, sBar, not na(bLvl) or not na(sLvl)]
 
// ================== VISIBLE RANGE (display only: nothing in the patterns, the statistics or the alerts reads it) ==================
 
int   visL  = chart.left_visible_bar_time
int   visR  = chart.right_visible_bar_time
bool  inVis = not na(visL) and not na(visR) and time >= visL and time <= visR
float sideW = inVis ? (visR - visL) * SIDE_SHARE : na
bool  inRgt = inVis and time >= visR - sideW
bool  inLft = inVis and time <= visL + sideW
var int firstBarTime = time
float avgBarMs = last_bar_index > 0 ? (last_bar_time - firstBarTime) / last_bar_index : na
float visBars = not na(visL) and not na(visR) and not na(avgBarMs) and avgBarMs > 0 ? (visR - visL) / avgBarMs : na
// Far zoom: the labels on screen shrink to their score (the full text stays in the tooltip)
bool  zoomOut = inVis and not na(visBars) and visBars > ZOOM_BARS
float hiNow = high
float loNow = low
 
var float visHi = na
var float visLo = na
var float rgtHi = na
var float rgtLo = na
var float lftHi = na
var float lftLo = na
if inVis
    visHi := na(visHi) ? hiNow : math.max(visHi, hiNow)
    visLo := na(visLo) ? loNow : math.min(visLo, loNow)
if inRgt
    rgtHi := na(rgtHi) ? hiNow : math.max(rgtHi, hiNow)
    rgtLo := na(rgtLo) ? loNow : math.min(rgtLo, loNow)
if inLft
    lftHi := na(lftHi) ? hiNow : math.max(lftHi, hiNow)
    lftLo := na(lftLo) ? loNow : math.min(lftLo, loNow)
float visSpan = not na(visHi) and not na(visLo) ? visHi - visLo : na
// Approximate height of one label as a share of the visible price span (pane of about 600 px)
float lblH = not na(visSpan) and visSpan > 0 ? visSpan * (labelSize == "Small" ? 0.045 : labelSize == "Large" ? 0.08 : 0.06) : 0.0
 
// ================== SCORE, LABELS AND LIFE OF THE PATTERN ==================
 
// Score 0-100 of the pattern ending on this closed bar. Returns [total, size, close, level, volume] (parts out of 25, 20, 30, 25)
scoreOf(float loT, float hiT, int dir, float lvl, bool ctxExt) =>
    float pSize  = math.min((hiT - loT) / atrRef / 1.5, 1.0) * 25
    float cl     = rng > 0 ? (dir > 0 ? (close - low) / rng : dir < 0 ? (high - close) / rng : 0.5) : 0.5
    float pClose = cl * 20
    float pLvl   = ctxExt ? 15.0 : 0.0
    if not na(lvl)
        float d = lvl >= loT and lvl <= hiT ? 0.0 : math.min(math.abs(loT - lvl), math.abs(hiT - lvl))
        pLvl := (1.0 - math.min(d / (atrRef * ctxMult), 1.0)) * 30
    float pVol = na(volRel) ? 12.5 : math.min(volRel / 2.0, 1.0) * 25
    int iS = math.round(pSize)
    int iC = math.round(pClose)
    int iL = math.round(pLvl)
    int iV = math.round(pVol)
    [math.min(iS + iC + iL + iV, 100), iS, iC, iL, iV]
 
// Register a candidate: a pattern with more candles beats one with fewer; at equal size the first registered wins,
// so the calls below go from the most specific to the most generic inside each tier.
offer(Cand c, bool cond, string name, int dir, int tier, int kind, int grp) =>
    if cond and tier > c.tier
        c.name := name
        c.dir  := dir
        c.tier := tier
        c.kind := kind
        c.grp  := grp
    cond
 
// Decide the pending events on this closed bar. Returns [confirmed now, invalidated now]
resolveEvents(State s) =>
    int nConf = 0
    int nInv  = 0
    if events.size() > 0
        for i = events.size() - 1 to 0
            Ev e = events.get(i)
            string res = ""
            if e.dir > 0
                res := close > e.trig ? "Confirmed" : close < e.inval ? "Invalidated" : bar_index - e.born >= confirmBars ? "Expired" : ""
            else
                res := close < e.trig ? "Confirmed" : close > e.inval ? "Invalidated" : bar_index - e.born >= confirmBars ? "Expired" : ""
            if res != ""
                s.total := s.total + 1
                grpTot.set(e.grp, grpTot.get(e.grp) + 1)
                if res == "Confirmed"
                    s.hits := s.hits + 1
                    grpHit.set(e.grp, grpHit.get(e.grp) + 1)
                    nConf += 1
                else
                    label.set_color(e.lbl, color.new(e.col, 75))
                    label.set_textcolor(e.lbl, textCol)
                    if res == "Invalidated"
                        nInv += 1
                string stTxt = res + " in " + plural(bar_index - e.born, "bar", "bars")
                label.set_text(e.lbl, str.contains(e.txt, "\n") ? e.txt + "\n" + stTxt : e.txt)
                if e.born == s.lastBar
                    s.lastStatus := stTxt
                events.remove(i)
    [nConf, nInv]
 
drawPattern(State s, string name, int dir, string ctx, float lvlPrice, int lvlBar, int grp, int score, int pSz, int pCl, int pLv, int pVo, float loT, float hiT) =>
    // Labels closer than STACK_BARS on the same side climb one step each, so they never overlap
    bool below = dir >= 0
    int  lastB = below ? s.lastBelowBar : s.lastAboveBar
    int  lastL = below ? s.belowLvl : s.aboveLvl
    int  stk   = not na(lastB) and bar_index - lastB <= STACK_BARS ? (lastL + 1) % 3 : 0
    bool compact = zoomOut
    float step = atrRef * (compact ? 0.8 : 1.4)
    float y    = below ? low - atrRef * 0.15 - stk * step : high + atrRef * 0.15 + stk * step
    if below
        s.lastBelowBar := bar_index
        s.belowLvl     := stk
    else
        s.lastAboveBar := bar_index
        s.aboveLvl     := stk
    lst = below ? label.style_label_up : label.style_label_down
    col = dirColor(dir)
    string rateTxt = rateText(s.hits, s.total)
    string txt = compact ? str.tostring(score) : name + "\n" + str.tostring(score) + (dir != 0 ? " · " + rateTxt : "")
    string tip = ctx + "\nScore " + str.tostring(score) + " / 100 (size " + str.tostring(pSz) + "/25, close " + str.tostring(pCl) + "/20, level " + str.tostring(pLv) + "/30, volume " + str.tostring(pVo) + "/25)"
    if dir != 0
        int gT = grpTot.get(grp)
        tip += "\nHit rate of the symbol: " + rateTxt + "\nHit rate of this family: " + rateText(grpHit.get(grp), gT) + "\nHit = a close beyond the pattern in its direction within " + str.tostring(confirmBars) + " bars, before a close beyond its other end."
    else
        tip += "\nNeutral candle: no direction, so it has no hit or miss."
    label lb = label.new(bar_index, y, txt, style = lst, color = color.new(col, lblTr), textcolor = txtOn(col), size = compact ? size.tiny : lblSz, tooltip = tip)
    lblArr.push(lb)
    while lblArr.size() > maxLbls
        label.delete(lblArr.shift())
    if showLevel and not na(lvlPrice) and not na(lvlBar)
        lnArr.push(line.new(lvlBar, lvlPrice, bar_index, lvlPrice, color = color.new(col, lnTr), style = line.style_dashed, width = 1))
        while lnArr.size() > maxLbls
            line.delete(lnArr.shift())
    if dir != 0
        float evTrig  = dir > 0 ? high : low
        float evInval = dir > 0 ? loT : hiT
        events.push(Ev.new(lb, txt, dir, grp, bar_index, evTrig, evInval, col))
        while events.size() > 30
            events.shift()
    s.lastName   := name
    s.lastCtx    := ctx
    s.lastBar    := bar_index
    s.lastDir    := dir
    s.lastScore  := score
    s.lastStatus := dir != 0 ? "Pending" : "Neutral, not tracked"
    s.shown      := s.shown + 1
 
drawUnfiltered(State s, int dir) =>
    if showUnfilt
        y  = dir >= 0 ? low : high
        lst = dir >= 0 ? label.style_label_up : label.style_label_down
        dotArr.push(label.new(bar_index, y, "·", style = lst, color = color.new(dirColor(dir), 85), textcolor = color.new(textCol, 60), size = size.tiny))
        while dotArr.size() > maxLbls
            label.delete(dotArr.shift())
    s.filtered := s.filtered + 1
 
// ================== PATTERN DETECTION (closed bars only) ==================
 
anyBull   = false
anyBear   = false
dojiSig   = false
engulfSig = false
haramiSig = false
starSig   = false
pinSig    = false
threeSig  = false
insideSig = false
maruSig   = false
pierceSig = false
tweezSig  = false
hiScoreSig = false
evConfirmed = false
evInvalid   = false
 
if barstate.isconfirmed
    [nConf, nInv] = resolveEvents(S)
    evConfirmed := nConf > 0
    evInvalid   := nInv > 0
 
if barstate.isconfirmed and not na(atrRef) and not na(bodyAvg) and rng > 0 and bar_index > trendLen + 3
    // --- direction gate measured BEFORE the pattern started (1, 2 or 3 candles back) ---
    fromDn1 = close[1] < close[1 + trendLen]
    fromUp1 = close[1] > close[1 + trendLen]
    fromDn2 = close[2] < close[2 + trendLen]
    fromUp2 = close[2] > close[2 + trendLen]
    fromDn3 = close[3] < close[3 + trendLen]
    fromUp3 = close[3] > close[3 + trendLen]
 
    // --- single-candle shapes ---
    pinLow  = not isDoji and dnWick >= body * wickMult and upWick <= body and dnWick >= rng * 0.6
    pinUp   = not isDoji and upWick >= body * wickMult and dnWick <= body and upWick >= rng * 0.6
    maru    = not isDoji and body >= bodyAvg * maruMult and upWick <= rng * 0.05 and dnWick <= rng * 0.05
    dojiDragon = isDoji and dnWick >= rng * 0.6 and upWick <= rng * 0.15
    dojiGrave  = isDoji and upWick >= rng * 0.6 and dnWick <= rng * 0.15
    dojiLong   = isDoji and upWick >= rng * 0.3 and dnWick >= rng * 0.3
    dojiName   = dojiDragon ? "Dragonfly Doji" : dojiGrave ? "Gravestone Doji" : dojiLong ? "Long-legged Doji" : "Doji"
 
    // --- two-candle shapes ---
    bullEng  = bull and bear[1] and close >= open[1] and open <= close[1] and body > body[1] and longBody
    bearEng  = bear and bull[1] and close <= open[1] and open >= close[1] and body > body[1] and longBody
    inPrevBody = bodyHi <= bodyHi[1] and bodyLo >= bodyLo[1] and body < body[1]
    bullHarX = bear[1] and longBody[1] and isDoji and inPrevBody
    bearHarX = bull[1] and longBody[1] and isDoji and inPrevBody
    bullHar  = bear[1] and longBody[1] and bull and inPrevBody
    bearHar  = bull[1] and longBody[1] and bear and inPrevBody
    pierce   = bear[1] and longBody[1] and bull and open < close[1] and close > (open[1] + close[1]) / 2 and close < open[1]
    darkC    = bull[1] and longBody[1] and bear and open > close[1] and close < (open[1] + close[1]) / 2 and close > open[1]
    twzBot   = bear[1] and longBody[1] and bull and math.abs(low - low[1]) <= atrRef * 0.1
    twzTop   = bull[1] and longBody[1] and bear and math.abs(high - high[1]) <= atrRef * 0.1
 
    // --- three-candle shapes ---
    mornStar = bear[2] and longBody[2] and body[1] <= body[2] * 0.3 and bull and close > (open[2] + close[2]) / 2
    evenStar = bull[2] and longBody[2] and body[1] <= body[2] * 0.3 and bear and close < (open[2] + close[2]) / 2
    mornDoji = mornStar and isDoji[1]
    evenDoji = evenStar and isDoji[1]
    soldiers = bull and bull[1] and bull[2] and close > close[1] and close[1] > close[2] and open > open[1] and open[1] > open[2] and open < close[1] and open[1] < close[2] and body >= bodyAvg * 0.8 and body[1] >= bodyAvg[1] * 0.8 and body[2] >= bodyAvg[2] * 0.8 and upWick <= body * 0.5 and upWick[1] <= body[1] * 0.5
    crows    = bear and bear[1] and bear[2] and close < close[1] and close[1] < close[2] and open < open[1] and open[1] < open[2] and open > close[1] and open[1] > close[2] and body >= bodyAvg * 0.8 and body[1] >= bodyAvg[1] * 0.8 and body[2] >= bodyAvg[2] * 0.8 and dnWick <= body * 0.5 and dnWick[1] <= body[1] * 0.5
    threeInUp = bear[2] and longBody[2] and bull[1] and bodyHi[1] <= open[2] and bodyLo[1] >= close[2] and bull and close > open[2]
    threeInDn = bull[2] and longBody[2] and bear[1] and bodyHi[1] <= close[2] and bodyLo[1] >= open[2] and bear and close < open[2]
 
    // --- one candidate per bar, most candles first, most specific first ---
    C = Cand.new("", 0, 0, 0, 0)
    offer(C, usStar and mornDoji and fromDn3,  "Morning Doji Star", 1, 3, 0, 3)
    offer(C, usStar and evenDoji and fromUp3,  "Evening Doji Star", -1, 3, 0, 3)
    offer(C, usStar and mornStar and fromDn3,  "Morning Star", 1, 3, 0, 3)
    offer(C, usStar and evenStar and fromUp3,  "Evening Star", -1, 3, 0, 3)
    offer(C, usThreeIn and threeInUp and fromDn3, "Three Inside Up", 1, 3, 0, 5)
    offer(C, usThreeIn and threeInDn and fromUp3, "Three Inside Down", -1, 3, 0, 5)
    offer(C, usThree and soldiers, "Three White Soldiers", 1, 3, 1, 5)
    offer(C, usThree and crows,    "Three Black Crows", -1, 3, 1, 5)
    offer(C, usHarami and bullHarX and fromDn2, "Bull Harami Cross", 1, 2, 0, 2)
    offer(C, usHarami and bearHarX and fromUp2, "Bear Harami Cross", -1, 2, 0, 2)
    offer(C, usEngulf and bullEng and fromDn2,  "Bull Engulfing", 1, 2, 0, 1)
    offer(C, usEngulf and bearEng and fromUp2,  "Bear Engulfing", -1, 2, 0, 1)
    offer(C, usHarami and bullHar and fromDn2,  "Bull Harami", 1, 2, 0, 2)
    offer(C, usHarami and bearHar and fromUp2,  "Bear Harami", -1, 2, 0, 2)
    offer(C, usPierce and pierce and fromDn2,   "Piercing Line", 1, 2, 0, 9)
    offer(C, usPierce and darkC and fromUp2,    "Dark Cloud Cover", -1, 2, 0, 9)
    offer(C, usTweezer and twzBot and fromDn2,  "Tweezer Bottom", 1, 2, 0, 10)
    offer(C, usTweezer and twzTop and fromUp2,  "Tweezer Top", -1, 2, 0, 10)
    offer(C, usMaru and maru and bull, "Bull Marubozu", 1, 1, 1, 7)
    offer(C, usMaru and maru and bear, "Bear Marubozu", -1, 1, 1, 7)
    offer(C, usPin and pinLow and fromDn1, "Hammer", 1, 1, 0, 4)
    offer(C, usPin and pinLow and fromUp1, "Hanging Man", -1, 1, 0, 4)
    offer(C, usPin and pinUp and fromDn1,  "Inverted Hammer", 1, 1, 0, 4)
    offer(C, usPin and pinUp and fromUp1,  "Shooting Star", -1, 1, 0, 4)
    offer(C, usDoji and bigDoji, dojiName, 0, 1, 2, 8)
 
    // --- global cooldown: one label every N bars, whatever the direction ---
    free = na(S.lastBar) or bar_index - S.lastBar > cooldown
 
    // --- context of the whole pattern range, then the gates (context, silence, score) ---
    if C.tier > 0
        loT = C.tier == 3 ? math.min(low, low[1], low[2]) : C.tier == 2 ? math.min(low, low[1]) : low
        hiT = C.tier == 3 ? math.max(high, high[1], high[2]) : C.tier == 2 ? math.max(high, high[1]) : high
        [bullCtx, bullTxt, bLvl, bBar, bearCtx, bearTxt, sLvl, sBar, anyLvl] = contextOf(loT, hiT)
        ctxOk = not useCtx or (C.kind == 2 ? anyLvl : C.dir > 0 ? bullCtx : bearCtx)
        ctxRaw = C.dir > 0 ? bullTxt : C.dir < 0 ? bearTxt : not na(bLvl) ? bullTxt : bearTxt
        lvlP   = C.dir > 0 ? bLvl : C.dir < 0 ? sLvl : not na(bLvl) ? bLvl : sLvl
        lvlB   = C.dir > 0 ? bBar : C.dir < 0 ? sBar : not na(bLvl) ? bBar : sBar
        [score, pSz, pCl, pLv, pVo] = scoreOf(loT, hiT, C.dir, lvlP, na(lvlP) and ctxRaw != "")
        if ctxOk and free and score >= minScore
            ctxTxt = ctxRaw == "" ? "No context (filter off)" : ctxRaw
            drawPattern(S, C.name, C.dir, ctxTxt, lvlP, lvlB, C.grp, score, pSz, pCl, pLv, pVo, loT, hiT)
            anyBull   := C.dir > 0
            anyBear   := C.dir < 0
            dojiSig   := C.grp == 8
            engulfSig := C.grp == 1
            haramiSig := C.grp == 2
            starSig   := C.grp == 3
            pinSig    := C.grp == 4
            threeSig  := C.grp == 5
            maruSig   := C.grp == 7
            pierceSig := C.grp == 9
            tweezSig  := C.grp == 10
            hiScoreSig := score >= alertScore
        else
            drawUnfiltered(S, C.dir)
 
    // --- inside bar: armed in context, confirmed by the breakout of the mother bar (never on a bar that already has a label) ---
    if not na(S.motherBar)
        if bar_index - S.motherBar > insideWait
            S.motherBar := na
        else if (close > S.motherHigh or close < S.motherLow) and (na(S.lastBar) or bar_index - S.lastBar > cooldown)
            int  bDir = close > S.motherHigh ? 1 : -1
            bool bExt = na(S.motherLvl) and str.contains(S.motherCtx, "Extended")
            [iScore, iSz, iCl, iLv, iVo] = scoreOf(S.motherLow, S.motherHigh, bDir, S.motherLvl, bExt)
            if iScore >= minScore
                insideSig  := true
                anyBull    := bDir > 0
                anyBear    := bDir < 0
                hiScoreSig := hiScoreSig or iScore >= alertScore
                drawPattern(S, bDir > 0 ? "Inside Bar ↑" : "Inside Bar ↓", bDir, S.motherCtx, S.motherLvl, S.motherLvlBar, 6, iScore, iSz, iCl, iLv, iVo, S.motherLow, S.motherHigh)
            else
                S.filtered := S.filtered + 1
            S.motherBar := na
    rawInside = usInside and high < high[1] and low > low[1]
    if rawInside and na(S.motherBar)
        [bullCtx1, bullTxt1, bLvl1, bBar1, bearCtx1, bearTxt1, sLvl1, sBar1, anyLvl1] = contextOf(low[1], high[1])
        if not useCtx or bullCtx1 or bearCtx1
            S.motherHigh   := high[1]
            S.motherLow    := low[1]
            S.motherBar    := bar_index
            S.motherLvl    := not na(bLvl1) ? bLvl1 : sLvl1
            S.motherLvlBar := not na(bLvl1) ? bBar1 : sBar1
            S.motherCtx    := "Inside bar · " + (bullCtx1 ? bullTxt1 : bearCtx1 ? bearTxt1 : "no context (filter off)")
        else
            drawUnfiltered(S, 0)
 
// ================== CANDLE HIGHLIGHT ==================
 
barcolor(paintBar and anyBull ? bullCol : paintBar and anyBear ? bearCol : paintBar and dojiSig ? neutCol : na)
 
// ================== RIGHT-EDGE LABELS (last swing high and low) ==================
 
var tmpLines  = array.new<line>()
var tmpLabels = array.new<label>()
float lblTop = na   // top and bottom of the label stack, read by the panel to choose its corner
float lblBot = na
 
array<float>  lvP = array.new<float>()
array<string> lvT = array.new<string>()
array<color>  lvC = array.new<color>()
if barstate.islast and atrRef > 0
    if not na(lastSwingHi) and bar_index - lastSwingHiBar <= lvlLife
        lvP.push(lastSwingHi)
        lvT.push("Swing high " + fmt(lastSwingHi) + " " + pctShort(lastSwingHi))
        lvC.push(bearCol)
    if not na(lastSwingLo) and bar_index - lastSwingLoBar <= lvlLife
        lvP.push(lastSwingLo)
        lvT.push("Swing low " + fmt(lastSwingLo) + " " + pctShort(lastSwingLo))
        lvC.push(bullCol)
 
if barstate.islast
    while tmpLines.size() > 0
        line.delete(tmpLines.pop())
    while tmpLabels.size() > 0
        label.delete(tmpLabels.pop())
    if showLevels and lvP.size() > 0
        int xe = bar_index + extR
        // Gap between label centres: Label Spacing in ATR, never less than one label height plus a margin
        float sep = math.max(labelSep * nz(atrRef), lblH * 1.25)
        array<int> ord = lvP.sort_indices(order.descending)
        float prevY = na
        for k = 0 to ord.size() - 1
            int   i = ord.get(k)
            float p = lvP.get(i)
            float y = na(prevY) ? p : math.min(p, prevY - sep)
            prevY := y
            lblTop := na(lblTop) ? y + lblH / 2 : math.max(lblTop, y + lblH / 2)
            lblBot := na(lblBot) ? y - lblH / 2 : math.min(lblBot, y - lblH / 2)
            tmpLines.push(line.new(bar_index, p, xe, p, color = color.new(lvC.get(i), lnTr), style = line.style_dashed, width = 1))
            if y != p
                tmpLines.push(line.new(xe, p, xe, y, color = color.new(lvC.get(i), lnTr), style = line.style_dotted, width = 1))
            // style_label_right: the label ends at the end of its line and grows to the left, never past the right edge
            tmpLabels.push(label.new(xe, y, lvT.get(i), style = label.style_label_right, color = color.new(lvC.get(i), lblTr), textcolor = #ffffff, size = lblSz, tooltip = lvT.get(i) + " - distance from the close " + pctShort(p)))
 
// ================== PANEL ==================
 
varip int lastCorner = -1   // corner used on the previous tick of the live candle (display only)
 
if showPanel
    panelPosTV = switch panelPos
        "Top Right"    => position.top_right
        "Top Left"     => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left"  => position.bottom_left
        => position.top_right
 
    // Created ONCE (var) and moved with table.set_position: changing the corner never leaves a ghost panel
    var table panel = table.new(panelPosTV, 2, 10, frame_color = isDark ? #363a45 : #b2b5be, frame_width = 1, border_color = isDark ? #434651 : #c8cbda, border_width = 1)
 
    if barstate.islast
        table.clear(panel, 0, 0, 1, 9)
        bool  full   = panelDetail == "Full"
        color bgMain = color.new(cellBg, panelTransp)
        color bgHead = color.new(headerBg, panelTransp)
        color bgSub  = color.new(subHeaderBg, panelTransp)
 
        // 1. Rows first, drawn once the corner is known
        bool   hasLast = not na(S.lastBar)
        string stTxt  = S.lastStatus
        color  stCol  = str.startswith(stTxt, "Confirmed") ? dirColor(S.lastDir) : str.startswith(stTxt, "Pending") ? numTxt : textCol
        array<string> rowK = array.new<string>()
        array<string> rowV = array.new<string>()
        array<color>  rowC = array.new<color>()
        addRow(rowK, rowV, rowC, "Last pattern", hasLast ? S.lastName : "None yet", hasLast ? dirColor(S.lastDir) : textCol)
        addRow(rowK, rowV, rowC, "Score", hasLast ? str.tostring(S.lastScore) + " / 100" : "-", textCol)
        addRow(rowK, rowV, rowC, "Status", hasLast ? stTxt : "-", stCol)
        addRow(rowK, rowV, rowC, "Hit rate", rateText(S.hits, S.total), textCol)
        if full
            addRow(rowK, rowV, rowC, "Context", hasLast ? S.lastCtx : "-", textCol)
            addRow(rowK, rowV, rowC, "When", hasLast ? agoTxt(S.lastBar) : "-", numTxt)
            addRow(rowK, rowV, rowC, "Shown / discarded", str.tostring(S.shown) + " / " + str.tostring(S.filtered), numTxt)
        string foot = full ? "Closed bars - hit = close past it within " + str.tostring(confirmBars) + " bars" : "Closed bars - not a signal"
        int nBody = math.min(rowK.size(), full ? MAX_BODY : MAX_BODY_C)
        int nRows = nBody + 2   // title + body + footer
 
        // 2. Corner. Room per corner as a share of the visible span: 0 top right, 1 bottom right, 2 top left, 3 bottom left,
        // minus the empty row kept for the TradingView legend (top left), icon (bottom right) or logo (bottom left)
        int cs = panelPos == "Top Right" ? 0 : panelPos == "Bottom Right" ? 1 : panelPos == "Top Left" ? 2 : 3
        if panelAvoid and not na(visSpan) and visSpan > 0 and not na(rgtHi) and not na(lftHi)
            bool  lastIn = visR >= time
            float scHi   = math.max(visHi, nz(lblTop, visHi))
            float scLo   = math.min(visLo, nz(lblBot, visLo))
            float scSpan = scHi - scLo
            float rTop   = lastIn and not na(lblTop) ? math.max(rgtHi, lblTop) : rgtHi
            float rBot   = lastIn and not na(lblBot) ? math.min(rgtLo, lblBot) : rgtLo
            array<float> room = array.from((scHi - rTop) / scSpan, (rBot - scLo) / scSpan - ICON_PCT / 100, (scHi - lftHi) / scSpan - LEGEND_PCT / 100, (lftLo - scLo) / scSpan - LOGO_PCT / 100)
            float need = (nRows + 1) * (panelSize == "Small" ? ROW_SHARE * 0.8 : ROW_SHARE)
            int   pi   = cs
            // Corners tried in order: the chosen one, the other one on the same side, then the other side
            array<int> tryOrd = array.from(pi, pi % 2 == 0 ? pi + 1 : pi - 1, (pi + 2) % 4, pi % 2 == 0 ? (pi + 3) % 4 : (pi + 1) % 4)
            int pick = -1
            int best = -1
            for k = 0 to 3
                int cn = tryOrd.get(k)
                if pick < 0 and room.get(cn) >= need
                    pick := cn
                if best < 0 or room.get(cn) > room.get(best)
                    best := cn
            int p0 = pick >= 0 ? pick : best
            // Live candle: keep the corner of the previous tick while it still fits, so the panel does not jump
            if lastCorner >= 0 and lastCorner != p0 and room.get(lastCorner) >= need and not (p0 == pi and room.get(pi) >= need * 1.15)
                p0 := lastCorner
            lastCorner := p0
            cs := p0
        string pos = cs == 0 ? position.top_right : cs == 1 ? position.bottom_right : cs == 2 ? position.top_left : position.bottom_left
 
        // 3. Draw. Top left: transparent spacer row 0 (TradingView legend). Bottom corners: spacer under the footer
        bool atTopLeft = pos == position.top_left
        bool atBottom  = pos == position.bottom_left or pos == position.bottom_right
        int  r0        = atTopLeft ? 1 : 0
        if atTopLeft
            table.cell(panel, 0, 0, "", height = LEGEND_PCT)
            table.merge_cells(panel, 0, 0, 1, 0)
        table.cell(panel, 0, r0, "EDO CANDLE CONTEXT", text_color = textCol, bgcolor = bgHead, text_size = panSz)
        table.merge_cells(panel, 0, r0, 1, r0)
        for i = 0 to nBody - 1
            panelRow(panel, r0 + 1 + i, rowK.get(i), rowV.get(i), rowC.get(i), bgMain)
        int rFoot = r0 + nBody + 1
        table.cell(panel, 0, rFoot, foot, text_color = numTxt, bgcolor = bgSub, text_size = panSz)
        table.merge_cells(panel, 0, rFoot, 1, rFoot)
        if atBottom and rFoot < 9
            table.cell(panel, 0, rFoot + 1, "", height = pos == position.bottom_left ? LOGO_PCT : ICON_PCT)
            table.merge_cells(panel, 0, rFoot + 1, 1, rFoot + 1)
        // With a spacer row the outer frame is hidden so it does not box the legend, the logo or the icon
        table.set_frame_width(panel, atBottom or atTopLeft ? 0 : 1)
        table.set_position(panel, pos)
 
// ================== ALERTS ==================
 
alertcondition(anyBull,   "Any bullish pattern",      "Edo Candle Context — Bullish candle pattern in context on {{ticker}}")
alertcondition(anyBear,   "Any bearish pattern",      "Edo Candle Context — Bearish candle pattern in context on {{ticker}}")
alertcondition(dojiSig,   "Doji at level",            "Edo Candle Context — Doji right on a swing level on {{ticker}}")
alertcondition(engulfSig, "Engulfing in context",     "Edo Candle Context — Engulfing candle at a level / extension on {{ticker}}")
alertcondition(haramiSig, "Harami in context",        "Edo Candle Context — Harami at a level / extension on {{ticker}}")
alertcondition(pierceSig, "Piercing / Dark Cloud",    "Edo Candle Context — Piercing line or dark cloud cover at a level / extension on {{ticker}}")
alertcondition(tweezSig,  "Tweezer in context",       "Edo Candle Context — Tweezer top or bottom at a level / extension on {{ticker}}")
alertcondition(starSig,   "Morning / Evening Star",   "Edo Candle Context — Star reversal at a level / extension on {{ticker}}")
alertcondition(pinSig,    "Pin bar in context",       "Edo Candle Context — Pin bar (hammer / star / inverted / hanging) at a level / extension on {{ticker}}")
alertcondition(threeSig,  "Three-candle pattern",     "Edo Candle Context — Three-candle pattern (soldiers / crows / three inside) at a level / extension on {{ticker}}")
alertcondition(insideSig, "Inside bar breakout",      "Edo Candle Context — Inside bar broke its mother bar on {{ticker}}")
alertcondition(maruSig,   "Marubozu in context",      "Edo Candle Context — Marubozu strength candle at a level / extension on {{ticker}}")
alertcondition(hiScoreSig, "High score pattern",      "Edo Candle Context — Pattern with a high score on {{ticker}}")
alertcondition(evConfirmed, "Pattern confirmed",      "Edo Candle Context — A pattern was confirmed by a close beyond it on {{ticker}}")
alertcondition(evInvalid, "Pattern invalidated",      "Edo Candle Context — A pattern was invalidated by a close beyond its other end on {{ticker}}")

← 返回列表