TOLAG Structure Precision | TGL 7

TOLAG · study · 858 行 · 点赞 683 · TradingView 原页

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

Pine Script

//@version=6
// Copyright (c) 2026 TOLAG Indicators. All rights reserved.
// TOLAG Structure Precision | TGL 7 + Original H3 LQ V1.1
// H3 event conditions and chart-label lifecycle follow the
// supplied H3 Liquidity Grab MTF v1.5 Color + Dashboard v2.4.
// H3 dashboard deliberately excluded.
 
indicator("TOLAG Structure Precision | TGL 7 + Original H3 LQ V1.1", shorttitle="TOLAG TGL7 H3", overlay=true, max_lines_count=400, max_labels_count=400, max_boxes_count=200, max_bars_back=500)
 
//============================================================
// INPUTS
//============================================================
string G1 = "01 | Structure"
pivotLen = input.int(5, "Major pivot length", minval=2, maxval=30, group=G1)
breakATR = input.float(0.10, "Break clearance ATR", minval=0, step=0.05, group=G1)
impulseATR = input.float(0.85, "Displacement body ATR", minval=0.1, step=0.05, group=G1)
originSearch = input.int(12, "Origin candle search", minval=2, maxval=40, group=G1)
zoneMaxATR = input.float(2.2, "Maximum zone height ATR", minval=0.2, step=0.1, group=G1)
maxZones = input.int(8, "Retained zones", minval=2, maxval=24, group=G1)
extendZones = input.int(70, "Zone extension", minval=10, maxval=250, group=G1)
showStructure = input.bool(true, "Show BOS / MSS", group=G1)
showZones = input.bool(true, "Show supply/demand zones", group=G1)
wickOrigin = input.bool(true, "Use origin wicks", group=G1)
 
string G2 = "02 | Estimated Pressure"
showPressure = input.bool(true, "Show estimated pressure", group=G2)
pressureLookback = input.int(5, "Origin sample", minval=1, maxval=12, group=G2)
pressureFloor = input.float(0.05, "Minimum directional share", minval=0, maxval=0.45, step=0.05, group=G2)
pressureOpacity = input.int(65, "Pressure transparency", minval=30, maxval=95, group=G2)
 
string G3 = "03 | Original H3 Liquidity"
signalSource = input.string("H3 Liquidity", "Signal source", options=["H3 Liquidity", "TGL 7 Precision", "Both Signals", "Confluence"], group=G3)
showH3Arrows = input.bool(true, "Show H3 BUY / SELL arrows", group=G3)
showH3Lines = input.bool(false, "Show original untapped level lines", group=G3)
maxH3Lines = input.int(20, "Max original liquidity lines", minval=1, maxval=100, group=G3)
h3LineWidth = input.int(1, "Liquidity line width", minval=1, maxval=4, group=G3)
h3LineColor = input.color(#624BFF, "Liquidity line color", group=G3)
h3BuyColor = input.color(#00F090, "Bottom marker BUY", group=G3)
h3SellColor = input.color(#FF3158, "Top marker SELL", group=G3)
h3MarkerSize = input.string("Small", "Marker size", options=["Tiny", "Small", "Normal", "Large"], group=G3)
h3HistoricalMode = input.string("Original Surviving LQ", "Historical marker behavior", options=["Original Surviving LQ", "Keep Every Signal"], group=G3)
 
string G4 = "04 | Precision Engine"
precisionEngine = input.string("Sweep + Shift", "Entry engine", options=["Sweep + Shift", "Displacement Retest", "Break + Retest", "Any Engine"], group=G4)
sweepPivot = input.int(6, "Sweep pivot length", minval=2, maxval=20, group=G4)
setupWindow = input.int(18, "Setup lifetime", minval=2, maxval=100, group=G4)
signalCooldown = input.int(8, "Precision cooldown", minval=0, maxval=100, group=G4)
requireHTF = input.bool(false, "Require HTF alignment", group=G4)
requirePressure = input.bool(false, "Require pressure advantage", group=G4)
minPressure = input.float(55, "Minimum directional pressure", minval=50, maxval=90, group=G4)
requireReclaim = input.bool(true, "Require zone midpoint reclaim", group=G4)
maxZoneTests = input.int(3, "Maximum qualifying zone visits", minval=1, maxval=10, group=G4)
confluenceBars = input.int(5, "Confluence window", minval=0, maxval=30, group=G4)
showPrecisionMarkers = input.bool(true, "Show original precision markers", group=G4)
 
string G5 = "05 | Optional Trade Drawings"
showTrades = input.bool(false, "Show trade drawings", group=G5)
tradeSource = input.string("Selected Signals", "Drawing source", options=["Selected Signals", "H3 Only", "Precision Only"], group=G5)
stopChoice = input.string("Structure + ATR", "Stop method", options=["Structure + ATR", "ATR Only", "Zone Invalidation"], group=G5)
stopATR = input.float(1.8, "ATR stop", minval=0.2, step=0.1, group=G5)
stopBuffer = input.float(0.25, "Structure buffer ATR", minval=0, step=0.05, group=G5)
tp1R = input.float(1.5, "TP1 R", minval=0.25, step=0.25, group=G5)
tp2R = input.float(3.0, "TP2 R", minval=0.5, step=0.25, group=G5)
tradeLength = input.int(35, "Drawing length", minval=5, maxval=150, group=G5)
retainTrades = input.int(3, "Retain drawings", minval=1, maxval=12, group=G5)
tradeOpacity = input.int(90, "Drawing transparency", minval=70, maxval=98, group=G5)
 
string G6 = "06 | MTF Context"
tf1 = input.timeframe("5", "TF1", group=G6)
tf2 = input.timeframe("15", "TF2", group=G6)
tf3 = input.timeframe("60", "TF3", group=G6)
tf4 = input.timeframe("240", "TF4", group=G6)
mtfFast = input.int(20, "Fast EMA", minval=2, group=G6)
mtfSlow = input.int(50, "Slow EMA", minval=5, group=G6)
 
string G7 = "07 | Chart Styling"
demandColor = input.color(#00CDB1, "Demand", group=G7)
supplyColor = input.color(#FF4164, "Supply", group=G7)
structureColor = input.color(#67B9FF, "BOS / MSS", group=G7)
zoneOpacity = input.int(87, "Zone transparency", minval=55, maxval=97, group=G7)
zoneFont = input.string("Tiny", "Zone font", options=["Tiny", "Small", "Normal", "Large"], group=G7)
eventFont = input.string("Tiny", "Structure font", options=["Tiny", "Small", "Normal", "Large"], group=G7)
showZonePrice = input.bool(false, "Show zone prices", group=G7)
 
string G8 = "08 | MTF Dashboard"
showDashboard = input.bool(true, "Show dashboard", group=G8)
dashPosition = input.string("Top Right", "Position", options=["Top Left", "Top Right", "Bottom Left", "Bottom Right", "Top Center", "Bottom Center", "Middle Left", "Middle Right"], group=G8)
dashFont = input.string("Small", "Size", options=["Tiny", "Small", "Normal", "Large"], group=G8)
dashLayout = input.string("Detailed", "Layout", options=["Compact", "Detailed"], group=G8)
dashBackground = input.color(#101A29, "Background", group=G8)
dashHeader = input.color(#243C56, "Header", group=G8)
dashText = input.color(#F2F7FF, "Text", group=G8)
dashAccent = input.color(#53C9FF, "Accent", group=G8)
 
string G9 = "09 | Action Panel"
showAction = input.bool(true, "Show action panel", group=G9)
actionPosition = input.string("Middle Right", "Position", options=["Top Left", "Top Right", "Bottom Left", "Bottom Right", "Top Center", "Bottom Center", "Middle Left", "Middle Right"], group=G9)
actionFont = input.string("Small", "Size", options=["Tiny", "Small", "Normal", "Large"], group=G9)
actionBackground = input.color(#142B37, "Background", group=G9)
actionHeader = input.color(#235163, "Header", group=G9)
 
//============================================================
// HELPERS
//============================================================
f_size(string v) =>
    switch v
        "Tiny" => size.tiny
        "Normal" => size.normal
        "Large" => size.large
        => size.small
 
f_pos(string v) =>
    switch v
        "Top Left" => position.top_left
        "Bottom Left" => position.bottom_left
        "Bottom Right" => position.bottom_right
        "Top Center" => position.top_center
        "Bottom Center" => position.bottom_center
        "Middle Left" => position.middle_left
        "Middle Right" => position.middle_right
        => position.top_right
 
f_price(float v) =>
    str.tostring(v, format.mintick)
 
f_pressure(int origin) =>
    float buyVol = 0.0
    float sellVol = 0.0
    for k = 0 to pressureLookback - 1
        int off = origin + k
        float rng = math.max(high[off] - low[off], syminfo.mintick)
        float share = math.max(pressureFloor, math.min(1.0 - pressureFloor, (close[off] - low[off]) / rng))
        float v = nz(volume[off], 0)
        buyVol += v * share
        sellVol += v * (1 - share)
    float total = buyVol + sellVol
    total > 0 ? 100 * buyVol / total : na
 
f_mtf(string tf) =>
    bool higher = timeframe.in_seconds(tf) > timeframe.in_seconds(timeframe.period)
    float confirmed = request.security(syminfo.tickerid, tf, (ta.ema(close, mtfFast) - ta.ema(close, mtfSlow))[1], lookahead=barmerge.lookahead_on)
    float sampled = request.security(syminfo.tickerid, tf, ta.ema(close, mtfFast) - ta.ema(close, mtfSlow), lookahead=barmerge.lookahead_off)
    float delta = higher ? confirmed : sampled
    na(delta) ? 0 : delta > 0 ? 1 : delta < 0 ? -1 : 0
 
f_dir(int d) =>
    d == 1 ? "UP" : d == -1 ? "DOWN" : "FLAT"
 
f_dirColor(int d) =>
    d == 1 ? h3BuyColor : d == -1 ? h3SellColor : dashText
 
//============================================================
// ORIGINAL H3 LIQUIDITY DETECTION
// Exact supplied source conditions.
//============================================================
float prevOpen = open[1]
float prevClose = close[1]
float prevHigh = high[1]
float prevLow = low[1]
 
float prevBodyHigh = math.max(prevOpen, prevClose)
float prevBodyLow = math.min(prevOpen, prevClose)
 
bool tookHigh = high > prevHigh
bool tookLow = low < prevLow
bool onlyOneSideTaken = tookHigh != tookLow
bool closeInsidePrevBody = close <= prevBodyHigh and close >= prevBodyLow
 
bool liquidityGrab = onlyOneSideTaken and closeInsidePrevBody
 
// Preserve the original chart's directional mapping:
// tookHigh => green marker below bar.
// tookLow  => red marker above bar.
bool h3Buy = barstate.isconfirmed and liquidityGrab and tookHigh
bool h3Sell = barstate.isconfirmed and liquidityGrab and tookLow
 
//============================================================
// ORIGINAL H3 LEVEL / LABEL LIFECYCLE
//
// Unlike plotshape(), label.new() allows historical labels
// to be deleted when their corresponding LQ is invalidated.
//
// This is the essential difference from the prior version.
//============================================================
var array<line> supportLines = array.new<line>()
var array<float> supportLevels = array.new<float>()
var array<label> supportLabels = array.new<label>()
 
var array<line> resistanceLines = array.new<line>()
var array<float> resistanceLevels = array.new<float>()
var array<label> resistanceLabels = array.new<label>()
 
bool manageLevels = showH3Arrows or showH3Lines
 
if manageLevels and h3HistoricalMode == "Original Surviving LQ"
    if array.size(supportLevels) > 0
        for i = array.size(supportLevels) - 1 to 0
            float level = array.get(supportLevels, i)
            if low < level
                line sl = array.get(supportLines, i)
                label lb = array.get(supportLabels, i)
                if not na(sl)
                    line.delete(sl)
                if not na(lb)
                    label.delete(lb)
                array.remove(supportLines, i)
                array.remove(supportLabels, i)
                array.remove(supportLevels, i)
 
    if array.size(resistanceLevels) > 0
        for i = array.size(resistanceLevels) - 1 to 0
            float level = array.get(resistanceLevels, i)
            if high > level
                line rl = array.get(resistanceLines, i)
                label lb = array.get(resistanceLabels, i)
                if not na(rl)
                    line.delete(rl)
                if not na(lb)
                    label.delete(lb)
                array.remove(resistanceLines, i)
                array.remove(resistanceLabels, i)
                array.remove(resistanceLevels, i)
 
// Original source creates a level from the OPPOSITE
// previous-candle extreme.
if manageLevels and (h3Buy or h3Sell)
    if h3Buy
        float level = prevLow
        label lb = na
        line ln = na
 
        if showH3Arrows
            lb := label.new(bar_index, low, "BUY", yloc=yloc.belowbar, style=label.style_label_up, color=h3BuyColor, textcolor=#062317, size=f_size(h3MarkerSize))
 
        if showH3Lines
            ln := line.new(bar_index, level, bar_index + 10, level, color=h3LineColor, width=h3LineWidth, extend=extend.right)
 
        array.push(supportLevels, level)
        array.push(supportLines, ln)
        array.push(supportLabels, lb)
 
    if h3Sell
        float level = prevHigh
        label lb = na
        line ln = na
 
        if showH3Arrows
            lb := label.new(bar_index, high, "SELL", yloc=yloc.abovebar, style=label.style_label_down, color=h3SellColor, textcolor=color.white, size=f_size(h3MarkerSize))
 
        if showH3Lines
            ln := line.new(bar_index, level, bar_index + 10, level, color=h3LineColor, width=h3LineWidth, extend=extend.right)
 
        array.push(resistanceLevels, level)
        array.push(resistanceLines, ln)
        array.push(resistanceLabels, lb)
 
// Original support-first pruning when lines are enabled.
// It removes the oldest support first, then resistance.
if showH3Lines
    while array.size(supportLevels) + array.size(resistanceLevels) > maxH3Lines
        if array.size(supportLevels) > 0
            line ln = array.shift(supportLines)
            label lb = array.shift(supportLabels)
            array.shift(supportLevels)
            if not na(ln)
                line.delete(ln)
            if not na(lb)
                label.delete(lb)
        else if array.size(resistanceLevels) > 0
            line ln = array.shift(resistanceLines)
            label lb = array.shift(resistanceLabels)
            array.shift(resistanceLevels)
            if not na(ln)
                line.delete(ln)
            if not na(lb)
                label.delete(lb)
 
// Safety limit for label-only operation.
// Original H3 has no max-line pruning when lines are OFF.
while array.size(supportLabels) + array.size(resistanceLabels) > 250
    if array.size(supportLabels) > 0
        label lb = array.shift(supportLabels)
        line ln = array.shift(supportLines)
        array.shift(supportLevels)
        if not na(lb)
            label.delete(lb)
        if not na(ln)
            line.delete(ln)
    else
        label lb = array.shift(resistanceLabels)
        line ln = array.shift(resistanceLines)
        array.shift(resistanceLevels)
        if not na(lb)
            label.delete(lb)
        if not na(ln)
            line.delete(ln)
 
// Optional permanent signal history.
// This mode is NOT the original H3 chart behavior.
plotshape(showH3Arrows and h3HistoricalMode == "Keep Every Signal" and h3Buy, title="Permanent H3 BUY", style=shape.triangleup, location=location.belowbar, color=h3BuyColor, text="BUY", textcolor=h3BuyColor, size=size.small)
plotshape(showH3Arrows and h3HistoricalMode == "Keep Every Signal" and h3Sell, title="Permanent H3 SELL", style=shape.triangledown, location=location.abovebar, color=h3SellColor, text="SELL", textcolor=h3SellColor, size=size.small)
 
//============================================================
// TGL 7 STRUCTURE ENGINE
//============================================================
float atr = ta.atr(14)
float ph = ta.pivothigh(high, pivotLen, pivotLen)
float pl = ta.pivotlow(low, pivotLen, pivotLen)
 
var float majorHigh = na
var float majorLow = na
var int majorHighBar = na
var int majorLowBar = na
 
var bool highTaken = false
var bool lowTaken = false
 
var int structureDir = 0
var int lastBullBreak = na
var int lastBearBreak = na
var string lastStructure = "NONE"
 
var array<box> zoneBoxes = array.new<box>()
var array<box> zoneBars = array.new<box>()
var array<float> zoneTop = array.new<float>()
var array<float> zoneBottom = array.new<float>()
var array<int> zoneDir = array.new<int>()
var array<int> zoneBirth = array.new<int>()
var array<int> zoneTests = array.new<int>()
var array<bool> zoneWasInside = array.new<bool>()
var array<float> zoneBuyPct = array.new<float>()
 
var array<line> structureLines = array.new<line>()
var array<label> structureLabels = array.new<label>()
 
bool bullBreak = false
bool bearBreak = false
 
if barstate.isconfirmed
    if not na(ph)
        majorHigh := ph
        majorHighBar := bar_index - pivotLen
        highTaken := false
 
    if not na(pl)
        majorLow := pl
        majorLowBar := bar_index - pivotLen
        lowTaken := false
 
    if not na(majorHigh) and not highTaken and close > majorHigh + atr * breakATR and close > open and close - open >= atr * impulseATR
        bullBreak := true
        bool shift = structureDir == -1
        structureDir := 1
        highTaken := true
        lastBullBreak := bar_index
        lastStructure := shift ? "BULL MSS" : "BULL BOS"
 
        if showStructure
            line ln = line.new(majorHighBar, majorHigh, bar_index, majorHigh, color=structureColor, style=line.style_dashed)
            label lb = label.new(bar_index, majorHigh, shift ? "MSS ↑" : "BOS ↑", color=color.new(structureColor, 85), textcolor=structureColor, size=f_size(eventFont), style=label.style_label_down)
            array.push(structureLines, ln)
            array.push(structureLabels, lb)
 
    if not na(majorLow) and not lowTaken and close < majorLow - atr * breakATR and close < open and open - close >= atr * impulseATR
        bearBreak := true
        bool shift = structureDir == 1
        structureDir := -1
        lowTaken := true
        lastBearBreak := bar_index
        lastStructure := shift ? "BEAR MSS" : "BEAR BOS"
 
        if showStructure
            line ln = line.new(majorLowBar, majorLow, bar_index, majorLow, color=structureColor, style=line.style_dashed)
            label lb = label.new(bar_index, majorLow, shift ? "MSS ↓" : "BOS ↓", color=color.new(structureColor, 85), textcolor=structureColor, size=f_size(eventFont), style=label.style_label_up)
            array.push(structureLines, ln)
            array.push(structureLabels, lb)
 
    if bullBreak or bearBreak
        int d = bullBreak ? 1 : -1
        int origin = na
 
        for k = 1 to originSearch
            if na(origin) and (d == 1 ? close[k] < open[k] : close[k] > open[k])
                origin := k
 
        if not na(origin)
            float hi = wickOrigin ? high[origin] : math.max(open[origin], close[origin])
            float lo = wickOrigin ? low[origin] : math.min(open[origin], close[origin])
 
            if hi > lo and hi - lo <= atr * zoneMaxATR
                float pct = f_pressure(origin)
                color c = d == 1 ? demandColor : supplyColor
 
                box outer = box.new(bar_index - origin, hi, bar_index + extendZones, lo, bgcolor=color.new(c, zoneOpacity), border_color=c)
                box inner = box.new(bar_index - origin, hi, bar_index - origin + 1, lo, bgcolor=color.new(demandColor, pressureOpacity), border_color=color.new(demandColor, 100))
 
                array.unshift(zoneBoxes, outer)
                array.unshift(zoneBars, inner)
                array.unshift(zoneTop, hi)
                array.unshift(zoneBottom, lo)
                array.unshift(zoneDir, d)
                array.unshift(zoneBirth, bar_index)
                array.unshift(zoneTests, 0)
                array.unshift(zoneWasInside, false)
                array.unshift(zoneBuyPct, pct)
 
while array.size(structureLines) > 65
    line.delete(array.shift(structureLines))
 
while array.size(structureLabels) > 65
    label.delete(array.shift(structureLabels))
 
//============================================================
// TGL 7 PIVOT SWEEP CONTEXT
//============================================================
float sweepH = ta.pivothigh(high, sweepPivot, sweepPivot)
float sweepL = ta.pivotlow(low, sweepPivot, sweepPivot)
 
var float bsl = na
var float ssl = na
var bool bslAvailable = false
var bool sslAvailable = false
var int lastBullSweep = na
var int lastBearSweep = na
 
if barstate.isconfirmed
    if not na(sweepH)
        bsl := sweepH
        bslAvailable := true
 
    if not na(sweepL)
        ssl := sweepL
        sslAvailable := true
 
    if bslAvailable and high > bsl
        if close < bsl
            lastBearSweep := bar_index
        bslAvailable := false
 
    if sslAvailable and low < ssl
        if close > ssl
            lastBullSweep := bar_index
        sslAvailable := false
 
//============================================================
// MTF TREND CONTEXT
//============================================================
int mtf1 = f_mtf(tf1)
int mtf2 = f_mtf(tf2)
int mtf3 = f_mtf(tf3)
int mtf4 = f_mtf(tf4)
int mtfScore = mtf1 + mtf2 + mtf3 + mtf4
 
bool bullHTF = mtf3 > 0 and mtf4 > 0
bool bearHTF = mtf3 < 0 and mtf4 < 0
 
//============================================================
// ZONE LIFECYCLE + PRECISION SIGNALS
//============================================================
var int lastPrecisionBar = na
bool precisionBuy = false
bool precisionSell = false
 
float precisionTop = na
float precisionBottom = na
 
if barstate.isconfirmed and array.size(zoneBoxes) > 0
    for i = array.size(zoneBoxes) - 1 to 0
        box outer = array.get(zoneBoxes, i)
        box inner = array.get(zoneBars, i)
 
        float hi = array.get(zoneTop, i)
        float lo = array.get(zoneBottom, i)
        int d = array.get(zoneDir, i)
        int birth = array.get(zoneBirth, i)
        int tests = array.get(zoneTests, i)
        bool wasInside = array.get(zoneWasInside, i)
        float pct = array.get(zoneBuyPct, i)
 
        bool invalid = d == 1 ? close < lo : close > hi
 
        if invalid and bar_index > birth
            box.delete(outer)
            box.delete(inner)
            array.remove(zoneBoxes, i)
            array.remove(zoneBars, i)
            array.remove(zoneTop, i)
            array.remove(zoneBottom, i)
            array.remove(zoneDir, i)
            array.remove(zoneBirth, i)
            array.remove(zoneTests, i)
            array.remove(zoneWasInside, i)
            array.remove(zoneBuyPct, i)
        else
            bool inside = high >= lo and low <= hi
            bool newTest = inside and not wasInside and bar_index > birth
 
            if newTest
                tests += 1
                array.set(zoneTests, i, tests)
 
            array.set(zoneWasInside, i, inside)
 
            bool directionalCandle = d == 1 ? close > open : close < open
            bool reclaim = not requireReclaim or (d == 1 ? close >= (hi + lo) / 2 : close <= (hi + lo) / 2)
 
            bool sweepContext = d == 1 ? not na(lastBullSweep) and bar_index - lastBullSweep <= setupWindow : not na(lastBearSweep) and bar_index - lastBearSweep <= setupWindow
 
            bool breakContext = d == 1 ? not na(lastBullBreak) and bar_index - lastBullBreak <= setupWindow : not na(lastBearBreak) and bar_index - lastBearBreak <= setupWindow
 
            bool displacementContext = breakContext and structureDir == d
 
            bool breakoutRetestContext = breakContext and (d == 1 ? not na(majorHigh) and close > majorHigh : not na(majorLow) and close < majorLow)
 
            bool engineOK = switch precisionEngine
                "Sweep + Shift" => sweepContext and breakContext
                "Displacement Retest" => displacementContext
                "Break + Retest" => breakoutRetestContext
                => (sweepContext and breakContext) or displacementContext or breakoutRetestContext
 
            bool pressureOK = not requirePressure or (not na(pct) and (d == 1 ? pct >= minPressure : 100 - pct >= minPressure))
            bool htfOK = not requireHTF or (d == 1 ? bullHTF : bearHTF)
            bool cooldownOK = na(lastPrecisionBar) or bar_index - lastPrecisionBar >= signalCooldown
 
            bool qualifies = newTest and tests <= maxZoneTests and directionalCandle and reclaim and engineOK and pressureOK and htfOK and cooldownOK
 
            if qualifies and not precisionBuy and not precisionSell
                precisionBuy := d == 1
                precisionSell := d == -1
                precisionTop := hi
                precisionBottom := lo
                lastPrecisionBar := bar_index
 
            box.set_right(outer, bar_index + extendZones)
 
            color c = d == 1 ? demandColor : supplyColor
            box.set_bgcolor(outer, showZones ? color.new(c, zoneOpacity) : color.new(c, 100))
            box.set_border_color(outer, showZones ? c : color.new(c, 100))
 
            int leftEdge = box.get_left(outer)
            int rightEdge = box.get_right(outer)
            float share = na(pct) ? 0.5 : pct / 100.0
            int fillRight = math.min(rightEdge, leftEdge + math.max(1, int((rightEdge - leftEdge) * share)))
 
            box.set_left(inner, leftEdge)
            box.set_right(inner, fillRight)
            box.set_top(inner, hi)
            box.set_bottom(inner, lo)
 
            box.set_bgcolor(inner, showZones and showPressure and not na(pct) ? color.new(demandColor, pressureOpacity) : color.new(demandColor, 100))
            box.set_border_color(inner, color.new(demandColor, 100))
 
            string desc = (d == 1 ? "DEMAND" : "SUPPLY") + " • " + (tests == 0 ? "FRESH" : "TEST " + str.tostring(tests))
 
            if showPressure
                desc += na(pct) ? "\nEST PRESSURE N/A" : "\nEST BUY " + str.tostring(pct, "#.0") + "% | SELL " + str.tostring(100 - pct, "#.0") + "%"
 
            if showZonePrice
                desc += "\n" + f_price(lo) + " - " + f_price(hi)
 
            box.set_text(outer, showZones ? desc : "")
            box.set_text_size(outer, f_size(zoneFont))
            box.set_text_color(outer, c)
            box.set_text_halign(outer, text.align_right)
 
while array.size(zoneBoxes) > maxZones
    box.delete(array.pop(zoneBoxes))
    box.delete(array.pop(zoneBars))
    array.pop(zoneTop)
    array.pop(zoneBottom)
    array.pop(zoneDir)
    array.pop(zoneBirth)
    array.pop(zoneTests)
    array.pop(zoneWasInside)
    array.pop(zoneBuyPct)
 
//============================================================
// SIGNAL ROUTING
//============================================================
var int lastPrecisionBuy = na
var int lastPrecisionSell = na
var int lastH3Buy = na
var int lastH3Sell = na
 
if precisionBuy
    lastPrecisionBuy := bar_index
if precisionSell
    lastPrecisionSell := bar_index
if h3Buy
    lastH3Buy := bar_index
if h3Sell
    lastH3Sell := bar_index
 
bool recentPrecisionBuy = not na(lastPrecisionBuy) and bar_index - lastPrecisionBuy <= confluenceBars
bool recentPrecisionSell = not na(lastPrecisionSell) and bar_index - lastPrecisionSell <= confluenceBars
bool recentH3Buy = not na(lastH3Buy) and bar_index - lastH3Buy <= confluenceBars
bool recentH3Sell = not na(lastH3Sell) and bar_index - lastH3Sell <= confluenceBars
 
bool confluenceBuyRaw = (h3Buy and recentPrecisionBuy) or (precisionBuy and recentH3Buy)
bool confluenceSellRaw = (h3Sell and recentPrecisionSell) or (precisionSell and recentH3Sell)
 
var int lastConfluenceBuy = na
var int lastConfluenceSell = na
 
bool confluenceBuy = confluenceBuyRaw and (na(lastConfluenceBuy) or bar_index - lastConfluenceBuy > confluenceBars)
bool confluenceSell = confluenceSellRaw and (na(lastConfluenceSell) or bar_index - lastConfluenceSell > confluenceBars)
 
if confluenceBuy
    lastConfluenceBuy := bar_index
if confluenceSell
    lastConfluenceSell := bar_index
 
bool selectedBuy = switch signalSource
    "H3 Liquidity" => h3Buy
    "TGL 7 Precision" => precisionBuy
    "Both Signals" => h3Buy or precisionBuy
    => confluenceBuy
 
bool selectedSell = switch signalSource
    "H3 Liquidity" => h3Sell
    "TGL 7 Precision" => precisionSell
    "Both Signals" => h3Sell or precisionSell
    => confluenceSell
 
if selectedBuy and selectedSell
    selectedBuy := false
    selectedSell := false
 
bool displayPrecision = signalSource == "TGL 7 Precision" or signalSource == "Both Signals"
 
plotshape(showPrecisionMarkers and displayPrecision and precisionBuy, title="Precision BUY", style=shape.labelup, location=location.belowbar, color=h3BuyColor, text="BUY", textcolor=#062317, size=size.tiny)
plotshape(showPrecisionMarkers and displayPrecision and precisionSell, title="Precision SELL", style=shape.labeldown, location=location.abovebar, color=h3SellColor, text="SELL", textcolor=color.white, size=size.tiny)
 
plotshape(signalSource == "Confluence" and confluenceBuy, title="Confluence BUY", style=shape.diamond, location=location.belowbar, color=h3BuyColor, size=size.small)
plotshape(signalSource == "Confluence" and confluenceSell, title="Confluence SELL", style=shape.diamond, location=location.abovebar, color=h3SellColor, size=size.small)
 
//============================================================
// ZONE STATISTICS
//============================================================
int demandCount = 0
int supplyCount = 0
float nearestBuyPressure = na
float nearestSellPressure = na
float demandDist = na
float supplyDist = na
float nearestDemandLow = na
float nearestSupplyHigh = na
 
if array.size(zoneBoxes) > 0
    for i = 0 to array.size(zoneBoxes) - 1
        int d = array.get(zoneDir, i)
        float hi = array.get(zoneTop, i)
        float lo = array.get(zoneBottom, i)
        float pct = array.get(zoneBuyPct, i)
        float dist = close > hi ? close - hi : close < lo ? lo - close : 0.0
 
        if d == 1
            demandCount += 1
            if na(demandDist) or dist < demandDist
                demandDist := dist
                nearestBuyPressure := pct
                nearestDemandLow := lo
        else
            supplyCount += 1
            if na(supplyDist) or dist < supplyDist
                supplyDist := dist
                nearestSellPressure := pct
                nearestSupplyHigh := hi
 
//============================================================
// OPTIONAL TRADE DRAWINGS - OFF BY DEFAULT
//============================================================
var array<line> tradeLines = array.new<line>()
var array<label> tradeLabels = array.new<label>()
var array<box> tradeBoxes = array.new<box>()
 
var string lastSignal = "NONE"
var float lastEntry = na
var float lastStop = na
var float lastTP1 = na
var float lastTP2 = na
 
if selectedBuy
    lastSignal := "BUY"
else if selectedSell
    lastSignal := "SELL"
 
bool tradeBuy = switch tradeSource
    "H3 Only" => h3Buy
    "Precision Only" => precisionBuy
    => selectedBuy
 
bool tradeSell = switch tradeSource
    "H3 Only" => h3Sell
    "Precision Only" => precisionSell
    => selectedSell
 
if tradeBuy and tradeSell
    tradeBuy := false
    tradeSell := false
 
if showTrades and barstate.isconfirmed and (tradeBuy or tradeSell)
    int d = tradeBuy ? 1 : -1
    float entry = close
    float atrStop = entry - d * atr * stopATR
 
    float reference = d == 1 ? (not na(precisionBottom) ? precisionBottom : not na(nearestDemandLow) ? nearestDemandLow : low) : (not na(precisionTop) ? precisionTop : not na(nearestSupplyHigh) ? nearestSupplyHigh : high)
 
    if d == 1 and reference >= entry
        reference := low
    if d == -1 and reference <= entry
        reference := high
 
    float zoneStop = d == 1 ? reference - atr * stopBuffer : reference + atr * stopBuffer
 
    float stop = switch stopChoice
        "ATR Only" => atrStop
        "Zone Invalidation" => zoneStop
        => d == 1 ? math.min(atrStop, zoneStop) : math.max(atrStop, zoneStop)
 
    float risk = math.max(math.abs(entry - stop), syminfo.mintick)
    float tp1 = entry + d * risk * tp1R
    float tp2 = entry + d * risk * tp2R
 
    lastEntry := entry
    lastStop := stop
    lastTP1 := tp1
    lastTP2 := tp2
 
    int x2 = bar_index + tradeLength
    color c = d == 1 ? h3BuyColor : h3SellColor
 
    box reward = box.new(bar_index, math.max(entry, tp2), x2, math.min(entry, tp2), bgcolor=color.new(c, tradeOpacity), border_color=color.new(c, 70))
    box danger = box.new(bar_index, math.max(entry, stop), x2, math.min(entry, stop), bgcolor=color.new(h3SellColor, tradeOpacity), border_color=color.new(h3SellColor, 70))
 
    array.push(tradeBoxes, reward)
    array.push(tradeBoxes, danger)
 
    array.push(tradeLines, line.new(bar_index, entry, x2, entry, color=#F8CE72))
    array.push(tradeLines, line.new(bar_index, stop, x2, stop, color=h3SellColor))
    array.push(tradeLines, line.new(bar_index, tp1, x2, tp1, color=#63D9FF, style=line.style_dotted))
    array.push(tradeLines, line.new(bar_index, tp2, x2, tp2, color=h3BuyColor))
 
    array.push(tradeLabels, label.new(x2, entry, "ENTRY " + f_price(entry), style=label.style_label_left, color=color.new(#F8CE72, 85), textcolor=#F8CE72, size=size.tiny))
    array.push(tradeLabels, label.new(x2, stop, "SL " + f_price(stop), style=label.style_label_left, color=color.new(h3SellColor, 85), textcolor=h3SellColor, size=size.tiny))
    array.push(tradeLabels, label.new(x2, tp1, "TP1 " + f_price(tp1), style=label.style_label_left, color=color.new(#63D9FF, 85), textcolor=#63D9FF, size=size.tiny))
    array.push(tradeLabels, label.new(x2, tp2, "TP2 " + f_price(tp2), style=label.style_label_left, color=color.new(h3BuyColor, 85), textcolor=h3BuyColor, size=size.tiny))
 
while array.size(tradeLines) > retainTrades * 4
    line.delete(array.shift(tradeLines))
 
while array.size(tradeLabels) > retainTrades * 4
    label.delete(array.shift(tradeLabels))
 
while array.size(tradeBoxes) > retainTrades * 2
    box.delete(array.shift(tradeBoxes))
 
//============================================================
// DASHBOARDS - NO H3 DASHBOARD
//============================================================
string action = "WAIT"
string actionReason = "Awaiting confirmed liquidity event"
color actionColor = dashAccent
 
if selectedBuy
    action := "BUY CONFIRMED"
    actionReason := signalSource
    actionColor := h3BuyColor
else if selectedSell
    action := "SELL CONFIRMED"
    actionReason := signalSource
    actionColor := h3SellColor
else if structureDir == 1
    action := "WATCH BUY"
    actionReason := "Bullish structure • awaiting signal"
    actionColor := h3BuyColor
else if structureDir == -1
    action := "WATCH SELL"
    actionReason := "Bearish structure • awaiting signal"
    actionColor := h3SellColor
 
var table dashboard = table.new(f_pos(dashPosition), 4, 8, bgcolor=dashBackground, border_width=1, border_color=color.new(dashAccent, 80))
var table actionPanel = table.new(f_pos(actionPosition), 2, 3, bgcolor=actionBackground, border_width=1, border_color=color.new(dashAccent, 80))
 
if barstate.islast
    table.clear(dashboard, 0, 0, 3, 7)
    table.clear(actionPanel, 0, 0, 1, 2)
 
    if showDashboard
        table.cell(dashboard, 0, 0, "TOLAG", bgcolor=dashHeader, text_color=dashAccent, text_size=f_size(dashFont))
        table.cell(dashboard, 1, 0, "STRUCTURE", bgcolor=dashHeader, text_color=dashText, text_size=f_size(dashFont))
        table.cell(dashboard, 2, 0, "PRECISION", bgcolor=dashHeader, text_color=dashText, text_size=f_size(dashFont))
        table.cell(dashboard, 3, 0, "TGL 7", bgcolor=dashHeader, text_color=dashAccent, text_size=f_size(dashFont))
 
        table.cell(dashboard, 0, 1, tf1, text_color=dashText, text_size=f_size(dashFont))
        table.cell(dashboard, 1, 1, tf2, text_color=dashText, text_size=f_size(dashFont))
        table.cell(dashboard, 2, 1, tf3, text_color=dashText, text_size=f_size(dashFont))
        table.cell(dashboard, 3, 1, tf4, text_color=dashText, text_size=f_size(dashFont))
 
        table.cell(dashboard, 0, 2, f_dir(mtf1), text_color=f_dirColor(mtf1), text_size=f_size(dashFont))
        table.cell(dashboard, 1, 2, f_dir(mtf2), text_color=f_dirColor(mtf2), text_size=f_size(dashFont))
        table.cell(dashboard, 2, 2, f_dir(mtf3), text_color=f_dirColor(mtf3), text_size=f_size(dashFont))
        table.cell(dashboard, 3, 2, f_dir(mtf4), text_color=f_dirColor(mtf4), text_size=f_size(dashFont))
 
        table.cell(dashboard, 0, 3, "MTF", bgcolor=dashHeader, text_color=dashAccent, text_size=f_size(dashFont))
        table.cell(dashboard, 1, 3, str.tostring(mtfScore) + " / 4", bgcolor=dashHeader, text_color=dashText, text_size=f_size(dashFont))
        table.cell(dashboard, 2, 3, "ZONES D/S", bgcolor=dashHeader, text_color=dashAccent, text_size=f_size(dashFont))
        table.cell(dashboard, 3, 3, str.tostring(demandCount) + " / " + str.tostring(supplyCount), bgcolor=dashHeader, text_color=dashText, text_size=f_size(dashFont))
 
        if dashLayout == "Detailed"
            table.cell(dashboard, 0, 4, "BUY EST", text_color=h3BuyColor, text_size=f_size(dashFont))
            table.cell(dashboard, 1, 4, na(nearestBuyPressure) ? "N/A" : str.tostring(nearestBuyPressure, "#.0") + "%", text_color=dashText, text_size=f_size(dashFont))
            table.cell(dashboard, 2, 4, "SELL EST", text_color=h3SellColor, text_size=f_size(dashFont))
            table.cell(dashboard, 3, 4, na(nearestSellPressure) ? "N/A" : str.tostring(100 - nearestSellPressure, "#.0") + "%", text_color=dashText, text_size=f_size(dashFont))
 
            table.cell(dashboard, 0, 5, "STRUCTURE", text_color=dashAccent, text_size=f_size(dashFont))
            table.cell(dashboard, 1, 5, lastStructure, text_color=dashText, text_size=f_size(dashFont))
            table.cell(dashboard, 2, 5, "SOURCE", text_color=dashAccent, text_size=f_size(dashFont))
            table.cell(dashboard, 3, 5, signalSource, text_color=dashText, text_size=f_size(dashFont))
 
            table.cell(dashboard, 0, 6, "LAST", text_color=dashAccent, text_size=f_size(dashFont))
            table.cell(dashboard, 1, 6, lastSignal, text_color=dashText, text_size=f_size(dashFont))
            table.cell(dashboard, 2, 6, "DRAWINGS", text_color=dashAccent, text_size=f_size(dashFont))
            table.cell(dashboard, 3, 6, showTrades ? "ON" : "OFF", text_color=dashText, text_size=f_size(dashFont))
 
        int actionRow = dashLayout == "Detailed" ? 7 : 4
 
        table.cell(dashboard, 0, actionRow, "ACTION", bgcolor=dashHeader, text_color=dashAccent, text_size=f_size(dashFont))
        table.cell(dashboard, 1, actionRow, action, bgcolor=dashHeader, text_color=actionColor, text_size=f_size(dashFont))
        table.cell(dashboard, 2, actionRow, "BIAS", bgcolor=dashHeader, text_color=dashAccent, text_size=f_size(dashFont))
        table.cell(dashboard, 3, actionRow, structureDir == 1 ? "BULL" : structureDir == -1 ? "BEAR" : "FLAT", bgcolor=dashHeader, text_color=f_dirColor(structureDir), text_size=f_size(dashFont))
 
    if showAction
        table.cell(actionPanel, 0, 0, "TOLAG PRECISION", bgcolor=actionHeader, text_color=dashText, text_size=f_size(actionFont))
        table.cell(actionPanel, 1, 0, signalSource, bgcolor=actionHeader, text_color=dashAccent, text_size=f_size(actionFont))
 
        table.cell(actionPanel, 0, 1, action, text_color=actionColor, text_size=f_size(actionFont))
        table.cell(actionPanel, 1, 1, actionReason, text_color=dashText, text_size=f_size(actionFont))
 
        table.cell(actionPanel, 0, 2, "LAST SIGNAL", text_color=dashAccent, text_size=f_size(actionFont))
        table.cell(actionPanel, 1, 2, lastSignal, text_color=lastSignal == "BUY" ? h3BuyColor : lastSignal == "SELL" ? h3SellColor : dashText, text_size=f_size(actionFont))
 
//============================================================
// ALERTS
// Original event conditions; confirmed candle close.
// Historical label deletion does not cancel an alert.
//============================================================
alertcondition(h3Buy, "TOLAG Original H3 BUY", "TOLAG H3 BUY | {{ticker}} | {{interval}} | {{close}}")
alertcondition(h3Sell, "TOLAG Original H3 SELL", "TOLAG H3 SELL | {{ticker}} | {{interval}} | {{close}}")
 
alertcondition(precisionBuy, "TOLAG Precision BUY", "TOLAG Precision BUY | {{ticker}} | {{interval}} | {{close}}")
alertcondition(precisionSell, "TOLAG Precision SELL", "TOLAG Precision SELL | {{ticker}} | {{interval}} | {{close}}")
 
alertcondition(selectedBuy, "TOLAG Selected BUY", "TOLAG Selected BUY | {{ticker}} | {{interval}} | {{close}}")
alertcondition(selectedSell, "TOLAG Selected SELL", "TOLAG Selected SELL | {{ticker}} | {{interval}} | {{close}}")
 
alertcondition(bullBreak, "TOLAG Bullish BOS/MSS", "TOLAG Bullish Structure | {{ticker}} | {{interval}}")
alertcondition(bearBreak, "TOLAG Bearish BOS/MSS", "TOLAG Bearish Structure | {{ticker}} | {{interval}}")

← 返回列表