Mbedaiwi Candlestick Patterns & Setups

mbedaiwi · study · 850 行 · 点赞 105 · TradingView 原页

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

Pine Script

//@version=6
indicator("Mbedaiwi Candlestick Patterns & Setups", overlay=true, max_labels_count=500, max_lines_count=500)
 
// =====================================================================================
// Mbedaiwi Candlestick Patterns & Setups — v1.0
// Candlestick patterns and price setups.
//   • Classic candles: Doji, Engulfing, Piercing Line, Dark Cloud Cover, Harami,
//     Morning / Evening Star, Hammer family — body sizes measured against the
//     average body of the previous 10 bars, with a stochastic filter on the
//     single-bar reversal candles.
//   • Setups: pattern concepts popularised in S. W. Bigalow's and S. Nison's books;
//     the detection rules and thresholds here are the author's own (ATR, Stochastic
//     14/3 timing, support / resistance location, RSI divergence, EMA 8/21, SMA 50/200,
//     volume).
//   • Early warning: a yellow dot on the first reversal bar at support / resistance;
//     a confirmed reversal (✔) needs the next bar to close beyond it.
// Bullish names are printed below the bar, bearish names above it.
// With "One name per bar" on, the first match in the priority list wins.
// =====================================================================================
 
// ─────────────── Inputs ───────────────
grpA = "1 - Groups"
useDojiSet  = input.bool(true, "Doji setups", group=grpA, display=display.none)
useGapSet   = input.bool(true, "Gap / Kicker setups", group=grpA, display=display.none)
usePriceSet = input.bool(true, "Price setups", group=grpA, display=display.none)
useClassic  = input.bool(true, "Classic candles", group=grpA, display=display.none)
usePlainDoji = input.bool(true, "Show plain Doji", group=grpA, display=display.none)
singleName  = input.bool(true, "One name per bar (first match in priority list)", group=grpA, display=display.none)
classicInfo = input.bool(false, "Classic candles: colour and arrow only in context", group=grpA, tooltip="Engulfing, Harami, Piercing Line, Dark Cloud Cover, Morning / Evening Star, Hanging Man and Shooting Star always show their name. They get their colour and an arrow only when the context agrees: bullish at support with Stochastic oversold and the market index EMA 8 rising; bearish at resistance with Stochastic overbought and the market index EMA 8 falling. Otherwise the name is grey (shape information only). Turn off to colour every classic candle.", display=display.none)
displaySet  = input.string("Both", "Display set", options=["Both", "Setups only", "Classic candles only"], group=grpA, tooltip="Setups only: hides the single and multi-bar classic candles for a cleaner chart. Pattern positions do not change.", display=display.none)
 
grpB = "2 - Candle parameters"
kDoji    = input.float(0.05, "Doji: body <= avg body (prev 10) x", step=0.01, group=grpB, display=display.none)
kSmall   = input.float(0.25, "Small body (Spinning Top / Hammer family): body <= avg body (prev 10) x", step=0.01, group=grpB, tooltip="Spinning Top = small body that is not a Doji. The Hammer family uses the same small-body size.", display=display.none)
kLong    = input.float(2.00, "Long candle: body >= avg body (prev 10) x", step=0.05, group=grpB, tooltip="Used for the first bar of Harami / Morning Star / Evening Star / Dark Cloud Cover and both bars of Piercing Line. The second bar of Dark Cloud Cover needs at least an average body.", display=display.none)
allowEq  = input.bool(false, "Engulfing: allow equal open/close", group=grpB, display=display.none)
kShadow  = input.float(0.10, "Hammer family: opposite shadow <= range x", step=0.01, group=grpB, tooltip="Hammer / Inverted Hammer: small body, long shadow >= 2/3 of the range, not a Doji.", display=display.none)
lookTrend = input.int(3, "Prior-trend bars (reversal candles)", minval=1, group=grpB, display=display.none)
ctxMode  = input.string("Shape only (no trend)", "Trend context", options=["Textbook (trend required)", "Shape only (no trend)"], group=grpB, tooltip="Textbook: Hanging Man, Dark Cloud Cover, Bearish Engulfing, Evening Star need a prior rise; Hammer, Piercing Line, Bullish Engulfing, Morning Star need a prior fall.\nShape only: the trend is ignored.", display=display.none)
 
grpE = "2b - Setup engine"
atrLen  = input.int(14, "ATR length (setup sizes)", minval=2, group=grpE, display=display.none)
rsiLen  = input.int(14, "RSI length (divergence)", minval=2, group=grpE, display=display.none)
useVol  = input.bool(true, "Volume confirmation for breakouts", group=grpE, tooltip="Doji Cluster Breakout / Breakdown, Cup & Handle and MA Retest Breakout also need volume >= the 20-bar average x the multiplier below. Skipped on symbols without volume.", display=display.none)
volMult = input.float(1.5, "Volume multiplier", minval=1.0, step=0.1, group=grpE, display=display.none)
 
grpW = "2c - Early warning & confirmation"
useWarn  = input.bool(true, "Early warning dot on the first reversal bar", group=grpW, tooltip="A reversal-type candle at support (resistance) with Stochastic stretched. It is an alert only: wait for the confirmation.", display=display.none)
useConf  = input.bool(true, "Confirmation mark (✔) when the next bar closes beyond it", group=grpW, tooltip="The confirming bar gets a ✔. If no named pattern sits on it, it is named Bullish Reversal / Bearish Reversal (Upthrust Reversal when it rejects a break above a tight shelf). A confirmation needs Stochastic below 20 (above 80) in the last 3 bars, %K crossing its signal line and volume at least average.", display=display.none)
showWeak = input.bool(false, "Show low-reliability setups", group=grpW, tooltip="Cup & Handle, Base Reversal, Bearish / Upthrust Reversal and Doji Cluster Breakdown. Off by default because they were less reliable in the author's historical review. Base Reversal is always shown on non-Saudi symbols.", display=display.none)
hamConf  = input.bool(true, "Hammer: wait for confirmation", group=grpW, tooltip="The Hammer bar is named in yellow as a watch only. The signal is the next bar, named Hammer ✔, when it closes above the Hammer's high. Unconfirmed Hammers were less reliable than confirmed ones in the author's historical review. Past behaviour does not guarantee future results.", display=display.none)
useMkt   = input.bool(true, "Market filter for Bullish Reversal", group=grpW, tooltip="When the market index's EMA 8 is falling, Bullish Reversal is shown in grey and does not trigger the alert. In the author's historical review it held up better when the index EMA 8 was rising. Past behaviour does not guarantee future results.\nAutomatic index: TADAWUL:TASI for Saudi stocks, SP:SPX for other stocks and funds, none for other instruments.", display=display.none)
showStop = input.bool(true, "Stop line under Bullish Reversal", group=grpW, tooltip="A grey dashed line at the low of the warning and confirmation bars. It runs until a close below it (the signal is void) or for 20 bars.", display=display.none)
mktSym   = input.symbol("", "Market index (empty = automatic)", group=grpW, tooltip="Empty: TADAWUL:TASI for Saudi stocks, SP:SPX for other stocks and funds, no filter for other instruments (forex, crypto, futures).", display=display.none)
useDiv   = input.bool(true, "★ RSI divergence", group=grpW, tooltip="Adds ★ to the name / ✔ when price made a lower low (higher high) while RSI made a higher low (lower high).", display=display.none)
stLen    = input.int(14, "Stochastic length", minval=3, group=grpW, display=display.none)
stOS     = input.float(25, "Stochastic oversold <", group=grpW, display=display.none)
stOB     = input.float(75, "Stochastic overbought >", group=grpW, display=display.none)
 
grpP = "2d - Performance table"
perfOn   = input.bool(false, "Show performance table", group=grpP, tooltip="For every signal on this chart: did price move 1 x ATR in the signal direction before 1 x ATR against it, within the bar limit? Past results only; they do not predict the future.", display=display.none)
perfBars = input.int(10, "Bars allowed", minval=2, group=grpP, display=display.none)
perfMult = input.float(1.0, "Target / stop (x ATR)", minval=0.2, step=0.1, group=grpP, display=display.none)
perfWhere = input.string("Middle right", "Table position", options=["Top right", "Top left", "Bottom left", "Middle right"], group=grpP, display=display.none)
 
grpC = "3 - Display"
closedOnly  = input.bool(true, "Bar close only (non-repainting)", group=grpC, display=display.none)
paintBars   = input.bool(true, "Colour pattern bar (blue / dark red)", group=grpC, display=display.none)
nameSize    = input.int(10, "Text size (pt)", minval=6, maxval=30, group=grpC, display=display.none)
arrowSel    = input.string("Tiny", "Arrow size", options=["Tiny", "Small", "Normal", "Large", "Huge"], group=grpC, display=display.none)
nameMode    = input.string("Name", "Pattern name", options=["Name", "Tooltip only"], group=grpC, tooltip="Tooltip only: a small ⓘ mark instead of the name; hover it to read the name and notes.", display=display.none)
noteLang    = input.string("English", "Notes language", options=["English", "العربية", "Off"], group=grpC, tooltip="Hover a pattern name to read a short note on what it shows and how to confirm it.", display=display.none)
panelOn     = input.bool(true, "Notes panel (latest pattern)", group=grpC, display=display.none)
panelWhere  = input.string("Top right", "Panel position", options=["Top right", "Bottom right", "Bottom left", "Top left"], group=grpC, display=display.none)
panelSize   = input.int(11, "Panel text size (pt)", minval=8, maxval=30, group=grpC, tooltip="The title is 2 pt larger, the header line 1 pt smaller.", display=display.none)
themeSel    = input.string("Auto", "Colour theme", options=["Auto", "Dark background", "Light background"], group=grpC, tooltip="Auto follows the chart background.", display=display.none)
splitWords  = input.bool(true, "One word per line (narrow names)", group=grpC, display=display.none)
offsetNear  = input.bool(true, "Offset names on neighbouring bars", group=grpC, display=display.none)
plotE8   = input.bool(true, "EMA 8", group=grpC, display=display.none)
plotE3   = input.bool(false, "EMA 3", group=grpC, display=display.none)
plotS20  = input.bool(false, "SMA 20", group=grpC, display=display.none)
plotS50  = input.bool(false, "SMA 50", group=grpC, display=display.none)
plotS200 = input.bool(false, "SMA 200", group=grpC, display=display.none)
 
grpD = "4 - Trade markers (optional)"
tradeMarks = input.bool(false, "Show BUY / EXIT markers", group=grpD, display=display.none)
stopAtr    = input.float(1.5, "Stop (ATR)", minval=0.2, step=0.1, group=grpD, display=display.none)
 
// ─────────────── Utilities ───────────────
// slow stochastic %K: smoothed (close - lowest low) / (highest high - lowest low)
slowK(int len, int smooth) =>
    float up = math.sum(close - ta.lowest(low, len), smooth)
    float dn = math.sum(ta.highest(high, len) - ta.lowest(low, len), smooth)
    dn == 0 ? na : 100 * up / dn
 
// true if c happened on this bar or within the previous n-1 bars
within(bool c, int n) => math.sum(c ? 1 : 0, n) > 0
 
// running extreme of x since the bar where c was last true
maxFrom(bool c, float x) =>
    var float m = na
    if c
        m := x
    else if not na(m)
        m := math.max(m, x)
    m
minFrom(bool c, float x) =>
    var float m = na
    if c
        m := x
    else if not na(m)
        m := math.min(m, x)
    m
 
// ─────────────── Price data ───────────────
float o = open
float h = high
float l = low
float c = close
float bodySz = math.abs(o - c)
float span   = h - l
float bTop   = math.max(o, c)
float bBot   = math.min(o, c)
float wickUp = h - bTop
float wickDn = bBot - l
float bodyAvg10 = ta.sma(bodySz, 10)
float e8   = ta.ema(c, 8)
float e3   = ta.ema(c, 3)
float s20  = ta.sma(c, 20)
float s50  = ta.sma(c, 50)
float s200 = ta.sma(c, 200)
float k12  = slowK(12, 3)
 
// ─────────────── Classic candles ───────────────
bool up   = c > o
bool down = c < o
float refBody = bodyAvg10[1]                 // average body of the previous 10 bars
bool isDoji   = bodySz <= refBody * kDoji
bool isSmall  = bodySz <= refBody * kSmall
bool isSpin   = not isDoji and isSmall
bool isLong   = bodySz >= refBody * kLong
bool longUp   = up and isLong
bool longDown = down and isLong
bool engUp    = up and down[1] and (allowEq ? o <= c[1] and c >= o[1] : o < c[1] and c > o[1]) and bodySz > bodySz[1]
bool engDown  = down and up[1] and (allowEq ? o >= c[1] and c <= o[1] : o > c[1] and c < o[1]) and bodySz > bodySz[1]
bool hamForm  = span > 0 and isSpin and wickDn >= span * 2 / 3 and wickUp <= span * kShadow
bool invForm  = span > 0 and isSpin and wickUp >= span * 2 / 3 and wickDn <= span * kShadow
bool strict   = ctxMode == "Textbook (trend required)"
// prior trend, measured before the first bar of a 1-, 2- or 3-bar pattern
bool fell1 = not strict or c[1] < c[1 + lookTrend]
bool rose1 = not strict or c[1] > c[1 + lookTrend]
bool fell2 = not strict or c[2] < c[2 + lookTrend]
bool rose2 = not strict or c[2] > c[2 + lookTrend]
bool fell3 = not strict or c[3] < c[3 + lookTrend]
bool rose3 = not strict or c[3] > c[3 + lookTrend]
bool pHammer  = hamForm and fell1
bool pHanging = hamForm and rose1
bool pInvHam  = invForm and fell1
bool pShooter = invForm and rose1
bool pEngUp   = engUp and fell2
bool pEngDown = engDown and rose2
bool pPiercing  = fell2 and down[1] and isLong[1] and up and isLong and o < c[1] and c > (o[1] + c[1]) / 2
// the second (black) bar needs only an average-size body: a long white bar, then a normal black bar that opens above
// its close and closes below its midpoint (a long second bar is rare on intraday charts)
bool pDarkCloud = rose2 and up[1] and isLong[1] and down and bodySz >= refBody and o > c[1] and c < (o[1] + c[1]) / 2
// Harami: a long candle, then an opposite-colour Spinning Top inside its body
bool pHaramiUp   = fell2 and longDown[1] and up and isSpin and bTop <= o[1] and bBot >= c[1]
bool pHaramiDown = rose2 and longUp[1] and down and isSpin and bTop <= c[1] and bBot >= o[1]
// Stars: long candle, Spinning Top star gapping away from its body, then a reversal
// candle opening beyond the star body and closing past the first body's midpoint
bool pMorning = fell3 and longDown[2] and isSpin[1] and math.max(o[1], c[1]) < c[2] and up and o > math.max(o[1], c[1]) and c >= (o[2] + c[2]) / 2
bool pEvening = rose3 and longUp[2] and isSpin[1] and math.min(o[1], c[1]) > c[2] and down and o < math.min(o[1], c[1]) and c <= (o[2] + c[2]) / 2
bool pHammerOS  = pHammer and k12 < 20
bool pInvHamOS  = pInvHam and k12 < 20                 // Inverted Hammer: only when oversold
bool pHangingOB = pHanging and k12 > 80                // Hanging Man: only when overbought (bearish)
bool pShooterOB = pShooter and k12 > 80 and o >= h[1]
 
// =====================================================================================
// SETUP ENGINE — shared measures (volatility, momentum, location, trend, volume)
// Sizes are measured in ATR so the rules adapt to each instrument and timeframe.
// =====================================================================================
float atrV   = ta.atr(atrLen)
float rsiV   = ta.rsi(c, rsiLen)
float hi20   = ta.highest(h, 20)
float lo20   = ta.lowest(l, 20)
float loc20  = hi20 - lo20 > 0 ? (c - lo20) / (hi20 - lo20) : 0.5   // 0 = at 20-bar low, 1 = at 20-bar high
float e21    = ta.ema(c, 21)
float volAvg = ta.sma(volume, 20)
bool  volOk  = not useVol or na(volAvg) or volAvg == 0 or volume >= volAvg * volMult
bool  quiet  = isDoji or isSpin or bodySz <= atrV * 0.3              // indecision bar
float stK    = ta.sma(ta.stoch(c, h, l, stLen), 3)                  // Stochastic %K (smoothed)
float stD    = ta.sma(stK, 3)
bool  weakLo = stK < stOS or stK[1] < stOS or loc20 < 0.2              // stretched to the downside
bool  weakHi = stK > stOB or stK[1] > stOB or loc20 > 0.8              // stretched to the upside
// support / resistance: the prior 20-bar extreme or the last confirmed swing point (5 bars each side)
float lo20p  = ta.lowest(l, 20)[1]
float hi20p  = ta.highest(h, 20)[1]
float pivL   = ta.pivotlow(l, 5, 5)
float pivH   = ta.pivothigh(h, 5, 5)
float lastPL = ta.valuewhen(not na(pivL), pivL, 0)
float lastPH = ta.valuewhen(not na(pivH), pivH, 0)
bool  atSup  = l <= lo20p + atrV * 0.5 or (not na(lastPL) and math.abs(l - lastPL) <= atrV * 0.5)
bool  atRes  = h >= hi20p - atrV * 0.5 or (not na(lastPH) and math.abs(h - lastPH) <= atrV * 0.5)
// Hammer types only count at support: the 20-bar low or the last swing low
bool  pHammerQ = pHammerOS and atSup
// Inverted Hammer (own rule): long upper shadow, almost no lower shadow, a body no larger
// than the 10-bar average, a wide bar (>= 1.2 ATR) whose low is within 1 ATR of the prior 20-bar low
bool  invWide  = span > 0 and not isDoji and wickUp >= span * 0.6 and wickDn <= span * 0.1 and bodySz <= refBody and span >= atrV * 1.2 and l <= lo20p + atrV
bool  pInvHamQ = invWide and fell1
// Hammer confirmation: the next bar closes above the Hammer's high
bool  hamDone  = hamConf and pHammerQ[1] and c > h[1]
// market filter: direction of the market index EMA 8 (same timeframe, closed bars)
string mktAuto = syminfo.prefix == "TADAWUL" ? "TADAWUL:TASI" : (syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "dr") ? "SP:SPX" : ""
string mktId  = mktSym != "" ? mktSym : mktAuto
bool   mktOn  = mktId != ""
float  mktE8  = request.security(mktOn ? mktId : syminfo.tickerid, timeframe.period, ta.ema(close, 8), lookahead=barmerge.lookahead_off)
bool   mktUp  = not mktOn or na(mktE8) or na(mktE8[1]) or mktE8 > mktE8[1]
bool   mktDn  = mktOn and not na(mktE8) and not na(mktE8[1]) and mktE8 < mktE8[1]
bool  baseShow = showWeak or syminfo.prefix != "TADAWUL"
bool  trendUp = e8 > e21 and e21 >= e21[3]
bool  trendDn = e8 < e21 and e21 <= e21[3]
// RSI divergence: a new 25-bar low (high) while RSI holds above (below) its value at the earlier extreme
float prevLo   = ta.lowest(l, 25)[5]
float prevHi   = ta.highest(h, 25)[5]
int   prevLoAt = nz(5 - ta.lowestbars(l, 25)[5], 5)
int   prevHiAt = nz(5 - ta.highestbars(h, 25)[5], 5)
float rsiAtLo  = rsiV[prevLoAt]
float rsiAtHi  = rsiV[prevHiAt]
bool  divUp    = l < prevLo and rsiV > rsiAtLo + 2 and rsiV < 50
bool  divDn    = h > prevHi and rsiV < rsiAtHi - 2 and rsiV > 50
bool  divUpNear = within(divUp, 3)
bool  divDnNear = within(divDn, 3)
bool  strongUp = up and bodySz >= atrV * 0.8 and bodySz >= span * 0.55
bool  strongDn = down and bodySz >= atrV * 0.8 and bodySz >= span * 0.55
bool  solidUp  = up and bodySz >= atrV * 0.6 and bodySz >= span * 0.5
bool  solidDn  = down and bodySz >= atrV * 0.6 and bodySz >= span * 0.5
float under21  = math.sum(c < e21 ? 1 : 0, 10)
 
// =====================================================================================
// DOJI SETUPS
// =====================================================================================
// indecision bar at a stretched low / high, then a gap away from it
bool xDojiGapUp   = quiet[1] and (weakLo[1] or loc20[1] < 0.4) and up and o > h[1]
bool xDojiGapDown = quiet[1] and (weakHi[1] or loc20[1] > 0.6) and down and o < l[1]
// indecision bar, then an engulfing candle at least 0.8 ATR long
bool xDojiEngUp   = quiet[1] and weakLo[1] and (atSup or atSup[1]) and engUp and bodySz >= atrV * 0.8
bool xDojiEngDown = quiet[1] and weakHi[1] and (atRes or atRes[1]) and engDown and bodySz >= atrV * 0.8
 
// Doji cluster: 3+ indecision bars in 5, packed inside 1.5 ATR, then a close 0.25 ATR beyond the box
float quietN = math.sum(quiet ? 1 : 0, 5)
float boxHi  = ta.highest(h, 5)
float boxLo  = ta.lowest(l, 5)
bool  boxOn  = quietN >= 3 and (boxHi - boxLo) <= atrV * 1.5
bool xClusterUp   = boxOn[1] and weakLo[1] and c > boxHi[1] + atrV * 0.25 and c > e8 and volOk
bool xClusterDown = boxOn[1] and weakHi[1] and c < boxLo[1] - atrV * 0.25 and c < e8 and volOk
 
// Doji continuation: strong bar, a pause that holds its upper (lower) half, then a close beyond its extreme
bool  cuBar = up and bodySz >= atrV * 0.5 and bodySz >= span * 0.5
bool xContUp   = trendUp and cuBar[2] and quiet[1] and bBot[1] >= (o[2] + c[2]) / 2 and cuBar and c > c[2]
bool  cdBar = down and bodySz >= span * 0.5
bool xContDown = e8 < e21 and cdBar[2] and quiet[1] and bTop[1] <= (o[2] + c[2]) / 2 and cdBar and c < math.min(c[1], c[2])
// Morning Star followed within 6 bars by a strong close above everything since the star
bool  starNear = within(pMorning, 6)
float hi6      = ta.highest(h, 6)
bool xStarCont = starNear[1] and strongUp and c > hi6[1]
 
// =====================================================================================
// GAP / KICKER SETUPS
// =====================================================================================
// Kicker: opposite-colour bodies of at least 0.5 ATR, the second opening at or beyond the first open
// and never trading back into the first body
bool kDn1 = down and bodySz >= math.min(atrV * 0.3, bodyAvg10 * 0.5)
bool kUp1 = up and bodySz >= math.min(atrV * 0.3, bodyAvg10 * 0.5)
bool xKickUp   = kDn1[1] and kUp1 and o >= o[1]
bool xKickDown = kUp1[1] and kDn1 and o <= o[1]
// Doji gap kicker: solid bar, an indecision bar that holds beyond its close, then a solid bar
// opening past the indecision body and closing beyond the first bar's open
bool xGapKickUp   = kDn1[2] and quiet[1] and bBot[1] > c[2] and o > bTop[1] and kUp1 and c > bTop[1]
bool xGapKickDown = kUp1[2] and quiet[1] and bTop[1] < c[2] and o < bBot[1] and kDn1 and c < bBot[1]
 
// =====================================================================================
// PRICE SETUPS
// =====================================================================================
// Rounding bottom / top (saucer): price spent most of the last 25 bars under (over) EMA 21, the 25-bar
// low (high) sits inside that span, EMA 8 has turned from falling to rising (rising to falling),
// then a thrust bar (body >= 1 ATR or a gap) clears the 10-bar high (low)
float rbUnder  = math.sum(c < e21 ? 1 : 0, 25)
float rbOver   = math.sum(c > e21 ? 1 : 0, 25)
int   rbLowAt  = -ta.lowestbars(l, 25)
int   rbHighAt = -ta.highestbars(h, 25)
float rbHi10   = ta.highest(h, 10)
float rbLo10   = ta.lowest(l, 10)
bool  e8TurnUp = e8 > e8[3] and e8[8] < e8[13]
bool  e8TurnDn = e8 < e8[3] and e8[8] > e8[13]
bool  thrustUp = up and (bodySz >= atrV or o > h[1])
bool  thrustDn = down and (bodySz >= atrV or o < l[1])
bool rbBotRaw = rbUnder[1] >= 12 and rbLowAt >= 3 and rbLowAt <= 18 and e8TurnUp and thrustUp and c > rbHi10[1]
bool rbTopRaw = rbOver[1] >= 12 and rbHighAt >= 3 and rbHighAt <= 18 and e8TurnDn and thrustDn and c < rbLo10[1]
// one signal per formation: ignore repeats within 15 bars
bool rbBotSeen = within(rbBotRaw, 15)
bool rbTopSeen = within(rbTopRaw, 15)
bool xRoundBot = rbBotRaw and not rbBotSeen[1]
bool xRoundTop = rbTopRaw and not rbTopSeen[1]
 
// Pullback hook: a run of 5+ ATR into a peak 4-12 bars ago, a 25-62% pullback, then the
// first bar that closes above the prior high near the pullback low
int   pkAt   = -ta.highestbars(h, 12)
float pkHi   = ta.highest(h, 12)
float runLo  = ta.lowest(l, 25)
float pbLo   = ta.lowest(l, 5)
int   pbAt   = -ta.lowestbars(l, 5)
float runSz  = pkHi - runLo
float pbPct  = runSz > 0 ? (pkHi - pbLo) / runSz : 0
bool  hookOn = pkAt >= 4 and pkAt <= 12 and runSz >= atrV * 5 and pbPct >= 0.25 and pbPct <= 0.62 and pbAt >= 1 and pbAt <= 3
float stLo4 = ta.lowest(stK, 4)
bool  hookRaw = hookOn and e21 > e21[10] and up and c > h[1] and c < pkHi and c > e8 and stK > stK[1] and stLo4 < 50
bool  hookSeen = within(hookRaw, 10)
bool xHook = hookRaw and not hookSeen[1]
// Cup & handle: left rim 20-49 bars back, cup at least 4 ATR deep with its low mid-way, right side back within 15%
// of the depth, a handle that keeps to the upper 40% of the cup, then a close above the handle
float cupRim  = ta.highest(h, 30)[20]
float cupLow  = ta.lowest(l, 45)[5]
float hdlHi   = ta.highest(h, 5)[1]
float hdlLo   = ta.lowest(l, 5)[1]
float cupDep  = cupRim - cupLow
int   cupLowAt = -ta.lowestbars(l, 45)[5]
bool  cupOk   = cupDep >= atrV * 4 and cupLowAt >= 8 and cupLowAt <= 30 and hdlHi >= cupRim - cupDep * 0.15 and hdlLo >= cupRim - cupDep * 0.4
bool  hdlBreak = c > hdlHi and c[1] <= hdlHi[1]
bool  cupRaw  = cupOk and hdlBreak and volOk and c > e21 and e21 > e21[5]
bool  cupSeen = within(cupRaw, 20)
bool xCupHandle = cupRaw and not cupSeen[1]
 
// Spring / Upthrust: a 10-bar shelf (<= 3.5 ATR tall, ending 3 bars ago), a break of up to 3 ATR beyond it
// within the last 5 bars, then a close back inside that rejects the break
float spHi   = ta.highest(h, 10)[3]
float spLo   = ta.lowest(l, 10)[3]
float dip5   = ta.lowest(l, 5)
float pop5   = ta.highest(h, 5)
bool  spFlat = (spHi - spLo) <= atrV * 3.5
bool  spBack = ta.crossover(c, spLo)
float stMin3 = ta.lowest(stK, 5)
bool  spCtx  = spFlat and dip5 < spLo and dip5 >= spLo - atrV * 3
bool  utCtx  = spFlat and pop5 > spHi and pop5 <= spHi + atrV * 3
// the bar that rejects the break: closes higher, in the upper part of its range, back above the base low
bool  spRej  = c > spLo and c > c[1] and span > 0 and (c - l) >= span * 0.6
bool  spRaw  = spCtx and (spBack or spRej) and stMin3 < 35 and c > (spHi + spLo) / 2
bool  spSeen = within(spRaw, 15)
bool xSpring = spRaw and not spSeen[1]
 
// Belt hold: opens at its extreme (shadow on that side <= 5% of range), body >= 1.5 ATR, after a stretch
bool xBeltUp   = up and wickDn <= span * 0.1 and bodySz >= atrV * 1.5 and (weakLo[1] or loc20[1] < 0.3) and (atSup or atSup[1] or o < l[1])
bool xBeltDown = down and wickUp <= span * 0.1 and bodySz >= atrV * 1.5 and (weakHi[1] or loc20[1] > 0.7) and (atRes or atRes[1] or o > h[1])
 
// Base reversal: a large black "headboard" at a stretched low, 3-10 mostly indecisive bars that stay
// below its open, then a white "footboard" at least 70% of its size closing above the base
bool  headBar   = down and bodySz >= atrV * 0.8 and (weakLo or loc20 < 0.3)
int   sinceHead = ta.barssince(headBar)
float headBody  = ta.valuewhen(headBar, bodySz, 0)
float headOpen  = ta.valuewhen(headBar, o, 0)
float quietCum  = ta.cum(quiet ? 1.0 : 0.0)
float quietAtHd = ta.valuewhen(headBar, quietCum, 0)
float baseHi    = maxFrom(headBar[1], h)
bool xBaseRev = sinceHead >= 3 and sinceHead <= 10 and quietCum[1] - quietAtHd >= (sinceHead - 1) / 2.0 and baseHi[1] < headOpen and up and bodySz >= headBody * 0.7 and c > baseHi[1]
 
// EMA 8 pullback breakout: established uptrend (EMA 8 > EMA 21, no close under EMA 21 for 10 bars),
// a touch of EMA 8 in the last 3 bars, then a white close above the 3-bar high
bool  touch8  = l <= e8 + atrV * 0.1
bool  touched = within(touch8, 3)
float hi3     = ta.highest(h, 3)
bool  e8Raw   = e8 > e21 and under21 == 0 and touched[1] and up and c > hi3[1]
bool  e8Seen  = within(e8Raw, 8)
bool xE8Pull = e8Raw and not e8Seen[1]
 
// Rising EMA curve breakout: EMA 8 rising and accelerating (3-bar slope above the previous one) and above EMA 21,
// price held within 0.3 ATR of EMA 8 in 5 of the last 6 bars and touched it in the last 4, at least 2 down closes in the
// prior 5 bars, then a white close above the 5-bar high
float cvSlope = e8 - e8[3]
bool  cvAcc   = cvSlope > 0 and cvSlope > cvSlope[1]
bool  cvNear  = l <= e8 + atrV * 0.3
bool  cvTouch = within(cvNear, 4)
float cvHold  = math.sum(c >= e8 - atrV * 0.3 ? 1 : 0, 6)
float cvDn5   = math.sum(c < c[1] ? 1 : 0, 5)
float cvHi5   = ta.highest(h, 5)
bool  cvBrk   = up and c > cvHi5[1] and c[1] <= cvHi5[2]
bool  cvRaw  = cvAcc and e8 > e21 and cvTouch and cvHold >= 5 and cvDn5[1] >= 2 and cvBrk
bool  cvSeen = within(cvRaw, 2)
bool xCurve = cvRaw and not cvSeen[1]
 
// MA retest breakout: close crosses above SMA 50 / 200, within 3-15 bars price comes back within
// 0.5 ATR of it without closing more than 0.25 ATR below, then closes above the 5-bar high
bool  up50     = ta.crossover(c, s50)
bool  up200    = ta.crossover(c, s200)
int   since50  = ta.barssince(up50)
int   since200 = ta.barssince(up200)
float lowSince50  = minFrom(up50, l)
float lowSince200 = minFrom(up200, l)
float clsSince50  = minFrom(up50, c)
float clsSince200 = minFrom(up200, c)
float hi5      = ta.highest(h, 5)
bool  newHi5   = c > hi5[1] and c[1] <= hi5[2]
bool  rt50  = since50 >= 3 and since50 <= 15 and lowSince50 <= s50 + atrV * 0.5 and clsSince50 >= s50 - atrV * 0.25
bool  rt200 = since200 >= 3 and since200 <= 15 and lowSince200 <= s200 + atrV * 0.5 and clsSince200 >= s200 - atrV * 0.25
bool  rtRaw   = (rt50 or rt200) and newHi5 and up and volOk
bool  rtSeen  = within(rtRaw, 15)
bool xMaRetest = rtRaw and not rtSeen[1]
 
// =====================================================================================
// OUTPUT
// =====================================================================================
bool setOn = displaySet != "Classic candles only"
bool clsOn = displaySet != "Setups only"
bool onDoji    = useDojiSet and setOn
bool onGap     = useGapSet and setOn
bool onPrice   = usePriceSet and setOn
bool onClassic = useClassic and clsOn
isInfoK(string k) => k == "U:Bullish Engulfing" or k == "D:Bearish Engulfing" or k == "D:Hanging Man" or k == "U:Piercing Line" or k == "D:Dark Cloud Cover" or k == "U:Bullish Harami" or k == "D:Bearish Harami" or k == "U:Morning Star" or k == "D:Evening Star" or k == "D:Shooting Star"
join(string s, bool ok, string n) => ok ? (s == "" ? n : s + "\n" + n) : s
 
string bullTxt = ""   // drawn below the bar
string bearTxt = ""   // drawn above the bar
if onDoji
    bearTxt := join(bearTxt, xDojiGapDown, "Overbought Doji Gap-Down")
    bullTxt := join(bullTxt, xDojiGapUp, "Oversold Doji Gap-Up")
    bullTxt := join(bullTxt, xDojiEngUp, "Doji + Bullish Engulfing")
    bearTxt := join(bearTxt, xDojiEngDown, "Doji + Bearish Engulfing")
    bullTxt := join(bullTxt, xClusterUp, "Doji Cluster Breakout")
    bearTxt := join(bearTxt, xClusterDown and showWeak, "Doji Cluster Breakdown")
    bullTxt := join(bullTxt, xContUp, "Bullish Doji Continuation")
    bearTxt := join(bearTxt, xContDown, "Bearish Doji Continuation")
    bullTxt := join(bullTxt, xStarCont, "Morning Star Continuation")
if onGap
    bearTxt := join(bearTxt, xGapKickDown, "Bearish Doji Gap Kicker")
    bearTxt := join(bearTxt, xKickDown, "Bearish Kicker")
    bullTxt := join(bullTxt, xGapKickUp, "Bullish Doji Gap Kicker")
    bullTxt := join(bullTxt, xKickUp, "Bullish Kicker")
if onPrice
    bullTxt := join(bullTxt, xSpring, "Spring Reversal")
    bullTxt := join(bullTxt, xRoundBot, "Rounding Bottom")
    bullTxt := join(bullTxt, xHook, "Pullback Hook Breakout")
    bullTxt := join(bullTxt, xCupHandle and showWeak, "Cup & Handle Breakout")
    bearTxt := join(bearTxt, xBeltDown, "Bearish Belt Hold")
    bullTxt := join(bullTxt, xBeltUp, "Bullish Belt Hold")
    bearTxt := join(bearTxt, xRoundTop, "Rounding Top")
    bullTxt := join(bullTxt, xBaseRev and baseShow, "Base Reversal")
    bullTxt := join(bullTxt, xCurve, "Rising EMA Curve Breakout")
    bullTxt := join(bullTxt, xE8Pull, "EMA 8 Pullback Breakout")
    bullTxt := join(bullTxt, xMaRetest, "MA Retest Breakout")
if onClassic
    bullTxt := join(bullTxt, usePlainDoji and isDoji, "Doji")
    bullTxt := join(bullTxt, pEngUp, "Bullish Engulfing")
    bearTxt := join(bearTxt, pEngDown, "Bearish Engulfing")
    bullTxt := join(bullTxt, hamDone, "Hammer ✔")
    bullTxt := join(bullTxt, pHammerQ, "Hammer")
    bearTxt := join(bearTxt, pHangingOB, "Hanging Man")
    bullTxt := join(bullTxt, pPiercing, "Piercing Line")
    bearTxt := join(bearTxt, pDarkCloud, "Dark Cloud Cover")
    bullTxt := join(bullTxt, pHaramiUp, "Bullish Harami")
    bearTxt := join(bearTxt, pHaramiDown, "Bearish Harami")
    bullTxt := join(bullTxt, pMorning, "Morning Star")
    bearTxt := join(bearTxt, pEvening, "Evening Star")
    bearTxt := join(bearTxt, pShooterOB, "Shooting Star")
    bullTxt := join(bullTxt, pInvHamQ, "Inverted Hammer")
 
// ─────────────── Early warning & confirmation ───────────────
// warning: a reversal-type candle at support (resistance) while the Stochastic is stretched
bool revUpBar = isDoji or isSpin or hamForm or invForm or engUp or pHaramiUp or pPiercing or pMorning or (span > 0 and wickDn >= span * 0.5)
bool revDnBar = isDoji or isSpin or hamForm or invForm or engDown or pHaramiDown or pDarkCloud or pEvening or (span > 0 and wickUp >= span * 0.5)
bool warnUp = useWarn and revUpBar and atSup and weakLo
bool warnDn = useWarn and revDnBar and atRes and weakHi and not warnUp
// confirmation: the next bar closes beyond the warning bar's body, with the Stochastic turning
// or a strong reversal bar straight off a stretched support (resistance): it confirms itself
// (a long white body, or a wide bar that rejects the low / high and closes beyond the prior extreme)
bool bullRej = span >= atrV and c > c[1] and (c - l) >= span * 0.6
bool bearRej = span >= atrV and c < c[1] and (h - c) >= span * 0.6
bool volIn = na(volAvg) or volAvg == 0 or volume >= volAvg
// a confirmed turn needs a deep stretch: Stochastic below 20 (above 80) within the last 3 bars
float stLo3 = ta.lowest(stK, 3)
float stHi3 = ta.highest(stK, 3)
bool confUpRaw = useConf and volIn and stK > stD and stLo3 < 20 and ((warnUp[1] and up and c > bTop[1] and c > c[1] and stK > stK[1]) or (atSup[1] and weakLo[1] and (strongUp or bullRej) and c > h[1] and stK > stK[1]))
bool confDnRaw = useConf and volIn and c < e8 and e8 < e8[1] and stK < stD and stHi3 > 80 and ((warnDn[1] and down and c < bBot[1] and c < c[1] and stK < stK[1]) or (atRes[1] and weakHi[1] and (strongDn or bearRej) and c < l[1] and stK < stK[1]))
// one confirmation per turn: ignore a repeat within 3 bars
bool confUpSeen = within(confUpRaw, 3)
bool confDnSeen = within(confDnRaw, 3)
bool confUp = confUpRaw and not confUpSeen[1]
bool confDn = confDnRaw and not confDnSeen[1]
bool starUp = useDiv and divUpNear
bool starDn = useDiv and divDnNear
 
// One name per bar: the first true condition in this priority list
string key = ""
key := key == "" and onDoji and xDojiGapDown  ? "D:Overbought Doji Gap-Down" : key
key := key == "" and onDoji and xDojiGapUp    ? "U:Oversold Doji Gap-Up" : key
key := key == "" and onDoji and xDojiEngUp    ? "U:Doji + Bullish Engulfing" : key
key := key == "" and onDoji and xDojiEngDown  ? "D:Doji + Bearish Engulfing" : key
key := key == "" and onDoji and xClusterUp    ? "U:Doji Cluster Breakout" : key
key := key == "" and onDoji and showWeak and xClusterDown  ? "D:Doji Cluster Breakdown" : key
key := key == "" and onDoji and xContUp       ? "U:Bullish Doji Continuation" : key
key := key == "" and onDoji and xContDown     ? "D:Bearish Doji Continuation" : key
key := key == "" and onDoji and xStarCont     ? "U:Morning Star Continuation" : key
key := key == "" and onGap and xGapKickDown   ? "D:Bearish Doji Gap Kicker" : key
key := key == "" and onGap and xKickDown      ? "D:Bearish Kicker" : key
key := key == "" and onGap and xGapKickUp     ? "U:Bullish Doji Gap Kicker" : key
key := key == "" and onGap and xKickUp        ? "U:Bullish Kicker" : key
key := key == "" and onPrice and xSpring      ? "U:Spring Reversal" : key
key := key == "" and onPrice and xRoundBot ? "U:Rounding Bottom" : key
key := key == "" and onPrice and xHook        ? "U:Pullback Hook Breakout" : key
key := key == "" and onPrice and showWeak and xCupHandle   ? "U:Cup & Handle Breakout" : key
key := key == "" and onPrice and xBeltDown    ? "D:Bearish Belt Hold" : key
key := key == "" and onPrice and xBeltUp      ? "U:Bullish Belt Hold" : key
key := key == "" and onPrice and xRoundTop    ? "D:Rounding Top" : key
key := key == "" and onPrice and baseShow and xBaseRev     ? "U:Base Reversal" : key
key := key == "" and onPrice and xCurve       ? "U:Rising EMA Curve Breakout" : key
key := key == "" and onPrice and xE8Pull      ? "U:EMA 8 Pullback Breakout" : key
key := key == "" and onPrice and xMaRetest    ? "U:MA Retest Breakout" : key
key := key == "" and onClassic and usePlainDoji and isDoji ? "U:Doji" : key
key := key == "" and onClassic and pEngUp        ? "U:Bullish Engulfing" : key
key := key == "" and onClassic and pEngDown      ? "D:Bearish Engulfing" : key
key := key == "" and onClassic and hamDone ? "U:Hammer ✔" : key
key := key == "" and onClassic and pHammerQ ? "U:Hammer" : key
key := key == "" and onClassic and pHangingOB    ? "D:Hanging Man" : key
key := key == "" and onClassic and pPiercing     ? "U:Piercing Line" : key
key := key == "" and onClassic and pDarkCloud    ? "D:Dark Cloud Cover" : key
key := key == "" and onClassic and pHaramiUp     ? "U:Bullish Harami" : key
key := key == "" and onClassic and pHaramiDown   ? "D:Bearish Harami" : key
key := key == "" and onClassic and pMorning      ? "U:Morning Star" : key
key := key == "" and onClassic and pEvening      ? "D:Evening Star" : key
key := key == "" and onClassic and pShooterOB    ? "D:Shooting Star" : key
key := key == "" and onClassic and pInvHamQ ? "U:Inverted Hammer" : key
// a confirmed reversal with no named pattern on that bar gets a name from its context
key := key == "" and confUp ? "U:Bullish Reversal" : key
key := key == "" and confDn and showWeak ? (utCtx ? "D:Upthrust Reversal" : "D:Bearish Reversal") : key
// Bullish Reversal while the market index is falling: shown in grey as a weaker signal
bool revWeak = useMkt and not mktUp and key == "U:Bullish Reversal"
// classic candles: colour and arrow only when support / resistance, the stretch and the market agree
bool clsCtxUp  = atSup and weakLo and mktUp
bool clsCtxDn  = atRes and weakHi and mktDn
bool clsCtx    = str.startswith(key, "U:") ? clsCtxUp : clsCtxDn
bool isInfoKey = classicInfo and singleName and isInfoK(key) and not clsCtx
if singleName
    bullTxt := str.startswith(key, "U:") ? str.substring(key, 2) : ""
    bearTxt := str.startswith(key, "D:") ? str.substring(key, 2) : ""
 
bool live = not closedOnly or barstate.isconfirmed
 
// Colour theme: follow the chart background (or a forced choice)
float lum = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color)
bool darkBg = themeSel == "Dark background" or (themeSel == "Auto" and lum < 128)
color colUp    = darkBg ? color.lime : #089981
color colDn    = darkBg ? color.red : #d50000
color colBox   = darkBg ? color.new(#131722, 10) : color.new(#ffffff, 5)
color colText  = darkBg ? color.white : #131722
color colHead  = darkBg ? color.silver : #787b86
color colEdge  = darkBg ? color.new(color.gray, 40) : color.new(#787b86, 60)
color colLine  = darkBg ? color.gray : #5d606b
color colDoji  = darkBg ? color.silver : #787b86     // plain Doji: neutral
color colWarn  = darkBg ? color.yellow : #f9a825      // early warning
int fontIdx = nameSize <= 8 ? 0 : 1
int arrowIdx = switch arrowSel
    "Tiny"   => 0
    "Small"  => 1
    "Normal" => 2
    "Large"  => 3
    => 4
// one word per line when requested
shape(string t) =>
    string r = splitWords ? str.replace_all(t, " ", "\n") : t
    splitWords ? str.replace_all(r, "\n\n", "\n") : r
blank(int n) =>
    string r = ""
    if n > 0
        for i = 1 to n
            r += "\n"
    r
// multi-name mode: neighbouring labels are pushed further away so they do not overlap
int padBase = arrowIdx + 1 + (fontIdx == 0 ? 1 : 0)
var float bullY = na
var float bearY = na
var int bullBar = na
var int bearBar = na
var int bullPad = 0
var int bearPad = 0
var int bullRows = 0
var int bearRows = 0
if live and bullTxt != ""
    string t1 = shape(str.replace_all(bullTxt, "\n", "\n·\n"))
    bool close1 = offsetNear and not na(bullBar) and bar_index - bullBar <= 2
    bullPad := close1 ? bullPad + bullRows + 1 : padBase
    bullY := close1 ? math.min(low, bullY) : low
    if bullPad > 16
        bullPad := padBase
        bullY := low
    bullRows := array.size(str.split(t1, "\n"))
    bullBar := bar_index
    if nameMode == "Name" and not singleName
        label.new(bar_index, bullY, blank(bullPad) + t1, yloc=yloc.price, color=color.new(color.black, 100), textcolor=colUp, style=label.style_label_up, size=nameSize, tooltip=bullTxt)
if live and bearTxt != ""
    string t2 = shape(str.replace_all(bearTxt, "\n", "\n·\n"))
    bool close2 = offsetNear and not na(bearBar) and bar_index - bearBar <= 2
    bearPad := close2 ? bearPad + bearRows + 1 : padBase
    bearY := close2 ? math.max(high, bearY) : high
    if bearPad > 16
        bearPad := padBase
        bearY := high
    bearRows := array.size(str.split(t2, "\n"))
    bearBar := bar_index
    if nameMode == "Name" and not singleName
        label.new(bar_index, bearY, t2 + blank(bearPad), yloc=yloc.price, color=color.new(color.black, 100), textcolor=colDn, style=label.style_label_down, size=nameSize, tooltip=bearTxt)
 
// ─────────────── Notes (tooltip and panel) ───────────────
note(string k, bool ar) =>
    switch k
        "D:Overbought Doji Gap-Down" => ar ? "شمعة تردد بعد صعود ممتد (الستوكاستك فوق 75 أو قرب قمة 20 شمعة) عند مقاومة، ثم افتتاح بفجوة تحت قاعها وإغلاق هابط.\nالتردد في القمة حُسم لصالح البائعين.\nيُلغى إذا عاد السعر فوق قمة شمعة التردد." : "An indecision bar after a stretched advance (Stochastic above 75 or near the 20-bar high) at resistance, then an open gapping below its low and a lower close.\nIndecision at the high was settled by sellers.\nVoid if price trades back above the indecision bar's high."
        "U:Oversold Doji Gap-Up" => ar ? "شمعة تردد بعد هبوط ممتد (الستوكاستك تحت 25 أو قرب قاع 20 شمعة) عند دعم، ثم افتتاح بفجوة فوق قمتها وإغلاق صاعد.\nالتردد في القاع حُسم لصالح المشترين.\nيُلغى إذا عاد السعر تحت شمعة التردد." : "An indecision bar after a stretched decline (Stochastic below 25 or near the 20-bar low) at support, then an open gapping above its high and a higher close.\nIndecision at the low was settled by buyers.\nVoid if price falls back below the indecision bar."
        "U:Doji + Bullish Engulfing" => ar ? "شمعة تردد عند قاع ممتد، ثم ابتلاع شرائي طوله 0.8 ATR على الأقل.\nالتوقف ثم الابتلاع أقوى من الابتلاع وحده.\nيضعف إذا أغلق السعر تحت منتصف جسم شمعة الابتلاع." : "An indecision bar at a stretched low, then a Bullish Engulfing candle at least 0.8 ATR long.\nThe pause plus the engulf is stronger than the engulf alone.\nWeakens on a close below the middle of the engulfing body."
        "D:Doji + Bearish Engulfing" => ar ? "شمعة تردد عند قمة ممتدة، ثم ابتلاع بيعي طوله 0.8 ATR على الأقل.\nالتوقف ثم الابتلاع أقوى من الابتلاع وحده.\nيضعف إذا أغلق السعر فوق منتصف جسم شمعة الابتلاع." : "An indecision bar at a stretched high, then a Bearish Engulfing candle at least 0.8 ATR long.\nThe pause plus the engulf is stronger than the engulf alone.\nWeakens on a close above the middle of the engulfing body."
        "U:Doji Cluster Breakout" => ar ? "ثلاث شموع تردد أو أكثر خلال 5 شموع داخل نطاق لا يتجاوز 1.5 ATR بعد هبوط، ثم إغلاق فوق النطاق بربع ATR.\nانتهت مرحلة التردد بخروج لأعلى.\nيُلغى إذا عاد السعر داخل النطاق." : "Three or more indecision bars within 5, packed inside 1.5 ATR after a decline, then a close a quarter ATR above the box.\nThe indecision phase resolved upward.\nVoid if price returns inside the box."
        "D:Doji Cluster Breakdown" => ar ? "ثلاث شموع تردد أو أكثر خلال 5 شموع داخل نطاق لا يتجاوز 1.5 ATR بعد صعود، ثم إغلاق تحت النطاق بربع ATR.\nانتهت مرحلة التردد بخروج لأسفل.\nيُلغى إذا عاد السعر داخل النطاق." : "Three or more indecision bars within 5, packed inside 1.5 ATR after an advance, then a close a quarter ATR below the box.\nThe indecision phase resolved downward.\nVoid if price returns inside the box."
        "U:Bullish Doji Continuation" => ar ? "شمعة بيضاء قوية، توقف قصير يحافظ على نصفها العلوي، ثم شمعة بيضاء قوية تغلق فوق قمتها.\nالتوقف لم يوقف الصعود: احتمال استمرار نحو المقاومة التالية." : "A strong white bar, a short pause that holds its upper half, then another strong white bar closing above its high.\nThe pause did not stop the rise: likely continuation toward the next resistance."
        "D:Bearish Doji Continuation" => ar ? "في اتجاه هابط (EMA 8 تحت EMA 21): شمعة سوداء قوية، توقف قصير يبقى في نصفها السفلي، ثم شمعة سوداء قوية تغلق تحت إغلاق الشمعتين.\nالتوقف لم يوقف الهبوط: احتمال استمرار نحو الدعم التالي." : "In a downtrend (EMA 8 below EMA 21): a strong black bar, a short pause that stays in its lower half, then another strong black bar closing below both closes.\nThe pause did not stop the fall: likely continuation toward the next support."
        "U:Morning Star Continuation" => ar ? "نجمة صباح، ثم خلال 6 شموع شمعة بيضاء قوية تغلق فوق كل ما تداول منذ النجمة.\nانعكاس تبعه تأكيد واضح.\nيضعف إذا عاد السعر تحت قاع النجمة." : "A Morning Star, then within 6 bars a strong white bar closing above everything traded since the star.\nA reversal with clear follow-through.\nWeakens if price returns below the star's low."
        "U:Bullish Kicker" => ar ? "شمعة سوداء قوية الجسم، ثم شمعة بيضاء قوية الجسم تفتح عند افتتاح السوداء أو فوقه.\nتحوّل مفاجئ في المعنويات.\nيُلغى إذا تداول السعر تحت افتتاح الشمعة السوداء." : "A solid black bar, then a solid white bar opening at or above the black bar's open.\nA sudden change in sentiment.\nVoid if price trades below the black bar's open."
        "D:Bearish Kicker" => ar ? "شمعة بيضاء قوية الجسم، ثم شمعة سوداء قوية الجسم تفتح عند افتتاح البيضاء أو تحته.\nتحوّل مفاجئ في المعنويات.\nيُلغى إذا تداول السعر فوق افتتاح الشمعة البيضاء." : "A solid white bar, then a solid black bar opening at or below the white bar's open.\nA sudden change in sentiment.\nVoid if price trades above the white bar's open."
        "U:Bullish Doji Gap Kicker" => ar ? "شمعة سوداء قوية، ثم شمعة تردد تبقى فوق إغلاقها، ثم شمعة بيضاء قوية تفتح فوق جسم التردد وتغلق فوق افتتاح السوداء.\nالهبوط لم يجد متابعة.\nيُلغى إذا تداول السعر تحت شمعة التردد." : "A strong black bar, an indecision bar holding above its close, then a strong white bar opening above the indecision body and closing above the black bar's open.\nThe drop found no follow-through.\nVoid if price trades below the indecision bar."
        "D:Bearish Doji Gap Kicker" => ar ? "شمعة بيضاء قوية، ثم شمعة تردد تبقى تحت إغلاقها، ثم شمعة سوداء قوية تفتح تحت جسم التردد وتغلق تحت افتتاح البيضاء.\nالصعود لم يجد متابعة.\nيُلغى إذا تداول السعر فوق شمعة التردد." : "A strong white bar, an indecision bar holding below its close, then a strong black bar opening below the indecision body and closing below the white bar's open.\nThe rise found no follow-through.\nVoid if price trades above the indecision bar."
        "U:Spring Reversal" => ar ? "قاعدة ضيقة (10 شموع)، كسر تحتها لا يتجاوز 3 ATR، ثم إغلاق أعلى يعيد السعر فوق منتصف القاعدة ويرفض الكسر.\nالكسر استنفد البائعين (Spring بمصطلح Wyckoff).\nيُلغى بإغلاق تحت أدنى نقطة في الكسر." : "A tight 10-bar shelf, a break of up to 3 ATR beneath it, then a close back above the middle of the shelf that rejects the break.\nThe break exhausted sellers (a Wyckoff Spring).\nVoid on a close below the low of the break."
        "U:Rounding Bottom" => ar ? "السعر قضى أغلب آخر 25 شمعة تحت EMA 21 والقاع في منتصف الفترة، وانعطف EMA 8 للأعلى، ثم شمعة بيضاء قوية تخترق قمة آخر 10 شموع.\nالبيع تلاشى تدريجياً قبل أن يعود الطلب.\nيضعف إذا عاد السعر تحت EMA 21." : "Price spent most of the last 25 bars below EMA 21 with the low inside that span, EMA 8 has turned up, then a strong white bar clears the 10-bar high.\nSelling faded gradually before demand returned.\nWeakens if price falls back below EMA 21."
        "U:Pullback Hook Breakout" => ar ? "صعود قوي لا يقل عن 5 ATR، تراجع بين 25% و62% منه، ثم أول شمعة بيضاء تغلق فوق قمة السابقة قرب قاع التراجع.\nالتصحيح كان استراحة وليس انعكاساً. الهدف الأول: القمة السابقة.\nيُلغى بإغلاق تحت قاع التراجع." : "A strong run of at least 5 ATR, a 25–62% pullback, then the first white bar closing above the prior high near the pullback low.\nThe pullback was a rest, not a reversal. First target: the recent peak.\nVoid on a close below the pullback low."
        "U:Cup & Handle Breakout" => ar ? "حافة يسرى، كوب بعمق 4 ATR على الأقل، جانب أيمن يعود قرب الحافة، ومقبض في الجزء العلوي من الكوب، ثم إغلاق فوق المقبض.\nاختراق بعد تجميع منظم.\nيضعف إذا عاد السعر تحت قاع المقبض." : "A left rim, a cup at least 4 ATR deep, a right side back near the rim and a handle in the upper part of the cup, then a close above the handle.\nA breakout after orderly accumulation.\nWeakens if price falls back below the handle low."
        "U:Bullish Belt Hold" => ar ? "بعد هبوط ممتد: شمعة بيضاء تفتح عند قاعها تقريباً وجسمها 1.5 ATR على الأقل.\nالمشترون سيطروا من أول التداول.\nيضعف إذا أغلق السعر تحت الشمعة." : "After a stretched decline: a white bar opening at or near its low with a body of at least 1.5 ATR.\nBuyers were in control from the open.\nWeakens on a close below the bar."
        "D:Bearish Belt Hold" => ar ? "بعد صعود ممتد: شمعة سوداء تفتح عند قمتها تقريباً وجسمها 1.5 ATR على الأقل.\nالبائعون سيطروا من أول التداول.\nيضعف إذا أغلق السعر فوق الشمعة." : "After a stretched advance: a black bar opening at or near its high with a body of at least 1.5 ATR.\nSellers were in control from the open.\nWeakens on a close above the bar."
        "D:Rounding Top" => ar ? "السعر قضى أغلب آخر 25 شمعة فوق EMA 21 والقمة في منتصف الفترة، وانعطف EMA 8 للأسفل، ثم شمعة سوداء قوية تكسر قاع آخر 10 شموع.\nالشراء تلاشى تدريجياً قبل أن يعود العرض.\nيضعف إذا عاد السعر فوق EMA 21." : "Price spent most of the last 25 bars above EMA 21 with the high inside that span, EMA 8 has turned down, then a strong black bar breaks the 10-bar low.\nBuying faded gradually before supply returned.\nWeakens if price climbs back above EMA 21."
        "U:Base Reversal" => ar ? "شمعة سوداء كبيرة عند قاع ممتد، ثم 3 إلى 10 شموع أغلبها تردد تحت افتتاحها، ثم شمعة بيضاء لا تقل عن 70% من حجمها تغلق فوق القاعدة.\nالهبوط امتُصّ داخل القاعدة.\nيضعف بإغلاق تحت منتصف الشمعة البيضاء." : "A large black bar at a stretched low, 3–10 mostly indecisive bars below its open, then a white bar at least 70% of its size closing above the base.\nThe drop was absorbed inside the base.\nWeakens on a close below the middle of the white bar."
        "U:Rising EMA Curve Breakout" => ar ? "EMA 8 يتسارع صعوداً فوق EMA 21 والسعر مستند عليه، تراجع قصير (إغلاقان هابطان على الأقل)، ثم إغلاق أبيض فوق قمة آخر 5 شموع.\nاتجاه صاعد منتظم يستأنف.\nيضعف بإغلاق تحت EMA 8." : "EMA 8 is accelerating upward above EMA 21 with price riding it, a short dip (at least two lower closes), then a white close above the 5-bar high.\nAn orderly uptrend resuming.\nWeakens on a close below EMA 8."
        "U:EMA 8 Pullback Breakout" => ar ? "اتجاه صاعد (EMA 8 فوق EMA 21 ولا إغلاق تحت EMA 21 لعشر شموع)، ملامسة EMA 8، ثم إغلاق أبيض فوق قمة 3 شموع.\nالتراجع وجد دعماً عند المتوسط.\nيضعف بإغلاق تحت EMA 8." : "An uptrend (EMA 8 above EMA 21, no close below EMA 21 for 10 bars), a touch of EMA 8, then a white close above the 3-bar high.\nThe pullback found support at the average.\nWeakens on a close below EMA 8."
        "U:MA Retest Breakout" => ar ? "إغلاق فوق المتوسط 50 أو 200، ثم إعادة اختبار له خلال 3 إلى 15 شمعة دون إغلاق واضح تحته، ثم إغلاق فوق قمة 5 شموع.\nالمتوسط تحوّل من مقاومة إلى دعم.\nيضعف إذا عاد الإغلاق تحت المتوسط." : "A close above SMA 50 or 200, a retest within 3–15 bars without a clear close beneath it, then a close above the 5-bar high.\nThe average turned from resistance into support.\nWeakens if closes slip back under the average."
        "U:Bullish Reversal" => ar ? "إنذار مبكر (نقطة صفراء) عند دعم والستوكاستك في التشبع البيعي، ثم شمعة بيضاء تغلق فوق جسمه والستوكاستك يتجه للأعلى (✔).\nانعكاس صاعد مؤكد.\nيُلغى بإغلاق تحت قاع شمعة الإنذار." : "An early-warning bar (yellow dot) at support with Stochastic oversold, then a white bar closing above its body with Stochastic turning up (✔).\nA confirmed bullish turn.\nVoid on a close below the warning bar's low."
        "D:Bearish Reversal" => ar ? "إنذار مبكر (نقطة صفراء) عند مقاومة والستوكاستك في التشبع الشرائي، ثم شمعة سوداء تغلق تحت جسمه والستوكاستك يتجه للأسفل (✔).\nانعكاس هابط مؤكد.\nيُلغى بإغلاق فوق قمة شمعة الإنذار." : "An early-warning bar (yellow dot) at resistance with Stochastic overbought, then a black bar closing below its body with Stochastic turning down (✔).\nA confirmed bearish turn.\nVoid on a close above the warning bar's high."
        "D:Upthrust Reversal" => ar ? "قاعدة ضيقة (10 شموع)، اختراق قصير فوقها لا يتجاوز 3 ATR، ثم انعكاس هابط مؤكد (✔).\nالاختراق استنفد المشترين (Upthrust بمصطلح Wyckoff).\nيُلغى بإغلاق فوق أعلى نقطة في الاختراق." : "A tight 10-bar shelf, a brief break of up to 3 ATR above it, then a confirmed bearish turn (✔).\nThe break exhausted buyers (a Wyckoff Upthrust).\nVoid on a close above the high of the break."
        "U:Doji" => ar ? "الافتتاح والإغلاق متساويان تقريباً: توازن بين المشترين والبائعين.\nالدوجي وحده ليس إشارة؛ معناه يأتي من مكانه. انتظر الشمعة التالية." : "Open and close are almost equal: buyers and sellers in balance.\nA Doji alone is not a signal; its meaning comes from where it appears. Let the next bar show the direction."
        "U:Bullish Engulfing" => ar ? "جسم أبيض يغطي جسم الشمعة السوداء السابقة كاملاً.\nانتقال السيطرة إلى المشترين؛ أقوى بعد هبوط وعند دعم." : "A white body covers the whole previous black body.\nControl passes to buyers; stronger after a decline and at support."
        "D:Bearish Engulfing" => ar ? "جسم أسود يغطي جسم الشمعة البيضاء السابقة كاملاً.\nانتقال السيطرة إلى البائعين؛ أقوى بعد صعود وعند مقاومة." : "A black body covers the whole previous white body.\nControl passes to sellers; stronger after an advance and at resistance."
        "U:Hammer" => ar ? "جسم صغير وذيل سفلي طويل والستوكاستك تحت 20، عند قاع 20 شمعة أو دعم سابق.\nمراقبة فقط (أصفر): المطرقة وحدها أقل موثوقية من المؤكدة.\nالإشارة: إغلاق الشمعة التالية فوق قمة المطرقة (Hammer ✔)." : "A small body with a long lower shadow and Stochastic under 20, at the 20-bar low or a swing support.\nWatch only (yellow): an unconfirmed Hammer is less reliable than a confirmed one.\nThe signal: the next bar closes above the Hammer's high (Hammer ✔)."
        "U:Hammer ✔" => ar ? "مطرقة عند دعم، ثم شمعة تغلق فوق قمتها.\nالمشترون تابعوا الارتداد، وهذا ما يجعل المطرقة إشارة.\nيُلغى بإغلاق تحت قاع المطرقة." : "A Hammer at support, then a bar closing above its high.\nBuyers followed through, which is what turns a Hammer into a signal.\nVoid on a close below the Hammer's low."
        "U:Hanging Man" => ar ? "نفس شكل المطرقة لكن بعد صعود.\nتحذير من ضعف الطلب؛ يحتاج تأكيداً بإغلاق أدنى." : "The Hammer shape, but after a rise.\nA warning that demand is thinning; needs a lower close to confirm."
        "D:Hanging Man" => ar ? "نفس شكل المطرقة لكن بعد صعود والستوكاستك فوق 80.\nتحذير من ضعف الطلب؛ يحتاج تأكيداً بإغلاق أدنى." : "The Hammer shape, but after a rise with Stochastic above 80.\nA warning that demand is thinning; needs a lower close to confirm."
        "U:Piercing Line" => ar ? "سوداء طويلة، ثم بيضاء طويلة تفتح تحت إغلاقها وتغلق فوق منتصف جسمها.\nالمشترون استعادوا أكثر من نصف الخسارة." : "A long black bar, then a long white bar opening below its close and closing above its midpoint.\nBuyers recovered more than half of the loss."
        "D:Dark Cloud Cover" => ar ? "بيضاء طويلة، ثم سوداء طويلة تفتح فوق إغلاقها وتغلق تحت منتصف جسمها.\nالبائعون محوا أكثر من نصف المكسب." : "A long white bar, then a long black bar opening above its close and closing below its midpoint.\nSellers erased more than half of the gain."
        "U:Bullish Harami" => ar ? "سوداء طويلة يتبعها جسم أبيض صغير داخل جسمها.\nزخم الهبوط توقف؛ إشارة مبكرة تحتاج تأكيداً." : "A long black bar followed by a small white body inside it.\nDownside momentum has stalled; an early signal that needs confirmation."
        "D:Bearish Harami" => ar ? "بيضاء طويلة يتبعها جسم أسود صغير داخل جسمها.\nزخم الصعود توقف؛ إشارة مبكرة تحتاج تأكيداً." : "A long white bar followed by a small black body inside it.\nUpside momentum has stalled; an early signal that needs confirmation."
        "U:Morning Star" => ar ? "سوداء طويلة، نجمة صغيرة تحت جسمها، ثم بيضاء تغلق فوق منتصف الأولى.\nانعكاس صاعد من ثلاث شموع." : "A long black bar, a small star below its body, then a white bar closing above the first one's midpoint.\nThree-bar bullish reversal."
        "D:Evening Star" => ar ? "بيضاء طويلة، نجمة صغيرة فوق جسمها، ثم سوداء تغلق تحت منتصف الأولى.\nانعكاس هابط من ثلاث شموع." : "A long white bar, a small star above its body, then a black bar closing below the first one's midpoint.\nThree-bar bearish reversal."
        "U:Shooting Star" => ar ? "افتتاح فوق قمة الشمعة السابقة والستوكاستك فوق 80، ثم ظل علوي طويل وجسم صغير.\nالصعود رُفض؛ يحتاج تأكيداً بإغلاق أدنى." : "Opens above the previous high with Stochastic above 80, then leaves a long upper shadow and a small body.\nThe rally was rejected; needs a lower close to confirm."
        "D:Shooting Star" => ar ? "افتتاح فوق قمة الشمعة السابقة والستوكاستك فوق 80، ثم ظل علوي طويل وجسم صغير.\nالصعود رُفض؛ يحتاج تأكيداً بإغلاق أدنى." : "Opens above the previous high with Stochastic above 80, then leaves a long upper shadow and a small body.\nThe rally was rejected; needs a lower close to confirm."
        "U:Inverted Hammer" => ar ? "شمعة واسعة (1.2 ATR أو أكثر) ظلها العلوي 60% منها على الأقل وبلا ظل سفلي تقريباً، وقاعها ضمن 1 ATR من قاع آخر 20 شمعة.\nالمشترون دفعوا السعر بقوة من القاع؛ البائعون ردّوه لكن دون كسر القاع.\nيضعف بإغلاق تحت قاعها." : "A wide bar (1.2 ATR or more) whose upper shadow is at least 60% of its range with almost no lower shadow, its low within 1 ATR of the prior 20-bar low.\nBuyers pushed hard off the low; sellers pushed back but did not break it.\nWeakens on a close below its low."
        => ""
 
// wrap long note lines for the panel
wrapText(string s, int n) =>
    string out = ""
    for para in str.split(s, "\n")
        string line = ""
        for wd in str.split(para, " ")
            if line != "" and str.length(line) + str.length(wd) + 1 > n
                out += line + "\n"
                line := wd
            else
                line := line == "" ? wd : line + " " + wd
        out += line + "\n"
    out
 
// one-name mode: names as labels so the text size setting applies
var label nameLbl = na
var int   nameBar = na
var string nameTxt = ""
var string nameTip = ""
var bool  nameBull = true
if live and singleName and key != ""
    bool isBull = str.startswith(key, "U:")
    bool star = key != "U:Doji" and (isBull ? starUp : starDn)
    bool conf = isBull ? confUp : confDn
    string nm = str.substring(key, 2) + (conf and not str.contains(key, "✔") ? " ✔" : "") + (star ? " ★" : "")
    string shown = nameMode == "Name" ? shape(nm) : "ⓘ"
    string nt = noteLang == "Off" ? "" : note(key, noteLang == "العربية")
    string tip = nt == "" ? nm : nm + "\n\n" + nt
    tip := star ? tip + "\n★ RSI divergence." : tip
    tip := isInfoKey ? tip + "\n\nGrey: the context does not agree (support / resistance, Stochastic or market direction), so this is shape information only. رمادي: السياق غير داعم، فهي وصف للشكل فقط." : classicInfo and isInfoK(key) ? tip + "\n\nContext agrees: " + (str.startswith(key, "U:") ? "at support, oversold, market rising." : "at resistance, overbought, market falling.") + " السياق داعم." : tip
    tip := key == "U:Bullish Reversal" ? tip + "\nStop / الوقف: " + str.tostring(math.min(low, low[1]), format.mintick) : tip
    tip := revWeak ? tip + "\n\nMarket (" + mktId + ") EMA 8 is falling: weaker signal. السوق هابط: إشارة أضعف." : tip
    string gap = blank(arrowIdx)
    nameTxt := shown
    nameTip := tip
    nameBull := isBull
    nameBar := bar_index
    nameLbl := label.new(bar_index, isBull ? low : high, isBull ? gap + shown : shown + gap, yloc=isBull ? yloc.belowbar : yloc.abovebar, color=color.new(color.black, 100), textcolor=key == "U:Doji" or revWeak or isInfoKey ? colDoji : (hamConf and key == "U:Hammer") ? colWarn : isBull ? colUp : colDn, style=label.style_none, size=nameSize, tooltip=tip)
 
// Stop line under Bullish Reversal: runs until a close below it or 20 bars
var line  stopLn  = na
var float stopLvR = na
var int   stopBar = na
if live and showStop and singleName and key == "U:Bullish Reversal"
    stopLvR := math.min(low, low[1])
    stopBar := bar_index
    stopLn  := line.new(bar_index - 1, stopLvR, bar_index, stopLvR, color=colDoji, style=line.style_dashed, width=1)
else if live and not na(stopLn)
    line.set_x2(stopLn, bar_index)
    if close < stopLvR or bar_index - stopBar >= 20
        stopLn := na
 
// Notes panel: latest pattern with symbol, timeframe and date
var string lastKey = ""
var int lastTime = na
var bool lastInfo = false
if live and key != ""
    lastKey := key
    lastTime := time
    lastInfo := isInfoKey
string boxPos = panelWhere == "Top right" ? position.top_right : panelWhere == "Bottom left" ? position.bottom_left : panelWhere == "Top left" ? position.top_left : position.bottom_right
var table notesBox = table.new(boxPos, 1, 3, bgcolor=colBox, frame_color=colEdge, frame_width=1, border_width=4)
if barstate.islast and panelOn and lastKey != "" and noteLang != "Off"
    table.set_bgcolor(notesBox, colBox)
    table.set_frame_color(notesBox, colEdge)
    bool arBox = noteLang == "العربية"
    bool upBox = str.startswith(lastKey, "U:")
    string head = syminfo.ticker + "  ·  " + timeframe.period + "  ·  " + str.format_time(lastTime, "yyyy-MM-dd", syminfo.timezone)
    table.cell(notesBox, 0, 0, head, text_color=colHead, text_size=math.max(panelSize - 1, 6))
    table.cell(notesBox, 0, 1, str.substring(lastKey, 2), text_color=lastKey == "U:Doji" or lastInfo ? colDoji : upBox ? colUp : colDn, text_size=panelSize + 2)
    table.cell(notesBox, 0, 2, wrapText(note(lastKey, arBox), 45), text_color=colText, text_size=panelSize, text_halign=arBox ? text.align_right : text.align_left)
 
// Arrows
bool plainDoji = live and bullTxt == "Doji"
bool bullMark = live and bullTxt != "" and not plainDoji and not isInfoKey
plotshape(plainDoji, "Doji mark", shape.diamond, location.belowbar, warnUp ? colWarn : colDoji, size=size.tiny, display=display.pane)
bool warnOnlyUp = live and warnUp and bullTxt == "" and bearTxt == ""
bool warnOnlyDn = live and warnDn and bullTxt == "" and bearTxt == ""
plotshape(warnOnlyUp, "Early warning (bull)", shape.circle, location.belowbar, colWarn, size=size.tiny, display=display.pane)
plotshape(warnOnlyDn, "Early warning (bear)", shape.circle, location.abovebar, colWarn, size=size.tiny, display=display.pane)
bool bearMark = live and bearTxt != "" and not isInfoKey
plotshape(bullMark and arrowSel == "Tiny",   "Bull arrow tiny",   shape.triangleup,   location.belowbar, revWeak ? colDoji : warnUp or (hamConf and bullTxt == "Hammer") ? colWarn : colUp, size=size.tiny, display=display.pane)
plotshape(bullMark and arrowSel == "Small",  "Bull arrow small",  shape.triangleup,   location.belowbar, revWeak ? colDoji : warnUp or (hamConf and bullTxt == "Hammer") ? colWarn : colUp, size=size.small, display=display.pane)
plotshape(bullMark and arrowSel == "Normal", "Bull arrow normal", shape.triangleup,   location.belowbar, revWeak ? colDoji : warnUp or (hamConf and bullTxt == "Hammer") ? colWarn : colUp, size=size.normal, display=display.pane)
plotshape(bullMark and arrowSel == "Large",  "Bull arrow large",  shape.triangleup,   location.belowbar, revWeak ? colDoji : warnUp or (hamConf and bullTxt == "Hammer") ? colWarn : colUp, size=size.large, display=display.pane)
plotshape(bullMark and arrowSel == "Huge",   "Bull arrow huge",   shape.triangleup,   location.belowbar, revWeak ? colDoji : warnUp or (hamConf and bullTxt == "Hammer") ? colWarn : colUp, size=size.huge, display=display.pane)
plotshape(bearMark and arrowSel == "Tiny",   "Bear arrow tiny",   shape.triangledown, location.abovebar, warnDn ? colWarn : colDn, size=size.tiny, display=display.pane)
plotshape(bearMark and arrowSel == "Small",  "Bear arrow small",  shape.triangledown, location.abovebar, warnDn ? colWarn : colDn, size=size.small, display=display.pane)
plotshape(bearMark and arrowSel == "Normal", "Bear arrow normal", shape.triangledown, location.abovebar, warnDn ? colWarn : colDn, size=size.normal, display=display.pane)
plotshape(bearMark and arrowSel == "Large",  "Bear arrow large",  shape.triangledown, location.abovebar, warnDn ? colWarn : colDn, size=size.large, display=display.pane)
plotshape(bearMark and arrowSel == "Huge",   "Bear arrow huge",   shape.triangledown, location.abovebar, warnDn ? colWarn : colDn, size=size.huge, display=display.pane)
 
// Bar colour (bullish = blue, bearish = dark red)
bool hamWatch = hamConf and bullTxt == "Hammer"
bool bullSig = bullTxt != "" and bullTxt != "Doji" and not hamWatch and not revWeak and not isInfoKey   // plain Doji and an unconfirmed Hammer are not bullish alerts
bool bearSig = bearTxt != "" and not isInfoKey
barcolor(paintBars and live ? (bullSig ? color.blue : bearSig ? color.maroon : na) : na)
 
plot(plotE8 ? e8 : na, "EMA 8", color=colLine, linewidth=2)
plot(plotE3 ? e3 : na, "EMA 3", color=color.fuchsia)
plot(plotS20 ? s20 : na, "SMA 20", color=color.silver)
plot(plotS50 ? s50 : na, "SMA 50", color=color.blue)
plot(plotS200 ? s200 : na, "SMA 200", color=color.red)
// signal codes for the Data Window / alerts on plot values (hidden on the chart)
plot(live and key != "" and key != "U:Doji" ? (str.startswith(key, "U:") ? 1 : -1) : 0, "Signal direction", display=display.data_window)
plot(live ? (confUp ? 1 : confDn ? -1 : 0) : 0, "Confirmed reversal", display=display.data_window)
plot(live ? (warnUp ? 1 : warnDn ? -1 : 0) : 0, "Early warning", display=display.data_window)
 
// ─────────────── Optional trade markers ───────────────
bool anyBull = xDojiGapUp or xDojiEngUp or xClusterUp or xContUp or xStarCont or xKickUp or xGapKickUp or xSpring or xRoundBot or xHook or xCupHandle or xBeltUp or xBaseRev or xCurve or xE8Pull or xMaRetest or (not classicInfo and (pEngUp or pPiercing or pHaramiUp or pMorning)) or (hamConf ? hamDone : pHammerQ) or pInvHamQ
float atr14 = ta.atr(14)
var int inPos = 0
var float stopLv = na
bool buyHere = false
bool exitHere = false
if tradeMarks and barstate.isconfirmed
    if inPos == 1 and (low <= stopLv or c < e8)
        exitHere := true
        inPos := 0
    else if inPos == 0 and anyBull
        buyHere := true
        inPos := 1
        stopLv := c - stopAtr * atr14
plotshape(buyHere, "BUY", shape.labelup, location.belowbar, color.green, text="BUY", textcolor=color.white, size=size.tiny)
plotshape(exitHere, "EXIT", shape.labeldown, location.abovebar, color.orange, text="EXIT", textcolor=color.black, size=size.tiny)
 
// ─────────────── Performance table ───────────────
// each signal: did price reach 1 x ATR in its direction before 1 x ATR against it, within the bar limit?
var array<string> pkName = array.new<string>()
var array<int>    pkDir  = array.new<int>()
var array<float>  pkEnt  = array.new<float>()
var array<float>  pkRisk = array.new<float>()
var array<int>    pkBar  = array.new<int>()
var map<string, int> pfWin = map.new<string, int>()
var map<string, int> pfAll = map.new<string, int>()
if perfOn and barstate.isconfirmed
    int pn = array.size(pkName)
    if pn > 0
        for i = pn - 1 to 0
            int pd = array.get(pkDir, i)
            float pe = array.get(pkEnt, i)
            float pr = array.get(pkRisk, i)
            bool hitT = pd == 1 ? h >= pe + pr : l <= pe - pr
            bool hitS = pd == 1 ? l <= pe - pr : h >= pe + pr
            bool timeUp = bar_index - array.get(pkBar, i) >= perfBars
            if hitT or hitS or timeUp
                string pk = array.get(pkName, i)
                bool won = hitS ? false : hitT ? true : (pd == 1 ? c > pe : c < pe)
                pfAll.put(pk, nz(pfAll.get(pk)) + 1)
                pfWin.put(pk, nz(pfWin.get(pk)) + (won ? 1 : 0))
                array.remove(pkName, i)
                array.remove(pkDir, i)
                array.remove(pkEnt, i)
                array.remove(pkRisk, i)
                array.remove(pkBar, i)
    if key != "" and key != "U:Doji" and not (hamConf and key == "U:Hammer") and not revWeak and not isInfoKey and not na(atrV)
        array.push(pkName, str.substring(key, 2))
        array.push(pkDir, str.startswith(key, "U:") ? 1 : -1)
        array.push(pkEnt, c)
        array.push(pkRisk, atrV * perfMult)
        array.push(pkBar, bar_index)
string pfPos = perfWhere == "Top left" ? position.top_left : perfWhere == "Bottom left" ? position.bottom_left : perfWhere == "Middle right" ? position.middle_right : position.top_right
var table pfTab = table.new(pfPos, 3, 50, bgcolor=colBox, frame_color=colEdge, frame_width=1, border_width=2)
if perfOn and barstate.islast
    int pfSize = math.max(panelSize - 3, 8)
    table.clear(pfTab, 0, 0, 2, 49)
    table.cell(pfTab, 0, 0, "Pattern", text_color=colHead, text_size=pfSize, text_halign=text.align_left)
    table.cell(pfTab, 1, 0, "Signals", text_color=colHead, text_size=pfSize)
    table.cell(pfTab, 2, 0, "Win %", text_color=colHead, text_size=pfSize)
    int row = 1
    int sumAll = 0
    int sumWin = 0
    for [pk, tot] in pfAll
        int wn = nz(pfWin.get(pk))
        sumAll += tot
        sumWin += wn
        if row < 49
            float wr = tot > 0 ? 100.0 * wn / tot : 0
            color wc = tot < 5 ? colHead : wr >= 55 ? colUp : wr < 45 ? colDn : colText
            table.cell(pfTab, 0, row, pk, text_color=colText, text_size=pfSize, text_halign=text.align_left)
            table.cell(pfTab, 1, row, str.tostring(tot), text_color=colText, text_size=pfSize)
            table.cell(pfTab, 2, row, str.tostring(wr, "#") + "%", text_color=wc, text_size=pfSize)
            row += 1
    if sumAll > 0
        table.cell(pfTab, 0, row, "All", text_color=colHead, text_size=pfSize, text_halign=text.align_left)
        table.cell(pfTab, 1, row, str.tostring(sumAll), text_color=colHead, text_size=pfSize)
        table.cell(pfTab, 2, row, str.tostring(100.0 * sumWin / sumAll, "#") + "%", text_color=colHead, text_size=pfSize)
 
alertcondition(bullSig and live, "Bullish pattern", "Bullish pattern on {{ticker}} at {{close}}")
alertcondition(confUp and live and not (useMkt and not mktUp), "Confirmed bullish reversal", "Confirmed bullish reversal on {{ticker}} at {{close}}")
alertcondition(confDn and live, "Confirmed bearish reversal", "Confirmed bearish reversal on {{ticker}} at {{close}}")
alertcondition(warnUp and live, "Early warning (bullish)", "Possible bullish reversal forming on {{ticker}} at {{close}}")
alertcondition(warnDn and live, "Early warning (bearish)", "Possible bearish reversal forming on {{ticker}} at {{close}}")
alertcondition(bearSig and live, "Bearish pattern", "Bearish pattern on {{ticker}} at {{close}}")

← 返回列表