UHV Reversal Boxes v6 - Live Extend + Fade On Break

meerakmeer114 · study · 594 行 · 点赞 117 · TradingView 原页

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

Pine Script

//@version=6
indicator("UHV Reversal Boxes v6 - Live Extend + Fade On Break", shorttitle="UHV Gold v6", overlay=true, max_boxes_count=500, max_labels_count=500, max_lines_count=500)
 
// ============================================================
//  UHV Reversal Boxes v4  -  Multi-Timeframe, reference-style
//
//  Built to behave like the reference chart (junaidbhatti1122):
//   * Zones from SEVERAL timeframes (default 30m, 1H, 4H) on one chart
//   * Each box is anchored at the OPEN of the higher-timeframe signal candle
//   * Box colour = timeframe (blue / green / purple), tag at the box end: "30m ▼", "1H ▲", "4H ▼"
//   * Box text = raw "Vol: N  /  Spread: X" of the signal candle
//   * No score filter, no merging, no minimum box height  (pure volume + spread + reversal logic)
//   * DEFAULTS = the reference indicator's own settings (from its Inputs screenshots):
//       Volume filter ON : lookback 10, "Highest" mode, multiplier 1   (volume >= highest volume of the previous 10 candles)
//       Spread filter OFF (lookback 5, Highest, x1.5 - inactive)
//       Reversal distance $30, Confirmation = Close beyond, Max bars to wait 20
//       Box: fixed 51 bars, black solid border width 1, label inside, keep 5 boxes
//       Colours: box after a BULLISH candle = red, after a BEARISH candle = green
//   * Reference Point is set to "Close" (the screenshot only showed "Candle ..."): switch to "Extreme" if it was High/Low
//
//  Detection per timeframe (evaluated on the CLOSED higher-timeframe candle - no repaint):
//   1) Signal candle = volume spike AND wide spread
//   2) Bull candle -> bearish trap zone (upper wick), bear candle -> bullish trap zone (lower wick)
//   3) Zone is confirmed when price pushes reversalDist beyond the reference point
//      (Close / Extreme) by close-beyond or wick-touch, within maxWait candles of THAT timeframe
//   4) Retest entries with SL / TP1 / TP2 (as v2/v3), TP scaled by zone timeframe
//
//  Optional extras (OFF by default so the output matches the reference):
//   rejection-wick filter and absorption candles
// ============================================================
 
// ---------------- Inputs ----------------
grpP = "Multi-Timeframe Zones"
useTf1    = input.bool(true, "Zones From TF 1", group=grpP)
tf1       = input.timeframe("30", "TF 1", group=grpP)
useTf2    = input.bool(true, "Zones From TF 2", group=grpP)
tf2       = input.timeframe("60", "TF 2", group=grpP)
useTf3    = input.bool(true, "Zones From TF 3", group=grpP)
tf3       = input.timeframe("240", "TF 3", group=grpP)
colorMode = input.string("By Direction", "Box Colour", options=["By Direction", "By Timeframe"], tooltip="By Direction = reference colours (red after bullish candle, green after bearish candle). By Timeframe = one colour per timeframe.", group=grpP)
tfCol1    = input.color(color.new(#2962ff, 25), "TF 1 Colour (By Timeframe)", group=grpP)
tfCol2    = input.color(color.new(#43a047, 25), "TF 2 Colour (By Timeframe)", group=grpP)
tfCol3    = input.color(color.new(#c2188f, 25), "TF 3 Colour (By Timeframe)", group=grpP)
showTfTag = input.bool(true, "Show Timeframe Tag (30m ▼)", group=grpP)
 
grpV = "Volume Filter"
useVol  = input.bool(true, "Enable Volume Filter", group=grpV)
volMode = input.string("Lookback High", "Volume Comparison Mode", options=["Multiplier", "Lookback High"], tooltip="Lookback High: volume >= highest volume of the previous N candles x multiplier (reference setting).\nMultiplier: volume >= SMA(N) x multiplier.", group=grpV)
volLen  = input.int(10, "Volume Lookback Period", minval=2, group=grpV)
volMult = input.float(1.0, "Volume Multiplier", minval=0.1, step=0.1, group=grpV)
 
grpS = "Spread Filter (High - Low)"
useSpr  = input.bool(false, "Enable Spread Filter", group=grpS)
sprMode = input.string("Lookback High", "Spread Definition Mode", options=["Multiplier", "Lookback High"], tooltip="Lookback High: spread >= highest spread of the previous N candles x multiplier (reference setting).\nMultiplier: spread >= SMA(N) x multiplier.", group=grpS)
sprLen  = input.int(5, "Spread Lookback Period", minval=2, group=grpS)
sprMult = input.float(1.5, "Spread Multiplier", minval=0.1, step=0.1, group=grpS)
 
grpW = "Extra Filters (not in reference - OFF by default)"
minWickPct = input.float(0.0, "Min Rejection Wick (% of range)", minval=0.0, maxval=90.0, step=1.0, tooltip="0 = off (reference behaviour). A wide candle must show at least this much wick in the trap direction.", group=grpW)
useAbs     = input.bool(false, "Detect Absorption Candles (high vol, narrow spread)", group=grpW)
absSwing   = input.int(20, "Absorption: Swing Lookback", minval=5, group=grpW)
absWickPct = input.float(30.0, "Absorption: Min Rejection Wick (%)", minval=0.0, maxval=90.0, step=1.0, group=grpW)
 
grpR = "Reversal Trigger"
revDist    = input.float(30.0, "Reversal Distance in Dollars", minval=0.05, step=0.1, group=grpR)
useAtrDist = input.bool(false, "Use ATR instead of fixed $ distance", group=grpR)
atrLen     = input.int(14, "ATR Length (chart TF)", minval=1, group=grpR)
atrMult    = input.float(0.6, "ATR Multiplier", minval=0.1, step=0.1, group=grpR)
refMode    = input.string("Close", "Reference Point", options=["Close", "Extreme"], group=grpR)
confMode   = input.string("Close Beyond", "Confirmation", options=["Close Beyond", "Wick Touch"], group=grpR)
maxWait    = input.int(20, "Max Bars to Wait (candles of the signal's own timeframe)", minval=1, maxval=60, group=grpR)
scaleToChart = input.bool(false, "Scale Reversal Distance To Chart Timeframe", tooltip="OFF = exactly the reference ($30 on any chart).\nON = distance x sqrt(chart TF / 30m): 30m = x1, 15m = x0.71, 5m = x0.41, 1H = x1.41. Use it when running the indicator on a chart other than 30m, where a fixed $30 is too big or too small.", group=grpR)
 
grpB = "Boxes"
boxMode   = input.string("Wick Zone", "Box Range", options=["Wick Zone", "Full Range"], group=grpB)
minBoxH   = input.float(0.0, "Minimum Box Height ($)", minval=0.0, step=0.1, group=grpB)
extMode   = input.string("Until Close Through", "Extend Box To", options=["Fixed Bars", "Until Close Through", "Until Live Bar"], tooltip="Until Close Through (default) = the box keeps extending to the right edge of the chart until a candle CLOSES through it (above a red box / below a green box). It then stops extending, its fill fades and only the border stays.\nFixed Bars = box runs a fixed number of chart bars (reference = 51).\nUntil Live Bar = always extends, never fades.", group=grpB)
fadeTransp = input.int(95, "Faded Box Transparency (after close-through)", minval=80, maxval=100, tooltip="Fill transparency of a box once price has closed through it. 100 = fill invisible (border only).", group=grpB)
fixedBars = input.int(51, "Number of bars to extend", minval=1, maxval=490, group=grpB)
maxKeep   = input.int(5, "Max Boxes to Keep on Chart (per direction, per timeframe)", minval=1, maxval=100, group=grpB)
showLabel = input.bool(true, "Show Label Inside Box", group=grpB)
showRetest = input.bool(true, "Show Retest Markers", group=grpB)
bearCol   = input.color(color.new(#e8405f, 25), "Box Colour - after BULLISH candle (red, zone above price)", group=grpB)
bullCol   = input.color(color.new(#4caf50, 25), "Box Colour - after BEARISH candle (green, zone below price)", group=grpB)
bdrCol    = input.color(color.new(#000000, 0), "Border Color", group=grpB)
bdrW      = input.int(1, "Border Width", minval=0, maxval=5, group=grpB)
bStyleIn  = input.string("Solid", "Border Style", options=["Solid", "Dashed", "Dotted"], group=grpB)
 
grpE = "Entry Signal (on zone retest)"
showEntry     = input.bool(true, "Enable Entry Signals", group=grpE)
entryMode     = input.string("Rejection Candle", "Entry Confirmation", options=["Rejection Candle", "Close Out Of Zone", "Touch (Aggressive)"], tooltip="Rejection Candle: candle touches the zone, closes in the reversal direction and does NOT close through the zone.\nClose Out Of Zone: stricter - candle must also close back outside the zone.\nTouch (Aggressive): enters on any touch that has not closed through the zone.", group=grpE)
entryMinRvol  = input.float(2.0, "Min Signal Volume For Entry (x SMA 50)", minval=0.0, step=0.1, tooltip="Zones are drawn exactly like the reference (loose volume filter). Entry signals are only given on zones whose signal candle volume was at least this many times the 50-bar average volume. 0 = entries on every zone.", group=grpE)
maxEntries    = input.int(2, "Max Entries Per Zone", minval=1, maxval=10, group=grpE)
entryCooldown = input.int(3, "Cooldown Bars Between Entries", minval=0, group=grpE)
 
grpX = "Entry Filters (decide AFTER reading the stats table)"
entryTf1 = input.bool(true, "Allow Entries From TF 1 Zones", group=grpX)
entryTf2 = input.bool(true, "Allow Entries From TF 2 Zones", group=grpX)
entryTf3 = input.bool(true, "Allow Entries From TF 3 Zones", group=grpX)
entryAsia = input.bool(true, "Allow Entries In Asia Session", group=grpX)
entryLdn  = input.bool(true, "Allow Entries In London Session", group=grpX)
entryOvl  = input.bool(true, "Allow Entries In London + NY Overlap", group=grpX)
entryNy   = input.bool(true, "Allow Entries In New York Session", group=grpX)
londonSess = input.session("0700-1600", "London (UTC)", group=grpX)
nySess     = input.session("1200-2100", "New York (UTC)", group=grpX)
 
grpL = "Stop Loss"
slAtrMult  = input.float(0.25, "SL Buffer (x ATR)", minval=0.0, step=0.05, group=grpL)
minSlBuf   = input.float(0.5, "Min SL Buffer ($)", minval=0.0, step=0.1, group=grpL)
minRiskAtr = input.float(0.4, "Min Risk (x ATR)", minval=0.0, step=0.05, group=grpL)
maxRiskAtr = input.float(2.0, "Max Risk (x ATR)", minval=0.2, step=0.1, tooltip="If the stop would be wider than this, the signal is skipped.", group=grpL)
 
grpT = "Take Profit"
tp1RR       = input.float(1.0, "TP1 (R multiple)", minval=0.2, step=0.1, group=grpT)
tp2RR       = input.float(2.0, "TP2 (R multiple)", minval=0.4, step=0.1, group=grpT)
minRR       = input.float(1.5, "Min RR To Take Signal (TP2)", minval=0.5, step=0.1, group=grpT)
useTfScale  = input.bool(true, "Scale Targets By Zone Timeframe", tooltip="Higher-timeframe zones carry more weight: factor = 1 + 0.15 x log2(zone TF / chart TF), capped by the max below.", group=grpT)
maxVolScale = input.float(1.5, "Max Timeframe Scale", minval=1.0, step=0.1, group=grpT)
useOrigin   = input.bool(true, "Cap TP2 At Spike Origin", group=grpT)
useHtfCap   = input.bool(true, "Cap TP2 By Higher-TF ATR", group=grpT)
htfIn       = input.string("Auto", "ATR Cap Timeframe", options=["Auto", "60", "240", "D", "W"], tooltip="Auto: <=5m -> 1H, <=1H -> 4H, <=4H -> Daily, above -> Weekly.", group=grpT)
htfCapMult  = input.float(1.0, "ATR Cap (x)", minval=0.1, step=0.1, group=grpT)
beAfterTp1  = input.bool(true, "Move SL To Breakeven After TP1", group=grpT)
 
grpM = "Trade Display"
showTradeLbl = input.bool(true, "Show Trade Label", group=grpM)
maxTrades    = input.int(15, "Max Trades On Chart", minval=1, maxval=60, group=grpM)
maxTradeBars = input.int(80, "Trade Expiry (bars)", minval=5, group=grpM)
showStats    = input.bool(true, "Show Stats Table", group=grpM)
dynAlerts    = input.bool(true, "Send Dynamic alert() Messages", group=grpM)
 
// ---------------- Types ----------------
type Sig
    int idx
    string tfName
    int tfMs
    float hi
    float lo
    float bodyHi
    float bodyLo
    float ref
    bool bearSetup
    float vol
    float spr
    float origin
    float rvol
    int tOpen
    int expireT
 
type Zone
    box bx
    label lbl
    color col
    float top
    float bot
    bool bear
    bool alive = true
    int touches = 0
    bool inside = false
    int born
    int endT
    float origin
    float rvol
    int entries = 0
    int lastEntry = -1000
    bool entryDone = false
    int tfIdx
    int tfMs
    string tfName
 
type Trade
    bool isShort
    float entry
    float sl
    float tp1
    float tp2
    int bar
    int tfIdx
    int sessId
    bool tp1Hit = false
    bool closed = false
    line lnE
    line lnS
    line lnT1
    line lnT2
    label lbl
 
// ---------------- Helpers ----------------
f_style(string s) =>
    s == "Solid" ? line.style_solid : s == "Dashed" ? line.style_dashed : line.style_dotted
 
f_autoHtf() =>
    int secs = timeframe.in_seconds()
    secs <= 300 ? "60" : secs <= 3600 ? "240" : secs <= 14400 ? "D" : "W"
 
f_tfName(string tf) =>
    int sec = timeframe.in_seconds(tf)
    sec < 3600 ? str.tostring(sec / 60, "#") + "m" : sec < 86400 ? str.tostring(sec / 3600, "#") + "H" : sec < 604800 ? str.tostring(sec / 86400, "#") + "D" : "W"
 
// Runs INSIDE request.security for every timeframe. Returns the PREVIOUS (closed) candle's data,
// so with lookahead_on the values are final and never repaint.
f_tfSig() =>
    float r = high - low
    float vSma = ta.sma(volume, volLen)
    float vHi  = ta.highest(volume, volLen)[1]
    float sSma = ta.sma(r, sprLen)
    float sHi  = ta.highest(r, sprLen)[1]
    float swH  = ta.highest(high, absSwing)[1]
    float swL  = ta.lowest(low, absSwing)[1]
    bool vOk = not useVol or (volMode == "Multiplier" ? volume >= vSma * volMult : volume >= vHi * volMult)
    bool sOk = not useSpr or (sprMode == "Multiplier" ? r >= sSma * sprMult : r >= sHi * sprMult)
    float vSma50 = ta.sma(volume, 50)
    float rv = vSma50 > 0 ? volume / vSma50 : 0.0
    bool warmH = bar_index > math.max(volLen, sprLen)
    float wU = r > 0 ? (high - math.max(open, close)) / r : 0.0
    float wD = r > 0 ? (math.min(open, close) - low) / r : 0.0
    bool wide  = warmH and vOk and sOk
    bool cBear = wide and close > open and wU >= minWickPct / 100.0
    bool cBull = wide and close <= open and wD >= minWickPct / 100.0
    bool aBear = useAbs and warmH and vOk and not sOk and r > syminfo.mintick and high >= swH and close <= low + r * 0.5 and wU >= absWickPct / 100.0
    bool aBull = useAbs and warmH and vOk and not sOk and r > syminfo.mintick and low <= swL and close >= low + r * 0.5 and wD >= absWickPct / 100.0
    int dirI = (cBear or aBear) ? 1 : (cBull or aBull) ? -1 : 0
    float org = wide ? (dirI == 1 ? low : high) : (dirI == 1 ? swL : swH)
    float bodyH = math.max(open, close)
    float bodyL = math.min(open, close)
    [dirI[1], high[1], low[1], bodyH[1], bodyL[1], close[1], volume[1], r[1], time[1], org[1], rv[1]]
 
// ---------------- Chart-timeframe basics ----------------
int chartMs = timeframe.in_seconds() * 1000
float atrV  = ta.atr(atrLen)
float dist  = (useAtrDist ? atrV * atrMult : revDist) * (scaleToChart ? math.sqrt(timeframe.in_seconds() / 1800.0) : 1.0)
 
// session of the current bar (UTC): 0 Asia/other, 1 London, 2 London+NY overlap, 3 New York
bool inLon = timeframe.isintraday and not na(time(timeframe.period, londonSess, "Etc/UTC"))
bool inNy  = timeframe.isintraday and not na(time(timeframe.period, nySess, "Etc/UTC"))
int sessId = (inLon and inNy) ? 2 : inLon ? 1 : inNy ? 3 : 0
bool sessAllowed = not timeframe.isintraday or (sessId == 0 ? entryAsia : sessId == 1 ? entryLdn : sessId == 2 ? entryOvl : entryNy)
 
string htfTf = htfIn == "Auto" ? f_autoHtf() : htfIn
float htfAtr = request.security(syminfo.tickerid, htfTf, ta.atr(14)[1], lookahead=barmerge.lookahead_off)
 
// ---------------- Multi-timeframe signal feeds ----------------
int tfMs1 = timeframe.in_seconds(tf1) * 1000
int tfMs2 = timeframe.in_seconds(tf2) * 1000
int tfMs3 = timeframe.in_seconds(tf3) * 1000
string tfName1 = f_tfName(tf1)
string tfName2 = f_tfName(tf2)
string tfName3 = f_tfName(tf3)
// a timeframe lower than the chart cannot be read reliably -> ignored
bool ok1 = useTf1 and tfMs1 >= chartMs
bool ok2 = useTf2 and tfMs2 >= chartMs
bool ok3 = useTf3 and tfMs3 >= chartMs
 
[d1, hi1, lo1, bh1, bl1, cl1, v1, r1, t1, o1, rv1] =request.security(syminfo.tickerid, tf1, f_tfSig(), lookahead=barmerge.lookahead_on)
[d2, hi2, lo2, bh2, bl2, cl2, v2, r2, t2, o2, rv2] =request.security(syminfo.tickerid, tf2, f_tfSig(), lookahead=barmerge.lookahead_on)
[d3, hi3, lo3, bh3, bl3, cl3, v3, r3, t3, o3, rv3] =request.security(syminfo.tickerid, tf3, f_tfSig(), lookahead=barmerge.lookahead_on)
 
float ch1 = ta.change(t1)
float ch2 = ta.change(t2)
float ch3 = ta.change(t3)
 
var array<Sig> sigs = array.new<Sig>()
var array<Zone> zones = array.new<Zone>()
var array<Trade> trades = array.new<Trade>()
 
var int nSig = 0
var int nTp1 = 0
var int nTp2 = 0
var int nSl  = 0
var int nZ1  = 0
var int nZ2  = 0
var int nZ3  = 0
 
// per-bucket results: 0-2 = zone timeframe 1..3, 3-6 = session (Asia, London, London+NY, New York)
var array<int> stE  = array.new<int>(7, 0)
var array<int> stT1 = array.new<int>(7, 0)
var array<int> stT2 = array.new<int>(7, 0)
var array<int> stSl = array.new<int>(7, 0)
 
f_bump(array<int> arr, int tfI, int sI) =>
    arr.set(tfI - 1, arr.get(tfI - 1) + 1)
    arr.set(3 + sI, arr.get(3 + sI) + 1)
    true
 
bool newBull = false
bool newBear = false
bool newHtf  = false
bool retBull = false
bool retBear = false
bool newBuy  = false
bool newSell = false
string alertMsg = ""
 
f_pushSig(int idx, string nm, int tfMs, int dirI, float hi, float lo, float bh, float bl, float cl, float vol, float spr, int tOpen, float org, float rv) =>
    bool bs = dirI == 1
    float refP = bs ? (refMode == "Close" ? cl : hi) : (refMode == "Close" ? cl : lo)
    sigs.push(Sig.new(idx=idx, tfName=nm, tfMs=tfMs, hi=hi, lo=lo, bodyHi=bh, bodyLo=bl, ref=refP, bearSetup=bs, vol=vol, spr=spr, origin=org, rvol=rv, tOpen=tOpen, expireT=tOpen + tfMs * (maxWait + 1)))
    true
 
// ---------------- New closed higher-timeframe signal candles ----------------
if barstate.isconfirmed
    if ok1 and not na(t1) and ch1 != 0 and d1 != 0
        f_pushSig(1, tfName1, tfMs1, d1, hi1, lo1, bh1, bl1, cl1, v1, r1, t1, o1, rv1)
    if ok2 and not na(t2) and ch2 != 0 and d2 != 0
        f_pushSig(2, tfName2, tfMs2, d2, hi2, lo2, bh2, bl2, cl2, v2, r2, t2, o2, rv2)
    if ok3 and not na(t3) and ch3 != 0 and d3 != 0
        f_pushSig(3, tfName3, tfMs3, d3, hi3, lo3, bh3, bl3, cl3, v3, r3, t3, o3, rv3)
 
// ---------------- Pending signals -> zones ----------------
if barstate.isconfirmed and sigs.size() > 0
    for i = sigs.size() - 1 to 0
        Sig s = sigs.get(i)
        float lvl = s.bearSetup ? s.ref - dist : s.ref + dist
        bool trig = false
        if s.bearSetup
            trig := confMode == "Close Beyond" ? close <= lvl : low <= lvl
        else
            trig := confMode == "Close Beyond" ? close >= lvl : high >= lvl
        if trig
            float zTop = 0.0
            float zBot = 0.0
            if s.bearSetup
                zTop := s.hi
                zBot := boxMode == "Wick Zone" ? s.bodyHi : s.lo
                if zTop - zBot < minBoxH
                    zBot := zTop - minBoxH
            else
                zBot := s.lo
                zTop := boxMode == "Wick Zone" ? s.bodyLo : s.hi
                if zTop - zBot < minBoxH
                    zTop := zBot + minBoxH
            color col = colorMode == "By Timeframe" ? (s.idx == 1 ? tfCol1 : s.idx == 2 ? tfCol2 : tfCol3) : (s.bearSetup ? bearCol : bullCol)
            int endT = s.tOpen + fixedBars * chartMs
            int rightT = extMode == "Fixed Bars" ? endT : time
            string txt = showLabel ? "Vol: " + str.tostring(s.vol, "#") + "\nSpread: " + str.tostring(s.spr, "#.##") : ""
            box b = box.new(left=s.tOpen, top=zTop, right=rightT, bottom=zBot, xloc=xloc.bar_time, border_color=bdrCol, border_width=bdrW, border_style=f_style(bStyleIn), bgcolor=col, text=txt, text_size=size.tiny, text_color=color.white, text_halign=text.align_center, text_valign=text.align_center)
            label tl = na
            if showTfTag
                tl := label.new(x=rightT, y=(zTop + zBot) / 2, text=s.tfName + (s.bearSetup ? " ▼" : " ▲"), xloc=xloc.bar_time, style=label.style_label_left, color=color.new(col, 100), textcolor=color.new(col, 0), size=size.small)
            zones.push(Zone.new(bx=b, lbl=tl, col=col, top=zTop, bot=zBot, bear=s.bearSetup, born=bar_index, endT=endT, origin=s.origin, rvol=s.rvol, tfIdx=s.idx, tfMs=s.tfMs, tfName=s.tfName))
            // keep only the newest maxKeep boxes per timeframe and per direction (reference: "Max Boxes to Keep on Chart")
            int kept = 0
            for j = zones.size() - 1 to 0
                Zone q = zones.get(j)
                if q.tfIdx == s.idx and q.bear == s.bearSetup
                    kept += 1
                    if kept > maxKeep
                        box.delete(q.bx)
                        if not na(q.lbl)
                            label.delete(q.lbl)
                        zones.remove(j)
            if s.idx == 1
                nZ1 += 1
            else if s.idx == 2
                nZ2 += 1
            else
                nZ3 += 1
            if s.bearSetup
                newBear := true
            else
                newBull := true
            if s.idx >= 2
                newHtf := true
            sigs.remove(i)
        else if time + chartMs >= s.expireT
            sigs.remove(i)
 
// ---------------- Zone life cycle (extension, mitigation, retests, entries) ----------------
if zones.size() > 0
    for i = zones.size() - 1 to 0
        Zone z = zones.get(i)
        if z.alive
            if extMode != "Fixed Bars"
                box.set_right(z.bx, time)
                if not na(z.lbl)
                    label.set_x(z.lbl, time)
            if barstate.isconfirmed
                if extMode == "Until Close Through"
                    bool broken = z.bear ? close > z.top : close < z.bot
                    if broken
                        z.alive := false
                        box.set_right(z.bx, time)
                        box.set_bgcolor(z.bx, color.new(z.col, fadeTransp))
                        box.set_text_color(z.bx, color.new(color.gray, 75))
                        if not na(z.lbl)
                            label.set_x(z.lbl, time)
                            label.set_textcolor(z.lbl, color.new(z.col, 70))
                else if extMode == "Fixed Bars"
                    if time >= z.endT
                        z.alive := false
                if z.alive and bar_index > z.born
                    bool touching = high >= z.bot and low <= z.top
                    if touching and not z.inside
                        z.touches += 1
                        if z.bear
                            retBear := true
                        else
                            retBull := true
                        if showRetest
                            label.new(bar_index, z.bear ? high : low, "R" + str.tostring(z.touches), style=z.bear ? label.style_label_down : label.style_label_up, color=color.new(z.col, 20), textcolor=color.white, size=size.tiny)
                    z.inside := touching
 
                    // ===== entry signal with SL / TP =====
                    if not touching
                        z.entryDone := false
                    else if showEntry and not z.entryDone and z.entries < maxEntries and z.rvol >= entryMinRvol and (z.tfIdx == 1 ? entryTf1 : z.tfIdx == 2 ? entryTf2 : entryTf3) and sessAllowed and (bar_index - z.lastEntry) >= entryCooldown and not na(atrV)
                        bool notThrough = z.bear ? close <= z.top : close >= z.bot
                        bool dirOk = z.bear ? close < open : close > open
                        bool conf = false
                        if entryMode == "Touch (Aggressive)"
                            conf := notThrough
                        else if entryMode == "Rejection Candle"
                            conf := notThrough and dirOk
                        else
                            conf := dirOk and (z.bear ? close < z.bot : close > z.top)
 
                        if conf
                            // --- Stop loss: beyond zone / rejection wick + ATR buffer ---
                            float entryP = close
                            float buf = math.max(atrV * slAtrMult, minSlBuf)
                            float slBase = z.bear ? math.max(z.top, high) : math.min(z.bot, low)
                            float slP = z.bear ? slBase + buf : slBase - buf
                            float riskD = math.abs(slP - entryP)
                            float minRiskD = atrV * minRiskAtr
                            if riskD < minRiskD
                                riskD := minRiskD
                                slP := z.bear ? entryP + riskD : entryP - riskD
                            bool riskOk = riskD <= atrV * maxRiskAtr
 
                            // --- Take profits: R-multiples x timeframe factor, capped by origin and HTF ATR ---
                            float tfRatio = math.max(z.tfMs / chartMs, 1.0)
                            float vf = useTfScale ? math.min(1.0 + 0.15 * math.log(tfRatio) / math.log(2.0), maxVolScale) : 1.0
                            float d1x = riskD * tp1RR * vf
                            float d2x = riskD * tp2RR * vf
                            float dOrg = z.bear ? entryP - z.origin : z.origin - entryP
                            if useOrigin
                                d2x := math.min(d2x, math.max(dOrg, 0.0))
                            if useHtfCap and not na(htfAtr)
                                d2x := math.min(d2x, htfAtr * htfCapMult)
                            d1x := math.min(d1x, d2x * 0.65)
                            bool rrOk = d2x / riskD >= minRR
 
                            if riskOk and rrOk
                                float slF  = math.round_to_mintick(slP)
                                float tp1P = math.round_to_mintick(z.bear ? entryP - d1x : entryP + d1x)
                                float tp2P = math.round_to_mintick(z.bear ? entryP - d2x : entryP + d2x)
                                float entF = math.round_to_mintick(entryP)
 
                                line lE  = line.new(bar_index, entF, bar_index + 1, entF, color=color.new(color.gray, 0), style=line.style_dotted, width=1)
                                line lS  = line.new(bar_index, slF, bar_index + 1, slF, color=color.new(color.red, 0), style=line.style_dashed, width=1)
                                line lT1 = line.new(bar_index, tp1P, bar_index + 1, tp1P, color=color.new(color.green, 0), style=line.style_dashed, width=1)
                                line lT2 = line.new(bar_index, tp2P, bar_index + 1, tp2P, color=color.new(color.green, 0), style=line.style_solid, width=1)
 
                                label lb = na
                                if showTradeLbl
                                    string side = z.bear ? "SELL" : "BUY"
                                    string ttxt = side + " [" + z.tfName + "] @ " + str.tostring(entF, format.mintick) + "\nSL  " + str.tostring(slF, format.mintick) + "\nTP1 " + str.tostring(tp1P, format.mintick) + "\nTP2 " + str.tostring(tp2P, format.mintick) + "\nRR 1:" + str.tostring(d2x / riskD, "#.#")
                                    lb := label.new(bar_index + 1, entF, ttxt, style=label.style_label_left, color=color.new(z.col, 15), textcolor=color.white, size=size.tiny, textalign=text.align_left)
 
                                trades.push(Trade.new(isShort=z.bear, entry=entF, sl=slF, tp1=tp1P, tp2=tp2P, bar=bar_index, tfIdx=z.tfIdx, sessId=sessId, lnE=lE, lnS=lS, lnT1=lT1, lnT2=lT2, lbl=lb))
                                nSig += 1
                                f_bump(stE, z.tfIdx, sessId)
                                z.entries += 1
                                z.lastEntry := bar_index
                                z.entryDone := true
                                if z.bear
                                    newSell := true
                                else
                                    newBuy := true
                                alertMsg := (z.bear ? "UHV SELL " : "UHV BUY ") + z.tfName + " " + syminfo.ticker + " " + timeframe.period + " | Entry " + str.tostring(entF, format.mintick) + " | SL " + str.tostring(slF, format.mintick) + " | TP1 " + str.tostring(tp1P, format.mintick) + " | TP2 " + str.tostring(tp2P, format.mintick)
 
// ---------------- Trade tracking (hit detection, line extension, stats) ----------------
if barstate.isconfirmed and trades.size() > 0
    for i = 0 to trades.size() - 1
        Trade t = trades.get(i)
        if not t.closed and bar_index > t.bar
            line.set_x2(t.lnE, bar_index)
            line.set_x2(t.lnS, bar_index)
            line.set_x2(t.lnT1, bar_index)
            line.set_x2(t.lnT2, bar_index)
            bool slHit = t.isShort ? high >= t.sl : low <= t.sl
            bool tp1H  = t.isShort ? low <= t.tp1 : high >= t.tp1
            bool tp2H  = t.isShort ? low <= t.tp2 : high >= t.tp2
            string res = ""
            if not t.tp1Hit
                if slHit
                    // conservative: if SL and a target are hit in the same bar, SL counts first
                    t.closed := true
                    nSl += 1
                    f_bump(stSl, t.tfIdx, t.sessId)
                    res := "\nX SL hit"
                else if tp2H
                    t.tp1Hit := true
                    t.closed := true
                    nTp1 += 1
                    nTp2 += 1
                    f_bump(stT1, t.tfIdx, t.sessId)
                    f_bump(stT2, t.tfIdx, t.sessId)
                    res := "\nOK TP2 hit"
                else if tp1H
                    t.tp1Hit := true
                    nTp1 += 1
                    f_bump(stT1, t.tfIdx, t.sessId)
                    if beAfterTp1
                        t.sl := t.entry
                        line.set_y1(t.lnS, t.entry)
                        line.set_y2(t.lnS, t.entry)
            else
                if slHit
                    t.closed := true
                    res := "\nOK TP1 then BE"
                else if tp2H
                    t.closed := true
                    nTp2 += 1
                    f_bump(stT2, t.tfIdx, t.sessId)
                    res := "\nOK TP2 hit"
            if not t.closed and bar_index - t.bar >= maxTradeBars
                t.closed := true
                res := "\n.. expired"
            if res != "" and not na(t.lbl)
                label.set_text(t.lbl, label.get_text(t.lbl) + res)
 
while trades.size() > maxTrades
    Trade oldT = trades.shift()
    line.delete(oldT.lnE)
    line.delete(oldT.lnS)
    line.delete(oldT.lnT1)
    line.delete(oldT.lnT2)
    if not na(oldT.lbl)
        label.delete(oldT.lbl)
 
while zones.size() > 300
    Zone old = zones.shift()
    box.delete(old.bx)
    if not na(old.lbl)
        label.delete(old.lbl)
 
// ---------------- Stats table (per zone timeframe and per session) ----------------
f_row(table tb, int r, string nm, int bucket, color bg) =>
    int e   = stE.get(bucket)
    int a1  = stT1.get(bucket)
    int a2  = stT2.get(bucket)
    int ls  = stSl.get(bucket)
    int dec = a1 + ls
    string w = dec > 0 ? str.tostring(a1 / dec * 100, "#") + "%" : "-"
    table.cell(tb, 0, r, nm, text_color=color.white, bgcolor=bg, text_size=size.tiny, text_halign=text.align_left)
    table.cell(tb, 1, r, str.tostring(e), text_color=color.white, bgcolor=bg, text_size=size.tiny)
    table.cell(tb, 2, r, str.tostring(a1), text_color=color.white, bgcolor=bg, text_size=size.tiny)
    table.cell(tb, 3, r, str.tostring(a2), text_color=color.white, bgcolor=bg, text_size=size.tiny)
    table.cell(tb, 4, r, str.tostring(ls), text_color=color.white, bgcolor=bg, text_size=size.tiny)
    table.cell(tb, 5, r, w, text_color=color.white, bgcolor=bg, text_size=size.tiny)
    true
 
var table tbl = table.new(position.bottom_left, 6, 10, border_width=1, frame_color=color.gray, frame_width=1)
if showStats and barstate.islast
    int decided = nTp1 + nSl
    string wr = decided > 0 ? str.tostring(nTp1 / decided * 100, "#.#") + "%" : "-"
    string zc = (ok1 ? tfName1 + " " + str.tostring(nZ1) : "-") + " | " + (ok2 ? tfName2 + " " + str.tostring(nZ2) : "-") + " | " + (ok3 ? tfName3 + " " + str.tostring(nZ3) : "-")
    color hdr = color.new(color.gray, 25)
    color rowc = color.new(color.gray, 60)
    color rowd = color.new(color.gray, 75)
    table.cell(tbl, 0, 0, "UHV by zone TF / session", text_color=color.white, bgcolor=hdr, text_size=size.tiny, text_halign=text.align_left)
    table.cell(tbl, 1, 0, "Entries", text_color=color.white, bgcolor=hdr, text_size=size.tiny)
    table.cell(tbl, 2, 0, "TP1", text_color=color.white, bgcolor=hdr, text_size=size.tiny)
    table.cell(tbl, 3, 0, "TP2", text_color=color.white, bgcolor=hdr, text_size=size.tiny)
    table.cell(tbl, 4, 0, "SL", text_color=color.white, bgcolor=hdr, text_size=size.tiny)
    table.cell(tbl, 5, 0, "TP1 win%", text_color=color.white, bgcolor=hdr, text_size=size.tiny)
    f_row(tbl, 1, "Zone TF " + tfName1, 0, rowc)
    f_row(tbl, 2, "Zone TF " + tfName2, 1, rowc)
    f_row(tbl, 3, "Zone TF " + tfName3, 2, rowc)
    f_row(tbl, 4, "Asia (UTC)", 3, rowd)
    f_row(tbl, 5, "London", 4, rowd)
    f_row(tbl, 6, "London+NY", 5, rowd)
    f_row(tbl, 7, "New York", 6, rowd)
    table.cell(tbl, 0, 8, "TOTAL", text_color=color.white, bgcolor=hdr, text_size=size.tiny, text_halign=text.align_left)
    table.cell(tbl, 1, 8, str.tostring(nSig), text_color=color.white, bgcolor=hdr, text_size=size.tiny)
    table.cell(tbl, 2, 8, str.tostring(nTp1), text_color=color.white, bgcolor=hdr, text_size=size.tiny)
    table.cell(tbl, 3, 8, str.tostring(nTp2), text_color=color.white, bgcolor=hdr, text_size=size.tiny)
    table.cell(tbl, 4, 8, str.tostring(nSl), text_color=color.white, bgcolor=hdr, text_size=size.tiny)
    table.cell(tbl, 5, 8, wr, text_color=color.white, bgcolor=hdr, text_size=size.tiny)
    table.cell(tbl, 0, 9, "Zones created", text_color=color.white, bgcolor=rowc, text_size=size.tiny, text_halign=text.align_left)
    table.cell(tbl, 1, 9, zc, text_color=color.white, bgcolor=rowc, text_size=size.tiny)
    table.merge_cells(tbl, 1, 9, 5, 9)
 
// ---------------- Alerts ----------------
alertcondition(newBear, "UHV Bearish Zone Confirmed", "UHV: Bearish reversal zone confirmed on {{ticker}} {{interval}}")
alertcondition(newBull, "UHV Bullish Zone Confirmed", "UHV: Bullish reversal zone confirmed on {{ticker}} {{interval}}")
alertcondition(newHtf, "UHV Higher-TF Zone Confirmed", "UHV: Higher-timeframe (TF2/TF3) zone confirmed on {{ticker}} {{interval}}")
alertcondition(retBear, "UHV Bearish Zone Retest", "UHV: Price retesting a bearish UHV zone on {{ticker}} {{interval}}")
alertcondition(retBull, "UHV Bullish Zone Retest", "UHV: Price retesting a bullish UHV zone on {{ticker}} {{interval}}")
alertcondition(newSell, "UHV SELL Entry", "UHV: SELL entry signal on {{ticker}} {{interval}} - check chart for SL/TP")
alertcondition(newBuy, "UHV BUY Entry", "UHV: BUY entry signal on {{ticker}} {{interval}} - check chart for SL/TP")
if dynAlerts and alertMsg != "" and barstate.isconfirmed
    alert(alertMsg, alert.freq_once_per_bar_close)

← 返回列表