Fractal Structure & Momentum v0.3

TalentedInvestor · study · 1161 行 · 点赞 18 · TradingView 原页

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

Pine Script

//@version=6
// Fractal Structure & Momentum v0.3
// Directional candle merging -> confirmed fractal turns -> qualifying swings.
// Three-swing overlap cores identify consolidation; a coarser swing path adds context.
// B1/S1 compare a new price extreme with same-direction MACD histogram area.
// B2/S2 track the first respectful pullback; B3/S3 track the first outside-core retest.
// Geometric tails can revise after later fractals cross a starting extreme.
// Issued-event records preserve their original detection bars across revisions.
// Labels default to the bar when their information becomes available.
// Question marks identify developing endpoint assessments that can change.
// Area = current directional histogram area / reference directional area.
// The guide explains confirmation timing, startup requirements and research limits.
 
indicator("Fractal Structure & Momentum v0.3", shorttitle = "FSM", overlay = true,
     max_bars_back = 500, dynamic_requests = true, max_lines_count = 500, max_boxes_count = 150, max_labels_count = 400)
 
gCore = "Structural rules"
minimumSeparation = input.int(4, "Stroke endpoint separation (merged bars)", minval = 2, maxval = 12, group = gCore,
     tooltip = "Endpoints must be this many merged-bar positions apart. Default 4 spans at least 5 merged candles. A fractal waits until its right neighbor is sealed by a further noncontained candle.", display = display.none)
displayHistory = input.int(2000, "Display history (raw bars)", minval = 100, maxval = 4000, group = gCore,
     tooltip = "The bounded engine streams all loaded closed bars. This setting limits the visible drawings. Loading a different amount of price history can affect its earliest structures.", display = display.none)
showStrokes = input.bool(true, "Show strokes", group = gCore, display = display.none)
showCoarse = input.bool(true, "Show coarse swing guide", group = gCore,
     tooltip = "A second swing layer from extrema among three same-side sealed endpoints. Its newest endpoint can extend as the coarser swing develops.", display = display.none)
showLivePath = input.bool(true, "Show developing path to current price", group = gCore, display = display.none)
drawStrokeCount = input.int(180, "Maximum visible strokes", minval = 20, maxval = 300, group = gCore, display = display.none)
 
gZones = "Consolidation zones"
showCenters = input.bool(true, "Show confirmed overlap cores", group = gZones, display = display.none)
showVirtual = input.bool(true, "Show provisional overlap core", group = gZones,
     tooltip = "The last three strokes can form a prospective zone while their newest endpoint remains provisional. Its dashed box can change.", display = display.none)
showEnvelope = input.bool(false, "Show zone envelopes", group = gZones,
     tooltip = "The envelope records the full high/low span of strokes extending a zone. It is an expansion guide around the fixed overlap core.", display = display.none)
zoneTransparency = input.int(90, "Confirmed core transparency", minval = 0, maxval = 100, group = gZones, display = display.none)
drawZoneCount = input.int(30, "Maximum visible zones", minval = 5, maxval = 60, group = gZones, display = display.none)
 
gSignals = "Signal display and timing"
showLabels = input.bool(true, "Show sealed-point B/S labels", group = gSignals, display = display.none)
showCandidates = input.bool(true, "Show provisional endpoint signals (?)", group = gSignals, display = display.none)
labelPlacement = input.string("Detection bar", "Signal label position", options = ["Detection bar", "Structure anchor (historical)"], group = gSignals,
     tooltip = "Detection bar shows when the structure became available. Anchor placement draws at the earlier turning point; actual detection-bar triangles remain visible in that mode.", display = display.none)
showAvailabilityMarks = input.bool(false, "Show detection-bar triangles", group = gSignals, display = display.none)
drawSignalCount = input.int(100, "Maximum visible signal labels", minval = 10, maxval = 200, group = gSignals, display = display.none)
 
gArea = "Momentum comparison"
macdFast = input.int(12, "MACD fast", minval = 1, maxval = 100, group = gArea, tooltip = "Choose a fast length below the slow length. Area-divergence signals require fast < slow.", display = display.none)
macdSlow = input.int(26, "MACD slow", minval = 2, maxval = 200, group = gArea, display = display.none)
macdSignal = input.int(9, "MACD signal", minval = 1, maxval = 100, group = gArea, display = display.none)
maximumAreaRatio = input.float(1.0, "Area ratio must be below", minval = 0.05, maxval = 1.0, step = 0.05, group = gArea,
     tooltip = "B1/S1 rule: a new stroke price extreme with a smaller same-direction MACD histogram area than the prior same-direction stroke. Ratio = current area / reference area. Reference stroke starts after slow+signal raw bars.", display = display.none)
showAreaRatio = input.bool(true, "Show MACD area ratio on B1/S1 labels", group = gArea, display = display.none)
 
gColors = "Colors"
buyColor = input.color(#00DFA2, "Buy-side points / rising strokes", group = gColors, display = display.none)
sellColor = input.color(#FF667A, "Sell-side points / falling strokes", group = gColors, display = display.none)
coarseUpColor = input.color(#66B3FF, "Rising coarse guide", group = gColors, display = display.none)
coarseDownColor = input.color(#C4A0FF, "Falling coarse guide", group = gColors, display = display.none)
 
gContext = "Weekly and market context"
useWeekly = input.bool(true, "Include confirmed Weekly structure", group = gContext, display = display.none)
weeklyDivergenceAge = input.int(8, "Weekly momentum context age (weeks)", minval = 1, maxval = 52, group = gContext, display = display.none)
showWeeklyLevels = input.bool(false, "Show confirmed Weekly zone boundaries", group = gContext, display = display.none)
showContextTags = input.bool(false, "Add compact context tags to signal labels", group = gContext, tooltip = "W+ agrees with the confirmed Weekly higher-high/higher-low or lower-high/lower-low trend. W- opposes it. M! means the market benchmark closed below its Daily EMA. R+ / R- describe relative performance. Full details stay in each signal's tooltip.", display = display.none)
showAlignedMarks = input.bool(false, "Mark Weekly-aligned structural signals", group = gContext, display = display.none)
useMarket = input.bool(true, "Include market caution", group = gContext, tooltip = "All structural signals remain available. The market condition adds context and separate alerts.", display = display.none)
marketSymbol = input.symbol("NASDAQ:QQQ", "Market benchmark", group = gContext, display = display.none)
marketEmaLength = input.int(50, "Market Daily EMA", minval = 2, maxval = 250, group = gContext, display = display.none)
useRS = input.bool(true, "Include relative-strength context", group = gContext, display = display.none)
rsBenchmarkChoice = input.string("QQQ", "RS benchmark", options = ["QQQ", "SOXX", "SPY", "Custom"], group = gContext, display = display.none)
rsCustomBenchmark = input.symbol("NASDAQ:QQQ", "Custom RS benchmark", group = gContext, display = display.none)
rsCurrencyBasis = input.string("USD", "RS currency basis", options = ["USD", "Local prices"], group = gContext, tooltip = "USD converts both prices using TradingView's daily FX conversion. Local prices compares each listing's native price performance. Different market sessions may provide different quote times.", display = display.none)
rsLookback = input.int(20, "RS comparison (chart bars)", minval = 2, maxval = 200, group = gContext, display = display.none)
 
gEarly = "Earlier developing warnings"
enableEarly = input.bool(false, "Enable earlier warnings (experimental)", group = gEarly, tooltip = "Closed-bar reversal observations before an opposite endpoint is accepted. They can fail. These are separate EW B? / EW S? events and preserve their original detection time.", display = display.none)
enableEarlyAlerts = input.bool(false, "Enable early-warning alert conditions", group = gEarly, display = display.none)
earlyAtrLength = input.int(14, "Warning ATR length", minval = 2, maxval = 100, group = gEarly, display = display.none)
earlyLegAtr = input.float(2.0, "Minimum developing leg (ATR)", minval = 0.5, maxval = 10, step = 0.25, group = gEarly, display = display.none)
earlyReversalAtr = input.float(0.75, "Reversal from developing extreme (ATR)", minval = 0.25, maxval = 5, step = 0.25, group = gEarly, display = display.none)
earlyExpiry = input.int(20, "Warning observation window (chart bars)", minval = 2, maxval = 100, group = gEarly, display = display.none)
drawEarlyCount = input.int(30, "Maximum visible early warnings", minval = 1, maxval = 80, group = gEarly, display = display.none)
 
gLineStyle = "Line visibility"
strokeWidth = input.int(2, "Swing line width", minval = 1, maxval = 5, group = gLineStyle, display = display.none)
coarseWidth = input.int(3, "Coarse guide width", minval = 1, maxval = 6, group = gLineStyle, display = display.none)
developingWidth = input.int(2, "Developing path width", minval = 1, maxval = 5, group = gLineStyle, display = display.none)
levelWidth = input.int(2, "Invalidation / Weekly level width", minval = 1, maxval = 5, group = gLineStyle, display = display.none)
 
// Add alongside the other Inputs. All values stay out of the chart header.
gRisk = "Setup invalidation"
riskBoundary = input.string("Pattern extreme", "Invalidation boundary", options = ["Pattern extreme", "B3/S3 zone boundary"], group = gRisk,
     tooltip = "Pattern extreme freezes the detected B-pattern low or S-pattern high. Zone mode uses the original B3 upper-core or S3 lower-core boundary; other patterns use their endpoint price. A strict closed-bar breach invalidates that setup. These are structural reference levels.", display = display.none)
showInvalidation = input.bool(true, "Show latest active invalidation levels", group = gRisk, display = display.none)
showBreakMarks = input.bool(false, "Show setup invalidation markers", group = gRisk, display = display.none)
 
type MergedBar
    float h
    float l
    int highIndex
    int lowIndex
    int highTime
    int lowTime
    float highPositive
    float highNegative
    float lowPositive
    float lowNegative
    int sequence
 
type SwingPoint
    int kind
    float price
    int anchorIndex
    int anchorTime
    float positive
    float negative
    int mergedSequence
    int serial = 0
    int fractalKnownIndex = na
    int fractalKnownTime = na
    bool sealed = false
    int sealedIndex = na
    int sealedTime = na
 
type CoreZone
    int id
    int leftIndex
    int rightIndex
    float lower
    float upper
    float envelopeLow
    float envelopeHigh
    int direction
    bool active = true
    bool buyExitSeen = false
    bool sellExitSeen = false
    int knownIndex = na
 
type StructuralEvent
    string names
    int side
    float price
    int anchorIndex
    int anchorTime
    int knownIndex
    int knownTime
    float ratio
    float zoneBoundary = na
    string contextText = ""
    string contextTags = ""
 
type StructuralRevision
    int knownIndex
    int knownTime
    int changedFromIndex
    int removedPoints
    bool localReset
    int terminalAnchor
 
type StructureEngine
    array<MergedBar> bars
    array<SwingPoint> points
    array<SwingPoint> coarse
    array<CoreZone> zones
    array<StructuralEvent> events
    array<string> issuedKeys
    array<StructuralRevision> revisions
    int mergeDirection = 1
    int mergedSequence = 0
    int nextSerial = 0
    int nextZone = 0
    int seenRaw = 0
    int revisionCount = 0
    int lastRevisionIndex = na
    bool structuralRevisionNow = false
    CoreZone activeZone = na
    SwingPoint pendingBuy = na
    SwingPoint pendingSell = na
    SwingPoint oppositeExtreme = na
    CoreZone buyExitZone = na
    CoreZone sellExitZone = na
    int buyExitSerial = na
    int sellExitSerial = na
    bool newB1 = false
    bool newS1 = false
    bool newB2 = false
    bool newS2 = false
    bool newB3 = false
    bool newS3 = false
 
areaBetween(SwingPoint first, SwingPoint last) =>
    last.kind == 1 ? math.max(0.0, last.positive - first.positive) : math.max(0.0, last.negative - first.negative)
 
method resetBarEvents(StructureEngine e) =>
    e.structuralRevisionNow := false
    e.newB1 := false
    e.newS1 := false
    e.newB2 := false
    e.newS2 := false
    e.newB3 := false
    e.newS3 := false
    e
 
method areaRatio(StructureEngine e, int index) =>
    float ratio = na
    if index >= 3
        SwingPoint referenceStart = array.get(e.points, index - 3)
        SwingPoint referenceEnd = array.get(e.points, index - 2)
        SwingPoint latestStart = array.get(e.points, index - 1)
        SwingPoint latestEnd = array.get(e.points, index)
        float reference = areaBetween(referenceStart, referenceEnd)
        float latest = areaBetween(latestStart, latestEnd)
        if macdFast < macdSlow and referenceStart.anchorIndex >= macdSlow + macdSignal and reference > 0
            ratio := latest / reference
    ratio
 
// Pure assessment, also used by the mutable endpoint preview. The reference
// stroke spans (start, end] raw-bar histogram samples, clipped by direction.
method assess(StructureEngine e, int index) =>
    SwingPoint point = array.get(e.points, index)
    bool isBuy = point.kind == -1
    float ratio = e.areaRatio(index)
    bool first = false
    if index >= 3 and not na(ratio)
        SwingPoint previousSameSide = array.get(e.points, index - 2)
        bool newPriceExtreme = isBuy ? point.price < previousSameSide.price : point.price > previousSameSide.price
        first := newPriceExtreme and ratio < maximumAreaRatio
    SwingPoint pending = isBuy ? e.pendingBuy : e.pendingSell
    bool second = not na(pending) and point.serial > pending.serial and (isBuy ? point.price >= pending.price : point.price <= pending.price)
    CoreZone exitZone = isBuy ? e.buyExitZone : e.sellExitZone
    int exitSerial = isBuy ? e.buyExitSerial : e.sellExitSerial
    bool third = not na(exitZone) and point.serial > exitSerial and (isBuy ? point.price >= exitZone.upper : point.price <= exitZone.lower)
    [first, second, third, ratio]
 
signalNames(bool isBuy, bool first, bool second, bool third) =>
    string prefix = isBuy ? "B" : "S"
    string names = first ? prefix + "1" : ""
    if second
        names += (str.length(names) > 0 ? "+" : "") + prefix + "2"
    if third
        names += (str.length(names) > 0 ? "+" : "") + prefix + "3"
    names
 
issuedKey(string family, int anchorIndex) =>
    family + "|" + str.tostring(anchorIndex)
 
method previouslyIssued(StructureEngine e, string family, int anchorIndex) =>
    array.includes(e.issuedKeys, issuedKey(family, anchorIndex))
 
method rememberIssued(StructureEngine e, string family, int anchorIndex) =>
    string key = issuedKey(family, anchorIndex)
    if not array.includes(e.issuedKeys, key)
        array.push(e.issuedKeys, key)
        if array.size(e.issuedKeys) > 4096
            array.shift(e.issuedKeys)
    e
 
method analyzeSealed(StructureEngine e, int index, bool issueEvent = true) =>
    if index >= 1
        SwingPoint point = array.get(e.points, index)
        bool isBuy = point.kind == -1
        [first, second, third, ratio] = e.assess(index)
        string familyPrefix = isBuy ? "B" : "S"
        bool issueFirst = issueEvent and first and not e.previouslyIssued(familyPrefix + "1", point.anchorIndex)
        bool issueSecond = issueEvent and second and not e.previouslyIssued(familyPrefix + "2", point.anchorIndex)
        bool issueThird = issueEvent and third and not e.previouslyIssued(familyPrefix + "3", point.anchorIndex)
        float setupZoneBoundary = issueThird ? (isBuy ? e.buyExitZone.upper : e.sellExitZone.lower) : na
        // The first subsequent same-side endpoint consumes a B2/S2 attempt.
        // The first return after an exit consumes a B3/S3 attempt, including a
        // failed return. Follow-up variants require their own future rules.
        if isBuy
            if not na(e.pendingBuy) and point.serial > e.pendingBuy.serial
                e.pendingBuy := na
            if not na(e.buyExitZone) and point.serial > e.buyExitSerial
                e.buyExitZone := na
                e.buyExitSerial := na
            if first
                e.pendingBuy := point
            if issueEvent
                e.newB1 := issueFirst
            if issueEvent
                e.newB2 := issueSecond
            if issueEvent
                e.newB3 := issueThird
        else
            if not na(e.pendingSell) and point.serial > e.pendingSell.serial
                e.pendingSell := na
            if not na(e.sellExitZone) and point.serial > e.sellExitSerial
                e.sellExitZone := na
                e.sellExitSerial := na
            if first
                e.pendingSell := point
            if issueEvent
                e.newS1 := issueFirst
            if issueEvent
                e.newS2 := issueSecond
            if issueEvent
                e.newS3 := issueThird
        // Replayed state can qualify old setups; only a fresh normal seal may
        // issue an event, and each family/anchor pair is issued once.
        if issueFirst
            e.rememberIssued(familyPrefix + "1", point.anchorIndex)
        if issueSecond
            e.rememberIssued(familyPrefix + "2", point.anchorIndex)
        if issueThird
            e.rememberIssued(familyPrefix + "3", point.anchorIndex)
        string names = signalNames(isBuy, issueFirst, issueSecond, issueThird)
        if str.length(names) > 0
            array.push(e.events, StructuralEvent.new(names, isBuy ? 1 : -1, point.price,
                 point.anchorIndex, point.anchorTime, bar_index, time_close, issueFirst ? ratio : na, setupZoneBoundary))
            if array.size(e.events) > 300
                array.shift(e.events)
    e
 
method seedExit(StructureEngine e, CoreZone zone, SwingPoint point) =>
    if point.kind == 1 and point.price > zone.upper and not zone.buyExitSeen
        zone.buyExitSeen := true
        e.buyExitZone := zone
        e.buyExitSerial := point.serial
    if point.kind == -1 and point.price < zone.lower and not zone.sellExitSeen
        zone.sellExitSeen := true
        e.sellExitZone := zone
        e.sellExitSerial := point.serial
    e
 
method updateCenters(StructureEngine e, int index) =>
    if index >= 1
        SwingPoint point = array.get(e.points, index)
        SwingPoint previous = array.get(e.points, index - 1)
        float strokeLow = math.min(previous.price, point.price)
        float strokeHigh = math.max(previous.price, point.price)
        if not na(e.activeZone)
            CoreZone zone = e.activeZone
            e.seedExit(zone, point)
            bool overlaps = strokeHigh >= zone.lower and strokeLow <= zone.upper
            if overlaps
                zone.rightIndex := point.anchorIndex
                zone.envelopeLow := math.min(zone.envelopeLow, strokeLow)
                zone.envelopeHigh := math.max(zone.envelopeHigh, strokeHigh)
            else
                zone.active := false
                zone.rightIndex := previous.anchorIndex
                e.activeZone := na
        if na(e.activeZone) and index >= 3
            SwingPoint p0 = array.get(e.points, index - 3)
            SwingPoint p1 = array.get(e.points, index - 2)
            SwingPoint p2 = array.get(e.points, index - 1)
            float lower = math.max(math.min(p0.price, p1.price), math.max(math.min(p1.price, p2.price), math.min(p2.price, point.price)))
            float upper = math.min(math.max(p0.price, p1.price), math.min(math.max(p1.price, p2.price), math.max(p2.price, point.price)))
            if lower < upper
                e.nextZone += 1
                CoreZone zone = CoreZone.new(e.nextZone, p0.anchorIndex, point.anchorIndex,
                     lower, upper, math.min(math.min(p0.price, p1.price), math.min(p2.price, point.price)),
                     math.max(math.max(p0.price, p1.price), math.max(p2.price, point.price)), point.kind,
                     true, false, false, bar_index)
                array.push(e.zones, zone)
                if array.size(e.zones) > 80
                    array.shift(e.zones)
                e.activeZone := zone
                e.seedExit(zone, point)
    e
 
// A transparent second swing layer. It uses local extrema of three same-side
// sealed endpoints. Its latest endpoint can extend; full segment rules vary.
method updateCoarse(StructureEngine e, int index) =>
    if index >= 4
        SwingPoint before = array.get(e.points, index - 4)
        SwingPoint middle = array.get(e.points, index - 2)
        SwingPoint after = array.get(e.points, index)
        bool extremum = middle.kind == 1 ? middle.price > before.price and middle.price > after.price : middle.price < before.price and middle.price < after.price
        if extremum
            SwingPoint candidate = SwingPoint.new(middle.kind, middle.price, middle.anchorIndex, middle.anchorTime,
                 middle.positive, middle.negative, middle.mergedSequence, middle.serial, bar_index, time_close)
            int count = array.size(e.coarse)
            if count == 0
                array.push(e.coarse, candidate)
            else
                SwingPoint last = array.get(e.coarse, count - 1)
                if candidate.kind == last.kind
                    if candidate.kind == 1 ? candidate.price > last.price : candidate.price < last.price
                        array.set(e.coarse, count - 1, candidate)
                else if candidate.kind == 1 ? candidate.price > last.price : candidate.price < last.price
                    array.push(e.coarse, candidate)
                    if array.size(e.coarse) > 100
                        array.shift(e.coarse)
    e
 
// Reconstruct derived current structure after a tail repair. This routine
// leaves the actual-issued event ledger and event keys intact. Every assessment
// below is state replay, so it can never publish a historical alert.
method rebuildStructure(StructureEngine e) =>
    array.clear(e.zones)
    array.clear(e.coarse)
    e.activeZone := na
    e.pendingBuy := na
    e.pendingSell := na
    e.buyExitZone := na
    e.sellExitZone := na
    e.buyExitSerial := na
    e.sellExitSerial := na
    int count = array.size(e.points)
    if count >= 3
        for index = 1 to count - 2
            e.analyzeSealed(index, false)
            e.updateCenters(index)
            e.updateCoarse(index)
    if not na(e.activeZone)
        e.activeZone.rightIndex := bar_index
    e
 
// An unqualified opposite turn can exceed the developing leg's sealed start.
// Collapse that invalid tail causally, retaining a compatible earlier prefix.
// The guard concerns normalized-fractal extrema. Raw inclusion-filtered wicks
// retain the directional normalization semantics declared above.
method repairTail(StructureEngine e, SwingPoint candidate) =>
    bool working = true
    int removedCount = 0
    int changedFrom = candidate.anchorIndex
    bool localReset = false
    while working and array.size(e.points) >= 2
        int count = array.size(e.points)
        SwingPoint terminal = array.get(e.points, count - 1)
        SwingPoint starter = array.get(e.points, count - 2)
        bool crossesStarter = candidate.kind == starter.kind and (candidate.kind == 1 ? candidate.price > starter.price : candidate.price < starter.price)
        if not crossesStarter
            working := false
        else if count >= 3
            SwingPoint earlier = array.get(e.points, count - 3)
            bool terminalCrossesEarlier = terminal.kind == 1 ? terminal.price > earlier.price : terminal.price < earlier.price
            if terminalCrossesEarlier
                // Carry the stronger terminal back across an obsolete pair.
                array.pop(e.points)
                array.pop(e.points)
                array.pop(e.points)
                terminal.serial := earlier.serial
                terminal.sealed := false
                terminal.sealedIndex := na
                terminal.sealedTime := na
                array.push(e.points, terminal)
                removedCount += 2
                changedFrom := math.min(changedFrom, earlier.anchorIndex)
                if array.size(e.points) == 1
                    localReset := true
            else
                // The earlier start contains the whole opposing excursion.
                // Its following endpoint can extend to the new extreme.
                array.pop(e.points)
                candidate.serial := starter.serial
                candidate.sealed := false
                candidate.sealedIndex := na
                candidate.sealedTime := na
                array.set(e.points, count - 2, candidate)
                removedCount += 1
                changedFrom := math.min(changedFrom, earlier.anchorIndex)
                working := false
        else
            // A short overconstrained left edge starts a fresh local component.
            // Keeping its latest terminal avoids inventing a short valid stroke.
            array.shift(e.points)
            terminal.serial := starter.serial
            terminal.sealed := false
            terminal.sealedIndex := na
            terminal.sealedTime := na
            removedCount += 1
            changedFrom := math.min(changedFrom, starter.anchorIndex)
            localReset := true
            working := false
    if removedCount > 0
        SwingPoint terminal = array.get(e.points, array.size(e.points) - 1)
        e.oppositeExtreme := terminal.kind == candidate.kind ? na : candidate
        e.revisionCount += 1
        e.lastRevisionIndex := bar_index
        e.structuralRevisionNow := true
        array.push(e.revisions, StructuralRevision.new(bar_index, time_close,
             changedFrom, removedCount, localReset, terminal.anchorIndex))
        if array.size(e.revisions) > 128
            array.shift(e.revisions)
        e.rebuildStructure()
    e
 
method acceptFractal(StructureEngine e, SwingPoint candidate) =>
    int count = array.size(e.points)
    if count == 0
        e.nextSerial += 1
        candidate.serial := e.nextSerial
        array.push(e.points, candidate)
        e.oppositeExtreme := na
    else
        SwingPoint last = array.get(e.points, count - 1)
        if candidate.kind == last.kind
            bool moreExtreme = candidate.kind == 1 ? candidate.price > last.price : candidate.price < last.price
            if moreExtreme
                candidate.serial := last.serial
                array.set(e.points, count - 1, candidate)
                // Earlier counter-swings precede this new terminal start.
                e.oppositeExtreme := na
        else
            // Keep the most extreme opposing fractal even when its spacing is
            // insufficient. A later higher low/lower high cannot replace that
            // candidate merely by satisfying the distance rule. Equal extrema
            // select the latest anchor and may qualify after sufficient spacing.
            bool opposingExtreme = na(e.oppositeExtreme) or (candidate.kind == 1 ? candidate.price >= e.oppositeExtreme.price : candidate.price <= e.oppositeExtreme.price)
            if opposingExtreme
                e.oppositeExtreme := candidate
            bool separated = candidate.mergedSequence - last.mergedSequence >= minimumSeparation
            bool properOrder = candidate.kind == 1 ? candidate.price > last.price : candidate.price < last.price
            if opposingExtreme and separated and properOrder
                last.sealed := true
                last.sealedIndex := bar_index
                last.sealedTime := time_close
                e.nextSerial += 1
                candidate.serial := e.nextSerial
                array.push(e.points, candidate)
                e.oppositeExtreme := na
                if array.size(e.points) > 360
                    array.shift(e.points)
                int sealedIndex = array.size(e.points) - 2
                e.analyzeSealed(sealedIndex)
                e.updateCenters(sealedIndex)
                e.updateCoarse(sealedIndex)
            else if count >= 2
                SwingPoint starter = array.get(e.points, count - 2)
                bool crossesStarter = candidate.kind == starter.kind and (candidate.kind == 1 ? candidate.price > starter.price : candidate.price < starter.price)
                if crossesStarter
                    e.repairTail(candidate)
    e
 
method ingest(StructureEngine e, float h, float l, float o, float c, float positive, float negative) =>
    e.seenRaw += 1
    int count = array.size(e.bars)
    bool appended = false
    if count == 0
        e.mergeDirection := c >= o ? 1 : -1
        e.mergedSequence += 1
        array.push(e.bars, MergedBar.new(h, l, bar_index, bar_index, time, time,
             positive, negative, positive, negative, e.mergedSequence))
        appended := true
    else
        MergedBar last = array.get(e.bars, count - 1)
        bool included = (h <= last.h and l >= last.l) or (h >= last.h and l <= last.l)
        if included
            bool updateHigh = e.mergeDirection == 1 ? h >= last.h : h <= last.h
            bool updateLow = e.mergeDirection == 1 ? l >= last.l : l <= last.l
            if updateHigh
                last.h := h
                last.highIndex := bar_index
                last.highTime := time
                last.highPositive := positive
                last.highNegative := negative
            if updateLow
                last.l := l
                last.lowIndex := bar_index
                last.lowTime := time
                last.lowPositive := positive
                last.lowNegative := negative
        else
            e.mergeDirection := h > last.h ? 1 : -1
            e.mergedSequence += 1
            array.push(e.bars, MergedBar.new(h, l, bar_index, bar_index, time, time,
                 positive, negative, positive, negative, e.mergedSequence))
            if array.size(e.bars) > 8
                array.shift(e.bars)
            appended := true
    int mergedCount = array.size(e.bars)
    if appended and mergedCount >= 4
        // Arrival of a further noncontained candle seals the right neighbor.
        MergedBar left = array.get(e.bars, mergedCount - 4)
        MergedBar middle = array.get(e.bars, mergedCount - 3)
        MergedBar right = array.get(e.bars, mergedCount - 2)
        bool top = middle.h > left.h and middle.h > right.h and middle.l > left.l and middle.l > right.l
        bool bottom = middle.h < left.h and middle.h < right.h and middle.l < left.l and middle.l < right.l
        if top or bottom
            SwingPoint candidate = SwingPoint.new(top ? 1 : -1, top ? middle.h : middle.l,
                 top ? middle.highIndex : middle.lowIndex, top ? middle.highTime : middle.lowTime,
                 top ? middle.highPositive : middle.lowPositive, top ? middle.highNegative : middle.lowNegative,
                 middle.sequence, 0, bar_index, time_close)
            e.acceptFractal(candidate)
    if not na(e.activeZone)
        e.activeZone.rightIndex := bar_index
    e
 
// Integrate after StructuralEvent and before main calculations. Risk records
// track observations on their actual detection/close bar. Levels are frozen.
type RiskSetup
    int side
    float level = na
    string names = ""
    int issuedIndex = na
    int issuedTime = na
    bool usesZone = false
    bool active = false
 
type RiskObservation
    int side
    string outcome
    float level
    string names
    int issuedIndex
    int observedIndex
    int observedTime
 
type RiskBook
    RiskSetup buy
    RiskSetup sell
    array<RiskObservation> records
    int lastProcessedIndex = na
    bool newBuyBreach = false
    bool newSellBreach = false
    bool newBuyAlreadyBroken = false
    bool newSellAlreadyBroken = false
    int buyFailures = 0
    int sellFailures = 0
 
method observeRisk(RiskBook b, RiskSetup setup, string outcome, int at, int observedTime) =>
    array.push(b.records, RiskObservation.new(setup.side, outcome, setup.level, setup.names,
         setup.issuedIndex, at, observedTime))
    if array.size(b.records) > 300
        array.shift(b.records)
    b
 
method failRisk(RiskBook b, RiskSetup setup, bool alreadyBroken, int at, int observedTime) =>
    setup.active := false
    b.observeRisk(setup, alreadyBroken ? "Already broken at detection" : "Closed-bar breach", at, observedTime)
    if setup.side == 1
        b.newBuyBreach := b.newBuyBreach or not alreadyBroken
        b.newBuyAlreadyBroken := b.newBuyAlreadyBroken or alreadyBroken
        b.buyFailures += 1
    else
        b.newSellBreach := b.newSellBreach or not alreadyBroken
        b.newSellAlreadyBroken := b.newSellAlreadyBroken or alreadyBroken
        b.sellFailures += 1
    b
 
method checkRisk(RiskBook b, RiskSetup setup, float settledClose, int at, int observedTime) =>
    if setup.active and not na(setup.level)
        bool breached = setup.side == 1 ? settledClose < setup.level : settledClose > setup.level
        if breached
            b.failRisk(setup, false, at, observedTime)
    b
 
method activateRisk(RiskBook b, StructuralEvent event, float settledClose, int at, int observedTime) =>
    RiskSetup setup = event.side == 1 ? b.buy : b.sell
    if setup.active
        b.observeRisk(setup, "Replaced by newer same-side setup", at, observedTime)
    bool useZone = riskBoundary == "B3/S3 zone boundary" and not na(event.zoneBoundary)
    setup.level := useZone ? event.zoneBoundary : event.price
    setup.names := event.names
    setup.issuedIndex := event.knownIndex
    setup.issuedTime := event.knownTime
    setup.usesZone := useZone
    setup.active := not na(setup.level)
    if setup.active
        bool alreadyBroken = setup.side == 1 ? settledClose < setup.level : settledClose > setup.level
        if alreadyBroken
            b.failRisk(setup, true, at, observedTime)
    b
 
method updateRisk(RiskBook b, array<StructuralEvent> signals, float settledClose, int at, int observedTime, bool confirmed) =>
    b.newBuyBreach := false
    b.newSellBreach := false
    b.newBuyAlreadyBroken := false
    b.newSellAlreadyBroken := false
    if confirmed and (na(b.lastProcessedIndex) or at > b.lastProcessedIndex)
        b.lastProcessedIndex := at
        // Settle the previous setups before replacing them on this close.
        b.checkRisk(b.buy, settledClose, at, observedTime)
        b.checkRisk(b.sell, settledClose, at, observedTime)
        int count = array.size(signals)
        if count > 0
            for i = 0 to count - 1
                StructuralEvent event = array.get(signals, i)
                if event.knownIndex == at
                    b.activateRisk(event, settledClose, at, observedTime)
    b
 
newContextEngine() =>
    StructureEngine.new(array.new<MergedBar>(), array.new<SwingPoint>(), array.new<SwingPoint>(), array.new<CoreZone>(), array.new<StructuralEvent>(), array.new<string>(), array.new<StructuralRevision>())
 
// Snapshot primitives keep arrays inside their source context.
structureContext(StructureEngine e) =>
    int direction = 0
    int divergence = 0
    int latestSwing = 0
    int count = array.size(e.points)
    if count >= 3
        SwingPoint lastCompleted = array.get(e.points, count - 2)
        latestSwing := lastCompleted.kind
    if count >= 5
        SwingPoint a = array.get(e.points, count - 5)
        SwingPoint b = array.get(e.points, count - 4)
        SwingPoint c = array.get(e.points, count - 3)
        SwingPoint d = array.get(e.points, count - 2)
        bool higherPair = c.price > a.price and d.price > b.price
        bool lowerPair = c.price < a.price and d.price < b.price
        direction := higherPair ? 1 : lowerPair ? -1 : 0
    int events = array.size(e.events)
    if events > 0
        for i = events - 1 to 0
            StructuralEvent event = array.get(e.events, i)
            if bar_index - event.knownIndex > weeklyDivergenceAge
                break
            if str.contains(event.names, "B1") or str.contains(event.names, "S1")
                divergence := event.side
                break
    float lower = na(e.activeZone) ? na : e.activeZone.lower
    float upper = na(e.activeZone) ? na : e.activeZone.upper
    [direction, latestSwing, lower, upper, divergence]
 
closedWeeklySnapshot() =>
    [m, s, h] = ta.macd(close, macdFast, macdSlow, macdSignal)
    float positive = ta.cum(math.max(nz(h), 0.0))
    float negative = ta.cum(math.max(-nz(h), 0.0))
    var StructureEngine source = newContextEngine()
    source.resetBarEvents()
    // Rollback handles the developing source bar; only the prior closed
    // snapshot is exported. barstate.isconfirmed is kept outside security().
    source.ingest(high, low, open, close, positive, negative)
    [direction, latestSwing, lower, upper, divergence] = structureContext(source)
    [direction[1], latestSwing[1], lower[1], upper[1], divergence[1], close[1], time_close[1]]
 
contextTime(int stamp) =>
    na(stamp) ? "unavailable" : str.format_time(stamp, "yyyy-MM-dd HH:mm", "UTC") + " UTC"
 
weeklyContextText(int direction, int latestSwing, float lower, float upper, int divergence, float settledPrice, int stamp) =>
    string description = na(stamp) ? "Weekly context unavailable" : "Weekly structure: " + (direction == 1 ? "higher high and higher low" : direction == -1 ? "lower high and lower low" : "mixed or warming up")
    if not na(stamp)
        description += "\nLatest completed Weekly swing: " + (latestSwing == 1 ? "rising" : latestSwing == -1 ? "falling" : "warming up")
        description += "\nWeekly source close: " + contextTime(stamp)
        description += "\nRecent issued Weekly divergence: " + (divergence == 1 ? "buy-side" : divergence == -1 ? "sell-side" : "none within selected age")
        if not na(lower) and not na(upper)
            description += "\nWeekly zone: " + str.tostring(lower, format.mintick) + " to " + str.tostring(upper, format.mintick)
            description += "\nCompleted Weekly close: " + (settledPrice > upper ? "above zone" : settledPrice < lower ? "below zone" : "inside zone")
    description
 
contextTag(int side, int weeklyDirection, int weeklyTime, int marketState, float relativeChange) =>
    string tags = ""
    if useWeekly and not na(weeklyTime) and weeklyDirection != 0
        tags := weeklyDirection == side ? "W+" : "W-"
    if useMarket and marketState == -1
        tags += (str.length(tags) > 0 ? " " : "") + "M!"
    if useRS and not na(relativeChange)
        tags += (str.length(tags) > 0 ? " " : "") + (relativeChange > 0 ? "R+" : relativeChange < 0 ? "R-" : "R=")
    tags
 
type EarlyObservation
    int side
    int terminalSerial
    int terminalAnchor
    float extreme
    int extremeIndex
    int extremeTime
    int detectionIndex
    int detectionTime
    float atrAtDetection
    string contextText
    string state = "Developing"
    int resolutionIndex = na
    int resolutionTime = na
 
type EarlyBook
    array<EarlyObservation> records
    array<int> consumed
    EarlyObservation active = na
    int trackedSerial = na
    int trackedAnchor = na
    float trackedPrice = na
    float extreme = na
    int extremeIndex = na
    int extremeTime = na
    bool seeded = false
    bool newBuy = false
    bool newSell = false
    int lastProcessed = na
 
method sampleEarly(EarlyBook b, int kind, float h, float l, int sampleIndex, int sampleTime) =>
    float candidate = kind == -1 ? h : l
    if not na(candidate) and (na(b.extreme) or (kind == -1 ? candidate >= b.extreme : candidate <= b.extreme))
        b.extreme := candidate
        b.extremeIndex := sampleIndex
        b.extremeTime := sampleTime
    b
 
method resolveEarly(EarlyBook b, SwingPoint terminal, float settledClose) =>
    if not na(b.active)
        EarlyObservation observation = b.active
        string outcome = ""
        if terminal.serial != observation.terminalSerial
            outcome := "Terminal changed"
        else if observation.side == 1 ? settledClose < observation.extreme : settledClose > observation.extreme
            outcome := "Extreme broken"
        else if bar_index - observation.detectionIndex >= earlyExpiry
            outcome := "Observation window expired"
        if str.length(outcome) > 0
            observation.state := outcome
            observation.resolutionIndex := bar_index
            observation.resolutionTime := time_close
            b.active := na
    b
 
method updateEarly(EarlyBook b, StructureEngine e, float atrValue, float hist, float priorHist, string contextSnapshot) =>
    b.newBuy := false
    b.newSell := false
    if enableEarly and chart.is_standard and barstate.isconfirmed and (na(b.lastProcessed) or bar_index > b.lastProcessed)
        b.lastProcessed := bar_index
        int count = array.size(e.points)
        if count > 0
            SwingPoint terminal = array.last(e.points)
            b.resolveEarly(terminal, close)
            bool reset = na(b.trackedSerial) or terminal.serial != b.trackedSerial or terminal.anchorIndex != b.trackedAnchor or terminal.price != b.trackedPrice
            if reset
                b.trackedSerial := terminal.serial
                b.trackedAnchor := terminal.anchorIndex
                b.trackedPrice := terminal.price
                b.extreme := na
                b.extremeIndex := na
                b.extremeTime := na
                int age = bar_index - terminal.anchorIndex
                b.seeded := age >= 0 and age <= 499
                if b.seeded and age >= 1
                    for ago = age - 1 to 0
                        b.sampleEarly(terminal.kind, high[ago], low[ago], bar_index - ago, time[ago])
            else if b.seeded and bar_index > terminal.anchorIndex
                b.sampleEarly(terminal.kind, high, low, bar_index, time)
            int side = terminal.kind == -1 ? -1 : 1
            int dedupKey = terminal.serial * 2 + (side == 1 ? 1 : 0)
            bool ready = b.seeded and not na(b.extreme) and not na(b.extremeIndex) and b.extremeIndex >= terminal.anchorIndex + 2 and not na(atrValue) and atrValue > 0 and not na(hist) and not na(priorHist) and not na(close[1]) and macdFast < macdSlow and bar_index >= macdSlow + macdSignal
            if ready and not array.includes(b.consumed, dedupKey)
                bool excursion = terminal.kind == -1 ? b.extreme - terminal.price >= earlyLegAtr * atrValue : terminal.price - b.extreme >= earlyLegAtr * atrValue
                bool reversal = terminal.kind == -1 ? b.extreme - close >= earlyReversalAtr * atrValue and close < close[1] and hist < priorHist : close - b.extreme >= earlyReversalAtr * atrValue and close > close[1] and hist > priorHist
                if excursion and reversal
                    EarlyObservation observation = EarlyObservation.new(side, terminal.serial, terminal.anchorIndex,
                         b.extreme, b.extremeIndex, b.extremeTime, bar_index, time_close, atrValue, contextSnapshot)
                    array.push(b.records, observation)
                    array.push(b.consumed, dedupKey)
                    if array.size(b.records) > 120
                        array.shift(b.records)
                    if array.size(b.consumed) > 720
                        array.shift(b.consumed)
                    b.active := observation
                    b.newBuy := side == 1
                    b.newSell := side == -1
    b
 
 
[macdLine, signalLine, histogram] = ta.macd(close, macdFast, macdSlow, macdSignal)
float positiveArea = ta.cum(math.max(nz(histogram), 0.0))
float negativeArea = ta.cum(math.max(-nz(histogram), 0.0))
var StructureEngine engine = StructureEngine.new()
if barstate.isfirst
    engine.bars := array.new<MergedBar>()
    engine.points := array.new<SwingPoint>()
    engine.coarse := array.new<SwingPoint>()
    engine.zones := array.new<CoreZone>()
    engine.events := array.new<StructuralEvent>()
    engine.issuedKeys := array.new<string>()
    engine.revisions := array.new<StructuralRevision>()
 
engine.resetBarEvents()
if chart.is_standard and barstate.isconfirmed and not na(high) and not na(low)
    engine.ingest(high, low, open, close, positiveArea, negativeArea)
 
bool buyEvent = barstate.isconfirmed and (engine.newB1 or engine.newB2 or engine.newB3)
bool sellEvent = barstate.isconfirmed and (engine.newS1 or engine.newS2 or engine.newS3)
float chartSeconds = timeframe.in_seconds()
float weekSeconds = timeframe.in_seconds("1W")
float daySeconds = timeframe.in_seconds("1D")
int weeklyDirection = 0
int weeklyLastSwing = 0
int weeklyDivergence = 0
int weeklyTime = na
float weeklyLower = na
float weeklyUpper = na
float weeklyClose = na
var int lastChartClose = na
if chart.is_standard and barstate.isconfirmed
    lastChartClose := time_close
if useWeekly and chart.is_standard and chartSeconds < weekSeconds
    [wd, ws, wl, wu, wv, wc, wt] = request.security(ticker.standard(syminfo.tickerid), "1W", closedWeeklySnapshot(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on, currency = currency.NONE)
    if not na(wt) and wt <= time_close
        weeklyDirection := wd
        weeklyLastSwing := ws
        weeklyLower := wl
        weeklyUpper := wu
        weeklyDivergence := wv
        weeklyClose := wc
        weeklyTime := wt
else if useWeekly and chart.is_standard and timeframe.isweekly and timeframe.multiplier == 1
    [wd, ws, wl, wu, wv] = structureContext(engine)
    weeklyDirection := wd
    weeklyLastSwing := ws
    weeklyLower := wl
    weeklyUpper := wu
    weeklyDivergence := wv
    weeklyClose := barstate.isconfirmed ? close : close[1]
    weeklyTime := lastChartClose
 
// The market condition always uses Daily samples. Coarser chart bars inspect
// available Daily intrabars and enforce the chart-close timestamp cutoff.
float marketClose = na
float marketAverage = na
int marketTime = na
if useMarket and chart.is_standard and chartSeconds > daySeconds
    [dc, de, dt] = request.security_lower_tf(marketSymbol, "1D", [close, ta.ema(close, marketEmaLength), time_close], ignore_invalid_symbol = true, ignore_invalid_timeframe = true)
    int samples = array.size(dt)
    if samples > 0
        for i = samples - 1 to 0
            int sourceTime = array.get(dt, i)
            if sourceTime <= time_close and (not barstate.isrealtime or sourceTime <= timenow)
                marketClose := array.get(dc, i)
                marketAverage := array.get(de, i)
                marketTime := sourceTime
                break
else if useMarket and chart.is_standard and chartSeconds == daySeconds
    [dc, de, dt, pc, pe, pt] = request.security(marketSymbol, "1D", [close, ta.ema(close, marketEmaLength), time_close, close[1], ta.ema(close, marketEmaLength)[1], time_close[1]], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
    bool currentAvailable = not na(dt) and dt <= time_close and (not barstate.isrealtime or dt <= timenow)
    marketClose := currentAvailable ? dc : pc
    marketAverage := currentAvailable ? de : pe
    marketTime := currentAvailable ? dt : pt
else if useMarket and chart.is_standard
    [dc, de, dt] = request.security(marketSymbol, "1D", [close[1], ta.ema(close, marketEmaLength)[1], time_close[1]], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true)
    marketClose := dc
    marketAverage := de
    marketTime := dt
bool marketAvailable = useMarket and not na(marketTime) and marketTime <= time_close and time_close - marketTime <= 7 * 86400000 and not na(marketClose) and not na(marketAverage)
int marketState = marketAvailable ? (marketClose < marketAverage ? -1 : 1) : 0
 
string rsBenchmark = switch rsBenchmarkChoice
    "QQQ" => "NASDAQ:QQQ"
    "SOXX" => "NASDAQ:SOXX"
    "SPY" => "AMEX:SPY"
    => rsCustomBenchmark
string rsRequestedCurrency = rsCurrencyBasis == "USD" ? currency.USD : currency.NONE
float rsRatio = na
int rsSourceTime = na
int rsBenchmarkTime = na
if useRS and chart.is_standard
    [sc, st] = request.security(ticker.standard(syminfo.tickerid), timeframe.period, [close, time_close], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, currency = rsRequestedCurrency, ignore_invalid_symbol = true)
    [bc, bt, bp, bpt] = request.security(rsBenchmark, timeframe.period, [close, time_close, close[1], time_close[1]], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, currency = rsRequestedCurrency, ignore_invalid_symbol = true)
    bool benchmarkCurrent = not na(bt) and bt <= time_close and (not barstate.isrealtime or bt <= timenow)
    float benchmarkClose = benchmarkCurrent ? bc : bp
    int benchmarkTime = benchmarkCurrent ? bt : bpt
    bool sourceReady = not na(st) and st <= time_close and not na(benchmarkTime) and benchmarkTime <= time_close and time_close - benchmarkTime <= 7 * 86400000
    if sourceReady and not na(sc) and not na(benchmarkClose) and sc > 0 and benchmarkClose > 0
        rsRatio := sc / benchmarkClose
        rsSourceTime := st
        rsBenchmarkTime := benchmarkTime
float rsValidCount = math.sum(not na(rsRatio) ? 1.0 : 0.0, rsLookback + 1)
float rsRelativeChange = not na(rsRatio) and not na(rsRatio[rsLookback]) and rsRatio[rsLookback] > 0 and rsValidCount == rsLookback + 1 ? 100.0 * (rsRatio / rsRatio[rsLookback] - 1.0) : na
 
string currentContext = useWeekly ? weeklyContextText(weeklyDirection, weeklyLastSwing, weeklyLower, weeklyUpper, weeklyDivergence, weeklyClose, weeklyTime) : "Weekly context disabled"
currentContext += "\nMarket: " + (not useMarket ? "disabled" : marketState == 0 ? "unavailable" : marketState == -1 ? "CAUTION - below Daily EMA" : "at/above Daily EMA")
if marketAvailable
    currentContext += "\n" + marketSymbol + " Daily EMA " + str.tostring(marketEmaLength) + "; source close " + contextTime(marketTime)
currentContext += "\nRS: " + (not useRS ? "disabled" : na(rsRelativeChange) ? "unavailable / warming up" : ((rsRelativeChange > 0 ? "+" : "") + str.tostring(rsRelativeChange, "0.00")) + "% over " + str.tostring(rsLookback) + " chart bars versus " + rsBenchmark)
if not na(rsRelativeChange)
    currentContext += "\nRS basis: " + rsCurrencyBasis + "; stock close " + contextTime(rsSourceTime) + "; benchmark close " + contextTime(rsBenchmarkTime)
currentContext += "\nContext captured at signal detection. Structural signals remain enabled in all market conditions."
if barstate.isconfirmed and array.size(engine.events) > 0
    StructuralEvent latestEvent = array.last(engine.events)
    if latestEvent.knownIndex == bar_index
        latestEvent.contextText := currentContext
        latestEvent.contextTags := contextTag(latestEvent.side, weeklyDirection, weeklyTime, marketState, rsRelativeChange)
 
bool weeklyAlignedBuy = buyEvent and not na(weeklyTime) and weeklyDirection == 1
bool weeklyAlignedSell = sellEvent and not na(weeklyTime) and weeklyDirection == -1
plotshape(showAlignedMarks and weeklyAlignedBuy, "Weekly-aligned buy event", shape.circle, location.belowbar, buyColor, size = size.tiny, display = display.pane)
plotshape(showAlignedMarks and weeklyAlignedSell, "Weekly-aligned sell event", shape.circle, location.abovebar, sellColor, size = size.tiny, display = display.pane)
plot(showWeeklyLevels ? weeklyLower : na, "Confirmed Weekly zone lower", color.new(coarseUpColor, 10), linewidth = levelWidth, style = plot.style_linebr, display = display.pane)
plot(showWeeklyLevels ? weeklyUpper : na, "Confirmed Weekly zone upper", color.new(coarseDownColor, 10), linewidth = levelWidth, style = plot.style_linebr, display = display.pane)
plot(not na(weeklyTime) ? weeklyDirection : na, "Weekly higher-high/higher-low trend", display = display.data_window)
plot(not na(weeklyTime) ? weeklyDivergence : na, "Weekly recent momentum side", display = display.data_window)
plot(marketAvailable ? marketState : na, "Market Daily EMA state", display = display.data_window)
plot(rsRelativeChange, "Relative return versus benchmark %", display = display.data_window)
alertcondition(weeklyAlignedBuy, "Weekly-aligned buy structure", "FSM: {{ticker}} closed-bar buy structure agrees with the confirmed Weekly structural trend.")
alertcondition(weeklyAlignedSell, "Weekly-aligned sell structure", "FSM: {{ticker}} closed-bar sell structure agrees with the confirmed Weekly structural trend.")
alertcondition(buyEvent and marketState == -1, "Buy structure with market caution", "FSM: {{ticker}} closed-bar buy structure; market benchmark is below its Daily EMA.")
 
bool weeklyMomentumBuy = chartSeconds < weekSeconds and barstate.isconfirmed and engine.newB1 and not na(weeklyTime) and weeklyDivergence == 1
bool weeklyMomentumSell = chartSeconds < weekSeconds and barstate.isconfirmed and engine.newS1 and not na(weeklyTime) and weeklyDivergence == -1
alertcondition(weeklyMomentumBuy, "Chart and Weekly buy momentum agreement", "FSM: {{ticker}} closed-bar B1 agrees with a recent issued Weekly B1 inside the selected Weekly age window.")
alertcondition(weeklyMomentumSell, "Chart and Weekly sell momentum agreement", "FSM: {{ticker}} closed-bar S1 agrees with a recent issued Weekly S1 inside the selected Weekly age window.")
 
// Add after engine.ingest() and the buyEvent / sellEvent definitions.
var RiskBook riskBook = RiskBook.new(RiskSetup.new(1), RiskSetup.new(-1), array.new<RiskObservation>())
riskBook.updateRisk(engine.events, close, bar_index, time_close, chart.is_standard and barstate.isconfirmed)
bool buyRiskInvalid = barstate.isconfirmed and (riskBook.newBuyBreach or riskBook.newBuyAlreadyBroken)
bool sellRiskInvalid = barstate.isconfirmed and (riskBook.newSellBreach or riskBook.newSellAlreadyBroken)
plotshape(showBreakMarks and buyRiskInvalid, "Buy setup invalidated", shape.xcross, location.belowbar, buyColor, size = size.tiny, display = display.pane)
plotshape(showBreakMarks and sellRiskInvalid, "Sell setup invalidated", shape.xcross, location.abovebar, sellColor, size = size.tiny, display = display.pane)
plot(riskBook.buy.active ? riskBook.buy.level : na, "Active buy setup boundary", display = display.data_window)
plot(riskBook.sell.active ? riskBook.sell.level : na, "Active sell setup boundary", display = display.data_window)
plot(barstate.isconfirmed and riskBook.newBuyBreach ? 1 : 0, "Buy setup closed-bar breach", display = display.data_window)
plot(barstate.isconfirmed and riskBook.newSellBreach ? 1 : 0, "Sell setup closed-bar breach", display = display.data_window)
plot(barstate.isconfirmed and riskBook.newBuyAlreadyBroken ? 1 : 0, "Buy setup already broken at detection", display = display.data_window)
plot(barstate.isconfirmed and riskBook.newSellAlreadyBroken ? 1 : 0, "Sell setup already broken at detection", display = display.data_window)
alertcondition(buyRiskInvalid, "Buy setup invalidated", "FSM: {{ticker}} buy-side setup invalidated at this closed {{interval}} bar. The Data Window distinguishes an existing setup breach from a setup already broken at first detection.")
alertcondition(sellRiskInvalid, "Sell setup invalidated", "FSM: {{ticker}} sell-side setup invalidated at this closed {{interval}} bar. The Data Window distinguishes an existing setup breach from a setup already broken at first detection.")
alertcondition(barstate.isconfirmed and (riskBook.newBuyAlreadyBroken or riskBook.newSellAlreadyBroken), "Setup already broken at detection", "FSM: {{ticker}} newly detected structural setup is already beyond its frozen invalidation boundary on this closed {{interval}} bar.")
 
float earlyATR = ta.atr(earlyAtrLength)
var EarlyBook earlyBook = EarlyBook.new(array.new<EarlyObservation>(), array.new<int>())
earlyBook.updateEarly(engine, earlyATR, histogram, histogram[1], currentContext)
plot(barstate.isconfirmed and earlyBook.newBuy ? 1 : 0, "Early developing buy warning", display = display.data_window)
plot(barstate.isconfirmed and earlyBook.newSell ? 1 : 0, "Early developing sell warning", display = display.data_window)
alertcondition(enableEarlyAlerts and barstate.isconfirmed and earlyBook.newBuy, "Early developing buy warning", "FSM: {{ticker}} EW B? closed-bar reversal warning. The opposite structural endpoint has yet to be accepted; the warning can fail.")
alertcondition(enableEarlyAlerts and barstate.isconfirmed and earlyBook.newSell, "Early developing sell warning", "FSM: {{ticker}} EW S? closed-bar reversal warning. The opposite structural endpoint has yet to be accepted; the warning can fail.")
 
bool availabilityMarks = showAvailabilityMarks or labelPlacement == "Structure anchor (historical)"
plotshape(availabilityMarks and buyEvent, "Buy first available", shape.triangleup, location.belowbar, buyColor, size = size.tiny, display = display.pane)
plotshape(availabilityMarks and sellEvent, "Sell first available", shape.triangledown, location.abovebar, sellColor, size = size.tiny, display = display.pane)
plot(buyEvent ? 1 : 0, "Buy event available on this bar", display = display.data_window)
plot(sellEvent ? 1 : 0, "Sell event available on this bar", display = display.data_window)
plot(barstate.isconfirmed and engine.structuralRevisionNow ? 1 : 0, "Structure revised on this bar", display = display.data_window)
plot(engine.revisionCount, "Structural revision count", display = display.data_window)
alertcondition(barstate.isconfirmed and engine.structuralRevisionNow, "Structural tail revised", "FSM: {{ticker}} structural geometry revised on this closed bar. Issued-event timestamps are preserved.")
 
alertcondition(buyEvent, "Sealed buy-side structural event", "FSM: {{ticker}} buy-side structure became available on this closed {{interval}} bar.")
alertcondition(sellEvent, "Sealed sell-side structural event", "FSM: {{ticker}} sell-side structure became available on this closed {{interval}} bar.")
alertcondition(barstate.isconfirmed and engine.newB1, "B1 - own swing area divergence", "FSM: {{ticker}} B1 became available now; own MACD area comparison.")
alertcondition(barstate.isconfirmed and engine.newS1, "S1 - own swing area divergence", "FSM: {{ticker}} S1 became available now; own MACD area comparison.")
alertcondition(barstate.isconfirmed and engine.newB2, "B2 - first higher/equal low", "FSM: {{ticker}} B2 became available on this closed bar.")
alertcondition(barstate.isconfirmed and engine.newS2, "S2 - first lower/equal high", "FSM: {{ticker}} S2 became available on this closed bar.")
alertcondition(barstate.isconfirmed and engine.newB3, "B3 - first upper-core retest", "FSM: {{ticker}} B3 became available on this closed bar.")
alertcondition(barstate.isconfirmed and engine.newS3, "S3 - first lower-core retest", "FSM: {{ticker}} S3 became available on this closed bar.")
 
var array<line> renderedLines = array.new<line>()
var array<box> renderedBoxes = array.new<box>()
var array<label> renderedLabels = array.new<label>()
 
// Rendering is bounded and runs on the last bar. Event flags above are emitted
// by the chronological engine on every closed bar, independently of rendering.
if barstate.islast
    while array.size(renderedLines) > 0
        line.delete(array.pop(renderedLines))
    while array.size(renderedBoxes) > 0
        box.delete(array.pop(renderedBoxes))
    while array.size(renderedLabels) > 0
        label.delete(array.pop(renderedLabels))
    int leftLimit = math.max(0, bar_index - displayHistory + 1)
    int pointCount = array.size(engine.points)
    if showStrokes and pointCount >= 2
        int firstStroke = math.max(1, pointCount - drawStrokeCount)
        for i = firstStroke to pointCount - 1
            SwingPoint first = array.get(engine.points, i - 1)
            SwingPoint last = array.get(engine.points, i)
            if first.anchorIndex >= leftLimit
                color strokeColor = last.kind == 1 ? buyColor : sellColor
                array.push(renderedLines, line.new(first.anchorIndex, first.price, last.anchorIndex, last.price,
                     xloc = xloc.bar_index, color = color.new(strokeColor, last.sealed ? 0 : 15),
                     style = last.sealed ? line.style_solid : line.style_dashed, width = strokeWidth))
    int coarseCount = array.size(engine.coarse)
    if showCoarse and coarseCount >= 2
        for i = 1 to coarseCount - 1
            SwingPoint first = array.get(engine.coarse, i - 1)
            SwingPoint last = array.get(engine.coarse, i)
            if first.anchorIndex >= leftLimit
                array.push(renderedLines, line.new(first.anchorIndex, first.price, last.anchorIndex, last.price,
                     xloc = xloc.bar_index, color = last.kind == 1 ? coarseUpColor : coarseDownColor, width = coarseWidth))
    int zoneCount = array.size(engine.zones)
    if showCenters and zoneCount > 0
        int firstZone = math.max(0, zoneCount - drawZoneCount)
        for i = firstZone to zoneCount - 1
            CoreZone zone = array.get(engine.zones, i)
            if zone.rightIndex >= leftLimit
                color zoneColor = zone.direction == 1 ? buyColor : sellColor
                int left = math.max(leftLimit, zone.leftIndex)
                array.push(renderedBoxes, box.new(left, zone.upper, zone.rightIndex, zone.lower,
                     xloc = xloc.bar_index, border_color = color.new(zoneColor, 20),
                     bgcolor = color.new(zoneColor, zoneTransparency), border_width = 1))
                if showEnvelope
                    array.push(renderedBoxes, box.new(left, zone.envelopeHigh, zone.rightIndex, zone.envelopeLow,
                         xloc = xloc.bar_index, border_color = color.new(zoneColor, 75), border_style = line.style_dotted,
                         bgcolor = color.new(zoneColor, 98)))
    if pointCount > 0
        SwingPoint latest = array.get(engine.points, pointCount - 1)
        if showLivePath and latest.anchorIndex >= leftLimit and latest.anchorIndex < bar_index
            array.push(renderedLines, line.new(latest.anchorIndex, latest.price, bar_index, close,
                 xloc = xloc.bar_index, color = color.new(chart.fg_color, 20), style = line.style_dotted, width = developingWidth))
        if showCandidates and pointCount >= 2
            [first, second, third, ratio] = engine.assess(pointCount - 1)
            string names = signalNames(latest.kind == -1, first, second, third)
            if str.length(names) > 0
                string previewText = names + "?"
                if showAreaRatio and first and not na(ratio)
                    previewText += "\nArea " + str.tostring(ratio, "0.00")
                array.push(renderedLabels, label.new(bar_index, latest.price, previewText,
                     xloc = xloc.bar_index, style = latest.kind == -1 ? label.style_label_up : label.style_label_down,
                     color = color.new(latest.kind == -1 ? buyColor : sellColor, 65), textcolor = chart.fg_color,
                     size = size.tiny, tooltip = "Provisional endpoint. Its fractal is known, and its stroke can extend. A following accepted opposite endpoint seals it. This preview can change and has no alert."))
    if showVirtual and pointCount >= 4
        SwingPoint p0 = array.get(engine.points, pointCount - 4)
        SwingPoint p1 = array.get(engine.points, pointCount - 3)
        SwingPoint p2 = array.get(engine.points, pointCount - 2)
        SwingPoint p3 = array.get(engine.points, pointCount - 1)
        float lower = math.max(math.min(p0.price, p1.price), math.max(math.min(p1.price, p2.price), math.min(p2.price, p3.price)))
        float upper = math.min(math.max(p0.price, p1.price), math.min(math.max(p1.price, p2.price), math.max(p2.price, p3.price)))
        if lower < upper and p3.anchorIndex >= leftLimit
            color virtualColor = p3.kind == 1 ? buyColor : sellColor
            array.push(renderedBoxes, box.new(math.max(leftLimit, p0.anchorIndex), upper, bar_index, lower,
                 xloc = xloc.bar_index, border_color = color.new(virtualColor, 65), border_style = line.style_dashed,
                 bgcolor = color.new(virtualColor, 97)))
    int eventCount = array.size(engine.events)
    if showLabels and eventCount > 0
        int firstEvent = math.max(0, eventCount - drawSignalCount)
        for i = firstEvent to eventCount - 1
            StructuralEvent event = array.get(engine.events, i)
            int position = labelPlacement == "Detection bar" ? event.knownIndex : event.anchorIndex
            if position >= leftLimit
                string signalCaption = event.names
                if showContextTags and str.length(event.contextTags) > 0
                    signalCaption += "\n" + event.contextTags
                if showAreaRatio and not na(event.ratio)
                    signalCaption += "\nArea " + str.tostring(event.ratio, "0.00")
                string explanation = "Structure anchor: " + str.format_time(event.anchorTime, "yyyy-MM-dd HH:mm", syminfo.timezone)
                explanation += "\nFirst available: " + str.format_time(event.knownTime, "yyyy-MM-dd HH:mm", syminfo.timezone)
                explanation += "\nAvailability is the later detection bar. Geometry can revise after later turns; this event retains its issued coordinates."
                explanation += "\n\n" + event.contextText
                array.push(renderedLabels, label.new(position, event.price, signalCaption,
                     xloc = xloc.bar_index, style = event.side == 1 ? label.style_label_up : label.style_label_down,
                     color = event.side == 1 ? buyColor : sellColor, textcolor = color.black,
                     size = size.tiny, tooltip = explanation))
 
// Early observations preserve their first detection coordinates. Their later
// observation outcome is shown separately in the tooltip.
if barstate.islast and enableEarly and array.size(earlyBook.records) > 0
    int firstEarly = math.max(0, array.size(earlyBook.records) - drawEarlyCount)
    int earlyLeft = math.max(0, bar_index - displayHistory + 1)
    for i = firstEarly to array.size(earlyBook.records) - 1
        EarlyObservation observation = array.get(earlyBook.records, i)
        if observation.detectionIndex >= earlyLeft
            string details = "Earlier developing reversal observation"
            details += "\nObserved extreme: " + contextTime(observation.extremeTime)
            details += "\nFirst available: " + contextTime(observation.detectionTime)
            details += "\nATR at detection: " + str.tostring(observation.atrAtDetection, format.mintick)
            details += "\nLater observation: " + observation.state
            if not na(observation.resolutionTime)
                details += " at " + contextTime(observation.resolutionTime)
            details += "\nA terminal change records structural progress; trade performance remains unmeasured."
            details += "\n\n" + observation.contextText
            array.push(renderedLabels, label.new(observation.detectionIndex, observation.extreme,
                 observation.side == 1 ? "EW B?" : "EW S?", xloc = xloc.bar_index,
                 style = observation.side == 1 ? label.style_label_up : label.style_label_down,
                 color = color.new(observation.side == 1 ? buyColor : sellColor, 60), textcolor = chart.fg_color,
                 size = size.tiny, tooltip = details))
 
// This independent renderer draws at most two lines, without price labels.
// Put after the existing last-bar rendering block. Drawings respect displayHistory.
var line activeBuyRiskLine = na
var line activeSellRiskLine = na
if barstate.islast
    line.delete(activeBuyRiskLine)
    line.delete(activeSellRiskLine)
    activeBuyRiskLine := na
    activeSellRiskLine := na
    if showInvalidation and riskBook.buy.active
        int riskLeft = math.max(riskBook.buy.issuedIndex, math.max(0, bar_index - displayHistory + 1))
        activeBuyRiskLine := line.new(riskLeft, riskBook.buy.level, bar_index + 1, riskBook.buy.level,
             xloc = xloc.bar_index, extend = extend.right, color = color.new(buyColor, 5), style = line.style_dashed, width = levelWidth)
    if showInvalidation and riskBook.sell.active
        int riskLeft = math.max(riskBook.sell.issuedIndex, math.max(0, bar_index - displayHistory + 1))
        activeSellRiskLine := line.new(riskLeft, riskBook.sell.level, bar_index + 1, riskBook.sell.level,
             xloc = xloc.bar_index, extend = extend.right, color = color.new(sellColor, 5), style = line.style_dashed, width = levelWidth)

← 返回列表