Trading Room Hunter - Supply Demand Zones & FVG [DrFX] V3.0

raptoralgo · study · 772 行 · 点赞 45 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © raptoralgo
 
//@version=6
// Trading Room Hunter (TRH) v3.0 - public edition | Author: DrFX
// Educational overlay. Signals are confirmed at chart-bar close, not orders or fills.
//
// v3.0 changelog (vs v2)
//  - FIX: FVG confluence is now recorded when the zone is born (impulse imbalance).
//         v2 only checked LIVE gaps at the touch, but the retracement into a zone
//         normally fills the impulse FVG first, so FVG confluence almost never scored.
//  - FIX: "Body" zone mode now uses the body for the proximal edge too (v2 used the wick).
//  - FIX: A pending swing that price has already traded through is dropped, so a
//         zone is never anchored to a swing extreme that no longer holds.
//  - FIX: A displacement rejected as overlapping is consumed instead of re-firing later.
//  - FIX: Zone-price entries whose stop was already tagged on the signal candle are rejected.
//  - NEW: Classic Break of Structure: the leg must close beyond the swing that preceded it.
//  - NEW: Only the best-scoring signal per side per bar is drawn and alerted.
//  - NEW: Entry Price Basis: Zone Price (limit idea) or Signal Close (what a bot executes).
//  - NEW: TP/SL outcome tracking, hit markers and a stats table (heuristic, not a backtest).
//  - NEW: JSON alert format for webhook / MT5 bridge use.
indicator("Trading Room Hunter - Supply Demand Zones & FVG [DrFX]", "TRH v3", overlay = true,
     max_boxes_count = 500, max_labels_count = 500, max_lines_count = 500, max_bars_back = 1000)
 
// =============================================================================
// DATA STRUCTURES
// =============================================================================
type Zone
    float prox
    float dist
    int dir
    int born
    float power
    float velocity
    bool bos
    bool fvg
    int touches
    box bx
    line ln
 
type Position
    box zoneBox
    line zoneLine
    box tpBox
    box slBox
    line tpLine
    label signalMark
    label signalText
 
type Gap
    float top
    float bot
    int dir
    box bx
 
type Trade
    int dir
    float entry
    float stop
    float target
    float risk
    int bar
 
// =============================================================================
// INPUTS
// =============================================================================
GS = "Spike Filter | Movement"
minSpikeBars = input.int(4, "Minimum Spike Bars", minval = 1, maxval = 100, group = GS)
legMaxBars   = input.int(60, "Maximum Spike Bars", minval = 5, maxval = 500, group = GS)
useMovePower = input.bool(true, "Movement Power", inline = "MP", group = GS)
movePower    = input.float(4.5, "", minval = 0.1, step = 0.1, inline = "MP", group = GS,
     tooltip = "Minimum displacement from a confirmed pivot, in current ATR(14) units.")
pivotPeriod = input.int(5, "Pivot Period Zone", minval = 1, maxval = 100, group = GS,
     tooltip = "Swing pivots are confirmed this many bars after the actual extreme.")
zoneAnchor = input.string("Wick", "Zone Extremes", options = ["Wick", "Body"], group = GS)
dropTaken = input.bool(true, "Drop Swing Once Traded Through", group = GS,
     tooltip = "If price trades beyond a pending swing before displacement qualifies, that swing is discarded.")
 
GP = "Position Management"
useSLT = input.bool(true, "Stop-Loss Threshold", inline = "SL", group = GP)
sltVal = input.float(0.2, "", minval = 0, maxval = 5, step = 0.05, inline = "SL", group = GP)
rrRatio = input.float(2, "Risk-Reward Ratio", minval = 0.1, step = 0.1, group = GP)
wideFilt = input.bool(true, "Wide Zone Filter", inline = "WZ", group = GP)
wideMult = input.float(4, "", minval = 0.1, step = 0.1, inline = "WZ", group = GP)
entryBasis = input.string("Zone Price", "Entry Price Basis", options = ["Zone Price", "Signal Close"], group = GP,
     tooltip = "Zone Price: entry at the proximal (a resting limit idea). Signal Close: entry at the close that confirms the signal, which is what an alert-driven bot can actually execute. SL/TP and stats follow this choice.")
 
GQ = "Signal Quality"
entryMode = input.string("Close Inside", "Entry Trigger", options = ["Touch", "Close Inside", "Rejection"], group = GQ,
     tooltip = "All signals occur at chart-bar close. Touch: the candle tagged the zone. Close Inside: the candle also closes beyond the proximal in the intended direction. Rejection: adds directional candle/body confirmation.")
maxTouch = input.int(3, "Max Unconfirmed Touch Bars", minval = 1, maxval = 20, group = GQ)
blowGuard = input.bool(true, "Reject Blow-Through Bars", group = GQ)
anchorSwing = input.bool(true, "Anchor Distal to Swing Extreme", group = GQ)
useVel = input.bool(true, "Impulse Velocity Filter", inline = "VL", group = GQ)
minVel = input.float(0.35, "", minval = 0, step = 0.05, inline = "VL", group = GQ)
bosMode = input.string("Score", "Break of Structure", options = ["Off", "Score", "Required"], group = GQ,
     tooltip = "BOS = the impulse leg closed beyond the last confirmed swing that existed before the leg began.")
fvgMode = input.string("Score", "FVG Confluence", options = ["Off", "Score", "Required"], group = GQ,
     tooltip = "Counts when the impulse leg left a same-direction FVG (on either FVG timeframe), or a live gap overlaps the zone at the touch.")
trendMode = input.string("Score", "Trend Filter", options = ["Off", "Score", "Required"], group = GQ)
trendTf = input.timeframe("60", "Trend Timeframe", group = GQ,
     tooltip = "Higher timeframes use the previous completed EMA; lower timeframes use the last available intrabar EMA at chart close.")
trendLen = input.int(50, "Trend EMA Length", minval = 2, group = GQ)
minStopATR = input.float(0.15, "Minimum Stop Distance (ATR)", minval = 0, step = 0.05, group = GQ)
noOverlap = input.bool(true, "Reject Overlapping Zones", group = GQ)
minScore = input.int(50, "Minimum Signal Score", minval = 0, maxval = 100, group = GQ)
showScore = input.bool(true, "Show Score on Signal", group = GQ,
     tooltip = "Heuristic confluence score, NOT win probability or a performance statistic.")
 
GL = "Zone Life"
maxExtend = input.int(500, "Max Zone Extension (bars)", minval = 5, maxval = 5000, group = GL)
maxLive = input.int(8, "Max Live Zones per Side", minval = 1, maxval = 30, group = GL)
 
GD = "Display Setting"
dispMode = input.string("Signal", "Display Mode", options = ["Setup", "Signal"], group = GD)
showEntry = input.bool(true, "Show Entry Levels", group = GD)
onlyLast = input.bool(false, "Only Display the Last Position", group = GD)
setupW = input.int(2, "Setup Width Drawing", minval = 1, maxval = 100, group = GD)
 
GC = "Style"
bullCol = input.color(#0d9c4b, "Demand / Long", inline = "C1", group = GC)
bearCol = input.color(#b02a2a, "Supply / Short", inline = "C1", group = GC)
zoneTrans = input.int(65, "Zone Transparency", minval = 0, maxval = 95, group = GC)
setupTran = input.int(75, "Setup Transparency", minval = 0, maxval = 95, group = GC)
 
GA = "Alerts"
useAlert = input.bool(true, "Enable Dynamic Entry Alerts", group = GA)
alertFmt = input.string("Text", "Alert Format", options = ["Text", "JSON"], group = GA,
     tooltip = "JSON sends one object per signal: source, side, symbol, tf, entry, sl, tp, score, time.")
 
GT = "Performance (heuristic)"
showStats = input.bool(true, "Show Stats Table", group = GT,
     tooltip = "Tracks each signal to its first TP or SL hit at the chosen Entry Price Basis. If TP and SL fall in the same bar, SL is counted. Gaps through a level are filled at the open. Not a broker backtest: no spread, slippage or commission.")
statsPos = input.string("Top Right", "Table Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = GT)
showOutcome = input.bool(true, "Mark TP/SL Hits", group = GT)
tradeTimeout = input.int(0, "Close Open Trade After N Bars (0 = never)", minval = 0, group = GT)
 
GF = "Fair Value Gaps"
fvgOn = input.bool(true, "Enable FVG Engine", group = GF)
fvgMinOn = input.bool(false, "Minimum Gap Size", inline = "MG", group = GF)
fvgMinATR = input.float(0.25, "", minval = 0, step = 0.05, inline = "MG", group = GF)
fvgMax = input.int(6, "Max Live Gaps per Timeframe", minval = 1, maxval = 40, group = GF)
fvgTrans = input.int(80, "Gap Transparency", minval = 0, maxval = 95, group = GF)
fvgTxtPos = input.string("Right", "Label Position", options = ["Left", "Center", "Right"], group = GF)
tf1On = input.bool(true, "", inline = "F1", group = GF)
tf1 = input.timeframe("5", "", inline = "F1", group = GF)
tf1Txt = input.string("5 Minutes", "", inline = "F1", group = GF)
tf1Col = input.color(#e8c547, "", inline = "F1", group = GF)
tf2On = input.bool(true, "", inline = "F2", group = GF)
tf2 = input.timeframe("15", "", inline = "F2", group = GF)
tf2Txt = input.string("15 Minutes", "", inline = "F2", group = GF)
tf2Col = input.color(#4d90fe, "", inline = "F2", group = GF)
 
// =============================================================================
// CHART CONTEXT AND SAFETY
// =============================================================================
chartSec = timeframe.in_seconds(timeframe.period)
trendSec = timeframe.in_seconds(trendTf)
if barstate.isfirst
    if minSpikeBars > legMaxBars
        runtime.error("TRH: Minimum Spike Bars must not exceed Maximum Spike Bars.")
    if fvgMode == "Required" and not (fvgOn and (tf1On or tf2On))
        runtime.error("TRH: Required FVG confluence needs Enable FVG Engine and at least one FVG timeframe enabled.")
 
atr = ta.atr(14)
// HTF EMA is explicitly offset with lookahead_on: only a CLOSED HTF bar.
// At equal timeframes, use previous chart EMA. On LTFs, the last intrabar
// is sampled at the confirmed chart close (lookahead_off).
chartEma = ta.ema(close, trendLen)
securityEmaHTF = request.security(syminfo.tickerid, trendTf, ta.ema(close, trendLen)[1],
     lookahead = barmerge.lookahead_on)
securityEmaLTF = request.security(syminfo.tickerid, trendTf, ta.ema(close, trendLen),
     lookahead = barmerge.lookahead_off)
trendEma = trendSec == chartSec ? chartEma[1] : trendSec > chartSec ? securityEmaHTF : securityEmaLTF
trendUp = not na(trendEma) and close > trendEma
trendDn = not na(trendEma) and close < trendEma
rightMs = na(time_close) ? time + chartSec * 1000 : time_close
 
// =============================================================================
// FAIR VALUE GAPS: SAME TF, CONFIRMED HTF, COMPLETE AVAILABLE LTF INTRABARS
// (runs before zone registration so a zone can record the imbalance its leg left)
// =============================================================================
// All drawing/state mutations are performed after the chart candle closes.
// In LTF mode, each intrabar is processed chronologically. This avoids
// incorrectly filling a gap with an earlier wick from its birth chart bar.
// Returned lower-TF history depends on data availability and plan limits.
fvgRaw() =>
    bool up = low > high[2]
    bool dn = high < low[2]
    float top = up ? low : dn ? low[2] : na
    float bot = up ? high[2] : dn ? high : na
    int dir = up ? 1 : dn ? -1 : 0
    [top, bot, dir, time[2], time, ta.atr(14), high, low]
 
// Every expression, including event timestamp and ATR, is shifted one HTF bar.
// Paired with lookahead_on this follows TradingView's confirmed HTF pattern.
fvgConfirmedHTF() =>
    bool up = low[1] > high[3]
    bool dn = high[1] < low[3]
    float top = up ? low[1] : dn ? low[3] : na
    float bot = up ? high[3] : dn ? high[1] : na
    int dir = up ? 1 : dn ? -1 : 0
    [top, bot, dir, time[3], time[1], ta.atr(14)[1]]
 
var array<Gap> gaps1 = array.new<Gap>()
var array<Gap> gaps2 = array.new<Gap>()
// Chart bar_index at which the latest bullish [0] / bearish [1] gap was detected.
var array<int> gapBar = array.from(-1, -1)
var int lastEvent1 = 0
var int lastEvent2 = 0
alignText = fvgTxtPos == "Left" ? text.align_left : fvgTxtPos == "Right" ? text.align_right : text.align_center
 
// Kill fully mitigated gaps. Trim partially traded gaps using the current
// *source sequence*; never replay the entire chart candle over newborn LTF gaps.
mitigateGaps(array<Gap> gs, float barHigh, float barLow) =>
    if array.size(gs) > 0
        for i = array.size(gs) - 1 to 0
            Gap g = array.get(gs, i)
            bool filled = g.dir == 1 ? barLow <= g.bot : barHigh >= g.top
            if filled
                array.remove(gs, i)
                box.delete(g.bx)
            else
                if g.dir == 1
                    g.top := math.min(g.top, math.max(barLow, g.bot))
                else
                    g.bot := math.max(g.bot, math.min(barHigh, g.top))
                box.set_top(g.bx, g.top)
                box.set_bottom(g.bx, g.bot)
                box.set_right(g.bx, rightMs)
 
makeGap(array<Gap> gs, float top, float bot, int dir, int anchor, float sourceAtr,
        color col, string txt) =>
    bool created = false
    bool valid = dir != 0 and not na(top) and not na(bot) and not na(anchor) and top > bot
    bool sized = not fvgMinOn or (not na(sourceAtr) and sourceAtr > 0 and top - bot >= fvgMinATR * sourceAtr)
    if valid and sized
        box b = box.new(anchor, top, rightMs, bot, xloc = xloc.bar_time,
             border_color = color.new(col, 40), bgcolor = color.new(col, fvgTrans),
             text = txt, text_color = color.new(col, 10), text_size = size.small,
             text_halign = alignText, text_valign = text.align_center)
        array.push(gs, Gap.new(top, bot, dir, b))
        array.set(gapBar, dir == 1 ? 0 : 1, bar_index)
        created := true
        while array.size(gs) > fvgMax
            Gap old = array.shift(gs)
            box.delete(old.bx)
    created
 
updateFVG(array<Gap> gs, bool enabled, string srcTf, color col, string name, int seen) =>
    bool newGap = false
    int seenOut = seen
    int srcSec = timeframe.in_seconds(srcTf)
    // Build the fallback unconditionally: Pine can evaluate request expressions
    // independently of their conditional branch. Do not pass a higher TF to
    // request.security_lower_tf(), including on a 1m chart with 5m/15m FVGs.
    // Equality is valid; actual HTF gaps still use confirmed request.security().
    string safeLtf = srcSec < chartSec ? srcTf : timeframe.period
    if fvgOn and enabled and barstate.isconfirmed
        if srcSec < chartSec
            [tops, bots, dirs, anchors, births, atrs, highs, lows] = request.security_lower_tf(
                 syminfo.tickerid, safeLtf, fvgRaw(), ignore_invalid_timeframe = true)
            int n = array.size(dirs)
            if n > 0
                for i = 0 to n - 1
                    mitigateGaps(gs, array.get(highs, i), array.get(lows, i))
                    int evt = array.get(births, i)
                    int direction = array.get(dirs, i)
                    if direction != 0 and not na(evt) and evt > seenOut
                        seenOut := evt
                        bool made = makeGap(gs, array.get(tops, i), array.get(bots, i), direction,
                             array.get(anchors, i), array.get(atrs, i), col, name)
                        newGap := newGap or made
            else
                // No historical intrabars available: do not fabricate LTF gaps.
                mitigateGaps(gs, high, low)
        else if srcSec == chartSec
            mitigateGaps(gs, high, low)
            [t, b, direction, anchor, evt, a, sourceHigh, sourceLow] = fvgRaw()
            if direction != 0 and not na(evt) and evt > seenOut
                seenOut := evt
                newGap := makeGap(gs, t, b, direction, anchor, a, col, name)
        else
            mitigateGaps(gs, high, low)
            [t, b, direction, anchor, evt, a] = request.security(syminfo.tickerid,
                 srcTf, fvgConfirmedHTF(), lookahead = barmerge.lookahead_on)
            if direction != 0 and not na(evt) and evt > seenOut
                seenOut := evt
                bool filledNow = direction == 1 ? low <= b : high >= t
                if not filledNow
                    newGap := makeGap(gs, t, b, direction, anchor, a, col, name)
                    // Trim any partial fill that happened in the present chart bar.
                    if newGap
                        mitigateGaps(gs, high, low)
    [newGap, seenOut]
 
[created1, seenEvent1] = updateFVG(gaps1, tf1On, tf1, tf1Col, tf1Txt, lastEvent1)
lastEvent1 := seenEvent1
[created2, seenEvent2] = updateFVG(gaps2, tf2On and (not tf1On or tf2 != tf1), tf2,
     tf2Col, tf2Txt, lastEvent2)
lastEvent2 := seenEvent2
newFvg1 = created1
newFvg2 = created2
 
gapConfluence(array<Gap> gs, float top, float bot, int direction) =>
    bool present = false
    if array.size(gs) > 0
        for i = 0 to array.size(gs) - 1
            Gap g = array.get(gs, i)
            if g.dir == direction and g.top >= bot and g.bot <= top
                present := true
                break
    present
 
// =============================================================================
// SWING, STRUCTURE AND DISPLACEMENT
// =============================================================================
ph = ta.pivothigh(high, pivotPeriod, pivotPeriod)
pl = ta.pivotlow(low, pivotPeriod, pivotPeriod)
maxCloseP = ta.highest(close, pivotPeriod)
minCloseP = ta.lowest(close, pivotPeriod)
var float pendHigh = na
var int pendHighBar = na
var float pendLow = na
var int pendLowBar = na
var float lastPH = na
var float lastPL = na
// Structure each pending leg must break, and the most extreme close of that leg.
var float supRef = na
var float supMinClose = na
var float demRef = na
var float demMaxClose = na
 
// Extend the running leg extremes.
if not na(pendLow)
    demMaxClose := math.max(nz(demMaxClose, close), close)
if not na(pendHigh)
    supMinClose := math.min(nz(supMinClose, close), close)
 
// A pending swing that price has traded through no longer marks the extreme.
if dropTaken
    if not na(pendHigh) and high > pendHigh
        pendHigh := na
        pendHighBar := na
    if not na(pendLow) and low < pendLow
        pendLow := na
        pendLowBar := na
 
// New pivots: snapshot the opposing swing that existed BEFORE this one.
if not na(ph)
    pendHigh := ph
    pendHighBar := bar_index - pivotPeriod
    supRef := lastPL
    supMinClose := minCloseP
if not na(pl)
    pendLow := pl
    pendLowBar := bar_index - pivotPeriod
    demRef := lastPH
    demMaxClose := maxCloseP
if not na(ph)
    lastPH := ph
if not na(pl)
    lastPL := pl
 
ageCap = math.min(legMaxBars + 1, 900)
supAge = na(pendHighBar) ? 0 : math.min(bar_index - pendHighBar, ageCap)
demAge = na(pendLowBar) ? 0 : math.min(bar_index - pendLowBar, ageCap)
supPower = not na(pendHigh) and atr > 0 ? math.max((pendHigh - close) / atr, 0) : 0.0
demPower = not na(pendLow) and atr > 0 ? math.max((close - pendLow) / atr, 0) : 0.0
supVel = supAge > 0 ? supPower / supAge : 0.0
demVel = demAge > 0 ? demPower / demAge : 0.0
supBOS = not na(pendHigh) and not na(supRef) and not na(supMinClose) and supMinClose < supRef
demBOS = not na(pendLow) and not na(demRef) and not na(demMaxClose) and demMaxClose > demRef
 
warmed = bar_index > pivotPeriod * 3 + 10
bearDisp = warmed and barstate.isconfirmed and not na(pendHigh) and supAge >= minSpikeBars and supAge <= legMaxBars and
     (not useMovePower or supPower >= movePower) and (not useVel or supVel >= minVel) and (bosMode != "Required" or supBOS)
bullDisp = warmed and barstate.isconfirmed and not na(pendLow) and demAge >= minSpikeBars and demAge <= legMaxBars and
     (not useMovePower or demPower >= movePower) and (not useVel or demVel >= minVel) and (bosMode != "Required" or demBOS)
 
findOrigin(int legOff, bool seekBearish) =>
    int result = legOff
    for k = 0 to 5
        int offset = legOff + k
        if offset < bar_index
            bool matched = seekBearish ? close[offset] < open[offset] : close[offset] > open[offset]
            if matched
                result := offset
                break
    result
 
demOff = findOrigin(demAge, true)
supOff = findOrigin(supAge, false)
useWick = zoneAnchor == "Wick"
demProx = useWick ? high[demOff] : math.max(open[demOff], close[demOff])
demRaw = useWick ? low[demOff] : math.min(open[demOff], close[demOff])
supProx = useWick ? low[supOff] : math.min(open[supOff], close[supOff])
supRaw = useWick ? high[supOff] : math.max(open[supOff], close[supOff])
demDist = anchorSwing and useWick and not na(pendLow) ? math.min(demRaw, pendLow) : demRaw
supDist = anchorSwing and useWick and not na(pendHigh) ? math.max(supRaw, pendHigh) : supRaw
// Did the impulse leg leave a same-direction FVG (detected from origin to now)?
demFvg = fvgOn and array.get(gapBar, 0) >= bar_index - demOff
supFvg = fvgOn and array.get(gapBar, 1) >= bar_index - supOff
 
demOK = bullDisp and demProx > demDist and low > demProx and
     (not wideFilt or demProx - demDist <= wideMult * atr)
supOK = bearDisp and supDist > supProx and high < supProx and
     (not wideFilt or supDist - supProx <= wideMult * atr)
 
// =============================================================================
// ZONE STORAGE AND DRAWING LIFECYCLE
// =============================================================================
var array<Zone> zones = array.new<Zone>()
var array<Position> positions = array.new<Position>()
MAX_POS = 60
 
deletePosition(Position p) =>
    if not na(p.zoneBox)
        box.delete(p.zoneBox)
    if not na(p.zoneLine)
        line.delete(p.zoneLine)
    if not na(p.tpBox)
        box.delete(p.tpBox)
    if not na(p.slBox)
        box.delete(p.slBox)
    if not na(p.tpLine)
        line.delete(p.tpLine)
    if not na(p.signalMark)
        label.delete(p.signalMark)
    if not na(p.signalText)
        label.delete(p.signalText)
 
trimZones(int direction) =>
    int count = 0
    if array.size(zones) > 0
        for i = 0 to array.size(zones) - 1
            if array.get(zones, i).dir == direction
                count += 1
    while count > maxLive
        int first = -1
        for i = 0 to array.size(zones) - 1
            if array.get(zones, i).dir == direction
                first := i
                break
        if first < 0
            break
        Zone retired = array.remove(zones, first)
        if not na(retired.bx)
            box.delete(retired.bx)
        if not na(retired.ln)
            line.delete(retired.ln)
        count -= 1
 
overlapZone(int direction, float hi, float lo) =>
    bool found = false
    if array.size(zones) > 0
        for i = 0 to array.size(zones) - 1
            Zone z = array.get(zones, i)
            if z.dir == direction and math.max(z.prox, z.dist) >= lo and math.min(z.prox, z.dist) <= hi
                found := true
                break
    found
 
registerZone(bool isLong, float prox, float dist, int off, float power, float velocity, bool bos, bool fvg) =>
    color col = isLong ? bullCol : bearCol
    box newBox = na
    line newLine = na
    if showEntry
        newBox := box.new(bar_index - off, math.max(prox, dist), bar_index, math.min(prox, dist),
             xloc = xloc.bar_index, border_color = color.new(col, 25), bgcolor = color.new(col, zoneTrans))
        newLine := line.new(bar_index - off, prox, bar_index, prox, xloc = xloc.bar_index,
             color = color.new(col, 10), width = 1)
    array.push(zones, Zone.new(prox, dist, isLong ? 1 : -1, bar_index, power, velocity, bos, fvg, 0, newBox, newLine))
    trimZones(isLong ? 1 : -1)
 
// A qualified displacement is consumed even when rejected as overlapping,
// so the same swing cannot re-fire later with a stale origin.
if demOK
    if not noOverlap or not overlapZone(1, math.max(demProx, demDist), math.min(demProx, demDist))
        registerZone(true, demProx, demDist, demOff, demPower, demVel, demBOS, demFvg)
    pendLow := na
    pendLowBar := na
if supOK
    if not noOverlap or not overlapZone(-1, math.max(supProx, supDist), math.min(supProx, supDist))
        registerZone(false, supProx, supDist, supOff, supPower, supVel, supBOS, supFvg)
    pendHigh := na
    pendHighBar := na
 
// =============================================================================
// CONFLUENCE SCORE: HEURISTIC, NOT PROBABILITY OR BACKTESTED WIN RATE
// =============================================================================
scoreSignal(float power, float velocity, bool bos, bool fvg, bool trend) =>
    float earned = math.min(math.max(power, 0) / (useMovePower ? math.max(movePower, 0.01) : 1.0), 2.0) * 15.0
    float possible = 30.0
    if useVel
        earned += math.min(math.max(velocity, 0) / math.max(minVel, 0.01), 2.0) * 10.0
        possible += 20.0
    if bosMode != "Off"
        earned += bos ? 20.0 : 0.0
        possible += 20.0
    if fvgMode != "Off" and fvgOn
        earned += fvg ? 15.0 : 0.0
        possible += 15.0
    if trendMode != "Off"
        earned += trend ? 15.0 : 0.0
        possible += 15.0
    int(math.round(math.min(earned / possible * 100.0, 100.0)))
 
// =============================================================================
// OUTCOME TRACKING (evaluated before new signals, so a trade starts next bar)
// =============================================================================
var array<Trade> trades = array.new<Trade>()
var int nWin = 0
var int nLoss = 0
var int nFlat = 0
var float sumR = 0.0
var float grossWin = 0.0
var float grossLoss = 0.0
 
if barstate.isconfirmed and array.size(trades) > 0
    for i = array.size(trades) - 1 to 0
        Trade t = array.get(trades, i)
        if bar_index > t.bar and t.risk > 0
            bool hitSL = t.dir == 1 ? low <= t.stop : high >= t.stop
            bool hitTP = t.dir == 1 ? high >= t.target : low <= t.target
            bool timedOut = tradeTimeout > 0 and bar_index - t.bar >= tradeTimeout
            float exitPx = na
            string tag = ""
            // Conservative: when TP and SL share a bar, the stop is assumed first.
            // A gap through a level fills at the open.
            if hitSL
                exitPx := t.dir == 1 ? math.min(open, t.stop) : math.max(open, t.stop)
                tag := "SL"
            else if hitTP
                exitPx := t.dir == 1 ? math.max(open, t.target) : math.min(open, t.target)
                tag := "TP"
            else if timedOut
                exitPx := close
                tag := "Exit"
            if not na(exitPx)
                float r = (exitPx - t.entry) * t.dir / t.risk
                sumR += r
                if r > 0
                    nWin += 1
                    grossWin += r
                else if r < 0
                    nLoss += 1
                    grossLoss -= r
                else
                    nFlat += 1
                if showOutcome
                    color oc = r > 0 ? bullCol : r < 0 ? bearCol : color.gray
                    label.new(bar_index, exitPx, tag + " " + str.tostring(r, "+#.##;-#.##") + "R",
                         style = t.dir == 1 ? (r > 0 ? label.style_label_down : label.style_label_up) : (r > 0 ? label.style_label_up : label.style_label_down),
                         color = color.new(oc, 70), textcolor = color.white, size = size.tiny)
                array.remove(trades, i)
 
// =============================================================================
// CONFIRMED ENTRY SIGNALS (best score per side per bar)
// =============================================================================
bool longSignal = false
bool shortSignal = false
float longEntry = na
float longSL = na
float longTP = na
int longScore = na
float shortEntry = na
float shortSL = na
float shortTP = na
int shortScore = na
Zone bestLong = na
Zone bestShort = na
 
if barstate.isconfirmed and array.size(zones) > 0
    for i = array.size(zones) - 1 to 0
        Zone z = array.get(zones, i)
        int age = bar_index - z.born
        if not na(z.bx)
            box.set_right(z.bx, bar_index + 1)
        if not na(z.ln)
            line.set_x2(z.ln, bar_index + 1)
        bool fresh = age > 0
        bool touched = fresh and (z.dir == 1 ? low <= z.prox : high >= z.prox)
        bool invalid = fresh and (z.dir == 1 ? close < z.dist : close > z.dist)
        bool expired = age > maxExtend
        float candleRange = high - low
        float closeRank = candleRange > 0 ? (close - low) / candleRange : 0.5
        bool favorableClose = z.dir == 1 ? close > z.prox : close < z.prox
        bool confirmed = false
        if touched
            if entryMode == "Touch"
                confirmed := true
            else if entryMode == "Close Inside"
                confirmed := favorableClose
            else
                confirmed := favorableClose and (z.dir == 1 ? closeRank >= 0.5 and close > open : closeRank <= 0.5 and close < open)
        bool trigger = touched and confirmed and not (blowGuard and invalid)
        bool removeZone = false
        if trigger
            float zoneHeight = math.abs(z.prox - z.dist)
            // Zone Price is an indicative limit level, NOT an asserted intrabar fill.
            float zoneEntry = z.dir == 1 ? math.min(open, z.prox) : math.max(open, z.prox)
            float entry = entryBasis == "Signal Close" ? close : zoneEntry
            float buffer = useSLT ? sltVal * zoneHeight : 0.0
            float stop = z.dir == 1 ? z.dist - buffer : z.dist + buffer
            float risk = math.abs(entry - stop)
            float target = z.dir == 1 ? entry + rrRatio * risk : entry - rrRatio * risk
            bool correctSide = z.dir == 1 ? entry > stop : entry < stop
            // With a zone-price entry, a candle that already tagged the stop is a failed setup.
            bool stopTagged = entryBasis == "Zone Price" and (z.dir == 1 ? low <= stop : high >= stop)
            float zoneTop = math.max(z.prox, z.dist)
            float zoneBot = math.min(z.prox, z.dist)
            bool fvgOK = fvgOn and (z.fvg or gapConfluence(gaps1, zoneTop, zoneBot, z.dir) or
                 gapConfluence(gaps2, zoneTop, zoneBot, z.dir))
            bool trendOK = z.dir == 1 ? trendUp : trendDn
            bool bosOK = z.bos
            int score = scoreSignal(z.power, z.velocity, bosOK, fvgOK, trendOK)
            bool passes = correctSide and not stopTagged and risk >= minStopATR * atr and risk >= syminfo.mintick and
                 (fvgMode != "Required" or fvgOK) and (trendMode != "Required" or trendOK) and
                 (bosMode != "Required" or bosOK) and score >= minScore
            if not na(z.bx)
                box.set_right(z.bx, bar_index)
            if not na(z.ln)
                line.set_x2(z.ln, bar_index)
            if passes
                if z.dir == 1 and score > nz(longScore, -1)
                    longSignal := true
                    longEntry := entry
                    longSL := stop
                    longTP := target
                    longScore := score
                    bestLong := z
                else if z.dir == -1 and score > nz(shortScore, -1)
                    shortSignal := true
                    shortEntry := entry
                    shortSL := stop
                    shortTP := target
                    shortScore := score
                    bestShort := z
            removeZone := true
        else
            if touched
                z.touches += 1
            if invalid or expired or z.touches >= maxTouch
                // Invalidated zones are removed. Expired zones retain drawings
                // as historical context until TradingView drawing GC removes them.
                if invalid
                    if not na(z.bx)
                        box.delete(z.bx)
                    if not na(z.ln)
                        line.delete(z.ln)
                removeZone := true
        if removeZone
            array.remove(zones, i)
 
drawPosition(Zone z, float entry, float stop, float target, int score) =>
    color col = z.dir == 1 ? bullCol : bearCol
    int rightX = bar_index + setupW
    if onlyLast and array.size(positions) > 0
        for k = 0 to array.size(positions) - 1
            deletePosition(array.get(positions, k))
        array.clear(positions)
    box targetBox = na
    box riskBox = na
    line targetLine = na
    if dispMode == "Setup"
        targetBox := box.new(bar_index, math.max(entry, target), rightX, math.min(entry, target),
             border_color = color.new(bullCol, 40), bgcolor = color.new(bullCol, setupTran))
        riskBox := box.new(bar_index, math.max(entry, stop), rightX, math.min(entry, stop),
             border_color = color.new(bearCol, 40), bgcolor = color.new(bearCol, setupTran))
    if showEntry
        targetLine := line.new(bar_index, target, rightX, target, color = color.new(col, 20), style = line.style_dotted)
    label mark = na
    label textLabel = na
    if dispMode == "Signal"
        float markerY = z.dir == 1 ? low : high
        float textY = z.dir == 1 ? low - atr * 0.5 : high + atr * 0.5
        string title = z.dir == 1 ? "Long Signal" : "Short Signal"
        string caption = showScore ? title + " | " + str.tostring(score) + "/100" : title
        mark := label.new(bar_index, markerY, "", yloc = yloc.price,
             style = z.dir == 1 ? label.style_triangleup : label.style_triangledown,
             color = col, size = size.small)
        textLabel := label.new(bar_index, textY, caption, yloc = yloc.price,
             style = label.style_none, textcolor = col, size = size.tiny)
    array.push(positions, Position.new(z.bx, z.ln, targetBox, riskBox, targetLine, mark, textLabel))
    if array.size(positions) > MAX_POS
        deletePosition(array.shift(positions))
 
if longSignal
    drawPosition(bestLong, longEntry, longSL, longTP, longScore)
    array.push(trades, Trade.new(1, longEntry, longSL, longTP, math.abs(longEntry - longSL), bar_index))
if shortSignal
    drawPosition(bestShort, shortEntry, shortSL, shortTP, shortScore)
    array.push(trades, Trade.new(-1, shortEntry, shortSL, shortTP, math.abs(shortEntry - shortSL), bar_index))
while array.size(trades) > 200
    array.shift(trades)
 
// =============================================================================
// ALERTS (SEPARATE LONG/SHORT VALUES, NEVER SHARED OR OVERWRITTEN)
// =============================================================================
message(string side, float entry, float stop, float target, int score) =>
    string m = ""
    if alertFmt == "JSON"
        m := '{"source":"TRH","side":"' + side + '","symbol":"' + syminfo.ticker +
             '","tf":"' + timeframe.period +
             '","entry":' + str.tostring(entry, format.mintick) +
             ',"sl":' + str.tostring(stop, format.mintick) +
             ',"tp":' + str.tostring(target, format.mintick) +
             ',"score":' + str.tostring(score) +
             ',"time":' + str.tostring(time_close) + '}'
    else
        m := "TRH " + side + " | " + syminfo.ticker + " | " + timeframe.period +
             " | " + (entryBasis == "Signal Close" ? "Entry (close): " : "Indicative entry: ") + str.tostring(entry, format.mintick) +
             " | SL: " + str.tostring(stop, format.mintick) +
             " | TP: " + str.tostring(target, format.mintick) +
             " | Confluence score: " + str.tostring(score) + "/100"
    m
 
if useAlert and longSignal
    alert(message("LONG", longEntry, longSL, longTP, longScore), alert.freq_all)
if useAlert and shortSignal
    alert(message("SHORT", shortEntry, shortSL, shortTP, shortScore), alert.freq_all)
 
alertcondition(longSignal, "TRH Long Signal", "TRH: confirmed demand-zone long signal at chart-bar close.")
alertcondition(shortSignal, "TRH Short Signal", "TRH: confirmed supply-zone short signal at chart-bar close.")
alertcondition(longSignal or shortSignal, "TRH Any Signal", "TRH: confirmed zone signal at chart-bar close.")
alertcondition(newFvg1, "TRH FVG - TF1", "TRH: a new confirmed FVG was detected on timeframe 1.")
alertcondition(newFvg2, "TRH FVG - TF2", "TRH: a new confirmed FVG was detected on timeframe 2.")
alertcondition(newFvg1 or newFvg2, "TRH FVG - Any", "TRH: a new confirmed FVG was detected.")
 
// =============================================================================
// STATS TABLE (HEURISTIC; NO SPREAD, SLIPPAGE OR COMMISSION)
// =============================================================================
tblPos = statsPos == "Top Left" ? position.top_left : statsPos == "Bottom Right" ? position.bottom_right :
     statsPos == "Bottom Left" ? position.bottom_left : position.top_right
var table statTbl = table.new(tblPos, 2, 8, bgcolor = color.new(#131722, 15),
     border_color = color.new(color.gray, 75), border_width = 1)
 
statRow(table tb, int row, string k, string v, color vc) =>
    table.cell(tb, 0, row, k, text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, row, v, text_color = vc, text_size = size.small, text_halign = text.align_right)
 
if showStats and barstate.islast
    int decided = nWin + nLoss
    int closedN = decided + nFlat
    float winRate = decided > 0 ? nWin * 100.0 / decided : na
    float avgR = closedN > 0 ? sumR / closedN : na
    float pf = grossLoss > 0 ? grossWin / grossLoss : na
    color netCol = sumR > 0 ? bullCol : sumR < 0 ? bearCol : color.silver
    statRow(statTbl, 0, "TRH v3 Stats", entryBasis, color.white)
    statRow(statTbl, 1, "Closed trades", str.tostring(closedN), color.white)
    statRow(statTbl, 2, "Wins / Losses", str.tostring(nWin) + " / " + str.tostring(nLoss), color.white)
    statRow(statTbl, 3, "Win rate", na(winRate) ? "-" : str.tostring(winRate, "#.0") + "%", color.white)
    statRow(statTbl, 4, "Net R", str.tostring(sumR, "+#.##;-#.##"), netCol)
    statRow(statTbl, 5, "Avg R / trade", na(avgR) ? "-" : str.tostring(avgR, "+#.##;-#.##"), netCol)
    statRow(statTbl, 6, "Profit factor", na(pf) ? (grossWin > 0 ? "∞" : "-") : str.tostring(pf, "#.##"), color.white)
    statRow(statTbl, 7, "Open trades", str.tostring(array.size(trades)), color.white)
 
// Data-window values are na when there is no corresponding signal.
plot(longSignal ? 1 : 0, "Long Trigger", display = display.data_window)
plot(shortSignal ? 1 : 0, "Short Trigger", display = display.data_window)
plot(longEntry, "Long Entry", display = display.data_window)
plot(longSL, "Long Stop Loss", display = display.data_window)
plot(longTP, "Long Target", display = display.data_window)
plot(longScore, "Long Confluence Score", display = display.data_window)
plot(shortEntry, "Short Entry", display = display.data_window)
plot(shortSL, "Short Stop Loss", display = display.data_window)
plot(shortTP, "Short Target", display = display.data_window)
plot(shortScore, "Short Confluence Score", display = display.data_window)
plot(array.size(gaps1), "Live FVG TF1", display = display.data_window)
plot(array.size(gaps2), "Live FVG TF2", display = display.data_window)
plot(sumR, "Net R (closed)", display = display.data_window)

← 返回列表