本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// 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) v2 - public edition | Author: DrFX
// Educational overlay. Signals are confirmed at chart-bar close, not orders or fills.
indicator("Trading Room Hunter - Supply Demand Zones & FVG [DrFX]", "TRH v2", 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
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
// =============================================================================
// 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)
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)
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)
fvgMode = input.string("Score", "FVG Confluence", options = ["Off", "Score", "Required"], group = GQ)
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)
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
// =============================================================================
// SWING AND DISPLACEMENT
// =============================================================================
ph = ta.pivothigh(high, pivotPeriod, pivotPeriod)
pl = ta.pivotlow(low, pivotPeriod, pivotPeriod)
var float pendHigh = na
var int pendHighBar = na
var float pendLow = na
var int pendLowBar = na
var float lastPH = na
var int lastPHBar = na
var float lastPL = na
var int lastPLBar = na
if not na(ph)
pendHigh := ph
pendHighBar := bar_index - pivotPeriod
lastPH := ph
lastPHBar := bar_index - pivotPeriod
if not na(pl)
pendLow := pl
pendLowBar := bar_index - pivotPeriod
lastPL := pl
lastPLBar := bar_index - pivotPeriod
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(lastPL) and not na(pendHighBar) and lastPLBar > pendHighBar and close < lastPL
demBOS = not na(lastPH) and not na(pendLowBar) and lastPHBar > pendLowBar and close > lastPH
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 = high[demOff]
demRaw = useWick ? low[demOff] : math.min(open[demOff], close[demOff])
supProx = low[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
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) =>
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, 0, newBox, newLine))
trimZones(isLong ? 1 : -1)
if demOK and (not noOverlap or not overlapZone(1, math.max(demProx, demDist), math.min(demProx, demDist)))
registerZone(true, demProx, demDist, demOff, demPower, demVel, demBOS)
pendLow := na
pendLowBar := na
if supOK and (not noOverlap or not overlapZone(-1, math.max(supProx, supDist), math.min(supProx, supDist)))
registerZone(false, supProx, supDist, supOff, supPower, supVel, supBOS)
pendHigh := na
pendHighBar := na
// =============================================================================
// FAIR VALUE GAPS: SAME TF, CONFIRMED HTF, COMPLETE AVAILABLE LTF INTRABARS
// =============================================================================
// 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>()
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))
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
// =============================================================================
// 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)))
// =============================================================================
// CONFIRMED ENTRY SIGNALS
// =============================================================================
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
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)
// Entry is an indicative zone price, NOT an asserted intrabar fill.
float entry = z.dir == 1 ? math.min(open, z.prox) : math.max(open, z.prox)
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
float zoneTop = math.max(z.prox, z.dist)
float zoneBot = math.min(z.prox, z.dist)
bool fvgOK = fvgOn and (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 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 passes
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 keptBox = na
line keptLine = na
if not na(z.bx)
box.set_right(z.bx, bar_index)
keptBox := z.bx
if not na(z.ln)
line.set_x2(z.ln, bar_index)
keptLine := z.ln
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(keptBox, keptLine, targetBox, riskBox, targetLine, mark, textLabel))
if array.size(positions) > MAX_POS
deletePosition(array.shift(positions))
if z.dir == 1
longSignal := true
longEntry := entry
longSL := stop
longTP := target
longScore := score
else
shortSignal := true
shortEntry := entry
shortSL := stop
shortTP := target
shortScore := score
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)
// =============================================================================
// ALERTS (SEPARATE LONG/SHORT VALUES, NEVER SHARED OR OVERWRITTEN)
// =============================================================================
message(string side, float entry, float stop, float target, int score) =>
"TRH " + side + " | " + syminfo.ticker + " | " + timeframe.period +
" | 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"
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.")
// 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 Indicative 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 Indicative 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)