TOLAG Order Flow Structure | TGL 5.4 RC

TOLAG · study · 751 行 · 点赞 56 · TradingView 原页

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

Pine Script

//@version=6
// Copyright (c) 2026 TOLAG Indicators. All rights reserved.
// TOLAG Order Flow Structure | TGL 5.4 RC
// Original TGL 5 structure and order-block detection preserved.
// Premium zone focus, information, action intelligence and lifecycle controls.
 
indicator("TOLAG Order Flow Structure | TGL 5.4 RC", shorttitle="TOLAG TGL 5.4", overlay=true, max_boxes_count=150, max_lines_count=350, max_labels_count=350, max_bars_back=500)
 
//====================================================================
// 01 - ORIGINAL MARKET STRUCTURE
//====================================================================
gStructure = "01 - Market Structure"
swingLength = input.int(5, "Swing confirmation length", minval=2, maxval=25, group=gStructure)
showBOS = input.bool(true, "Show BOS / MSS", group=gStructure)
showSwingLabels = input.bool(false, "Show HH / HL / LH / LL", group=gStructure)
breakBuffer = input.float(0.05, "Structure break buffer (ATR)", minval=0, step=0.05, group=gStructure)
maxStructureEvents = input.int(75, "Retained structure events", minval=10, maxval=140, group=gStructure)
 
//====================================================================
// 02 - ORIGINAL ORDER BLOCK SETTINGS
//====================================================================
gOB = "02 - Order Blocks"
showOB = input.bool(true, "Show order blocks", group=gOB)
showBreaker = input.bool(true, "Convert invalidated OB to breaker", group=gOB)
originBars = input.int(15, "Origin candle search", minval=2, maxval=50, group=gOB)
minDisplacement = input.float(0.5, "Minimum displacement (ATR)", minval=0, step=0.1, group=gOB)
maxOBHeight = input.float(2.5, "Maximum OB height (ATR)", minval=0.2, step=0.1, group=gOB)
useWicks = input.bool(true, "Use full candle range", group=gOB)
maxZones = input.int(8, "Maximum retained zones", minval=2, maxval=30, group=gOB)
zoneExtension = input.int(80, "Zone extension bars", minval=10, maxval=300, group=gOB)
showZoneLabels = input.bool(true, "Show zone labels", group=gOB)
showEquilibrium = input.bool(false, "Show zone midpoint", group=gOB)
 
//====================================================================
// 03 - ZONE FOCUS
//====================================================================
gFocus = "03 - Zone Focus"
focusMode = input.string("Priority Highlight", "Zone focus mode", options=["All Original Zones", "Priority Highlight", "Priority Only"], group=gFocus)
priorityPerSide = input.int(2, "Priority zones per direction", minval=1, maxval=8, group=gFocus)
overlapThreshold = input.float(0.50, "Overlap threshold", minval=0.1, maxval=0.95, step=0.05, group=gFocus)
priorityBorderWidth = input.int(3, "Priority border width", minval=1, maxval=5, group=gFocus)
secondaryFade = input.int(94, "Secondary zone transparency", minval=70, maxval=100, group=gFocus)
showSecondaryLabels = input.bool(false, "Labels on secondary zones", group=gFocus)
 
//====================================================================
// 04 - ORIGINAL LIQUIDITY SETTINGS
//====================================================================
gLiquidity = "04 - Liquidity"
showLiquidity = input.bool(true, "Show liquidity levels", group=gLiquidity)
liquidityLength = input.int(7, "Liquidity swing length", minval=2, maxval=25, group=gLiquidity)
showSweeps = input.bool(true, "Show sweep and reclaim labels", group=gLiquidity)
liquidityExtension = input.int(80, "Liquidity extension bars", minval=10, maxval=300, group=gLiquidity)
maxLiquidityLabels = input.int(45, "Retained sweep labels", minval=5, maxval=100, group=gLiquidity)
 
//====================================================================
// 05 - HIGHER TIMEFRAME
//====================================================================
gHTF = "05 - Higher Timeframe"
showHTF = input.bool(false, "Show confirmed HTF levels", group=gHTF)
htfTimeframe = input.timeframe("60", "Higher timeframe", group=gHTF)
htfSwing = input.int(4, "HTF pivot length", minval=2, maxval=20, group=gHTF)
 
//====================================================================
// 06 - COLORS
//====================================================================
gColors = "06 - Colors"
bullColor = input.color(#18D9AB, "Bullish demand", group=gColors)
bearColor = input.color(#FF557D, "Bearish supply", group=gColors)
breakerBullColor = input.color(#12BFD6, "Bullish breaker", group=gColors)
breakerBearColor = input.color(#FFAA55, "Bearish breaker", group=gColors)
liquidityColor = input.color(#AA8BFF, "Liquidity", group=gColors)
structureColor = input.color(#F6C36A, "BOS / MSS", group=gColors)
swingHighColor = input.color(#FF819A, "Swing highs", group=gColors)
swingLowColor = input.color(#42E4C1, "Swing lows", group=gColors)
htfHighColor = input.color(#F184A8, "HTF resistance", group=gColors)
htfLowColor = input.color(#57D7D0, "HTF support", group=gColors)
zoneTransparency = input.int(82, "Fresh zone transparency", minval=50, maxval=95, group=gColors)
testedTransparency = input.int(90, "Tested zone transparency", minval=50, maxval=95, group=gColors)
breakerTransparency = input.int(88, "Breaker transparency", minval=50, maxval=95, group=gColors)
 
//====================================================================
// 07 - LINES AND BORDERS
//====================================================================
gLines = "07 - Lines and Borders"
zoneBorderWidth = input.int(1, "Zone border width", minval=1, maxval=4, group=gLines)
zoneBorderStyle = input.string("Solid", "Zone border style", options=["Solid", "Dashed", "Dotted"], group=gLines)
breakerBorderStyle = input.string("Dashed", "Breaker border style", options=["Solid", "Dashed", "Dotted"], group=gLines)
structureLineWidth = input.int(1, "BOS / MSS line width", minval=1, maxval=4, group=gLines)
structureLineStyle = input.string("Dashed", "BOS / MSS line style", options=["Solid", "Dashed", "Dotted"], group=gLines)
liquidityLineWidth = input.int(1, "Liquidity line width", minval=1, maxval=4, group=gLines)
liquidityLineStyle = input.string("Dotted", "Liquidity line style", options=["Solid", "Dashed", "Dotted"], group=gLines)
midlineWidth = input.int(1, "Midpoint line width", minval=1, maxval=3, group=gLines)
htfLineWidth = input.int(2, "HTF line width", minval=1, maxval=4, group=gLines)
 
//====================================================================
// 08 - BLOCK INFORMATION
//====================================================================
gLabels = "08 - Block Information"
showTimeframe = input.bool(true, "Show originating timeframe", group=gLabels)
showZoneState = input.bool(true, "Show fresh / tested status", group=gLabels)
showTouchCount = input.bool(true, "Show test count", group=gLabels)
showZonePrices = input.bool(false, "Show zone price range", group=gLabels)
showZoneAge = input.bool(false, "Show age in bars", group=gLabels)
showBreakerOrigin = input.bool(true, "Identify breaker origin", group=gLabels)
zoneTextAlign = input.string("Right", "Block text alignment", options=["Left", "Center", "Right"], group=gLabels)
 
//====================================================================
// 09 - INDIVIDUAL TYPOGRAPHY
//====================================================================
gFonts = "09 - Typography"
demandFont = input.string("Tiny", "Demand label font", options=["Tiny", "Small", "Normal", "Large"], group=gFonts)
supplyFont = input.string("Tiny", "Supply label font", options=["Tiny", "Small", "Normal", "Large"], group=gFonts)
breakerFont = input.string("Tiny", "Breaker label font", options=["Tiny", "Small", "Normal", "Large"], group=gFonts)
structureFont = input.string("Tiny", "BOS / MSS label font", options=["Tiny", "Small", "Normal", "Large"], group=gFonts)
swingFont = input.string("Tiny", "HH / HL / LH / LL font", options=["Tiny", "Small", "Normal", "Large"], group=gFonts)
liquidityFont = input.string("Tiny", "Liquidity event font", options=["Tiny", "Small", "Normal", "Large"], group=gFonts)
 
//====================================================================
// 10 - DASHBOARD
//====================================================================
gDash = "10 - Intelligence Dashboard"
showDashboard = input.bool(true, "Show dashboard", group=gDash)
dashboardPosition = input.string("Top Right", "Dashboard position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left", "Middle Right", "Middle Left", "Top Center", "Bottom Center"], group=gDash)
dashboardSize = input.string("Small", "Dashboard font", options=["Tiny", "Small", "Normal", "Large"], group=gDash)
dashboardLayout = input.string("Detailed", "Dashboard layout", options=["Compact", "Detailed"], group=gDash)
dashboardBg = input.color(#111B2B, "Dashboard background", group=gDash)
dashboardHeader = input.color(#1A2D45, "Dashboard header", group=gDash)
dashboardMuted = input.color(#9AACC4, "Description text", group=gDash)
dashboardText = input.color(#FFFFFF, "Value text", group=gDash)
 
//====================================================================
// 11 - ACTION INTELLIGENCE
//====================================================================
gAction = "11 - Action Intelligence"
showActionPanel = input.bool(true, "Show action panel", group=gAction)
actionPosition = input.string("Bottom Center", "Action panel position", options=["Bottom Center", "Top Center", "Bottom Left", "Bottom Right", "Top Left", "Top Right"], group=gAction)
actionFont = input.string("Normal", "Action font size", options=["Tiny", "Small", "Normal", "Large"], group=gAction)
actionPanelBg = input.color(#16243A, "Action panel background", group=gAction)
actionTextColor = input.color(#E4EDFA, "Action explanation text", group=gAction)
watchDistanceATR = input.float(0.5, "Zone proximity (ATR)", minval=0, step=0.1, group=gAction)
confirmationWindow = input.int(3, "Structure confirmation window (bars)", minval=1, maxval=20, group=gAction)
requireSweep = input.bool(false, "Require liquidity sweep for confirmation", group=gAction)
 
//====================================================================
// HELPERS
//====================================================================
getPosition(string p) =>
    switch p
        "Top Left" => position.top_left
        "Top Center" => position.top_center
        "Bottom Right" => position.bottom_right
        "Bottom Center" => position.bottom_center
        "Bottom Left" => position.bottom_left
        "Middle Right" => position.middle_right
        "Middle Left" => position.middle_left
        => position.top_right
 
getSize(string s) =>
    switch s
        "Tiny" => size.tiny
        "Normal" => size.normal
        "Large" => size.large
        => size.small
 
getLineStyle(string s) =>
    switch s
        "Solid" => line.style_solid
        "Dashed" => line.style_dashed
        => line.style_dotted
 
getAlign(string s) =>
    switch s
        "Left" => text.align_left
        "Center" => text.align_center
        => text.align_right
 
getTF() =>
    timeframe.isseconds ? timeframe.period + "S" : timeframe.isminutes ? timeframe.period + "m" : timeframe.isdaily ? timeframe.period + "D" : timeframe.isweekly ? timeframe.period + "W" : timeframe.ismonthly ? timeframe.period + "M" : timeframe.period
 
formatPrice(float p) =>
    str.tostring(p, format.mintick)
 
//====================================================================
// ORIGINAL TGL 5 ARRAYS
//====================================================================
var array<box> obBoxes = array.new<box>()
var array<line> obMidlines = array.new<line>()
var array<float> obTops = array.new<float>()
var array<float> obBottoms = array.new<float>()
var array<int> obDirections = array.new<int>()
var array<bool> obBreakers = array.new<bool>()
var array<int> obTouches = array.new<int>()
var array<bool> obWasInside = array.new<bool>()
var array<int> obCreationBars = array.new<int>()
var array<int> obOriginalDirections = array.new<int>()
 
var array<line> structureLines = array.new<line>()
var array<label> structureLabels = array.new<label>()
var array<label> sweepLabels = array.new<label>()
 
//====================================================================
// ORIGINAL TGL 5 MARKET STRUCTURE
//====================================================================
atr = ta.atr(14)
pivotHigh = ta.pivothigh(high, swingLength, swingLength)
pivotLow = ta.pivotlow(low, swingLength, swingLength)
 
var float structureHigh = na
var float structureLow = na
var float previousHigh = na
var float previousLow = na
var int highBar = na
var int lowBar = na
var bool highBroken = false
var bool lowBroken = false
var int marketTrend = 0
var string lastStructure = "WAITING"
 
bool bullishBOS = false
bool bearishBOS = false
bool bullishMSS = false
bool bearishMSS = false
 
if barstate.isconfirmed
    if not na(pivotHigh)
        previousHigh := structureHigh
        structureHigh := pivotHigh
        highBar := bar_index - swingLength
        highBroken := false
 
        if showSwingLabels
            string swingText = na(previousHigh) ? "H" : pivotHigh > previousHigh ? "HH" : "LH"
            label l = label.new(highBar, pivotHigh, swingText, style=label.style_label_down, color=color.new(swingHighColor, 85), textcolor=swingHighColor, size=getSize(swingFont))
            array.push(structureLabels, l)
 
    if not na(pivotLow)
        previousLow := structureLow
        structureLow := pivotLow
        lowBar := bar_index - swingLength
        lowBroken := false
 
        if showSwingLabels
            string swingText = na(previousLow) ? "L" : pivotLow > previousLow ? "HL" : "LL"
            label l = label.new(lowBar, pivotLow, swingText, style=label.style_label_up, color=color.new(swingLowColor, 85), textcolor=swingLowColor, size=getSize(swingFont))
            array.push(structureLabels, l)
 
    if not na(structureHigh) and not highBroken and close > structureHigh + atr * breakBuffer
        highBroken := true
        bullishMSS := marketTrend == -1
        bullishBOS := not bullishMSS
        marketTrend := 1
        lastStructure := bullishMSS ? "BULL MSS" : "BULL BOS"
 
        if showBOS
            line ln = line.new(highBar, structureHigh, bar_index, structureHigh, color=color.new(structureColor, 25), style=getLineStyle(structureLineStyle), width=structureLineWidth)
            label lb = label.new(bar_index, structureHigh, bullishMSS ? "MSS ↑" : "BOS ↑", style=label.style_label_down, color=color.new(structureColor, 85), textcolor=structureColor, size=getSize(structureFont))
            array.push(structureLines, ln)
            array.push(structureLabels, lb)
 
        if showOB and (high - low >= atr * minDisplacement)
            int origin = na
            for i = 1 to originBars
                if na(origin) and close[i] < open[i]
                    origin := i
 
            if not na(origin)
                float top = useWicks ? high[origin] : math.max(open[origin], close[origin])
                float bottom = useWicks ? low[origin] : math.min(open[origin], close[origin])
 
                if top > bottom and top - bottom <= atr * maxOBHeight
                    box b = box.new(bar_index - origin, top, bar_index + zoneExtension, bottom, border_color=bullColor, bgcolor=color.new(bullColor, zoneTransparency), text="DEMAND • FRESH", text_color=bullColor, text_size=getSize(demandFont), text_halign=getAlign(zoneTextAlign))
                    line m = line.new(bar_index - origin, (top + bottom) / 2, bar_index + zoneExtension, (top + bottom) / 2, color=color.new(bullColor, showEquilibrium ? 50 : 100), style=line.style_dotted)
                    array.unshift(obBoxes, b)
                    array.unshift(obMidlines, m)
                    array.unshift(obTops, top)
                    array.unshift(obBottoms, bottom)
                    array.unshift(obDirections, 1)
                    array.unshift(obBreakers, false)
                    array.unshift(obTouches, 0)
                    array.unshift(obWasInside, false)
                    array.unshift(obCreationBars, bar_index)
                    array.unshift(obOriginalDirections, 1)
 
    if not na(structureLow) and not lowBroken and close < structureLow - atr * breakBuffer
        lowBroken := true
        bearishMSS := marketTrend == 1
        bearishBOS := not bearishMSS
        marketTrend := -1
        lastStructure := bearishMSS ? "BEAR MSS" : "BEAR BOS"
 
        if showBOS
            line ln = line.new(lowBar, structureLow, bar_index, structureLow, color=color.new(structureColor, 25), style=getLineStyle(structureLineStyle), width=structureLineWidth)
            label lb = label.new(bar_index, structureLow, bearishMSS ? "MSS ↓" : "BOS ↓", style=label.style_label_up, color=color.new(structureColor, 85), textcolor=structureColor, size=getSize(structureFont))
            array.push(structureLines, ln)
            array.push(structureLabels, lb)
 
        if showOB and (high - low >= atr * minDisplacement)
            int origin = na
            for i = 1 to originBars
                if na(origin) and close[i] > open[i]
                    origin := i
 
            if not na(origin)
                float top = useWicks ? high[origin] : math.max(open[origin], close[origin])
                float bottom = useWicks ? low[origin] : math.min(open[origin], close[origin])
 
                if top > bottom and top - bottom <= atr * maxOBHeight
                    box b = box.new(bar_index - origin, top, bar_index + zoneExtension, bottom, border_color=bearColor, bgcolor=color.new(bearColor, zoneTransparency), text="SUPPLY • FRESH", text_color=bearColor, text_size=getSize(supplyFont), text_halign=getAlign(zoneTextAlign))
                    line m = line.new(bar_index - origin, (top + bottom) / 2, bar_index + zoneExtension, (top + bottom) / 2, color=color.new(bearColor, showEquilibrium ? 50 : 100), style=line.style_dotted)
                    array.unshift(obBoxes, b)
                    array.unshift(obMidlines, m)
                    array.unshift(obTops, top)
                    array.unshift(obBottoms, bottom)
                    array.unshift(obDirections, -1)
                    array.unshift(obBreakers, false)
                    array.unshift(obTouches, 0)
                    array.unshift(obWasInside, false)
                    array.unshift(obCreationBars, bar_index)
                    array.unshift(obOriginalDirections, -1)
 
// Limit structure drawing history without changing calculations.
while array.size(structureLines) > maxStructureEvents
    line.delete(array.shift(structureLines))
 
while array.size(structureLabels) > maxStructureEvents * 2
    label.delete(array.shift(structureLabels))
 
//====================================================================
// ORIGINAL TGL 5 ORDER BLOCK LIFECYCLE
//====================================================================
if barstate.isconfirmed and array.size(obBoxes) > 0
    for i = array.size(obBoxes) - 1 to 0
        box b = array.get(obBoxes, i)
        line m = array.get(obMidlines, i)
        float top = array.get(obTops, i)
        float bottom = array.get(obBottoms, i)
        int direction = array.get(obDirections, i)
        bool breaker = array.get(obBreakers, i)
        int touches = array.get(obTouches, i)
        bool wasInside = array.get(obWasInside, i)
        int created = array.get(obCreationBars, i)
 
        if bar_index > created
            bool invalidated = direction == 1 ? close < bottom : close > top
            bool inside = high >= bottom and low <= top
 
            if invalidated
                if showBreaker and not breaker
                    direction := -direction
                    breaker := true
                    touches := 0
                    wasInside := false
                    array.set(obDirections, i, direction)
                    array.set(obBreakers, i, true)
                    array.set(obTouches, i, 0)
                    array.set(obWasInside, i, false)
                else
                    box.delete(b)
                    line.delete(m)
                    array.remove(obBoxes, i)
                    array.remove(obMidlines, i)
                    array.remove(obTops, i)
                    array.remove(obBottoms, i)
                    array.remove(obDirections, i)
                    array.remove(obBreakers, i)
                    array.remove(obTouches, i)
                    array.remove(obWasInside, i)
                    array.remove(obCreationBars, i)
                    array.remove(obOriginalDirections, i)
                    continue
            else
                if inside and not wasInside
                    touches += 1
                    array.set(obTouches, i, touches)
                array.set(obWasInside, i, inside)
 
        color zoneColor = breaker ? (direction == 1 ? breakerBullColor : breakerBearColor) : (direction == 1 ? bullColor : bearColor)
        box.set_right(b, bar_index + zoneExtension)
        line.set_x2(m, bar_index + zoneExtension)
        box.set_border_color(b, zoneColor)
        box.set_border_style(b, getLineStyle(breaker ? breakerBorderStyle : zoneBorderStyle))
        box.set_border_width(b, zoneBorderWidth)
        box.set_bgcolor(b, color.new(zoneColor, breaker ? breakerTransparency : touches > 0 ? testedTransparency : zoneTransparency))
        line.set_color(m, color.new(zoneColor, showEquilibrium ? 50 : 100))
        line.set_width(m, midlineWidth)
 
// Original newest-first zone retention.
while array.size(obBoxes) > maxZones
    int last = array.size(obBoxes) - 1
    box.delete(array.get(obBoxes, last))
    line.delete(array.get(obMidlines, last))
    array.pop(obBoxes)
    array.pop(obMidlines)
    array.pop(obTops)
    array.pop(obBottoms)
    array.pop(obDirections)
    array.pop(obBreakers)
    array.pop(obTouches)
    array.pop(obWasInside)
    array.pop(obCreationBars)
    array.pop(obOriginalDirections)
 
//====================================================================
// ZONE PRIORITY & PRESENTATION
// Only box visibility and styling are changed.
//====================================================================
int demandCount = 0
int supplyCount = 0
int breakerCount = 0
int freshCount = 0
 
float nearestDemand = na
float nearestSupply = na
float demandDistance = na
float supplyDistance = na
bool inDemand = false
bool inSupply = false
 
if array.size(obBoxes) > 0
    for i = 0 to array.size(obBoxes) - 1
        int d = array.get(obDirections, i)
        bool br = array.get(obBreakers, i)
        int touches = array.get(obTouches, i)
        float top = array.get(obTops, i)
        float bottom = array.get(obBottoms, i)
 
        if d == 1
            demandCount += 1
        else
            supplyCount += 1
        if br
            breakerCount += 1
        if touches == 0
            freshCount += 1
 
        float distance = close > top ? close - top : close < bottom ? bottom - close : 0.0
 
        if d == 1
            if na(demandDistance) or distance < demandDistance
                demandDistance := distance
                nearestDemand := (top + bottom) / 2
            if close >= bottom and close <= top
                inDemand := true
        else
            if na(supplyDistance) or distance < supplyDistance
                supplyDistance := distance
                nearestSupply := (top + bottom) / 2
            if close >= bottom and close <= top
                inSupply := true
 
if barstate.islast and array.size(obBoxes) > 0
    for i = 0 to array.size(obBoxes) - 1
        box b = array.get(obBoxes, i)
        line m = array.get(obMidlines, i)
        float top = array.get(obTops, i)
        float bottom = array.get(obBottoms, i)
        int direction = array.get(obDirections, i)
        bool breaker = array.get(obBreakers, i)
        int touches = array.get(obTouches, i)
        int created = array.get(obCreationBars, i)
        int originalDirection = array.get(obOriginalDirections, i)
 
        float distance = close > top ? close - top : close < bottom ? bottom - close : 0.0
        float quality = (touches == 0 ? 25.0 : touches == 1 ? 15.0 : 5.0) + (breaker ? 4.0 : 0.0)
        float score = quality - distance / math.max(atr, syminfo.mintick) * 8.0 + math.max(0.0, 15.0 - (bar_index - created) * 0.1)
 
        int better = 0
        bool overlapDominated = false
 
        for j = 0 to array.size(obBoxes) - 1
            if j != i and array.get(obDirections, j) == direction
                float otherTop = array.get(obTops, j)
                float otherBottom = array.get(obBottoms, j)
                int otherTouches = array.get(obTouches, j)
                int otherCreated = array.get(obCreationBars, j)
                bool otherBreaker = array.get(obBreakers, j)
 
                float otherDistance = close > otherTop ? close - otherTop : close < otherBottom ? otherBottom - close : 0.0
                float otherQuality = (otherTouches == 0 ? 25.0 : otherTouches == 1 ? 15.0 : 5.0) + (otherBreaker ? 4.0 : 0.0)
                float otherScore = otherQuality - otherDistance / math.max(atr, syminfo.mintick) * 8.0 + math.max(0.0, 15.0 - (bar_index - otherCreated) * 0.1)
 
                bool otherBetter = otherScore > score or (otherScore == score and j < i)
                if otherBetter
                    better += 1
                    float common = math.max(0.0, math.min(top, otherTop) - math.max(bottom, otherBottom))
                    float smaller = math.min(top - bottom, otherTop - otherBottom)
                    float overlap = smaller > 0 ? common / smaller : 0.0
                    if overlap >= overlapThreshold
                        overlapDominated := true
 
        bool priority = better < priorityPerSide and not overlapDominated
        bool visible = focusMode != "Priority Only" or priority
        bool secondary = focusMode != "All Original Zones" and not priority
 
        color c = breaker ? (direction == 1 ? breakerBullColor : breakerBearColor) : (direction == 1 ? bullColor : bearColor)
        int baseOpacity = breaker ? breakerTransparency : touches > 0 ? testedTransparency : zoneTransparency
        int finalOpacity = secondary ? secondaryFade : baseOpacity
 
        box.set_bgcolor(b, visible ? color.new(c, finalOpacity) : color.new(c, 100))
        box.set_border_color(b, visible ? color.new(c, secondary ? 55 : 0) : color.new(c, 100))
        box.set_border_width(b, priority and focusMode != "All Original Zones" ? priorityBorderWidth : zoneBorderWidth)
        box.set_border_style(b, getLineStyle(breaker ? breakerBorderStyle : zoneBorderStyle))
 
        string title = breaker ? "BREAKER" : direction == 1 ? "DEMAND" : "SUPPLY"
        string state = touches == 0 ? "FRESH" : "TESTED"
        string info = ""
 
        if showTimeframe
            info += getTF() + " "
 
        info += title
 
        if showZoneState
            info += " • " + state
 
        if showTouchCount and touches > 0
            info += " " + str.tostring(touches)
 
        if breaker and showBreakerOrigin
            info += originalDirection == 1 ? " • FROM DEMAND" : " • FROM SUPPLY"
 
        if showZonePrices
            info += "\n" + formatPrice(bottom) + " - " + formatPrice(top)
 
        if showZoneAge
            info += "\nAGE " + str.tostring(bar_index - created) + " BARS"
 
        bool drawText = showZoneLabels and visible and (not secondary or showSecondaryLabels)
        box.set_text(b, drawText ? info : "")
        box.set_text_color(b, c)
        box.set_text_size(b, getSize(breaker ? breakerFont : direction == 1 ? demandFont : supplyFont))
        box.set_text_halign(b, getAlign(zoneTextAlign))
        line.set_color(m, visible and showEquilibrium ? color.new(c, secondary ? 80 : 50) : color.new(c, 100))
 
//====================================================================
// ORIGINAL TGL 5 LIQUIDITY ENGINE
//====================================================================
liqHigh = ta.pivothigh(high, liquidityLength, liquidityLength)
liqLow = ta.pivotlow(low, liquidityLength, liquidityLength)
 
var float buySideLevel = na
var float sellSideLevel = na
var int buySideBar = na
var int sellSideBar = na
var bool buySideActive = false
var bool sellSideActive = false
var line buySideLine = na
var line sellSideLine = na
var string lastLiquidity = "NONE"
 
bool bslSweep = false
bool sslSweep = false
 
if barstate.isconfirmed and showLiquidity
    if not na(liqHigh)
        if not na(buySideLine)
            line.delete(buySideLine)
        buySideLevel := liqHigh
        buySideBar := bar_index - liquidityLength
        buySideActive := true
        buySideLine := line.new(buySideBar, buySideLevel, bar_index + liquidityExtension, buySideLevel, color=liquidityColor, style=getLineStyle(liquidityLineStyle), width=liquidityLineWidth)
 
    if not na(liqLow)
        if not na(sellSideLine)
            line.delete(sellSideLine)
        sellSideLevel := liqLow
        sellSideBar := bar_index - liquidityLength
        sellSideActive := true
        sellSideLine := line.new(sellSideBar, sellSideLevel, bar_index + liquidityExtension, sellSideLevel, color=liquidityColor, style=getLineStyle(liquidityLineStyle), width=liquidityLineWidth)
 
    if buySideActive and bar_index > buySideBar + liquidityLength and high > buySideLevel
        bslSweep := close < buySideLevel
        buySideActive := false
        lastLiquidity := bslSweep ? "BSL SWEPT" : "BSL CONSUMED"
        line.set_x2(buySideLine, bar_index)
        line.set_style(buySideLine, line.style_dashed)
        if bslSweep and showSweeps
            label lb = label.new(bar_index, high, "BSL SWEEP\nRECLAIM ↓", style=label.style_label_down, color=color.new(liquidityColor, 85), textcolor=liquidityColor, size=getSize(liquidityFont))
            array.push(sweepLabels, lb)
 
    if sellSideActive and bar_index > sellSideBar + liquidityLength and low < sellSideLevel
        sslSweep := close > sellSideLevel
        sellSideActive := false
        lastLiquidity := sslSweep ? "SSL SWEPT" : "SSL CONSUMED"
        line.set_x2(sellSideLine, bar_index)
        line.set_style(sellSideLine, line.style_dashed)
        if sslSweep and showSweeps
            label lb = label.new(bar_index, low, "SSL SWEEP\nRECLAIM ↑", style=label.style_label_up, color=color.new(liquidityColor, 85), textcolor=liquidityColor, size=getSize(liquidityFont))
            array.push(sweepLabels, lb)
 
while array.size(sweepLabels) > maxLiquidityLabels
    label.delete(array.shift(sweepLabels))
 
//====================================================================
// CONFIRMED HTF LEVELS
//====================================================================
htfHigh = request.security(syminfo.tickerid, htfTimeframe, ta.valuewhen(not na(ta.pivothigh(high, htfSwing, htfSwing)), ta.pivothigh(high, htfSwing, htfSwing), 0)[1], lookahead=barmerge.lookahead_on)
htfLow = request.security(syminfo.tickerid, htfTimeframe, ta.valuewhen(not na(ta.pivotlow(low, htfSwing, htfSwing)), ta.pivotlow(low, htfSwing, htfSwing), 0)[1], lookahead=barmerge.lookahead_on)
validHTF = timeframe.in_seconds(htfTimeframe) > timeframe.in_seconds(timeframe.period)
 
plot(showHTF and validHTF ? htfHigh : na, "HTF Resistance", color=color.new(htfHighColor, 40), linewidth=htfLineWidth, style=plot.style_stepline)
plot(showHTF and validHTF ? htfLow : na, "HTF Support", color=color.new(htfLowColor, 40), linewidth=htfLineWidth, style=plot.style_stepline)
 
//====================================================================
// ACTION INTELLIGENCE
// A confirmed action requires a fresh directional structure event,
// a zone reaction, and optional same-direction liquidity sweep.
//====================================================================
var int lastBullStructureBar = na
var int lastBearStructureBar = na
var int lastBullSweepBar = na
var int lastBearSweepBar = na
var int lastDemandReactionBar = na
var int lastSupplyReactionBar = na
 
bool nearDemand = not na(demandDistance) and demandDistance <= atr * watchDistanceATR
bool nearSupply = not na(supplyDistance) and supplyDistance <= atr * watchDistanceATR
 
if barstate.isconfirmed
    if bullishBOS or bullishMSS
        lastBullStructureBar := bar_index
    if bearishBOS or bearishMSS
        lastBearStructureBar := bar_index
    if sslSweep
        lastBullSweepBar := bar_index
    if bslSweep
        lastBearSweepBar := bar_index
    if inDemand and close > open
        lastDemandReactionBar := bar_index
    if inSupply and close < open
        lastSupplyReactionBar := bar_index
 
bool recentBullStructure = not na(lastBullStructureBar) and bar_index - lastBullStructureBar <= confirmationWindow
bool recentBearStructure = not na(lastBearStructureBar) and bar_index - lastBearStructureBar <= confirmationWindow
bool recentBullSweep = not na(lastBullSweepBar) and bar_index - lastBullSweepBar <= confirmationWindow
bool recentBearSweep = not na(lastBearSweepBar) and bar_index - lastBearSweepBar <= confirmationWindow
bool recentDemandReaction = not na(lastDemandReactionBar) and bar_index - lastDemandReactionBar <= confirmationWindow
bool recentSupplyReaction = not na(lastSupplyReactionBar) and bar_index - lastSupplyReactionBar <= confirmationWindow
 
bool buyConfirmed = barstate.isconfirmed and marketTrend == 1 and recentBullStructure and recentDemandReaction and nearDemand and not nearSupply and (not requireSweep or recentBullSweep)
bool sellConfirmed = barstate.isconfirmed and marketTrend == -1 and recentBearStructure and recentSupplyReaction and nearSupply and not nearDemand and (not requireSweep or recentBearSweep)
 
string action = "WAIT"
string actionReason = "Await a qualified zone interaction"
string actionDetail = "No confirmed setup"
color actionColor = structureColor
 
if buyConfirmed
    action := "BUY CONFIRMED"
    actionReason := "Bullish structure and demand reaction aligned"
    actionDetail := requireSweep ? "Structure + demand + SSL sweep" : "Structure + demand confirmation"
    actionColor := bullColor
else if sellConfirmed
    action := "SELL CONFIRMED"
    actionReason := "Bearish structure and supply reaction aligned"
    actionDetail := requireSweep ? "Structure + supply + BSL sweep" : "Structure + supply confirmation"
    actionColor := bearColor
else if nearDemand and nearSupply
    action := "WAIT"
    actionReason := "Demand and supply zones compete"
    actionDetail := "Await directional resolution"
else if nearDemand
    action := "WATCH BUY"
    actionReason := "Demand nearby - bullish confirmation pending"
    actionDetail := "Monitor structure and demand reaction"
    actionColor := bullColor
else if nearSupply
    action := "WATCH SELL"
    actionReason := "Supply nearby - bearish confirmation pending"
    actionDetail := "Monitor structure and supply reaction"
    actionColor := bearColor
else if marketTrend == 1
    actionReason := "Bullish structure - await demand setup"
    actionDetail := "No qualifying demand reaction"
else if marketTrend == -1
    actionReason := "Bearish structure - await supply setup"
    actionDetail := "No qualifying supply reaction"
 
//====================================================================
// DASHBOARD
//====================================================================
var table dashboard = table.new(getPosition(dashboardPosition), 2, 11, border_width=1, border_color=color.new(#52647C, 65))
 
if barstate.islast
    table.clear(dashboard, 0, 0, 1, 10)
    if showDashboard
        string sz = getSize(dashboardSize)
        table.cell(dashboard, 0, 0, "TOLAG • TGL 5.4", bgcolor=dashboardHeader, text_color=dashboardText, text_size=sz)
        table.cell(dashboard, 1, 0, "FLOW INTELLIGENCE", bgcolor=dashboardHeader, text_color=structureColor, text_size=sz)
 
        table.cell(dashboard, 0, 1, "Market bias", bgcolor=dashboardBg, text_color=dashboardMuted, text_size=sz)
        table.cell(dashboard, 1, 1, marketTrend == 1 ? "BULLISH" : marketTrend == -1 ? "BEARISH" : "NEUTRAL", bgcolor=dashboardBg, text_color=marketTrend == 1 ? bullColor : marketTrend == -1 ? bearColor : dashboardMuted, text_size=sz)
 
        table.cell(dashboard, 0, 2, "Last structure", bgcolor=dashboardBg, text_color=dashboardMuted, text_size=sz)
        table.cell(dashboard, 1, 2, lastStructure, bgcolor=dashboardBg, text_color=structureColor, text_size=sz)
 
        table.cell(dashboard, 0, 3, "Demand / Supply", bgcolor=dashboardBg, text_color=dashboardMuted, text_size=sz)
        table.cell(dashboard, 1, 3, str.tostring(demandCount) + " / " + str.tostring(supplyCount), bgcolor=dashboardBg, text_color=dashboardText, text_size=sz)
 
        table.cell(dashboard, 0, 4, "Breaker blocks", bgcolor=dashboardBg, text_color=dashboardMuted, text_size=sz)
        table.cell(dashboard, 1, 4, str.tostring(breakerCount), bgcolor=dashboardBg, text_color=dashboardText, text_size=sz)
 
        if dashboardLayout == "Detailed"
            table.cell(dashboard, 0, 5, "Fresh zones", bgcolor=dashboardBg, text_color=dashboardMuted, text_size=sz)
            table.cell(dashboard, 1, 5, str.tostring(freshCount), bgcolor=dashboardBg, text_color=dashboardText, text_size=sz)
 
            table.cell(dashboard, 0, 6, "Nearest demand", bgcolor=dashboardBg, text_color=dashboardMuted, text_size=sz)
            table.cell(dashboard, 1, 6, na(nearestDemand) ? "NONE" : formatPrice(nearestDemand), bgcolor=dashboardBg, text_color=bullColor, text_size=sz)
 
            table.cell(dashboard, 0, 7, "Nearest supply", bgcolor=dashboardBg, text_color=dashboardMuted, text_size=sz)
            table.cell(dashboard, 1, 7, na(nearestSupply) ? "NONE" : formatPrice(nearestSupply), bgcolor=dashboardBg, text_color=bearColor, text_size=sz)
 
            table.cell(dashboard, 0, 8, "Liquidity", bgcolor=dashboardBg, text_color=dashboardMuted, text_size=sz)
            table.cell(dashboard, 1, 8, lastLiquidity, bgcolor=dashboardBg, text_color=liquidityColor, text_size=sz)
 
            table.cell(dashboard, 0, 9, "HTF levels", bgcolor=dashboardBg, text_color=dashboardMuted, text_size=sz)
            table.cell(dashboard, 1, 9, showHTF ? (validHTF ? htfTimeframe : "INVALID TF") : "OFF", bgcolor=dashboardBg, text_color=dashboardText, text_size=sz)
 
        table.cell(dashboard, 0, 10, "ACTION", bgcolor=dashboardHeader, text_color=actionColor, text_size=sz)
        table.cell(dashboard, 1, 10, action, bgcolor=dashboardHeader, text_color=actionColor, text_size=sz)
 
//====================================================================
// INDEPENDENT ACTION PANEL
//====================================================================
var table actionPanel = table.new(getPosition(actionPosition), 2, 3, border_width=1, border_color=color.new(#6683A8, 55))
 
if barstate.islast
    table.clear(actionPanel, 0, 0, 1, 2)
    if showActionPanel
        string sz = getSize(actionFont)
 
        table.cell(actionPanel, 0, 0, "ACTION", bgcolor=actionPanelBg, text_color=dashboardMuted, text_size=sz)
        table.cell(actionPanel, 1, 0, "TOLAG • " + getTF(), bgcolor=actionPanelBg, text_color=dashboardMuted, text_size=sz)
 
        table.cell(actionPanel, 0, 1, action, bgcolor=actionPanelBg, text_color=actionColor, text_size=sz)
        table.cell(actionPanel, 1, 1, actionReason, bgcolor=actionPanelBg, text_color=actionTextColor, text_size=sz)
 
        table.cell(actionPanel, 0, 2, "SETUP STATUS", bgcolor=actionPanelBg, text_color=dashboardMuted, text_size=size.tiny)
        table.cell(actionPanel, 1, 2, actionDetail, bgcolor=actionPanelBg, text_color=actionTextColor, text_size=size.tiny)
 
//====================================================================
// ALERTS
//====================================================================
alertcondition(bullishBOS and barstate.isconfirmed, "TOLAG Bullish BOS", "TGL 5.4 bullish BOS: {{ticker}} {{interval}}")
alertcondition(bearishBOS and barstate.isconfirmed, "TOLAG Bearish BOS", "TGL 5.4 bearish BOS: {{ticker}} {{interval}}")
alertcondition(bullishMSS and barstate.isconfirmed, "TOLAG Bullish MSS", "TGL 5.4 bullish MSS: {{ticker}} {{interval}}")
alertcondition(bearishMSS and barstate.isconfirmed, "TOLAG Bearish MSS", "TGL 5.4 bearish MSS: {{ticker}} {{interval}}")
alertcondition(bslSweep and barstate.isconfirmed, "TOLAG BSL Sweep", "TGL 5.4 buy-side liquidity swept: {{ticker}} {{interval}}")
alertcondition(sslSweep and barstate.isconfirmed, "TOLAG SSL Sweep", "TGL 5.4 sell-side liquidity swept: {{ticker}} {{interval}}")
alertcondition(buyConfirmed and not buyConfirmed[1] and barstate.isconfirmed, "TOLAG BUY Confirmed", "TGL 5.4 BUY context confirmed: {{ticker}} {{interval}}")
alertcondition(sellConfirmed and not sellConfirmed[1] and barstate.isconfirmed, "TOLAG SELL Confirmed", "TGL 5.4 SELL context confirmed: {{ticker}} {{interval}}")

← 返回列表