TOLAG Foresight X | TGL 1

TOLAG · study · 947 行 · 点赞 51 · TradingView 原页

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

Pine Script

//@version=6
indicator("TOLAG Foresight X | TGL 1", shorttitle="TOLAG TGL1", overlay=true, max_bars_back=2500, max_lines_count=450, max_labels_count=450, max_boxes_count=150)
 
// TOLAG INDICATORS
// Copyright (c) 2026 TOLAG Indicators.
// Clean Structure Revision
// Research indicator. Does not execute brokerage orders.
 
//====================================================
// 01 | FORECAST ENGINE
//====================================================
g1 = "01 | Forecast Engine"
 
engine = input.string("Selective Ensemble", "Forecast Model", options=["Selective Ensemble", "Analog Only", "Empirical Simulation Only", "Regression Only", "Swing Only", "Strict Consensus"], group=g1)
lookback = input.int(350, "Research Lookback", minval=100, maxval=800, group=g1)
neighbors = input.int(20, "Nearest Analogs", minval=5, maxval=60, group=g1)
simulations = input.int(80, "Empirical Samples", minval=20, maxval=200, group=g1)
regLen = input.int(55, "Regression Length", minval=10, maxval=150, group=g1)
swingLen = input.int(5, "Swing Strength", minval=2, maxval=20, group=g1)
atrLen = input.int(14, "ATR Length", minval=5, maxval=100, group=g1)
 
h1 = input.int(6, "Horizon 1", minval=1, maxval=100, group=g1)
h2 = input.int(12, "Horizon 2", minval=1, maxval=100, group=g1)
h3 = input.int(24, "Horizon 3", minval=1, maxval=100, group=g1)
h4 = input.int(48, "Horizon 4", minval=1, maxval=100, group=g1)
h5 = input.int(96, "Horizon 5", minval=1, maxval=100, group=g1)
 
wAnalog = input.float(1.0, "Analog Weight", minval=0.1, step=0.1, group=g1)
wEmpirical = input.float(1.0, "Empirical Weight", minval=0.1, step=0.1, group=g1)
wRegression = input.float(1.0, "Regression Weight", minval=0.1, step=0.1, group=g1)
wSwing = input.float(0.7, "Swing Weight", minval=0.1, step=0.1, group=g1)
 
//====================================================
// 02 | STRUCTURAL INTELLIGENCE
//====================================================
g2 = "02 | Structural Intelligence"
 
structureMode = input.string("Both", "Structure Display", options=["Both", "Detailed", "Major", "Off"], group=g2)
detailLen = input.int(5, "Detailed Pivot Length", minval=2, maxval=20, group=g2)
majorLen = input.int(14, "Major Pivot Length", minval=5, maxval=40, group=g2)
maxDetail = input.int(2, "Detailed Zones Per Side", minval=0, maxval=8, group=g2)
maxMajor = input.int(2, "Major Zones Per Side", minval=0, maxval=5, group=g2)
zoneDepth = input.float(0.45, "Detailed Zone Depth / ATR", minval=0.1, maxval=2, step=0.05, group=g2)
majorDepth = input.float(0.75, "Major Zone Depth / ATR", minval=0.1, maxval=3, step=0.05, group=g2)
zoneExtend = input.int(90, "Zone Extension Bars", minval=10, maxval=300, group=g2)
majorDisplacement = input.float(0.8, "Major Displacement / ATR", minval=0, maxval=3, step=0.1, group=g2)
 
// Volume measures are relative tick/exchange volume,
// not confirmed buy/sell orders.
showVolumeStrength = input.bool(true, "Show Relative Volume Strength", group=g2)
volumeLookback = input.int(30, "Volume Average Length", minval=5, maxval=200, group=g2)
strongVolumeRatio = input.float(1.5, "Strong Zone Volume Ratio", minval=1.0, maxval=5.0, step=0.1, group=g2)
zoneStrengthFilter = input.string("All", "Zone Volume Filter", options=["All", "Above Average", "Strong Only"], group=g2)
 
// Clean-structure controls
deduplicateZones = input.bool(true, "Consolidate Overlapping Zones", group=g2)
majorPriority = input.bool(true, "Major Zones Take Priority", group=g2)
minimumZoneSpacing = input.float(0.50, "Minimum Same-Type Spacing / ATR", minval=0, maxval=3, step=0.1, group=g2)
hideBrokenZones = input.bool(true, "Remove Invalidated Zones", group=g2)
zoneLabelMode = input.string("Detailed", "Zone Labels", options=["Compact", "Detailed", "Off"], group=g2)
zoneFont = input.string("Small", "Zone Label Size", options=["Tiny", "Small", "Normal", "Large"], group=g2)
 
showBOS = input.bool(false, "Show BOS Markers", group=g2)
showMSS = input.bool(false, "Show MSS Markers", group=g2)
showSweepLabels = input.bool(false, "Show Major Sweep Markers", group=g2)
showStructureLines = input.bool(false, "Show Major Structure Lines", group=g2)
 
supplyColor = input.color(color.rgb(241, 67, 93), "Supply Color", group=g2)
demandColor = input.color(color.rgb(16, 205, 161), "Demand Color", group=g2)
 
//====================================================
// 03 | FORECAST VISUALIZATION
//====================================================
g3 = "03 | Forecast Visualization"
 
showForecast = input.bool(true, "Show Forecast", group=g3)
forecastStyle = input.string("Original Fan", "Forecast Visualization", options=["Original Fan", "Segmented Corridor"], group=g3)
showMedian = input.bool(true, "Show Median Path", group=g3)
showInner = input.bool(true, "Show Inner Fan", group=g3)
showOuter = input.bool(true, "Show Outer Fan", group=g3)
showPrices = input.bool(true, "Show Projected Prices", group=g3)
 
innerFactor = input.float(0.65, "Inner ATR Factor", minval=0.1, maxval=5, step=0.05, group=g3)
outerFactor = input.float(1.30, "Outer ATR Factor", minval=0.2, maxval=8, step=0.1, group=g3)
corridorCap = input.float(12, "Maximum Width / ATR", minval=1, maxval=30, group=g3)
 
forecastBlue = input.color(color.rgb(60, 145, 245), "Forecast Color", group=g3)
bullColor = input.color(color.rgb(15, 213, 151), "Bullish Color", group=g3)
bearColor = input.color(color.rgb(245, 70, 95), "Bearish Color", group=g3)
 
//====================================================
// 04 | CONFIRMED SIGNALS
//====================================================
g4 = "04 | Confirmed Entry Signals"
 
enableSignals = input.bool(true, "Enable Signals", group=g4)
signalHorizon = input.string("H3", "Signal Horizon", options=["H1", "H2", "H3", "H4", "H5"], group=g4)
entryScore = input.float(62, "Entry Score", minval=51, maxval=95, group=g4)
exitScore = input.float(50, "Exit Score", minval=5, maxval=75, group=g4)
minAgreement = input.int(2, "Minimum Model Agreement", minval=1, maxval=4, group=g4)
entryMode = input.string("Hybrid Balanced", "Entry Engine", options=["Forecast Only", "Liquidity Reversal", "Trend Flow", "Hybrid Balanced"], group=g4)
 
sweepWindow = input.int(8, "Sweep Validity Bars", minval=1, maxval=30, group=g4)
requireMajorSweep = input.bool(false, "Require Major Sweep for Reversal", group=g4)
requireTrendAlignment = input.bool(true, "Require Trend Alignment for Continuation", group=g4)
cooldown = input.int(8, "Minimum Bars Between Entries", minval=0, maxval=100, group=g4)
 
showBuy = input.bool(true, "Show BUY Arrows", group=g4)
showSell = input.bool(true, "Show SELL Arrows", group=g4)
showExit = input.bool(false, "Show EXIT Markers", group=g4)
arrowSize = input.string("Medium", "BUY / SELL Arrow Size", options=["Tiny", "Small", "Medium", "Large"], group=g4)
 
//====================================================
// 05 | TRADE PLANNER
//====================================================
g5 = "05 | Trade Planner"
 
showPlanner = input.bool(true, "Show Trade Planner", group=g5)
showLongPlanner = input.bool(true, "Enable Long Planner", group=g5)
showShortPlanner = input.bool(true, "Enable Short Planner", group=g5)
plannerWidth = input.int(36, "Planner Width", minval=5, maxval=100, group=g5)
stopMode = input.string("Structure + ATR", "Stop Method", options=["ATR", "Structure + ATR"], group=g5)
stopATR = input.float(2.0, "Stop ATR Multiple", minval=0.25, step=0.25, group=g5)
stopBuffer = input.float(0.2, "Structure Stop Buffer / ATR", minval=0, step=0.1, group=g5)
tp1R = input.float(1.5, "Target 1 R", minval=0.25, step=0.25, group=g5)
tp2R = input.float(3.0, "Target 2 R", minval=0.5, step=0.25, group=g5)
plannerOpacity = input.int(86, "Planner Transparency", minval=40, maxval=98, group=g5)
 
//====================================================
// 06 | DASHBOARDS
//====================================================
g6 = "06 | Dashboards"
 
showMain = input.bool(true, "Show Forecast Dashboard", group=g6)
mainPos = input.string("Top Right", "Forecast Position", options=["Top Right", "Top Left", "Middle Right", "Middle Left", "Bottom Right", "Bottom Left"], group=g6)
mainSize = input.string("Small", "Forecast Size", options=["Tiny", "Small", "Normal", "Large"], group=g6)
 
showMTF = input.bool(true, "Show MTF Dashboard", group=g6)
mtfPos = input.string("Bottom Right", "MTF Position", options=["Top Right", "Top Left", "Middle Right", "Middle Left", "Bottom Right", "Bottom Left"], group=g6)
mtfSize = input.string("Small", "MTF Size", options=["Tiny", "Small", "Normal", "Large"], group=g6)
 
showValidation = input.bool(true, "Show Validation Dashboard", group=g6)
validationPos = input.string("Bottom Left", "Validation Position", options=["Top Right", "Top Left", "Middle Right", "Middle Left", "Bottom Right", "Bottom Left"], group=g6)
validationSize = input.string("Small", "Validation Size", options=["Tiny", "Small", "Normal", "Large"], group=g6)
validationSpacing = input.int(24, "Validation Sample Spacing", minval=1, maxval=100, group=g6)
validationLimit = input.int(120, "Validation Sample Limit", minval=20, maxval=250, group=g6)
 
//====================================================
// 07 | MTF SENTIMENT
//====================================================
g7 = "07 | MTF Sentiment"
 
tf1 = input.timeframe("1", "Timeframe 1", group=g7)
tf2 = input.timeframe("5", "Timeframe 2", group=g7)
tf3 = input.timeframe("15", "Timeframe 3", group=g7)
tf4 = input.timeframe("60", "Timeframe 4", group=g7)
tf5 = input.timeframe("240", "Timeframe 5", group=g7)
 
//====================================================
// HELPERS
//====================================================
f_clamp(float x, float a, float b) =>
    math.max(a, math.min(b, x))
 
f_price(float x) =>
    str.tostring(x, format.mintick)
 
f_pct(float x) =>
    na(x) ? "—" : str.tostring(x, "#.0") + "%"
 
f_size(string s) =>
    switch s
        "Tiny" => size.tiny
        "Normal" => size.normal
        "Large" => size.large
        => size.small
 
f_position(string s) =>
    switch s
        "Top Left" => position.top_left
        "Middle Right" => position.middle_right
        "Middle Left" => position.middle_left
        "Bottom Right" => position.bottom_right
        "Bottom Left" => position.bottom_left
        => position.top_right
 
f_scoreColor(float x) =>
    na(x) ? color.silver : x >= 55 ? bullColor : x <= 45 ? bearColor : color.silver
 
f_direction(float x) =>
    na(x) ? "N/A" : x >= 55 ? "BULL" : x <= 45 ? "BEAR" : "NEUTRAL"
 
f_mtfScore() =>
    float a = math.max(ta.atr(14), syminfo.mintick)
    float e = ta.ema(close, 34)
    float m = ta.ema(close, 12) - ta.ema(close, 26)
    f_clamp(50 + 25 * (close - e) / a + 15 * m / a, 0, 100)
 
//====================================================
// MARKET STATE
//====================================================
atr = ta.atr(atrLen)
safeATR = math.max(nz(atr, high - low), syminfo.mintick)
emaFast = ta.ema(close, 21)
emaSlow = ta.ema(close, 55)
rsiValue = ta.rsi(close, 14)
trendSlope = (emaFast - emaFast[5]) / safeATR
trendBull = emaFast > emaSlow and trendSlope > 0
trendBear = emaFast < emaSlow and trendSlope < 0
regime = math.abs(trendSlope) > 0.25 ? "TREND" : "RANGE"
 
//====================================================
// CONFIRMED MARKET STRUCTURE
//====================================================
detailHigh = ta.pivothigh(high, detailLen, detailLen)
detailLow = ta.pivotlow(low, detailLen, detailLen)
majorHigh = ta.pivothigh(high, majorLen, majorLen)
majorLow = ta.pivotlow(low, majorLen, majorLen)
 
var float lastDetailHigh = na
var float lastDetailLow = na
var float lastMajorHigh = na
var float lastMajorLow = na
var int marketDirection = 0
 
var int lastBullSweepBar = na
var int lastBearSweepBar = na
var int lastMajorBullSweepBar = na
var int lastMajorBearSweepBar = na
 
bool bullSweep = false
bool bearSweep = false
bool majorBullSweep = false
bool majorBearSweep = false
bool bullBOS = false
bool bearBOS = false
bool bullMSS = false
bool bearMSS = false
 
// Check sweeps against previously confirmed levels.
// Newly confirmed pivots become available afterward.
if barstate.isconfirmed
    bullSweep := not na(lastDetailLow) and low < lastDetailLow and close > lastDetailLow and close[1] >= lastDetailLow
    bearSweep := not na(lastDetailHigh) and high > lastDetailHigh and close < lastDetailHigh and close[1] <= lastDetailHigh
    majorBullSweep := not na(lastMajorLow) and low < lastMajorLow and close > lastMajorLow and close[1] >= lastMajorLow
    majorBearSweep := not na(lastMajorHigh) and high > lastMajorHigh and close < lastMajorHigh and close[1] <= lastMajorHigh
 
    if bullSweep
        lastBullSweepBar := bar_index
    if bearSweep
        lastBearSweepBar := bar_index
    if majorBullSweep
        lastMajorBullSweepBar := bar_index
    if majorBearSweep
        lastMajorBearSweepBar := bar_index
 
    bool brokeHigh = not na(lastMajorHigh) and close > lastMajorHigh and close[1] <= lastMajorHigh
    bool brokeLow = not na(lastMajorLow) and close < lastMajorLow and close[1] >= lastMajorLow
 
    bullMSS := brokeHigh and marketDirection == -1
    bearMSS := brokeLow and marketDirection == 1
    bullBOS := brokeHigh and not bullMSS
    bearBOS := brokeLow and not bearMSS
 
    if brokeHigh
        marketDirection := 1
    if brokeLow
        marketDirection := -1
 
    if not na(detailHigh)
        lastDetailHigh := detailHigh
    if not na(detailLow)
        lastDetailLow := detailLow
    if not na(majorHigh)
        lastMajorHigh := majorHigh
    if not na(majorLow)
        lastMajorLow := majorLow
 
plotshape(showBOS and bullBOS, title="Bull BOS", style=shape.circle, location=location.belowbar, color=demandColor, size=size.tiny)
plotshape(showBOS and bearBOS, title="Bear BOS", style=shape.circle, location=location.abovebar, color=supplyColor, size=size.tiny)
plotshape(showMSS and bullMSS, title="Bull MSS", style=shape.diamond, location=location.belowbar, color=demandColor, size=size.tiny)
plotshape(showMSS and bearMSS, title="Bear MSS", style=shape.diamond, location=location.abovebar, color=supplyColor, size=size.tiny)
plotshape(showSweepLabels and majorBullSweep, title="Major Bull Sweep", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny)
plotshape(showSweepLabels and majorBearSweep, title="Major Bear Sweep", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny)
 
//====================================================
// CLEAN STRUCTURE ZONES
//====================================================
type Zone
    box bx
    float top
    float bottom
    bool supply
    bool major
    int born
    float volRatio
 
var array<Zone> zones = array.new<Zone>()
volumeBaseline = ta.sma(volume, volumeLookback)
 
bool detailedVisible = structureMode == "Both" or structureMode == "Detailed"
bool majorVisible = structureMode == "Both" or structureMode == "Major"
 
f_overlaps(float top, float bottom, float otherTop, float otherBottom) =>
    math.min(top, otherTop) >= math.max(bottom, otherBottom)
 
f_zoneText(bool supply, bool major, float bottom, float top, float volRatio) =>
    string side = (major ? "MAJOR " : "") + (supply ? "SUPPLY" : "DEMAND")
    string strength = na(volRatio) ? "VOL N/A" : volRatio >= strongVolumeRatio ? "STRONG" : volRatio >= 1.0 ? "NORMAL" : "LIGHT"
    string volText = not showVolumeStrength ? "" : " | " + strength + " " + (na(volRatio) ? "" : str.tostring(volRatio, "#.##") + "x")
    switch zoneLabelMode
        "Detailed" => side + volText + "\n" + f_price(bottom) + " - " + f_price(top)
        "Compact" => side + volText
        => ""
 
f_addZone(float level, bool supply, bool major, int pivotLen) =>
    float a = nz(atr[pivotLen], safeATR)
    float depth = math.max(a * (major ? majorDepth : zoneDepth), syminfo.mintick)
    float top = supply ? level : level + depth
    float bottom = supply ? level - depth : level
    bool duplicate = false
    bool blockedByMajor = false
 
    if array.size(zones) > 0
        for i = 0 to array.size(zones) - 1
            Zone z = array.get(zones, i)
            if z.supply == supply
                bool overlap = f_overlaps(top, bottom, z.top, z.bottom)
                float center = (top + bottom) * 0.5
                float otherCenter = (z.top + z.bottom) * 0.5
                bool nearby = math.abs(center - otherCenter) <= a * minimumZoneSpacing
                if deduplicateZones and (overlap or nearby)
                    if z.major and not major
                        blockedByMajor := majorPriority
                    else if z.major == major
                        duplicate := true
 
    float pivotVol = volume[pivotLen]
    float avgVol = volumeBaseline[pivotLen]
    float volRatio = not na(pivotVol) and not na(avgVol) and avgVol > 0 ? pivotVol / avgVol : na
    bool passesVolume = zoneStrengthFilter == "All" or na(volRatio) or (zoneStrengthFilter == "Above Average" ? volRatio >= 1.0 : volRatio >= strongVolumeRatio)
    bool create = not duplicate and not blockedByMajor and passesVolume
 
    if create
        color zc = supply ? supplyColor : demandColor
        int transparency = major ? 87 : 94
        int borderTransparency = major ? 35 : 78
 
        box b = box.new(
             left=bar_index - pivotLen,
             top=top,
             right=bar_index + zoneExtend,
             bottom=bottom,
             bgcolor=color.new(zc, transparency),
             border_color=color.new(zc, borderTransparency),
             border_width=major ? 2 : 1,
             text=f_zoneText(supply, major, bottom, top, volRatio),
             text_color=color.new(zc, major ? 0 : 15),
             text_size=f_size(zoneFont),
             text_halign=text.align_right,
             text_valign=text.align_center)
 
        array.push(zones, Zone.new(b, top, bottom, supply, major, bar_index - pivotLen, volRatio))
 
    create
 
// First remove invalid and expired zones.
// Then add new zones and apply major-zone priority.
if barstate.isconfirmed
    if array.size(zones) > 0
        for i = array.size(zones) - 1 to 0
            Zone z = array.get(zones, i)
            bool invalid = z.supply ? close > z.top : close < z.bottom
            bool expired = bar_index - z.born > zoneExtend + 200
            if (hideBrokenZones and invalid) or expired
                box.delete(z.bx)
                array.remove(zones, i)
 
    // Major zones are processed first.
    if majorVisible
        bool majorHighQualified = not na(majorHigh) and math.abs(majorHigh - nz(lastMajorLow, majorHigh)) >= safeATR * majorDisplacement
        bool majorLowQualified = not na(majorLow) and math.abs(nz(lastMajorHigh, majorLow) - majorLow) >= safeATR * majorDisplacement
        if majorHighQualified
            f_addZone(majorHigh, true, true, majorLen)
        if majorLowQualified
            f_addZone(majorLow, false, true, majorLen)
 
    if detailedVisible
        if not na(detailHigh)
            f_addZone(detailHigh, true, false, detailLen)
        if not na(detailLow)
            f_addZone(detailLow, false, false, detailLen)
 
    // Remove detailed zones covered by major zones.
    if majorPriority and structureMode == "Both" and array.size(zones) > 1
        for i = array.size(zones) - 1 to 0
            Zone detail = array.get(zones, i)
            if not detail.major
                bool covered = false
                for j = 0 to array.size(zones) - 1
                    Zone majorZone = array.get(zones, j)
                    if majorZone.major and majorZone.supply == detail.supply
                        bool overlap = f_overlaps(detail.top, detail.bottom, majorZone.top, majorZone.bottom)
                        float centerDistance = math.abs((detail.top + detail.bottom - majorZone.top - majorZone.bottom) * 0.5)
                        if overlap or centerDistance <= safeATR * minimumZoneSpacing
                            covered := true
                if covered
                    box.delete(detail.bx)
                    array.remove(zones, i)
 
    // Enforce per-side limits, retaining the newest zones.
    if array.size(zones) > 0
        int detailSupplyCount = 0
        int detailDemandCount = 0
        int majorSupplyCount = 0
        int majorDemandCount = 0
 
        for i = array.size(zones) - 1 to 0
            Zone z = array.get(zones, i)
            bool excess = false
 
            if z.major and z.supply
                majorSupplyCount += 1
                excess := majorSupplyCount > maxMajor
            else if z.major and not z.supply
                majorDemandCount += 1
                excess := majorDemandCount > maxMajor
            else if not z.major and z.supply
                detailSupplyCount += 1
                excess := detailSupplyCount > maxDetail
            else
                detailDemandCount += 1
                excess := detailDemandCount > maxDetail
 
            if excess
                box.delete(z.bx)
                array.remove(zones, i)
            else
                box.set_right(z.bx, bar_index + zoneExtend)
 
plot(showStructureLines and majorVisible ? lastMajorHigh : na, "Major Resistance", color=color.new(supplyColor, 55), linewidth=1, style=plot.style_stepline)
plot(showStructureLines and majorVisible ? lastMajorLow : na, "Major Support", color=color.new(demandColor, 55), linewidth=1, style=plot.style_stepline)
 
//====================================================
// ORIGINAL FOUR-MODEL FORECAST ENGINE
//====================================================
f_model(int horizon) =>
    float currentMomentum = (close - close[5]) / safeATR
    float currentTrend = (emaFast - emaSlow) / safeATR
    float currentRSI = rsiValue
    float currentVolatility = safeATR / math.max(math.abs(close), syminfo.mintick)
 
    // Historical analog nearest-neighbor search.
    array<float> distances = array.new_float()
    array<float> outcomes = array.new_float()
 
    for j = horizon + 20 to lookback
        if not na(close[j + 5]) and not na(atr[j]) and not na(rsiValue[j])
            float a = math.max(atr[j], syminfo.mintick)
            float mom = (close[j] - close[j + 5]) / a
            float tr = (emaFast[j] - emaSlow[j]) / a
            float vol = a / math.max(math.abs(close[j]), syminfo.mintick)
            float distance = math.abs(currentMomentum - mom) + 0.7 * math.abs(currentTrend - tr) + 0.035 * math.abs(currentRSI - rsiValue[j]) + 100 * math.abs(currentVolatility - vol)
            float futureMove = close[j - horizon] - close[j]
            array.push(distances, distance)
            array.push(outcomes, futureMove)
 
    float analog = na
    if array.size(distances) > 0
        float totalWeighted = 0.0
        float totalWeight = 0.0
        int n = math.min(neighbors, array.size(distances))
 
        for k = 0 to n - 1
            int best = array.indexof(distances, array.min(distances))
            float dist = array.get(distances, best)
            float weight = 1.0 / (1.0 + dist)
            totalWeighted += array.get(outcomes, best) * weight
            totalWeight += weight
            array.set(distances, best, 1e10)
 
        analog := totalWeight > 0 ? totalWeighted / totalWeight : na
 
    // Empirical forward-change sample.
    float empiricalSum = 0.0
    int empiricalN = 0
    int stepSize = math.max(1, int(math.floor((lookback - horizon) / simulations)))
 
    for j = horizon + 1 to lookback by stepSize
        if not na(close[j]) and not na(close[j - horizon])
            empiricalSum += close[j - horizon] - close[j]
            empiricalN += 1
 
    float empirical = empiricalN > 0 ? empiricalSum / empiricalN : na
 
    // Linear regression extrapolation.
    float regNow = ta.linreg(close, regLen, 0)
    float regPrev = ta.linreg(close, regLen, 1)
    float regression = (regNow - regPrev) * horizon
 
    // Confirmed swing-structure projection.
    float structureMove = marketDirection * safeATR * math.sqrt(horizon) * 0.35
 
    float weightedSum = 0.0
    float weightSum = 0.0
    int bulls = 0
    int bears = 0
 
    if not na(analog)
        bulls += analog > 0 ? 1 : 0
        bears += analog < 0 ? 1 : 0
 
    if not na(empirical)
        bulls += empirical > 0 ? 1 : 0
        bears += empirical < 0 ? 1 : 0
 
    bulls += regression > 0 ? 1 : 0
    bears += regression < 0 ? 1 : 0
    bulls += structureMove > 0 ? 1 : 0
    bears += structureMove < 0 ? 1 : 0
 
    float regimeAnalog = regime == "TREND" ? 0.8 : 1.2
    float regimeRegression = regime == "TREND" ? 1.3 : 0.7
 
    if not na(analog)
        weightedSum += analog * wAnalog * regimeAnalog
        weightSum += wAnalog * regimeAnalog
 
    if not na(empirical)
        weightedSum += empirical * wEmpirical
        weightSum += wEmpirical
 
    weightedSum += regression * wRegression * regimeRegression
    weightSum += wRegression * regimeRegression
    weightedSum += structureMove * wSwing
    weightSum += wSwing
 
    float ensemble = weightSum > 0 ? weightedSum / weightSum : na
 
    float chosen = switch engine
        "Analog Only" => analog
        "Empirical Simulation Only" => empirical
        "Regression Only" => regression
        "Swing Only" => structureMove
        "Strict Consensus" => bulls == 4 or bears == 4 ? ensemble : 0.0
        => ensemble
 
    float scale = safeATR * math.sqrt(horizon)
    float score = na(chosen) ? na : f_clamp(50 + 20 * chosen / math.max(scale, syminfo.mintick), 0, 100)
 
    [chosen, score, bulls, bears]
 
[d1, p1, b1, s1] = f_model(h1)
[d2, p2, b2, s2] = f_model(h2)
[d3, p3, b3, s3] = f_model(h3)
[d4, p4, b4, s4] = f_model(h4)
[d5, p5, b5, s5] = f_model(h5)
 
//====================================================
// SELECTED FORECAST
//====================================================
selectedMove = switch signalHorizon
    "H1" => d1
    "H2" => d2
    "H3" => d3
    "H4" => d4
    => d5
 
selectedScore = switch signalHorizon
    "H1" => p1
    "H2" => p2
    "H3" => p3
    "H4" => p4
    => p5
 
selectedBulls = switch signalHorizon
    "H1" => b1
    "H2" => b2
    "H3" => b3
    "H4" => b4
    => b5
 
selectedBears = switch signalHorizon
    "H1" => s1
    "H2" => s2
    "H3" => s3
    "H4" => s4
    => s5
 
//====================================================
// LIQUIDITY-AWARE ENTRY ENGINE
//====================================================
recentBullSweep = not na(lastBullSweepBar) and bar_index - lastBullSweepBar <= sweepWindow
recentBearSweep = not na(lastBearSweepBar) and bar_index - lastBearSweepBar <= sweepWindow
recentMajorBull = not na(lastMajorBullSweepBar) and bar_index - lastMajorBullSweepBar <= sweepWindow
recentMajorBear = not na(lastMajorBearSweepBar) and bar_index - lastMajorBearSweepBar <= sweepWindow
 
longReversal = (requireMajorSweep ? recentMajorBull : recentBullSweep or recentMajorBull) and close > open
shortReversal = (requireMajorSweep ? recentMajorBear : recentBearSweep or recentMajorBear) and close < open
 
longFlow = trendBull and (not requireTrendAlignment or marketDirection >= 0)
shortFlow = trendBear and (not requireTrendAlignment or marketDirection <= 0)
 
longGate = switch entryMode
    "Liquidity Reversal" => longReversal
    "Trend Flow" => longFlow
    "Hybrid Balanced" => longReversal or longFlow
    => true
 
shortGate = switch entryMode
    "Liquidity Reversal" => shortReversal
    "Trend Flow" => shortFlow
    "Hybrid Balanced" => shortReversal or shortFlow
    => true
 
var int tradeState = 0
var int lastEntryBar = na
 
bool buySignal = false
bool sellSignal = false
bool exitSignal = false
 
canEnter = na(lastEntryBar) or bar_index - lastEntryBar >= cooldown
 
if enableSignals and barstate.isconfirmed and not na(selectedScore)
    if tradeState == 0 and canEnter
        if selectedScore >= entryScore and selectedBulls >= minAgreement and longGate
            buySignal := true
            tradeState := 1
            lastEntryBar := bar_index
        else if selectedScore <= 100 - entryScore and selectedBears >= minAgreement and shortGate
            sellSignal := true
            tradeState := -1
            lastEntryBar := bar_index
    else if tradeState == 1
        if selectedScore <= exitScore
            exitSignal := true
            tradeState := 0
    else if tradeState == -1
        if selectedScore >= 100 - exitScore
            exitSignal := true
            tradeState := 0
 
// Size must be compile-time constant in plotshape.
// Separate calls allow a user-selectable arrow size.
plotshape(showBuy and buySignal and arrowSize == "Tiny", title="BUY Tiny", style=shape.triangleup, location=location.belowbar, color=bullColor, size=size.tiny)
plotshape(showBuy and buySignal and arrowSize == "Small", title="BUY Small", style=shape.triangleup, location=location.belowbar, color=bullColor, size=size.small)
plotshape(showBuy and buySignal and arrowSize == "Medium", title="BUY Medium", style=shape.triangleup, location=location.belowbar, color=bullColor, size=size.normal)
plotshape(showBuy and buySignal and arrowSize == "Large", title="BUY Large", style=shape.triangleup, location=location.belowbar, color=bullColor, size=size.large)
 
plotshape(showSell and sellSignal and arrowSize == "Tiny", title="SELL Tiny", style=shape.triangledown, location=location.abovebar, color=bearColor, size=size.tiny)
plotshape(showSell and sellSignal and arrowSize == "Small", title="SELL Small", style=shape.triangledown, location=location.abovebar, color=bearColor, size=size.small)
plotshape(showSell and sellSignal and arrowSize == "Medium", title="SELL Medium", style=shape.triangledown, location=location.abovebar, color=bearColor, size=size.normal)
plotshape(showSell and sellSignal and arrowSize == "Large", title="SELL Large", style=shape.triangledown, location=location.abovebar, color=bearColor, size=size.large)
 
plotshape(showExit and exitSignal, title="EXIT", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny)
 
alertcondition(buySignal, "TOLAG BUY", "TOLAG Foresight X BUY | {{ticker}} | {{interval}}")
alertcondition(sellSignal, "TOLAG SELL", "TOLAG Foresight X SELL | {{ticker}} | {{interval}}")
alertcondition(exitSignal, "TOLAG EXIT", "TOLAG Foresight X EXIT | {{ticker}} | {{interval}}")
alertcondition(majorBullSweep, "TOLAG Major Bull Sweep", "TOLAG major bullish liquidity sweep | {{ticker}}")
alertcondition(majorBearSweep, "TOLAG Major Bear Sweep", "TOLAG major bearish liquidity sweep | {{ticker}}")
 
//====================================================
// TRADE PLANNER
//====================================================
var box riskBox = na
var box tp1Box = na
var box tp2Box = na
 
var label entryTag = na
var label stopTag = na
var label tp1Tag = na
var label tp2Tag = na
 
drawLong = buySignal and showLongPlanner
drawShort = sellSignal and showShortPlanner
 
if showPlanner and (drawLong or drawShort)
    if not na(riskBox)
        box.delete(riskBox)
    if not na(tp1Box)
        box.delete(tp1Box)
    if not na(tp2Box)
        box.delete(tp2Box)
 
    if not na(entryTag)
        label.delete(entryTag)
    if not na(stopTag)
        label.delete(stopTag)
    if not na(tp1Tag)
        label.delete(tp1Tag)
    if not na(tp2Tag)
        label.delete(tp2Tag)
 
    float side = drawLong ? 1.0 : -1.0
    float entry = close
    float atrRisk = safeATR * stopATR
    float structureRisk = atrRisk
 
    if stopMode == "Structure + ATR"
        if drawLong and not na(lastMajorLow) and lastMajorLow < entry
            structureRisk := math.max(atrRisk, entry - lastMajorLow + safeATR * stopBuffer)
        if drawShort and not na(lastMajorHigh) and lastMajorHigh > entry
            structureRisk := math.max(atrRisk, lastMajorHigh - entry + safeATR * stopBuffer)
 
    float risk = math.max(structureRisk, syminfo.mintick)
    float stop = entry - side * risk
    float firstR = math.min(tp1R, tp2R)
    float secondR = math.max(tp1R, tp2R)
    float target1 = entry + side * risk * firstR
    float target2 = entry + side * risk * secondR
    int right = bar_index + plannerWidth
 
    riskBox := box.new(bar_index, math.max(entry, stop), right, math.min(entry, stop), bgcolor=color.new(bearColor, plannerOpacity), border_color=color.new(bearColor, 35))
    tp1Box := box.new(bar_index, math.max(entry, target1), right, math.min(entry, target1), bgcolor=color.new(bullColor, plannerOpacity), border_color=color.new(bullColor, 35), text="TARGET 1 - " + str.tostring(firstR, "#.##") + "R", text_color=bullColor, text_size=size.tiny)
    tp2Box := box.new(bar_index, math.max(target1, target2), right, math.min(target1, target2), bgcolor=color.new(bullColor, math.min(98, plannerOpacity + 3)), border_color=color.new(bullColor, 45), text="TARGET 2 - " + str.tostring(secondR, "#.##") + "R", text_color=bullColor, text_size=size.tiny)
 
    entryTag := label.new(right, entry, "ENTRY " + f_price(entry), style=label.style_label_left, color=color.rgb(55, 68, 87), textcolor=color.white, size=size.tiny)
    stopTag := label.new(right, stop, "SL " + f_price(stop), style=label.style_label_left, color=bearColor, textcolor=color.white, size=size.tiny)
    tp1Tag := label.new(right, target1, "TP1 " + f_price(target1), style=label.style_label_left, color=bullColor, textcolor=color.black, size=size.tiny)
    tp2Tag := label.new(right, target2, "TP2 " + f_price(target2), style=label.style_label_left, color=bullColor, textcolor=color.black, size=size.tiny)
 
//====================================================
// ORIGINAL FORECAST FAN
//====================================================
var array<line> fanLines = array.new_line()
var array<linefill> fanFills = array.new_linefill()
var array<label> fanLabels = array.new_label()
 
if barstate.islast
    while array.size(fanFills) > 0
        linefill.delete(array.pop(fanFills))
 
    while array.size(fanLines) > 0
        line.delete(array.pop(fanLines))
 
    while array.size(fanLabels) > 0
        label.delete(array.pop(fanLabels))
 
    if showForecast
        array<int> horizons = array.from(h1, h2, h3, h4, h5)
        array<float> moves = array.from(d1, d2, d3, d4, d5)
 
        int previousX = bar_index
        float previousMedian = close
        float previousUpperOuter = close
        float previousLowerOuter = close
        float previousUpperInner = close
        float previousLowerInner = close
 
        for k = 0 to 4
            int horizon = array.get(horizons, k)
            float move = array.get(moves, k)
 
            if not na(move)
                int x = bar_index + horizon
                float median = close + move
                float inner = math.min(safeATR * corridorCap, safeATR * math.sqrt(horizon) * innerFactor)
                float outer = math.min(safeATR * corridorCap, safeATR * math.sqrt(horizon) * outerFactor)
                int originX = forecastStyle == "Original Fan" ? bar_index : previousX
                float originUpperOuter = forecastStyle == "Original Fan" ? close : previousUpperOuter
                float originLowerOuter = forecastStyle == "Original Fan" ? close : previousLowerOuter
                float originUpperInner = forecastStyle == "Original Fan" ? close : previousUpperInner
                float originLowerInner = forecastStyle == "Original Fan" ? close : previousLowerInner
 
                if showOuter
                    line upper = line.new(originX, originUpperOuter, x, median + outer, color=color.new(forecastBlue, 48))
                    line lower = line.new(originX, originLowerOuter, x, median - outer, color=color.new(forecastBlue, 48))
                    linefill fillArea = linefill.new(upper, lower, color.new(forecastBlue, 94))
                    array.push(fanLines, upper)
                    array.push(fanLines, lower)
                    array.push(fanFills, fillArea)
 
                if showInner
                    line upper = line.new(originX, originUpperInner, x, median + inner, color=color.new(forecastBlue, 70))
                    line lower = line.new(originX, originLowerInner, x, median - inner, color=color.new(forecastBlue, 70))
                    linefill fillArea = linefill.new(upper, lower, color.new(forecastBlue, 86))
                    array.push(fanLines, upper)
                    array.push(fanLines, lower)
                    array.push(fanFills, fillArea)
 
                if showMedian
                    line path = line.new(previousX, previousMedian, x, median, color=move >= 0 ? bullColor : bearColor, width=2, style=line.style_dashed)
                    array.push(fanLines, path)
 
                if showPrices
                    label priceLabel = label.new(x, median, "+" + str.tostring(horizon) + " | " + f_price(median), style=label.style_label_left, color=color.new(forecastBlue, 35), textcolor=color.white, size=size.tiny)
                    array.push(fanLabels, priceLabel)
 
                previousX := x
                previousMedian := median
                previousUpperOuter := median + outer
                previousLowerOuter := median - outer
                previousUpperInner := median + inner
                previousLowerInner := median - inner
 
//====================================================
// MTF SCORES
//====================================================
mtf1 = request.security(syminfo.tickerid, tf1, f_mtfScore(), lookahead=barmerge.lookahead_off)
mtf2 = request.security(syminfo.tickerid, tf2, f_mtfScore(), lookahead=barmerge.lookahead_off)
mtf3 = request.security(syminfo.tickerid, tf3, f_mtfScore(), lookahead=barmerge.lookahead_off)
mtf4 = request.security(syminfo.tickerid, tf4, f_mtfScore(), lookahead=barmerge.lookahead_off)
mtf5 = request.security(syminfo.tickerid, tf5, f_mtfScore(), lookahead=barmerge.lookahead_off)
 
mtfAverage = (mtf1 + mtf2 + mtf3 + mtf4 + mtf5) / 5.0
 
//====================================================
// HISTORICAL SAMPLED VALIDATION
// Lagged-direction proxy, NOT full model backtest.
//====================================================
f_validation(int horizon) =>
    float hitCount = 0.0
    float totalError = 0.0
    int samples = 0
    int maxJ = math.min(lookback, horizon + validationSpacing * validationLimit)
 
    for j = horizon to maxJ by validationSpacing
        // Momentum preceding the sampled historical bar.
        float predicted = close[j] - close[j + horizon]
 
        // Subsequent realized change.
        // j >= horizon, so j - horizon is not a future bar.
        float realized = close[j - horizon] - close[j]
 
        if not na(predicted) and not na(realized)
            hitCount += math.sign(predicted) == math.sign(realized) ? 1 : 0
            totalError += math.abs(predicted - realized)
            samples += 1
 
    float accuracy = samples > 0 ? 100 * hitCount / samples : na
    float mae = samples > 0 ? totalError / samples : na
    [accuracy, mae, samples]
 
[a1, e1, n1] = f_validation(h1)
[a2, e2, n2] = f_validation(h2)
[a3, e3, n3] = f_validation(h3)
[a4, e4, n4] = f_validation(h4)
[a5, e5, n5] = f_validation(h5)
 
//====================================================
// DASHBOARD TABLES
//====================================================
headerBG = color.rgb(16, 32, 55)
rowBG = color.rgb(21, 37, 60)
 
var table mainTable = table.new(f_position(mainPos), 3, 10, border_width=1, border_color=color.new(color.gray, 85))
var table mtfTable = table.new(f_position(mtfPos), 3, 8, border_width=1, border_color=color.new(color.gray, 85))
var table validationTable = table.new(f_position(validationPos), 4, 9, border_width=1, border_color=color.new(color.gray, 85))
 
f_cell(table t, int c, int r, string value, color textColor, color bg, string textSize) =>
    table.cell(t, c, r, value, text_color=textColor, bgcolor=bg, text_size=f_size(textSize))
 
f_forecastRow(int row, int horizon, float move, float score) =>
    f_cell(mainTable, 0, row, str.tostring(horizon) + " bars", color.silver, rowBG, mainSize)
    f_cell(mainTable, 1, row, na(move) ? "—" : f_price(close + move), color.white, rowBG, mainSize)
    f_cell(mainTable, 2, row, f_pct(score), f_scoreColor(score), rowBG, mainSize)
 
f_mtfRow(int row, string tf, float score) =>
    f_cell(mtfTable, 0, row, tf, color.silver, rowBG, mtfSize)
    f_cell(mtfTable, 1, row, f_pct(score), f_scoreColor(score), rowBG, mtfSize)
    f_cell(mtfTable, 2, row, f_direction(score), f_scoreColor(score), rowBG, mtfSize)
 
f_validationRow(int row, int horizon, float accuracy, float mae, int count) =>
    f_cell(validationTable, 0, row, str.tostring(horizon) + " bars", color.silver, rowBG, validationSize)
    f_cell(validationTable, 1, row, f_pct(accuracy), f_scoreColor(accuracy), rowBG, validationSize)
    f_cell(validationTable, 2, row, f_price(mae), color.silver, rowBG, validationSize)
    f_cell(validationTable, 3, row, str.tostring(count), color.silver, rowBG, validationSize)
 
if barstate.islast
    table.clear(mainTable, 0, 0, 2, 9)
    table.clear(mtfTable, 0, 0, 2, 7)
    table.clear(validationTable, 0, 0, 3, 8)
 
    if showMain
        f_cell(mainTable, 0, 0, "TOLAG", color.white, headerBG, mainSize)
        f_cell(mainTable, 1, 0, "FORESIGHT X", color.aqua, headerBG, mainSize)
        f_cell(mainTable, 2, 0, "TGL 1", color.white, headerBG, mainSize)
 
        f_cell(mainTable, 0, 1, "Horizon", color.silver, headerBG, mainSize)
        f_cell(mainTable, 1, 1, "Median", color.silver, headerBG, mainSize)
        f_cell(mainTable, 2, 1, "Up Score", color.silver, headerBG, mainSize)
 
        f_forecastRow(2, h1, d1, p1)
        f_forecastRow(3, h2, d2, p2)
        f_forecastRow(4, h3, d3, p3)
        f_forecastRow(5, h4, d4, p4)
        f_forecastRow(6, h5, d5, p5)
 
        f_cell(mainTable, 0, 7, "REGIME", color.silver, headerBG, mainSize)
        f_cell(mainTable, 1, 7, regime, color.orange, headerBG, mainSize)
        f_cell(mainTable, 2, 7, selectedBulls > selectedBears ? "BULL" : selectedBears > selectedBulls ? "BEAR" : "MIXED", color.white, headerBG, mainSize)
 
        f_cell(mainTable, 0, 8, "STRUCTURE", color.silver, rowBG, mainSize)
        f_cell(mainTable, 1, 8, structureMode, color.aqua, rowBG, mainSize)
        f_cell(mainTable, 2, 8, marketDirection == 1 ? "BULL" : marketDirection == -1 ? "BEAR" : "NEUTRAL", color.white, rowBG, mainSize)
 
        f_cell(mainTable, 0, 9, "STATUS", color.silver, headerBG, mainSize)
        f_cell(mainTable, 1, 9, "RESEARCH", color.orange, headerBG, mainSize)
        f_cell(mainTable, 2, 9, "UNVALIDATED", color.orange, headerBG, mainSize)
 
    if showMTF
        f_cell(mtfTable, 0, 0, "TOLAG", color.white, headerBG, mtfSize)
        f_cell(mtfTable, 1, 0, "MTF SENTIMENT", color.aqua, headerBG, mtfSize)
        f_cell(mtfTable, 2, 0, "TGL 1", color.white, headerBG, mtfSize)
 
        f_cell(mtfTable, 0, 1, "TF", color.silver, headerBG, mtfSize)
        f_cell(mtfTable, 1, 1, "Score", color.silver, headerBG, mtfSize)
        f_cell(mtfTable, 2, 1, "Bias", color.silver, headerBG, mtfSize)
 
        f_mtfRow(2, tf1, mtf1)
        f_mtfRow(3, tf2, mtf2)
        f_mtfRow(4, tf3, mtf3)
        f_mtfRow(5, tf4, mtf4)
        f_mtfRow(6, tf5, mtf5)
 
        f_cell(mtfTable, 0, 7, "OVERALL", color.white, headerBG, mtfSize)
        f_cell(mtfTable, 1, 7, f_pct(mtfAverage), f_scoreColor(mtfAverage), headerBG, mtfSize)
        f_cell(mtfTable, 2, 7, f_direction(mtfAverage), f_scoreColor(mtfAverage), headerBG, mtfSize)
 
    if showValidation
        f_cell(validationTable, 0, 0, "TOLAG", color.white, headerBG, validationSize)
        f_cell(validationTable, 1, 0, "VALIDATION", color.aqua, headerBG, validationSize)
        f_cell(validationTable, 2, 0, "TGL 1", color.white, headerBG, validationSize)
        f_cell(validationTable, 3, 0, "SAMPLED", color.orange, headerBG, validationSize)
 
        f_cell(validationTable, 0, 1, "Horizon", color.silver, headerBG, validationSize)
        f_cell(validationTable, 1, 1, "Hit %", color.silver, headerBG, validationSize)
        f_cell(validationTable, 2, 1, "MAE", color.silver, headerBG, validationSize)
        f_cell(validationTable, 3, 1, "N", color.silver, headerBG, validationSize)
 
        f_validationRow(2, h1, a1, e1, n1)
        f_validationRow(3, h2, a2, e2, n2)
        f_validationRow(4, h3, a3, e3, n3)
        f_validationRow(5, h4, a4, e4, n4)
        f_validationRow(6, h5, a5, e5, n5)
 
        f_cell(validationTable, 0, 7, "METHOD", color.silver, headerBG, validationSize)
        f_cell(validationTable, 1, 7, "LAG", color.orange, headerBG, validationSize)
        f_cell(validationTable, 2, 7, "RESEARCH", color.orange, headerBG, validationSize)
        f_cell(validationTable, 3, 7, "ONLY", color.orange, headerBG, validationSize)
 
        f_cell(validationTable, 0, 8, "NOTE", color.silver, headerBG, validationSize)
        f_cell(validationTable, 1, 8, "PROXY", color.orange, headerBG, validationSize)
        f_cell(validationTable, 2, 8, "NOT", color.orange, headerBG, validationSize)
        f_cell(validationTable, 3, 8, "BACKTEST", color.orange, headerBG, validationSize)

← 返回列表