ICT OTE Pro - Graded Optimal Trade Entry by jimmyjames4684

jimmyjames4684 · study · 1035 行 · 点赞 129 · TradingView 原页

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

Pine Script

//@version=6
indicator("ICT OTE Pro - Graded Optimal Trade Entry by jimmyjames4684", shorttitle="ICT OTE Pro", overlay=true, max_lines_count=500, max_boxes_count=500, max_labels_count=500, max_bars_back=1000)
 
// ============================================
// 1. SETTINGS
// ============================================
 
gP = "00 | Quick Setup"
preset       = input.string("Intraday (5-15m)", "Style preset", options=["Scalper (1-3m)", "Intraday (5-15m)", "Swing (1H+)", "Custom"], group=gP, display=display.none, tooltip="Sets swing length, displacement filter and setup expiry for your timeframe. Choose Custom to use the values in section 02.")
dashMode     = input.string("Standard", "Dashboard", options=["Minimal", "Standard", "Pro", "Off"], group=gP, display=display.none, tooltip="Minimal: one line.\nStandard: grade, entry, stop, targets, progress.\nPro: adds price ladder, structure, HTF bias and rules-based results.")
minGrade     = input.string("Any", "Minimum grade for signals", options=["Any", "C", "B", "A", "A+"], group=gP, display=display.none, tooltip="Setups below this grade are still drawn but never give an entry signal.")
confirmOnly  = input.bool(true, "Signals on bar close only", group=gP, display=display.none, tooltip="Entry signals only fire once the candle has closed, so they never appear and then disappear.")
pastMode     = input.string("Only setups price reached", "Past setups", options=["Only setups price reached", "All setups", "None"], group=gP, display=display.none, tooltip="'Only setups price reached' hides setups that were replaced or expired before price touched the zone.")
keepSetups   = input.int(5, "Past setups to keep", minval=0, maxval=50, group=gP, display=display.none)
showTradeBox = input.bool(true, "Trade boxes (risk / reward)", group=gP, display=display.none, tooltip="Position-tool style boxes from entry to stop (red) and entry to final target (green), plus the trade result in R when it closes.")
signalStyle  = input.string("Arrow", "Signal style", options=["Arrow", "Label"], group=gP, display=display.none, tooltip="Arrow: small triangle, hover for details.\nLabel: text bubble with the grade.")
 
gQ = "01 | Setup Quality"
sweepLook = input.int(30, "Sweep lookback (bars)", minval=5, maxval=200, group=gQ, display=display.none, tooltip="How far back to look for a swing high/low that the leg's origin swept before reversing.")
strongAtr = input.float(2.5, "Strong displacement (x ATR)", minval=0.5, step=0.25, group=gQ, display=display.none, tooltip="Legs at least this many ATRs long score a point for displacement.")
showFvg   = input.bool(true, "Show FVG inside the leg", group=gQ, display=display.none)
 
gS = "02 | Market Structure (Custom preset only)"
swingLenIn  = input.int(5, "Swing length (bars each side)", minval=2, maxval=50, group=gS, display=display.none, tooltip="Bars on each side needed to confirm a swing. Higher = bigger, fewer swings.")
minLegAtrIn = input.float(1.5, "Min impulse leg (x ATR)", minval=0, step=0.25, group=gS, display=display.none, tooltip="Legs smaller than this many ATRs are ignored. 0 = off.")
maxBarsIn   = input.int(150, "Expire untouched setup after (bars)", minval=10, group=gS, display=display.none)
breakMode   = input.string("Close", "Structure break confirmed by", options=["Close", "Wick"], group=gS, display=display.none)
showBOS     = input.bool(true, "Mark structure breaks (BOS / MSS)", group=gS, display=display.none)
 
gE = "03 | Entries & Trade Management"
entryMode   = input.string("Rejection close", "Entry signal", options=["Rejection close", "Zone touch", "Off"], group=gE, display=display.none, tooltip="Rejection close: a candle trades into the zone and closes back out of it in the trade direction.\nZone touch: first time price trades into the zone.")
exitPlan    = input.string("Partial at T1, rest at T2", "Exit plan", options=["Partial at T1, rest at T2", "All at one target"], group=gE, display=display.none, tooltip="Partial: take part of the position at Target 1, move the stop to breakeven, hold the rest for Target 2.\nAll at one target: exit everything at the target chosen below.")
partialPct  = input.int(50, "Partial size at T1 (%)", minval=10, maxval=90, step=10, group=gE, display=display.none)
completeAt  = input.string("Extension 1", "Single target / setup complete at", options=["Swing extreme (0)", "Extension 1", "Extension 2"], group=gE, display=display.none)
invalidMode = input.string("Close", "Invalidate when origin breaks by", options=["Close", "Wick"], group=gE, display=display.none)
stopBufferTicks = input.int(4, "Stop buffer beyond origin (ticks)", minval=0, group=gE, display=display.none)
 
gT = "04 | Liquidity Targets"
snapLiq    = input.bool(true, "Snap targets to nearby liquidity", group=gT, display=display.none, tooltip="Moves a target to the nearest liquidity pool (PDH/PDL, Asia/London high/low, swing high/low) when one is close to the Fibonacci extension.")
snapTol    = input.float(0.15, "Snap distance (x leg size)", minval=0.0, maxval=0.5, step=0.05, group=gT, display=display.none)
asiaSess   = input.session("2000-0000", "Asia session", group=gT, display=display.none)
londonSess = input.session("0200-0500", "London session", group=gT, display=display.none)
 
gB = "05 | Filters"
useHtf   = input.bool(false, "HTF trend filter", group=gB, display=display.none, tooltip="Only allow setups in the direction of the higher-timeframe EMA. HTF agreement is scored in the grade either way.")
htfTf    = input.timeframe("240", "HTF timeframe", group=gB, display=display.none)
htfLen   = input.int(50, "HTF EMA length", minval=1, group=gB, display=display.none)
useKz    = input.bool(false, "Only signal inside killzones", group=gB, display=display.none)
showKz   = input.bool(false, "Shade killzones", group=gB, display=display.none)
kzTz     = input.string("America/New_York", "Session timezone", group=gB, display=display.none)
kzLondon = input.session("0200-0500", "London killzone", group=gB, display=display.none)
kzNyAm   = input.session("0700-1000", "NY AM killzone", group=gB, display=display.none)
kzNyPm   = input.session("1330-1600", "NY PM killzone", group=gB, display=display.none)
 
gA = "06 | Appearance"
bullCol   = input.color(color.teal, "Bull / Bear", inline="c1", group=gA, display=display.none)
bearCol   = input.color(color.red, "", inline="c1", group=gA, display=display.none)
sweetCol  = input.color(color.yellow, "Entry / Risk / Reward", inline="c2", group=gA, display=display.none)
riskCol   = input.color(color.red, "", inline="c2", group=gA, display=display.none)
rewardCol = input.color(color.lime, "", inline="c2", group=gA, display=display.none)
fvgCol    = input.color(color.purple, "FVG", group=gA, display=display.none)
numbering = input.string("ICT (-0.27)", "Target numbering", options=["ICT (-0.27)", "Extension (1.27)"], group=gA, display=display.none)
showLevelLabels = input.bool(true, "Level labels on active setup", group=gA, display=display.none)
showTags  = input.bool(true, "Level prices on price scale", group=gA, display=display.none)
showEq    = input.bool(true, "Show equilibrium (0.5)", group=gA, display=display.none)
showExt   = input.bool(true, "Show target lines", group=gA, display=display.none)
showLegLine = input.bool(false, "Show impulse leg line", group=gA, display=display.none)
rightOffset = input.int(15, "Extend active setup right (bars)", minval=0, maxval=200, group=gA, display=display.none)
labelSizeIn = input.string("Normal", "Label text size", options=["Tiny", "Small", "Normal", "Large", "Huge"], group=gA, display=display.none)
tableSizeIn = input.string("Normal", "Dashboard text size", options=["Tiny", "Small", "Normal", "Large", "Huge"], group=gA, display=display.none)
tablePosIn  = input.string("Top Right", "Dashboard position", options=["Top Right", "Middle Right", "Top Left", "Bottom Right", "Bottom Left"], group=gA, display=display.none)
topPad      = input.int(0, "Top padding (rows)", minval=0, maxval=4, group=gA, display=display.none, tooltip="Pushes the dashboard down in a top corner. Leave at 0 on TradingView.")
 
gX = "07 | Advanced"
fOte1   = input.float(0.618, "OTE zone start", step=0.001, group=gX, display=display.none)
fOteMid = input.float(0.705, "OTE sweet spot (entry)", step=0.001, group=gX, display=display.none)
fOte2   = input.float(0.79, "OTE zone end", step=0.001, group=gX, display=display.none)
fExt1In = input.float(0.27, "Target 1 (beyond swing)", minval=0, step=0.01, group=gX, display=display.none, tooltip="0.27 = the -0.27 / 1.27 extension.")
fExt2In = input.float(0.62, "Target 2 (beyond swing)", minval=0, step=0.01, group=gX, display=display.none, tooltip="0.62 = the -0.62 / 1.62 extension.")
atrLen  = input.int(14, "ATR length", minval=1, group=gX, display=display.none)
 
float fExt1 = 0 - fExt1In
float fExt2 = 0 - fExt2In
bool  partialPlan = exitPlan == "Partial at T1, rest at T2"
float partialFrac = partialPct / 100.0
 
int   swingLen  = preset == "Scalper (1-3m)" ? 3 : preset == "Intraday (5-15m)" ? 5 : preset == "Swing (1H+)" ? 8 : swingLenIn
float minLegAtr = preset == "Scalper (1-3m)" ? 2.0 : preset == "Intraday (5-15m)" ? 1.5 : preset == "Swing (1H+)" ? 1.0 : minLegAtrIn
int   maxBars   = preset == "Scalper (1-3m)" ? 60 : preset == "Intraday (5-15m)" ? 150 : preset == "Swing (1H+)" ? 100 : maxBarsIn
 
// ============================================
// 2. HELPERS
// ============================================
 
sizeOf(string s) =>
    switch s
        "Tiny"  => size.tiny
        "Small" => size.small
        "Large" => size.large
        "Huge"  => size.huge
        => size.normal
 
posOf(string s) =>
    switch s
        "Middle Right" => position.middle_right
        "Top Left"     => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left"  => position.bottom_left
        => position.top_right
 
rankOf(string g) =>
    switch g
        "A+" => 4
        "A"  => 3
        "B"  => 2
        "C"  => 1
        => 0
 
string lblSize = sizeOf(labelSizeIn)
string tblSize = sizeOf(tableSizeIn)
int    minRank = rankOf(minGrade)
 
fTxt(float f) =>
    str.tostring(f, "#.###")
 
fibAt(float s, float e, float f) =>
    math.round_to_mintick(e + f * (s - e))
 
extName(float f) =>
    numbering == "ICT (-0.27)" ? fTxt(f) : fTxt(1 - f)
 
pTxt(float p) =>
    na(p) ? "—" : str.tostring(p, format.mintick)
 
rTxt(float t, float en, float risk) =>
    na(t) or na(en) or na(risk) or risk <= 0 ? "—" : str.tostring(math.abs(t - en) / risk, "#.##") + "R"
 
statusCol(string st) =>
    switch st
        "Waiting for retrace" => color.gray
        "Price in OTE zone"   => color.orange
        "Entry triggered"     => color.blue
        "Target hit"          => color.green
        "Invalidated"         => color.red
        => color.gray
 
gradeCol(string g) =>
    switch g
        "A+" => color.lime
        "A"  => color.green
        "B"  => color.orange
        "C"  => color.gray
        => color.gray
 
setH(line l, int x1, int x2, float y) =>
    line.set_xy1(l, x1, y)
    line.set_xy2(l, x2, y)
 
type SetupDraw
    box zA
    box zB
    box fvgBox
    box riskBox
    box rewardBox
    array<line> ls
 
method destroy(SetupDraw this) =>
    if not na(this.zA)
        box.delete(this.zA)
    if not na(this.zB)
        box.delete(this.zB)
    if not na(this.fvgBox)
        box.delete(this.fvgBox)
    if not na(this.riskBox)
        box.delete(this.riskBox)
    if not na(this.rewardBox)
        box.delete(this.rewardBox)
    if not na(this.ls)
        for l in this.ls
            line.delete(l)
 
// Line index: 0 leg, 1 swing (0), 2 equilibrium, 3 entry, 4 target 1, 5 target 2, 6 origin
updateDraw(SetupDraw d, float s, int sBar, float e, int eBar, int x2, float t1, float t2) =>
    float a1 = fibAt(s, e, fOte1)
    float am = fibAt(s, e, fOteMid)
    float a2 = fibAt(s, e, fOte2)
    box.set_lefttop(d.zA, eBar, math.max(a1, am))
    box.set_rightbottom(d.zA, x2, math.min(a1, am))
    box.set_lefttop(d.zB, eBar, math.max(am, a2))
    box.set_rightbottom(d.zB, x2, math.min(am, a2))
    if not na(d.fvgBox)
        box.set_right(d.fvgBox, x2)
    if d.ls.size() >= 7
        line.set_xy1(d.ls.get(0), sBar, s)
        line.set_xy2(d.ls.get(0), eBar, e)
        setH(d.ls.get(1), eBar, x2, e)
        setH(d.ls.get(2), eBar, x2, fibAt(s, e, 0.5))
        setH(d.ls.get(3), eBar, x2, am)
        setH(d.ls.get(4), eBar, x2, t1)
        setH(d.ls.get(5), eBar, x2, t2)
        setH(d.ls.get(6), sBar, x2, s)
 
closeDraw(SetupDraw d, string st, bool good) =>
    color fc = good ? color.new(color.green, 85) : color.new(color.gray, 90)
    box.set_bgcolor(d.zA, fc)
    box.set_bgcolor(d.zB, fc)
    box.set_border_color(d.zA, color.new(color.gray, 75))
    box.set_border_color(d.zB, color.new(color.gray, 75))
    box.set_right(d.zA, bar_index)
    box.set_right(d.zB, bar_index)
    box.set_text(d.zA, st)
    box.set_text_color(d.zA, good ? color.green : color.gray)
    if not na(d.fvgBox)
        box.set_right(d.fvgBox, bar_index)
    if d.ls.size() > 1
        for i = 1 to d.ls.size() - 1
            line.set_x2(d.ls.get(i), bar_index)
 
finishSetup(array<SetupDraw> h, SetupDraw d, string st, bool good, bool wasTapped) =>
    bool remove = pastMode == "None" or (pastMode == "Only setups price reached" and not wasTapped)
    if not remove
        closeDraw(d, st, good)
    if remove and h.size() > 0
        h.pop()
    if remove
        d.destroy()
 
// Nearest liquidity pool beyond `beyond`, within `tol` of the Fibonacci target.
snapT(array<float> ps, array<string> ns, float fibT, int d, float beyond, float tol) =>
    float best = na
    string nm = ""
    if ps.size() > 0 and not na(fibT)
        for i = 0 to ps.size() - 1
            float p = ps.get(i)
            if not na(p) and (d == 1 ? p > beyond : p < beyond) and math.abs(p - fibT) <= tol
                if na(best) or math.abs(p - fibT) < math.abs(best - fibT)
                    best := p
                    nm := ns.get(i)
    [na(best) ? fibT : best, nm]
 
getTargets(array<float> ps, array<string> ns, float s, float e, int d) =>
    float t1 = fibAt(s, e, fExt1)
    float t2 = fibAt(s, e, fExt2)
    string n1 = ""
    string n2 = ""
    if snapLiq and not na(s) and not na(e)
        float tol = snapTol * math.abs(s - e)
        [a1, b1] = snapT(ps, ns, t1, d, e, tol)
        t1 := a1
        n1 := b1
        [a2, b2] = snapT(ps, ns, t2, d, t1, tol)
        t2 := a2
        n2 := b2
    [t1, n1, t2, n2]
 
// ============================================
// 3. BASE DATA
// ============================================
 
float tick = syminfo.mintick
float atr  = ta.atr(atrLen)
 
plot(close, "Price anchor", color=color.new(color.white, 100), linewidth=1, display=display.pane, editable=false)
 
[htfC, htfE] = request.security(syminfo.tickerid, htfTf, [close[1], ta.ema(close, htfLen)[1]], lookahead=barmerge.lookahead_on)
int htfBias = na(htfE) ? 0 : htfC > htfE ? 1 : htfC < htfE ? -1 : 0
bool bullAllowed = not useHtf or htfBias == 1
bool bearAllowed = not useHtf or htfBias == -1
 
[pdh, pdl] = request.security(syminfo.tickerid, "D", [high[1], low[1]], lookahead=barmerge.lookahead_on)
 
bool inKz = not na(time(timeframe.period, kzLondon, kzTz)) or not na(time(timeframe.period, kzNyAm, kzTz)) or not na(time(timeframe.period, kzNyPm, kzTz))
bool kzOk = not useKz or inKz
bgcolor(showKz and inKz ? color.new(color.gray, 92) : na, title="Killzone")
 
// Asia / London completed session highs and lows (liquidity pools)
var float asiaRunH = na
var float asiaRunL = na
var float asiaH = na
var float asiaL = na
var float lonRunH = na
var float lonRunL = na
var float londonH = na
var float londonL = na
 
bool inAsia = not na(time(timeframe.period, asiaSess, kzTz))
bool inLon  = not na(time(timeframe.period, londonSess, kzTz))
 
if inAsia and not inAsia[1]
    asiaRunH := high
    asiaRunL := low
else if inAsia
    asiaRunH := math.max(asiaRunH, high)
    asiaRunL := math.min(asiaRunL, low)
if not inAsia and inAsia[1]
    asiaH := asiaRunH
    asiaL := asiaRunL
 
if inLon and not inLon[1]
    lonRunH := high
    lonRunL := low
else if inLon
    lonRunH := math.max(lonRunH, high)
    lonRunL := math.min(lonRunL, low)
if not inLon and inLon[1]
    londonH := lonRunH
    londonL := lonRunL
 
// ============================================
// 4. SWING STRUCTURE
// ============================================
 
float ph = ta.pivothigh(high, swingLen, swingLen)
float pl = ta.pivotlow(low, swingLen, swingLen)
 
var float lastSH    = na
var int   lastSHBar = na
var bool  shBroken  = true
var float lastSL    = na
var int   lastSLBar = na
var bool  slBroken  = true
var int   lastBreakDir = 0
 
var array<float> shP = array.new_float()
var array<int>   shB = array.new_int()
var array<float> slP = array.new_float()
var array<int>   slB = array.new_int()
 
if not na(ph)
    lastSH    := ph
    lastSHBar := bar_index - swingLen
    shBroken  := false
    shP.unshift(ph)
    shB.unshift(bar_index - swingLen)
    if shP.size() > 15
        shP.pop()
        shB.pop()
 
if not na(pl)
    lastSL    := pl
    lastSLBar := bar_index - swingLen
    slBroken  := false
    slP.unshift(pl)
    slB.unshift(bar_index - swingLen)
    if slP.size() > 15
        slP.pop()
        slB.pop()
 
float bullSrc = breakMode == "Close" ? close : high
float bearSrc = breakMode == "Close" ? close : low
 
bool bullBreak = not shBroken and not na(lastSH) and bullSrc > lastSH
bool bearBreak = not slBroken and not na(lastSL) and bearSrc < lastSL
 
if bullBreak and bearBreak
    if close >= open
        bearBreak := false
    else
        bullBreak := false
 
// Liquidity pool for target snapping
array<float>  poolP = array.new_float()
array<string> poolN = array.new_string()
poolP.push(pdh)
poolN.push("PDH")
poolP.push(pdl)
poolN.push("PDL")
poolP.push(asiaH)
poolN.push("Asia H")
poolP.push(asiaL)
poolN.push("Asia L")
poolP.push(londonH)
poolN.push("London H")
poolP.push(londonL)
poolN.push("London L")
if shP.size() > 0
    for i = 0 to shP.size() - 1
        poolP.push(shP.get(i))
        poolN.push("Swing H")
if slP.size() > 0
    for i = 0 to slP.size() - 1
        poolP.push(slP.get(i))
        poolN.push("Swing L")
 
// ============================================
// 5. STATE
// ============================================
 
var int    dir         = 0
var bool   active      = false
var float  legStart    = na
var int    legStartBar = na
var float  legEnd      = na
var int    legEndBar   = na
var bool   tapped      = false
var bool   signaled    = false
var string status      = "Waiting for structure break"
 
var string grade     = "—"
var int    gradeRank = 0
var int    score     = 0
var bool   qSweep = false
var bool   qFvg   = false
var bool   qDisp  = false
var bool   qHtf   = false
var bool   qKz    = false
var bool   qPd    = false
 
var float  lockT1  = na
var float  lockT2  = na
var string lockT1n = ""
var string lockT2n = ""
 
// Trade tracker (rules-based results)
var bool  inTrade  = false
var int   tDir     = 0
var float tEntry   = na
var float tStop    = na
var float tT1      = na
var float tFinal   = na
var float tRisk    = na
var float tRemain  = 1.0
var float tReal    = 0.0
var bool  tPartial = false
var int   tBar     = na
var int   tRank    = 0
var box   tRiskBox = na
var box   tRewBox  = na
 
var int   nTrades = 0
var int   nWins   = 0
var float sumR    = 0.0
var float grossW  = 0.0
var float grossL  = 0.0
var array<float> gSumR = array.from(0.0, 0.0, 0.0, 0.0)
var array<int>   gCnt  = array.from(0, 0, 0, 0)
 
var SetupDraw cur = na
var array<SetupDraw> hist = array.new<SetupDraw>()
var array<line>  bosLines  = array.new_line()
var array<label> bosLabels = array.new_label()
var array<label> sigLabels = array.new_label()
 
bool evNew      = false
bool evTap      = false
bool evEntry    = false
bool evTarget   = false
bool evInvalid  = false
bool evTradeEnd = false
string sigMsg   = ""
 
// ---------- Trade tracker ----------
if inTrade and bar_index > tBar
    bool closed = false
    if tDir == 1
        if low <= tStop
            tReal += tRemain * (tStop - tEntry) / tRisk
            closed := true
        else
            if partialPlan and not tPartial and high >= tT1
                tReal += partialFrac * (tT1 - tEntry) / tRisk
                tRemain := 1.0 - partialFrac
                tPartial := true
                tStop := tEntry
            if high >= tFinal
                tReal += tRemain * (tFinal - tEntry) / tRisk
                closed := true
    else
        if high >= tStop
            tReal += tRemain * (tEntry - tStop) / tRisk
            closed := true
        else
            if partialPlan and not tPartial and low <= tT1
                tReal += partialFrac * (tEntry - tT1) / tRisk
                tRemain := 1.0 - partialFrac
                tPartial := true
                tStop := tEntry
            if low <= tFinal
                tReal += tRemain * (tEntry - tFinal) / tRisk
                closed := true
 
    if closed
        inTrade := false
        evTradeEnd := true
        nTrades += 1
        sumR += tReal
        if tReal > 0
            nWins += 1
            grossW += tReal
        else
            grossL += math.abs(tReal)
        if tRank > 0
            gSumR.set(tRank - 1, gSumR.get(tRank - 1) + tReal)
            gCnt.set(tRank - 1, gCnt.get(tRank - 1) + 1)
        if not na(tRiskBox)
            box.set_right(tRiskBox, bar_index)
        if not na(tRewBox)
            box.set_right(tRewBox, bar_index)
        if showTradeBox
            sigLabels.push(label.new(bar_index, tDir == 1 ? high : low, str.tostring(tReal, "+#.##;-#.##") + "R", yloc=tDir == 1 ? yloc.abovebar : yloc.belowbar, style=label.style_none, textcolor=tReal > 0 ? color.lime : tReal < 0 ? color.red : color.gray, size=size.small))
    else
        if not na(tRiskBox)
            box.set_right(tRiskBox, bar_index + rightOffset)
        if not na(tRewBox)
            box.set_right(tRewBox, bar_index + rightOffset)
 
float completeF = completeAt == "Swing extreme (0)" ? 0.0 : completeAt == "Extension 1" ? fExt1 : fExt2
 
// ---------- Manage the active setup ----------
if active
    [m1, m1n, m2, m2n] = getTargets(poolP, poolN, legStart, legEnd, dir)
    float t1now = signaled ? lockT1 : m1
    float t2now = signaled ? lockT2 : m2
    float doneT = completeAt == "Swing extreme (0)" ? legEnd : completeAt == "Extension 1" ? t1now : t2now
 
    float invSrc = dir == 1 ? (invalidMode == "Close" ? close : low) : (invalidMode == "Close" ? close : high)
    bool broke = dir == 1 ? invSrc < legStart : invSrc > legStart
 
    if broke
        finishSetup(hist, cur, "Invalidated ✕", false, tapped)
        active    := false
        status    := "Invalidated"
        evInvalid := true
    else if tapped
        if (dir == 1 ? high >= doneT : low <= doneT)
            finishSetup(hist, cur, "Target hit ✓", true, tapped)
            active   := false
            status   := "Target hit"
            evTarget := true
    else
        if dir == 1 and high > legEnd
            legEnd    := high
            legEndBar := bar_index
        if dir == -1 and low < legEnd
            legEnd    := low
            legEndBar := bar_index
        if bar_index - legEndBar > maxBars
            finishSetup(hist, cur, "Expired", false, tapped)
            active := false
            status := "Expired"
 
    if active
        [u1, u1n, u2, u2n] = getTargets(poolP, poolN, legStart, legEnd, dir)
        float t1u = signaled ? lockT1 : u1
        float t2u = signaled ? lockT2 : u2
        float l618 = fibAt(legStart, legEnd, fOte1)
        bool inZone = dir == 1 ? low <= l618 : high >= l618
 
        if not tapped and inZone
            tapped := true
            status := "Price in OTE zone"
            evTap  := true
 
        bool gradeOk = gradeRank >= minRank
        bool barOk = not confirmOnly or barstate.isconfirmed
        if tapped and not signaled and entryMode != "Off" and kzOk and gradeOk and barOk
            bool trig = entryMode == "Zone touch" ? inZone : (dir == 1 ? (low <= l618 and close > l618) : (high >= l618 and close < l618))
            if trig
                signaled := true
                status   := "Entry triggered"
                evEntry  := true
                lockT1   := t1u
                lockT2   := t2u
                lockT1n  := u1n
                lockT2n  := u2n
 
                float en = close
                float sp = legStart - dir * stopBufferTicks * tick
                float fin = partialPlan ? t2u : (completeAt == "Swing extreme (0)" ? legEnd : completeAt == "Extension 1" ? t1u : t2u)
                float rk = math.abs(en - sp)
 
                string tip = (dir == 1 ? "Bullish" : "Bearish") + " OTE · grade " + grade + "\nEntry: " + pTxt(en) + "\nStop: " + pTxt(sp) + "\nTarget 1: " + pTxt(t1u) + " (" + rTxt(t1u, en, rk) + ")" + "\nTarget 2: " + pTxt(t2u) + " (" + rTxt(t2u, en, rk) + ")"
                sigMsg := '{"ticker":"' + syminfo.ticker + '","tf":"' + timeframe.period + '","side":"' + (dir == 1 ? "long" : "short") + '","grade":"' + grade + '","entry":' + str.tostring(en) + ',"stop":' + str.tostring(sp) + ',"t1":' + str.tostring(t1u) + ',"t2":' + str.tostring(t2u) + '}'
 
                color sc = dir == 1 ? bullCol : bearCol
                if signalStyle == "Arrow"
                    if dir == 1
                        sigLabels.push(label.new(bar_index, low, "", yloc=yloc.belowbar, style=label.style_triangleup, color=sc, size=size.small, tooltip=tip))
                    else
                        sigLabels.push(label.new(bar_index, high, "", yloc=yloc.abovebar, style=label.style_triangledown, color=sc, size=size.small, tooltip=tip))
                else
                    if dir == 1
                        sigLabels.push(label.new(bar_index, low, "OTE ▲ " + grade, yloc=yloc.belowbar, style=label.style_label_up, color=sc, textcolor=color.white, size=lblSize, tooltip=tip))
                    else
                        sigLabels.push(label.new(bar_index, high, "OTE ▼ " + grade, yloc=yloc.abovebar, style=label.style_label_down, color=sc, textcolor=color.white, size=lblSize, tooltip=tip))
 
                if not inTrade and rk > 0
                    inTrade  := true
                    tDir     := dir
                    tEntry   := en
                    tStop    := sp
                    tT1      := t1u
                    tFinal   := fin
                    tRisk    := rk
                    tRemain  := 1.0
                    tReal    := 0.0
                    tPartial := false
                    tBar     := bar_index
                    tRank    := gradeRank
                    tRiskBox := na
                    tRewBox  := na
                    if showTradeBox
                        tRiskBox := box.new(bar_index, math.max(en, sp), bar_index + rightOffset, math.min(en, sp), border_color=color.new(riskCol, 60), bgcolor=color.new(riskCol, 85))
                        tRewBox  := box.new(bar_index, math.max(en, fin), bar_index + rightOffset, math.min(en, fin), border_color=color.new(rewardCol, 60), bgcolor=color.new(rewardCol, 85))
                        cur.riskBox   := tRiskBox
                        cur.rewardBox := tRewBox
 
        updateDraw(cur, legStart, legStartBar, legEnd, legEndBar, bar_index + rightOffset, t1u, t2u)
 
while sigLabels.size() > 150
    label.delete(sigLabels.shift())
 
// ---------- Detect new setups ----------
int   newDir    = 0
float nStart    = na
int   nStartBar = na
float nEnd      = na
int   nEndBar   = na
bool  nSweep    = false
bool  nFvg      = false
bool  nFvgIn    = false
float nFvgTop   = na
float nFvgBot   = na
int   nFvgBar   = na
 
if bullBreak
    shBroken := true
    string tag = lastBreakDir == -1 ? "MSS" : "BOS"
    lastBreakDir := 1
    if showBOS
        bosLines.push(line.new(lastSHBar, lastSH, bar_index, lastSH, color=color.new(chart.fg_color, 60), style=line.style_dashed))
        bosLabels.push(label.new(math.round((lastSHBar + bar_index) / 2), lastSH, tag, style=label.style_label_down, color=color.new(color.black, 100), textcolor=color.new(bullCol, 10), size=size.small))
 
    int n = math.min(bar_index - lastSHBar, 900)
    float lo = low
    int loBar = bar_index
    for i = 0 to n
        if low[i] < lo
            lo    := low[i]
            loBar := bar_index - i
    float hi = high
    int hiBar = bar_index
    for i = 0 to bar_index - loBar
        if high[i] > hi
            hi    := high[i]
            hiBar := bar_index - i
 
    bool bigEnough = na(atr) or (hi - lo) >= minLegAtr * atr
    if bigEnough and bullAllowed
        newDir    := 1
        nStart    := lo
        nStartBar := loBar
        nEnd      := hi
        nEndBar   := hiBar
 
        // Sweep: origin took out an earlier swing low / PDL / session low and price reclaimed it
        if slP.size() > 0
            for i = 0 to slP.size() - 1
                float sv = slP.get(i)
                int sb = slB.get(i)
                if sb < loBar and loBar - sb <= sweepLook and lo < sv and close > sv
                    nSweep := true
                    break
        if not nSweep
            if (not na(pdl) and lo < pdl and close > pdl) or (not na(asiaL) and lo < asiaL and close > asiaL) or (not na(londonL) and lo < londonL and close > londonL)
                nSweep := true
 
        // FVG inside the leg (prefer one overlapping the OTE zone)
        float zHi = math.max(fibAt(lo, hi, fOte1), fibAt(lo, hi, fOte2))
        float zLo = math.min(fibAt(lo, hi, fOte1), fibAt(lo, hi, fOte2))
        int k0 = bar_index - hiBar
        int k1 = bar_index - loBar
        if k1 - 2 >= k0
            for k = k0 to k1 - 2
                if low[k] > high[k + 2]
                    float ft = low[k]
                    float fb = high[k + 2]
                    bool ov = ft >= zLo and fb <= zHi
                    if not nFvg or (ov and not nFvgIn)
                        nFvg    := true
                        nFvgIn  := ov
                        nFvgTop := ft
                        nFvgBot := fb
                        nFvgBar := bar_index - k - 1
                    if nFvgIn
                        break
 
if bearBreak
    slBroken := true
    string tag = lastBreakDir == 1 ? "MSS" : "BOS"
    lastBreakDir := -1
    if showBOS
        bosLines.push(line.new(lastSLBar, lastSL, bar_index, lastSL, color=color.new(chart.fg_color, 60), style=line.style_dashed))
        bosLabels.push(label.new(math.round((lastSLBar + bar_index) / 2), lastSL, tag, style=label.style_label_up, color=color.new(color.black, 100), textcolor=color.new(bearCol, 10), size=size.small))
 
    int n = math.min(bar_index - lastSLBar, 900)
    float hi = high
    int hiBar = bar_index
    for i = 0 to n
        if high[i] > hi
            hi    := high[i]
            hiBar := bar_index - i
    float lo = low
    int loBar = bar_index
    for i = 0 to bar_index - hiBar
        if low[i] < lo
            lo    := low[i]
            loBar := bar_index - i
 
    bool bigEnough = na(atr) or (hi - lo) >= minLegAtr * atr
    if bigEnough and bearAllowed
        newDir    := -1
        nStart    := hi
        nStartBar := hiBar
        nEnd      := lo
        nEndBar   := loBar
 
        if shP.size() > 0
            for i = 0 to shP.size() - 1
                float sv = shP.get(i)
                int sb = shB.get(i)
                if sb < hiBar and hiBar - sb <= sweepLook and hi > sv and close < sv
                    nSweep := true
                    break
        if not nSweep
            if (not na(pdh) and hi > pdh and close < pdh) or (not na(asiaH) and hi > asiaH and close < asiaH) or (not na(londonH) and hi > londonH and close < londonH)
                nSweep := true
 
        float zHi = math.max(fibAt(hi, lo, fOte1), fibAt(hi, lo, fOte2))
        float zLo = math.min(fibAt(hi, lo, fOte1), fibAt(hi, lo, fOte2))
        int k0 = bar_index - loBar
        int k1 = bar_index - hiBar
        if k1 - 2 >= k0
            for k = k0 to k1 - 2
                if high[k] < low[k + 2]
                    float ft = low[k + 2]
                    float fb = high[k]
                    bool ov = ft >= zLo and fb <= zHi
                    if not nFvg or (ov and not nFvgIn)
                        nFvg    := true
                        nFvgIn  := ov
                        nFvgTop := ft
                        nFvgBot := fb
                        nFvgBar := bar_index - k - 1
                    if nFvgIn
                        break
 
if bosLines.size() > 30
    line.delete(bosLines.shift())
if bosLabels.size() > 30
    label.delete(bosLabels.shift())
 
// ---------- Create the new setup ----------
if newDir != 0
    if active
        finishSetup(hist, cur, "Replaced", false, tapped)
 
    dir         := newDir
    legStart    := nStart
    legStartBar := nStartBar
    legEnd      := nEnd
    legEndBar   := nEndBar
    tapped      := false
    signaled    := false
    active      := true
    evNew       := true
 
    // Grade the setup (6 checks)
    float legSz = math.abs(nEnd - nStart)
    float enN   = fibAt(nStart, nEnd, fOteMid)
    float pdMid = (pdh + pdl) / 2
    qSweep := nSweep
    qFvg   := nFvg
    qDisp  := not na(atr) and legSz >= strongAtr * atr
    qHtf   := htfBias == newDir
    qKz    := inKz
    qPd    := not na(pdMid) and (newDir == 1 ? enN < pdMid : enN > pdMid)
    score  := (qSweep ? 1 : 0) + (qFvg ? 1 : 0) + (qDisp ? 1 : 0) + (qHtf ? 1 : 0) + (qKz ? 1 : 0) + (qPd ? 1 : 0)
    grade  := score >= 5 ? "A+" : score == 4 ? "A" : score == 3 ? "B" : "C"
    gradeRank := rankOf(grade)
    status := gradeRank >= minRank ? "Waiting for retrace" : "Grade " + grade + " · below filter"
 
    color c = dir == 1 ? bullCol : bearCol
    SetupDraw d = SetupDraw.new()
    d.zA := box.new(nEndBar, nEnd, bar_index, nEnd, border_color=color.new(c, 60), bgcolor=color.new(c, 88), text="OTE · " + grade, text_color=color.new(c, 10), text_size=size.small, text_halign=text.align_right, text_valign=text.align_center)
    d.zB := box.new(nEndBar, nEnd, bar_index, nEnd, border_color=color.new(c, 60), bgcolor=color.new(c, 72))
    if showFvg and nFvg
        d.fvgBox := box.new(nFvgBar, nFvgTop, bar_index + rightOffset, nFvgBot, border_color=color.new(fvgCol, 50), bgcolor=color.new(fvgCol, 85), text=nFvgIn ? "FVG ✓" : "FVG", text_color=color.new(fvgCol, 10), text_size=size.tiny, text_halign=text.align_left)
 
    array<line> ls = array.new_line()
    ls.push(line.new(nStartBar, nStart, nEndBar, nEnd, color=showLegLine ? color.new(c, 40) : color.new(c, 100), style=line.style_dotted))
    ls.push(line.new(nEndBar, nEnd, bar_index, nEnd, color=color.new(chart.fg_color, 50)))
    ls.push(line.new(nEndBar, nEnd, bar_index, nEnd, color=showEq ? color.new(chart.fg_color, 70) : color.new(chart.fg_color, 100), style=line.style_dashed))
    ls.push(line.new(nEndBar, nEnd, bar_index, nEnd, color=sweetCol, width=2))
    ls.push(line.new(nEndBar, nEnd, bar_index, nEnd, color=showExt ? color.new(rewardCol, 40) : color.new(rewardCol, 100), style=line.style_dashed))
    ls.push(line.new(nEndBar, nEnd, bar_index, nEnd, color=showExt ? color.new(rewardCol, 55) : color.new(rewardCol, 100), style=line.style_dashed))
    ls.push(line.new(nStartBar, nStart, bar_index, nStart, color=color.new(c, 40)))
    d.ls := ls
 
    cur := d
    hist.push(d)
    [c1, c1n, c2, c2n] = getTargets(poolP, poolN, legStart, legEnd, dir)
    updateDraw(cur, legStart, legStartBar, legEnd, legEndBar, bar_index + rightOffset, c1, c2)
 
    while hist.size() > keepSetups + 1
        SetupDraw old = hist.shift()
        old.destroy()
 
// ============================================
// 6. CURRENT LEVELS + PRICE SCALE TAGS
// ============================================
 
[e1, e1n, e2, e2n] = getTargets(poolP, poolN, legStart, legEnd, dir)
float  gT1    = active ? (signaled ? lockT1 : e1) : na
float  gT2    = active ? (signaled ? lockT2 : e2) : na
string gT1n   = signaled ? lockT1n : e1n
string gT2n   = signaled ? lockT2n : e2n
float  gZ1    = active ? fibAt(legStart, legEnd, fOte1) : na
float  gZ2    = active ? fibAt(legStart, legEnd, fOte2) : na
bool   liveTrade = inTrade and active and signaled
float  gEntry = active ? (liveTrade ? tEntry : fibAt(legStart, legEnd, fOteMid)) : na
float  gStop  = active ? legStart - dir * stopBufferTicks * tick : na
float  gRisk  = active ? math.abs(gEntry - gStop) : na
 
bool tagsOn = showTags and active
plot(tagsOn ? gEntry : na, "Entry", color=sweetCol, display=display.price_scale)
plot(tagsOn ? gZ1 : na, "OTE 0.618", color=dir == 1 ? bullCol : bearCol, display=display.price_scale)
plot(tagsOn ? gZ2 : na, "OTE 0.79", color=dir == 1 ? bullCol : bearCol, display=display.price_scale)
plot(tagsOn ? gStop : na, "Stop", color=riskCol, display=display.price_scale)
plot(tagsOn and showExt ? gT1 : na, "Target 1", color=rewardCol, display=display.price_scale)
plot(tagsOn and showExt ? gT2 : na, "Target 2", color=rewardCol, display=display.price_scale)
 
// ============================================
// 7. LEVEL LABELS / EMPTY STATE
// ============================================
 
mkLvl(int x, float y, string name, color bg, color tc) =>
    label.new(x, y, name + "  " + str.tostring(y, format.mintick), style=label.style_label_left, color=bg, textcolor=tc, size=lblSize)
 
var array<label> lvlLabels = array.new_label()
 
if barstate.islast
    for lb in lvlLabels
        label.delete(lb)
    lvlLabels.clear()
 
    if active and showLevelLabels
        int lx = bar_index + rightOffset
        if showExt
            lvlLabels.push(mkLvl(lx, gT2, "T2 " + extName(fExt2) + (gT2n != "" ? " · " + gT2n : ""), color.new(rewardCol, 35), color.black))
            lvlLabels.push(mkLvl(lx, gT1, "T1 " + extName(fExt1) + (gT1n != "" ? " · " + gT1n : ""), color.new(rewardCol, 35), color.black))
        lvlLabels.push(mkLvl(lx, legEnd, "0  Swing", color.new(chart.fg_color, 75), chart.fg_color))
        lvlLabels.push(mkLvl(lx, gEntry, liveTrade ? "Entry (filled)" : "★ Entry", color.new(sweetCol, 10), color.black))
        lvlLabels.push(mkLvl(lx, gStop, "Stop", color.new(riskCol, 25), color.white))
    else if not active
        lvlLabels.push(label.new(bar_index + 3, close, "Ultimate OTE · waiting for the next setup", style=label.style_label_left, color=color.new(color.black, 100), textcolor=color.new(chart.fg_color, 50), size=size.small))
 
// ============================================
// 8. DASHBOARD
// ============================================
 
var table dash = table.new(posOf(tablePosIn), 3, 30, border_width=1, border_color=color.new(chart.fg_color, 85))
 
int rowOff = str.contains(tablePosIn, "Top") ? topPad : 0
 
cell(int c, int r, string t, color tc, color bg) =>
    table.cell(dash, c, r + rowOff, t, text_color=tc, bgcolor=bg, text_size=tblSize, text_halign=text.align_left)
 
if barstate.islast and dashMode != "Off"
    table.clear(dash, 0, 0, 2, 29)
    if rowOff > 0
        for r = 0 to rowOff - 1
            table.cell(dash, 0, r, " ", bgcolor=color(na), text_size=tblSize)
 
    color fg  = chart.fg_color
    color dim = color.new(chart.fg_color, 45)
    color nob = color.new(chart.bg_color, 8)
    color dc  = dir == 1 ? bullCol : dir == -1 ? bearCol : color.gray
    color sc  = statusCol(status)
    string hdr = active ? (dir == 1 ? "▲ BULLISH OTE" : "▼ BEARISH OTE") : "ULTIMATE OTE"
    string chk = (qSweep ? "✓" : "✗") + " Sweep  " + (qFvg ? "✓" : "✗") + " FVG  " + (qDisp ? "✓" : "✗") + " Disp  " + (qHtf ? "✓" : "✗") + " HTF  " + (qKz ? "✓" : "✗") + " KZ  " + (qPd ? "✓" : "✗") + " P/D"
    string t1Name = "T1 " + extName(fExt1) + (gT1n != "" ? " · " + gT1n : "")
    string t2Name = "T2 " + extName(fExt2) + (gT2n != "" ? " · " + gT2n : "")
 
    string progBar = "—"
    string progTxt = ""
    if active
        float span = legStart - legEnd
        float fibNow = span != 0 ? (close - legEnd) / span : 0.0
        int pn = math.round(fibNow * 10)
        pn := math.max(0, math.min(10, pn))
        progBar := (pn > 0 ? str.repeat("▰", pn) : "") + (pn < 10 ? str.repeat("▱", 10 - pn) : "") + " " + str.tostring(fibNow, "#.##")
        if not tapped
            float dist = dir == 1 ? close - gZ1 : gZ1 - close
            progTxt := str.tostring(dist, "#.##") + " pts to zone"
        else if not signaled
            progTxt := "In zone"
        else
            progTxt := liveTrade ? "Trade live" + (tPartial ? " · BE" : "") : "Signalled"
 
    if dashMode == "Minimal"
        string arrow = active ? (dir == 1 ? "▲ " : "▼ ") : ""
        string txt = arrow + (active ? grade + " · " : "") + status + (active ? "  ·  Entry " + pTxt(gEntry) + "  ·  " + rTxt(gT1, gEntry, gRisk) : "")
        cell(0, 0, txt, fg, color.new(sc, 60))
 
    else
        cell(0, 0, hdr, color.white, color.new(dc, 25))
        cell(1, 0, syminfo.ticker + " · " + timeframe.period, color.white, color.new(dc, 25))
        cell(2, 0, "", color.white, color.new(dc, 25))
        cell(0, 1, "Status", dim, nob)
        cell(1, 1, status, color.white, color.new(sc, 45))
        cell(2, 1, active ? progTxt : "", color.white, color.new(sc, 45))
        cell(0, 2, "Grade", dim, nob)
        cell(1, 2, active ? grade + "  (" + str.tostring(score) + "/6)" : "—", active ? gradeCol(grade) : dim, nob)
        cell(2, 2, "", fg, nob)
        cell(0, 3, "", dim, nob)
        cell(1, 3, active ? chk : "", dim, nob)
        cell(2, 3, "", fg, nob)
 
        if dashMode == "Standard"
            cell(0, 4, liveTrade ? "Entry (filled)" : "★ Entry", sweetCol, nob)
            cell(1, 4, pTxt(gEntry), fg, nob)
            cell(2, 4, "", fg, nob)
            cell(0, 5, "Stop", riskCol, nob)
            cell(1, 5, pTxt(gStop), fg, nob)
            cell(2, 5, active ? str.tostring(gRisk, "#.##") + " pts" : "—", dim, nob)
            cell(0, 6, t1Name, rewardCol, nob)
            cell(1, 6, pTxt(gT1), fg, nob)
            cell(2, 6, rTxt(gT1, gEntry, gRisk), rewardCol, nob)
            cell(0, 7, t2Name, rewardCol, nob)
            cell(1, 7, pTxt(gT2), fg, nob)
            cell(2, 7, rTxt(gT2, gEntry, gRisk), rewardCol, nob)
            cell(0, 8, "Progress", dim, nob)
            cell(1, 8, progBar, dc, nob)
            cell(2, 8, "", fg, nob)
 
        else
            cell(0, 4, "Structure", dim, nob)
            cell(1, 4, lastBreakDir == 1 ? "Bullish" : lastBreakDir == -1 ? "Bearish" : "—", lastBreakDir == 1 ? bullCol : lastBreakDir == -1 ? bearCol : dim, nob)
            cell(2, 4, "", fg, nob)
            cell(0, 5, "HTF bias", dim, nob)
            cell(1, 5, (htfBias == 1 ? "Bullish" : htfBias == -1 ? "Bearish" : "Neutral") + " (" + htfTf + ")" + (useHtf ? " · filter on" : ""), htfBias == 1 ? bullCol : htfBias == -1 ? bearCol : dim, nob)
            cell(2, 5, "", fg, nob)
            cell(0, 6, "Progress", dim, nob)
            cell(1, 6, progBar, dc, nob)
            cell(2, 6, "", fg, nob)
            cell(0, 7, "Leg", dim, nob)
            cell(1, 7, active ? str.tostring(math.abs(legEnd - legStart), "#.##") + " pts" : "—", fg, nob)
            cell(2, 7, active and not na(atr) and atr > 0 ? str.tostring(math.abs(legEnd - legStart) / atr, "#.#") + " ATR" : "—", dim, nob)
            cell(0, 8, "Expires", dim, nob)
            cell(1, 8, active and not tapped ? str.tostring(maxBars - (bar_index - legEndBar)) + " bars" : "—", fg, nob)
            cell(2, 8, "", fg, nob)
 
            color lh = color.new(chart.fg_color, 85)
            cell(0, 9, "LEVEL", fg, lh)
            cell(1, 9, "PRICE", fg, lh)
            cell(2, 9, "R", fg, lh)
 
            int row = 10
            if active
                array<string> ln = array.from(t2Name, t1Name, "0  Swing", "OTE " + fTxt(fOte1), liveTrade ? "Entry (filled)" : "★ " + fTxt(fOteMid) + " Entry", "OTE " + fTxt(fOte2), "1.0  Origin", "Stop")
                array<float>  lp = array.from(gT2, gT1, legEnd, gZ1, gEntry, gZ2, legStart, gStop)
                array<string> lr = array.from(rTxt(gT2, gEntry, gRisk), rTxt(gT1, gEntry, gRisk), rTxt(legEnd, gEntry, gRisk), "", "", "", "", str.tostring(gRisk, "#.##") + " pts")
                if dir == -1
                    ln.reverse()
                    lp.reverse()
                    lr.reverse()
                bool placed = false
                for i = 0 to ln.size() - 1
                    float p = lp.get(i)
                    if not placed and close >= p
                        cell(0, row, "◄ PRICE", fg, color.new(chart.fg_color, 80))
                        cell(1, row, pTxt(close), fg, color.new(chart.fg_color, 80))
                        cell(2, row, "", fg, color.new(chart.fg_color, 80))
                        row += 1
                        placed := true
                    string nm = ln.get(i)
                    color nmCol = str.contains(nm, "T1") or str.contains(nm, "T2") ? rewardCol : nm == "Stop" ? riskCol : str.contains(nm, "Entry") ? sweetCol : dim
                    cell(0, row, nm, nmCol, nob)
                    cell(1, row, pTxt(p), fg, nob)
                    cell(2, row, lr.get(i), nmCol, nob)
                    row += 1
                if not placed
                    cell(0, row, "◄ PRICE", fg, color.new(chart.fg_color, 80))
                    cell(1, row, pTxt(close), fg, color.new(chart.fg_color, 80))
                    cell(2, row, "", fg, color.new(chart.fg_color, 80))
                    row += 1
            else
                cell(0, row, "No active setup", dim, nob)
                cell(1, row, "", fg, nob)
                cell(2, row, "", fg, nob)
                row += 1
 
            // Rules-based results on the loaded history
            cell(0, row, "RESULTS", fg, lh)
            cell(1, row, "loaded history · rules-based", dim, lh)
            cell(2, row, "", fg, lh)
            row += 1
            float avgR = nTrades > 0 ? sumR / nTrades : na
            float pf   = grossL > 0 ? grossW / grossL : na
            cell(0, row, "Trades", dim, nob)
            cell(1, row, str.tostring(nTrades) + (nTrades > 0 ? "  ·  win " + str.tostring(100.0 * nWins / nTrades, "#") + "%" : ""), fg, nob)
            cell(2, row, "", fg, nob)
            row += 1
            cell(0, row, "Avg R", dim, nob)
            cell(1, row, na(avgR) ? "—" : str.tostring(avgR, "+#.##;-#.##") + "R per trade", na(avgR) ? dim : avgR > 0 ? color.lime : color.red, nob)
            cell(2, row, na(pf) ? "" : "PF " + str.tostring(pf, "#.##"), fg, nob)
            row += 1
            string byG = ""
            array<string> gNames = array.from("C", "B", "A", "A+")
            for gi = 3 to 0
                int cnt = gCnt.get(gi)
                if cnt > 0
                    byG := byG + gNames.get(gi) + " " + str.tostring(gSumR.get(gi) / cnt, "+#.##;-#.##") + "R (" + str.tostring(cnt) + ")  "
            cell(0, row, "By grade", dim, nob)
            cell(1, row, byG == "" ? "—" : byG, fg, nob)
            cell(2, row, "", fg, nob)
 
// ============================================
// 9. ALERTS
// ============================================
 
alertcondition(evNew and dir == 1, "Bullish OTE setup", "New bullish OTE setup formed")
alertcondition(evNew and dir == -1, "Bearish OTE setup", "New bearish OTE setup formed")
alertcondition(evTap and dir == 1, "Price in bullish OTE", "Price entered the bullish OTE zone")
alertcondition(evTap and dir == -1, "Price in bearish OTE", "Price entered the bearish OTE zone")
alertcondition(evEntry and dir == 1, "Bullish OTE entry", "Bullish OTE entry signal")
alertcondition(evEntry and dir == -1, "Bearish OTE entry", "Bearish OTE entry signal")
alertcondition(evTarget, "OTE target hit", "OTE setup reached its target")
alertcondition(evInvalid, "OTE invalidated", "OTE setup invalidated (origin broken)")
 
if evEntry
    alert(sigMsg, alert.freq_once_per_bar_close)
if evNew
    alert(syminfo.ticker + " new " + (dir == 1 ? "bullish" : "bearish") + " OTE setup · grade " + grade, alert.freq_once_per_bar_close)

← 返回列表