MM Flow
FlowScripts

Perfected FlowScript

BTC Swing Intelligence

BTC Swing Intelligence V5.3e is indexed as 273_btc_swing_intelligence.flowscript. The exact FlowScript is viewable here; chart observe and trading automation use the current mmflow chart/recipe signal proxy until FlowScript v2 transpilation is available.

This exact FlowScript uses the v2 source dialect. It is viewable and connected to the chart/automation proxy, but direct editor execution needs the FlowScript v2 transpiler.

Dialect

flowscript-v2

Compatibility

flowscript-v2-needs-transpile

Position

onchart

Axis

false

Size

27.5 KB

Lines

592

Native Signal Candidates

14 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

14/14 guarded

ENTER LONG

line 460:5

Trigger

(showEntryLabels && enterLong)

Value

price.low

Deps

enterLong:var, showEntryLabels:input

ENTER SHORT

line 464:5

Trigger

(showEntryLabels && enterShort)

Value

price.high

Deps

enterShort:var, showEntryLabels:input

LONG TP1 2R

line 468:5

Trigger

(showManagementLabels && tp1Event && !isLiveUpdate && eventSide == 1)

Value

price.high

Deps

eventSide:var, isLiveUpdate:builtin, showManagementLabels:input, tp1Event:var

SHORT TP1 2R

line 472:5

Trigger

(showManagementLabels && tp1Event && !isLiveUpdate && eventSide == -1)

Value

price.low

Deps

eventSide:var, isLiveUpdate:builtin, showManagementLabels:input, tp1Event:var

LONG RUNNER 4R

line 476:5

Trigger

(showManagementLabels && runnerEvent && !isLiveUpdate && eventSide == 1)

Value

price.high

Deps

eventSide:var, isLiveUpdate:builtin, runnerEvent:var, showManagementLabels:input

SHORT RUNNER 4R

line 480:5

Trigger

(showManagementLabels && runnerEvent && !isLiveUpdate && eventSide == -1)

Value

price.low

Deps

eventSide:var, isLiveUpdate:builtin, runnerEvent:var, showManagementLabels:input

LONG RUNNER BE EXIT

line 484:5

Trigger

(showManagementLabels && beExitEvent && !isLiveUpdate && eventSide == 1)

Value

price.low

Deps

beExitEvent:var, eventSide:var, isLiveUpdate:builtin, showManagementLabels:input

SHORT RUNNER BE EXIT

line 488:5

Trigger

(showManagementLabels && beExitEvent && !isLiveUpdate && eventSide == -1)

Value

price.high

Deps

beExitEvent:var, eventSide:var, isLiveUpdate:builtin, showManagementLabels:input

LONG STOPPED

line 492:5

Trigger

(showManagementLabels && lossEvent && !isLiveUpdate && eventSide == 1)

Value

price.low

Deps

eventSide:var, isLiveUpdate:builtin, lossEvent:var, showManagementLabels:input

SHORT STOPPED

line 496:5

Trigger

(showManagementLabels && lossEvent && !isLiveUpdate && eventSide == -1)

Value

price.high

Deps

eventSide:var, isLiveUpdate:builtin, lossEvent:var, showManagementLabels:input

LONG ACCUM ARMED

line 500:5

Trigger

(showDiagnosticMarkers && longArmEvent)

Value

price.low

Deps

longArmEvent:var, showDiagnosticMarkers:input

LONG RECLAIMED

line 504:5

Trigger

(showDiagnosticMarkers && longReclaimEvent)

Value

price.low

Deps

longReclaimEvent:var, showDiagnosticMarkers:input

SHORT DIST ARMED

line 508:5

Trigger

(showDiagnosticMarkers && shortArmEvent)

Value

price.high

Deps

shortArmEvent:var, showDiagnosticMarkers:input

SHORT BREAK

line 512:5

Trigger

(showDiagnosticMarkers && shortBreakEvent)

Value

price.high

Deps

shortBreakEvent:var, showDiagnosticMarkers:input

273_btc_swing_intelligence.flowscript

source path: kscripts/perfected/273_btc_swing_intelligence.flowscript · sha256:d0b50158ad5263db68782cf9cbb032045673ee13ff0911a2d23adaf923b9695c

hash verified
//@version=2
// Source: kiyotaka.ai/hub/kscript (original)

define(title="BTC Swing Intelligence V5.3e", position="onchart", axis=false);

// BTC Swing Intelligence - V5.3e Grouped Dashboard Controls
// Hyperliquid BTC perpetual - intended for 4H chart.
//
// FORWARD-TEST CANDIDATE. DECISION SUPPORT ONLY.
//
// Validated architecture from available Kiyotaka historical window:
//
// SHORT MODEL:
// Kiyotaka-confirmed distribution at upper exhaustion
// -> bearish EMA21/EMA55 break
// -> failed retest into EMA resistance
// -> Kiyotaka asks confirm at entry
// -> ENTER SHORT
//
// LONG MODEL:
// Kiyotaka-confirmed accumulation at lower exhaustion
// -> persistent setup waits for bullish EMA21/EMA55 reversal
// -> later price-confirmed EMA support retest
// -> ENTER LONG without requiring a second bid-imbalance gate
//
// This asymmetry is intentional:
// - Entry-time asks filtered losing short candidates in the available sample.
// - Entry-time bids blocked the successful long recovery in the available sample.
//
// Management:
// - Only one active trade at a time.
// - Structural local stop.
// - TP1 at 2R; runner stop moves to breakeven.
// - Runner target at 4R.
// - If stop and target occur in the same 4H candle, stop is evaluated first.

// ==================== USER CONTROLS ====================

// Dashboard appearance controls.
// Group syntax matches the named-argument pattern already rendering the
// Direction and Setup sections in this Kiyotaka environment.
var showDashboard = input(name="showDashboard", type="boolean", defaultValue=true, label="Show Table", group="Dashboard");
var compactDashboard = input(name="compactDashboard", type="boolean", defaultValue=true, label="Compact Mode", group="Dashboard");
var dashboardTransparency = input(name="dashboardTransparency", type="number", defaultValue=28, label="Transparency Percent", constraints={min: 0, max: 80, step: 5}, group="Dashboard");

// General
var enableLongSignals = input(name="enableLongSignals", type="boolean", defaultValue=true, label="Enable Validated Long Architecture", group="Direction");
var enableShortSignals = input(name="enableShortSignals", type="boolean", defaultValue=true, label="Enable Validated Short Architecture", group="Direction");

// RSI Pro-style setup context
var rsiFastPeriod = input(name="rsiFastPeriod", type="number", defaultValue=14, label="RSI Pro Fast Period", constraints={min: 2, max: 50, step: 1}, group="Setup");
var rsiSmoothPeriod = input(name="rsiSmoothPeriod", type="number", defaultValue=3, label="RSI Pro EMA Smooth", constraints={min: 1, max: 20, step: 1}, group="Setup");
var topRsi = input(name="topRsi", type="number", defaultValue=62, label="Top Smoothed RSI Threshold", constraints={min: 50, max: 90, step: 1}, group="Setup");
var bottomRsi = input(name="bottomRsi", type="number", defaultValue=38, label="Bottom Smoothed RSI Threshold", constraints={min: 10, max: 50, step: 1}, group="Setup");
var topHitsNeeded = input(name="topHitsNeeded", type="number", defaultValue=2, label="Short Setup Confirmations To Arm", constraints={min: 1, max: 8, step: 1}, group="Setup");
var bottomHitsNeeded = input(name="bottomHitsNeeded", type="number", defaultValue=2, label="Long Accumulation Confirmations To Arm", constraints={min: 1, max: 8, step: 1}, group="Setup");

// Range location
var rangeLookback = input(name="rangeLookback", type="number", defaultValue=42, label="Range Lookback Bars", constraints={min: 20, max: 126, step: 1}, group="Location");
var topLocation = input(name="topLocation", type="number", defaultValue=0.65, label="Short Setup Minimum Range Location", constraints={min: 0.50, max: 0.95, step: 0.05}, group="Location");
var bottomLocation = input(name="bottomLocation", type="number", defaultValue=0.30, label="Long Setup Maximum Range Location", constraints={min: 0.05, max: 0.50, step: 0.05}, group="Location");
var shortEntryLocationMin = input(name="shortEntryLocationMin", type="number", defaultValue=0.30, label="Block New Short Below Range Location", constraints={min: 0.10, max: 0.60, step: 0.05}, group="Location");
var longEntryLocationMax = input(name="longEntryLocationMax", type="number", defaultValue=0.80, label="Block Retest Long Above Range Location", constraints={min: 0.40, max: 0.95, step: 0.05}, group="Location");

// Timing
var maxBarsWaitingForShortBreak = input(name="maxBarsWaitingForShortBreak", type="number", defaultValue=36, label="Maximum Short Bars Armed Before Break", constraints={min: 8, max: 100, step: 1}, group="State");
var maxBarsWaitingForShortRetest = input(name="maxBarsWaitingForShortRetest", type="number", defaultValue=18, label="Maximum Bars After Short Break For Retest", constraints={min: 4, max: 50, step: 1}, group="State");
var maxBarsWaitingForLongRetest = input(name="maxBarsWaitingForLongRetest", type="number", defaultValue=36, label="Maximum Bars After Long Reclaim For Retest", constraints={min: 4, max: 80, step: 1}, group="State");

// Kiyotaka short-side book pressure
var shortSetupRatio1 = input(name="shortSetupRatio1", type="number", defaultValue=0.90, label="Short Setup Max Bid Ask Ratio 1 Percent", constraints={min: 0.20, max: 1.0, step: 0.05}, group="Short Book");
var shortSetupRatio2 = input(name="shortSetupRatio2", type="number", defaultValue=0.95, label="Short Setup Max Bid Ask Ratio 2 Percent", constraints={min: 0.20, max: 1.20, step: 0.05}, group="Short Book");
var shortEntryRatio1 = input(name="shortEntryRatio1", type="number", defaultValue=0.95, label="Short Entry Max Bid Ask Ratio 1 Percent", constraints={min: 0.20, max: 1.10, step: 0.05}, group="Short Book");
var shortEntryRatio2 = input(name="shortEntryRatio2", type="number", defaultValue=1.00, label="Short Entry Max Bid Ask Ratio 2 Percent", constraints={min: 0.20, max: 1.20, step: 0.05}, group="Short Book");

// Kiyotaka long-side accumulation pressure
var longSetupRatio1 = input(name="longSetupRatio1", type="number", defaultValue=1.10, label="Long Accumulation Min Bid Ask Ratio 1 Percent", constraints={min: 1.0, max: 3.0, step: 0.05}, group="Long Book");
var longSetupRatio2 = input(name="longSetupRatio2", type="number", defaultValue=1.05, label="Long Accumulation Min Bid Ask Ratio 2 Percent", constraints={min: 0.80, max: 3.0, step: 0.05}, group="Long Book");

// Book wall safety
var opposingWallRatio = input(name="opposingWallRatio", type="number", defaultValue=1.75, label="Opposing Wall Block Ratio", constraints={min: 1.0, max: 5.0, step: 0.10}, group="Book Safety");

// Risk plan
var mainTargetR = input(name="mainTargetR", type="number", defaultValue=2.0, label="TP1 Target R", constraints={min: 1.0, max: 5.0, step: 0.5}, group="Risk Plan");
var runnerTargetR = input(name="runnerTargetR", type="number", defaultValue=4.0, label="Runner Target R", constraints={min: 2.0, max: 10.0, step: 0.5}, group="Risk Plan");
var minStopPct = input(name="minStopPct", type="number", defaultValue=0.25, label="Minimum Stop Distance Percent", constraints={min: 0.10, max: 2.0, step: 0.05}, group="Risk Plan");
var maxShortStopPct = input(name="maxShortStopPct", type="number", defaultValue=3.00, label="Maximum Short Stop Distance Percent", constraints={min: 0.50, max: 8.0, step: 0.25}, group="Risk Plan");
var maxLongStopPct = input(name="maxLongStopPct", type="number", defaultValue=4.00, label="Maximum Long Stop Distance Percent", constraints={min: 0.50, max: 10.0, step: 0.25}, group="Risk Plan");

// Funding and manual risk controls
var requireFundingTailwind = input(name="requireFundingTailwind", type="boolean", defaultValue=false, label="Require Funding Tailwind", group="Filters");
var macroRisk = input(name="macroRisk", type="boolean", defaultValue=false, label="Block New Entries For Major Macro Risk", group="Manual Blocks");
var geopoliticalRisk = input(name="geopoliticalRisk", type="boolean", defaultValue=false, label="Block New Entries For Geopolitical Risk", group="Manual Blocks");
var closeRisk = input(name="closeRisk", type="boolean", defaultValue=false, label="Block New Entries For Weekly Monthly Close", group="Manual Blocks");

// Display
var showEma = input(name="showEma", type="boolean", defaultValue=true, label="Show EMA21 EMA55", group="Display");
var showEntryLabels = input(name="showEntryLabels", type="boolean", defaultValue=true, label="Show Entry Labels", group="Display");
var showManagementLabels = input(name="showManagementLabels", type="boolean", defaultValue=true, label="Show TP Stop Labels", group="Display");
var showDiagnosticMarkers = input(name="showDiagnosticMarkers", type="boolean", defaultValue=false, label="Show Setup And Transition Markers", group="Display");

// ==================== KIYOTAKA SOURCES: 5 / 5 ====================
// OHLCV = 1; orderbook heatmap = 3; funding = 1.
timeseries price = ohlcv(symbol="BTC", exchange="HYPERLIQUID_FUTURES");
timeseries book = source("orderbook", "BTC", "HYPERLIQUID_FUTURES");
timeseries funding = source("funding_rate", "BTC", "HYPERLIQUID_FUTURES");

if (isnan(price.close[0])) {
    return;
}

// ==================== PRICE AND RSI CONTEXT ====================
timeseries close = price.close;
timeseries fastRsi = rsi(close, rsiFastPeriod);
var smoothRsi = ema(fastRsi, rsiSmoothPeriod);

var ema21 = ema(source=price.close, period=21);
var ema55 = ema(source=price.close, period=55);

var rangeHigh = highest(source=price, period=rangeLookback);
var rangeLow = lowest(source=price, period=rangeLookback);
var rangeSize = rangeHigh - rangeLow;
var rangeLocation = rangeSize > 0 ? (price.close - rangeLow) / rangeSize : 0.50;

// ==================== ORDERBOOK CONTEXT ====================
var bids1 = sumBids(book, 1);
var asks1 = sumAsks(book, 1);
var bids2 = sumBids(book, 2);
var asks2 = sumAsks(book, 2);
var maxBid1 = maxBidAmount(book, 1);
var maxAsk1 = maxAskAmount(book, 1);

var bookAvailable = bids1 > 0 && asks1 > 0 && bids2 > 0 && asks2 > 0 && maxBid1 > 0 && maxAsk1 > 0;
var ratio1 = bookAvailable ? bids1 / asks1 : na;
var ratio2 = bookAvailable ? bids2 / asks2 : na;
var bidWallRatio = bookAvailable ? maxBid1 / maxAsk1 : na;
var askWallRatio = bookAvailable ? maxAsk1 / maxBid1 : na;

// ==================== SETUP CONDITIONS ====================
var rawTop = smoothRsi >= topRsi && rangeLocation >= topLocation;
var rawBottom = smoothRsi <= bottomRsi && rangeLocation <= bottomLocation;

var shortSetupConfirm = rawTop && bookAvailable && ratio1 <= shortSetupRatio1 && ratio2 <= shortSetupRatio2;
var longSetupConfirm = rawBottom && bookAvailable && ratio1 >= longSetupRatio1 && ratio2 >= longSetupRatio2;

var shortBookAtEntry = bookAvailable && ratio1 <= shortEntryRatio1 && ratio2 <= shortEntryRatio2 && bidWallRatio < opposingWallRatio;

// ==================== FUNDING CONTEXT ====================
var shortFundingPass = !requireFundingTailwind || funding > 0;
var longFundingPass = !requireFundingTailwind || funding < 0;

var fundingState = "FLAT";
if (funding > 0) {
    fundingState = "POSITIVE - SHORT TAILWIND";
} else if (funding < 0) {
    fundingState = "NEGATIVE - LONG TAILWIND";
}

// ==================== SHARED CANDLE STRUCTURE ====================
var candleRange = price.high - price.low;
var bearishReject = candleRange > 0 && price.close < price.open && (price.close - price.low) / candleRange <= 0.55;
var bullishReject = candleRange > 0 && price.close > price.open && (price.high - price.close) / candleRange <= 0.55;

var bearishBreak = price.close < ema21 && price.close < ema55 && price.close < price.open && price.close < price.low[1];
var bullishRegime = ema21 > ema55;
var bullishReclaim = bullishRegime && price.close > ema21 && price.close > ema55 && price.close > price.high[1] && bullishReject;

// ==================== SHORT STATE ====================
// 0 idle, 1 distribution armed waiting break, 2 break registered waiting failed retest.
static shortStage = 0;
static shortHits = 0;
static shortStageBars = 0;

var shortArmEvent = shortStage == 0 && shortSetupConfirm && shortHits == topHitsNeeded - 1;
var shortBreakEvent = shortStage == 1 && bearishBreak;

if (!isLiveUpdate) {
    if (shortStage == 0) {
        if (shortSetupConfirm) {
            shortHits = shortHits + 1;
        } else if (rangeLocation < topLocation) {
            shortHits = 0;
        }

        if (shortHits >= topHitsNeeded) {
            shortStage = 1;
            shortStageBars = 0;
        }
    } else if (shortStage == 1) {
        shortStageBars = shortStageBars + 1;

        if (bearishBreak) {
            shortStage = 2;
            shortStageBars = 0;
        } else if (shortStageBars > maxBarsWaitingForShortBreak) {
            shortStage = 0;
            shortHits = 0;
            shortStageBars = 0;
        }
    } else if (shortStage == 2) {
        shortStageBars = shortStageBars + 1;

        if (shortStageBars > maxBarsWaitingForShortRetest || rangeLocation < shortEntryLocationMin) {
            shortStage = 0;
            shortHits = 0;
            shortStageBars = 0;
        }
    }
}

var shortRetestTouch = price.high >= ema21 || price.high >= ema55;
var shortFailedRetest = shortStage == 2 && shortStageBars >= 1 && shortRetestTouch && price.close < ema21 && bearishReject;
var shortStop = highest(source=price, period=3);
var shortRisk = shortStop - price.close;
var shortRiskPct = shortRisk > 0 ? shortRisk / price.close * 100 : 0;
var shortStopValid = shortRisk > 0 && shortRiskPct >= minStopPct && shortRiskPct <= maxShortStopPct;
var shortCandidate = enableShortSignals && shortFailedRetest && rangeLocation >= shortEntryLocationMin && shortBookAtEntry && shortFundingPass && shortStopValid;

// ==================== LONG STATE ====================
// 0 idle, 1 book-confirmed accumulation persistently armed, 2 bullish reclaim registered waiting retest.
static longStage = 0;
static longHits = 0;
static longStageBars = 0;

var longArmEvent = longStage == 0 && longSetupConfirm && longHits == bottomHitsNeeded - 1;
var longReclaimEvent = longStage == 1 && bullishReclaim;

if (!isLiveUpdate) {
    if (longStage == 0) {
        if (longSetupConfirm) {
            longHits = longHits + 1;
        } else if (rangeLocation > bottomLocation) {
            longHits = 0;
        }

        if (longHits >= bottomHitsNeeded) {
            longStage = 1;
            longStageBars = 0;
        }
    } else if (longStage == 1) {
        // Intentional: do not time out a book-confirmed accumulation base.
        if (bullishReclaim) {
            longStage = 2;
            longStageBars = 0;
        }
    } else if (longStage == 2) {
        longStageBars = longStageBars + 1;

        if (longStageBars > maxBarsWaitingForLongRetest || !bullishRegime) {
            longStage = 0;
            longHits = 0;
            longStageBars = 0;
        }
    }
}

var longRetestTouch = price.low <= ema21 || price.low <= ema55;
var longSuccessfulRetest = longStage == 2 && longStageBars >= 1 && bullishRegime && longRetestTouch && price.close > ema21 && price.close > ema55 && bullishReject;
var longStop = lowest(source=price, period=3);
var longRisk = price.close - longStop;
var longRiskPct = longRisk > 0 ? longRisk / price.close * 100 : 0;
var longStopValid = longRisk > 0 && longRiskPct >= minStopPct && longRiskPct <= maxLongStopPct;

// No entry-time bid requirement by design: bids qualify the accumulation base.
var longCandidate = enableLongSignals && longSuccessfulRetest && rangeLocation <= longEntryLocationMax && longFundingPass && longStopValid;

// ==================== SINGLE TRADE LIFECYCLE ====================
static activeSide = 0;
static trackedEntry = 0;
static trackedInitialStop = 0;
static trackedActiveStop = 0;
static trackedTp1 = 0;
static trackedRunner = 0;
static trackedTp1Reached = false;
static totalEntries = 0;
static totalStops = 0;
static totalTp1Hits = 0;
static totalRunnerHits = 0;
static totalBeExits = 0;

var manualBlocked = macroRisk || geopoliticalRisk || closeRisk;
var signalSlotOpen = activeSide == 0 && !manualBlocked;

var enterShort = signalSlotOpen && shortCandidate && !isLiveUpdate;
var enterLong = signalSlotOpen && longCandidate && !isLiveUpdate;

var shortTarget2 = shortRisk > 0 ? price.close - shortRisk * mainTargetR : na;
var shortTarget4 = shortRisk > 0 ? price.close - shortRisk * runnerTargetR : na;
var longTarget2 = longRisk > 0 ? price.close + longRisk * mainTargetR : na;
var longTarget4 = longRisk > 0 ? price.close + longRisk * runnerTargetR : na;

if (enterShort) {
    activeSide = -1;
    trackedEntry = price.close;
    trackedInitialStop = shortStop;
    trackedActiveStop = shortStop;
    trackedTp1 = shortTarget2;
    trackedRunner = shortTarget4;
    trackedTp1Reached = false;
    totalEntries = totalEntries + 1;

    shortStage = 0;
    shortHits = 0;
    shortStageBars = 0;
    longStage = 0;
    longHits = 0;
    longStageBars = 0;
}

if (enterLong) {
    activeSide = 1;
    trackedEntry = price.close;
    trackedInitialStop = longStop;
    trackedActiveStop = longStop;
    trackedTp1 = longTarget2;
    trackedRunner = longTarget4;
    trackedTp1Reached = false;
    totalEntries = totalEntries + 1;

    shortStage = 0;
    shortHits = 0;
    shortStageBars = 0;
    longStage = 0;
    longHits = 0;
    longStageBars = 0;
}

// Lifecycle integrity fix:
// Entry signals are confirmed at the candle close. A wick that occurred earlier
// during the signal candle cannot stop or hit a target for a position that did
// not exist until that close. Therefore, management events begin only on the
// candle after entry.
//
// Conservative assumption remains in effect after entry:
// if stop and target both touch during a later 4H candle, stop is counted first.
var entryPlacedThisBar = enterShort || enterLong;
var manageExistingTrade = activeSide != 0 && !entryPlacedThisBar;

var stopEvent = manageExistingTrade && ((activeSide == -1 && price.high >= trackedActiveStop) || (activeSide == 1 && price.low <= trackedActiveStop));
var runnerEvent = manageExistingTrade && (activeSide == -1 ? (!stopEvent && price.low <= trackedRunner) : (!stopEvent && price.high >= trackedRunner));
var tp1Event = manageExistingTrade && (activeSide == -1 ? (!trackedTp1Reached && !stopEvent && !runnerEvent && price.low <= trackedTp1) : (!trackedTp1Reached && !stopEvent && !runnerEvent && price.high >= trackedTp1));
var beExitEvent = manageExistingTrade && stopEvent && trackedTp1Reached;
var lossEvent = manageExistingTrade && stopEvent && !trackedTp1Reached;

var eventSide = activeSide;

if (!isLiveUpdate) {
    if (tp1Event) {
        trackedTp1Reached = true;
        totalTp1Hits = totalTp1Hits + 1;
        trackedActiveStop = trackedEntry;
    }

    if (runnerEvent) {
        if (!trackedTp1Reached) {
            totalTp1Hits = totalTp1Hits + 1;
        }
        totalRunnerHits = totalRunnerHits + 1;
        activeSide = 0;
        trackedEntry = 0;
        trackedInitialStop = 0;
        trackedActiveStop = 0;
        trackedTp1 = 0;
        trackedRunner = 0;
        trackedTp1Reached = false;
    } else if (beExitEvent) {
        totalBeExits = totalBeExits + 1;
        activeSide = 0;
        trackedEntry = 0;
        trackedInitialStop = 0;
        trackedActiveStop = 0;
        trackedTp1 = 0;
        trackedRunner = 0;
        trackedTp1Reached = false;
    } else if (lossEvent) {
        totalStops = totalStops + 1;
        activeSide = 0;
        trackedEntry = 0;
        trackedInitialStop = 0;
        trackedActiveStop = 0;
        trackedTp1 = 0;
        trackedRunner = 0;
        trackedTp1Reached = false;
    }
}

// ==================== LIVE DECISION DISPLAY ====================
var tradeState = "FLAT";
if (activeSide == 1) {
    tradeState = trackedTp1Reached ? "LONG RUNNER ACTIVE" : "LONG ACTIVE";
} else if (activeSide == -1) {
    tradeState = trackedTp1Reached ? "SHORT RUNNER ACTIVE" : "SHORT ACTIVE";
}

var setupState = "NONE";
if (activeSide != 0) {
    setupState = "TRADE ACTIVE";
} else if (shortStage == 1) {
    setupState = "SHORT ARMED WAIT BREAK";
} else if (shortStage == 2) {
    setupState = "SHORT BREAK WAIT RETEST";
} else if (longStage == 1) {
    setupState = "LONG ACCUM WAIT RECLAIM";
} else if (longStage == 2) {
    setupState = "LONG RECLAIM WAIT RETEST";
}

var decision = "NO TRADE";
var reason = "WAIT FOR QUALITY SETUP";

if (activeSide == 1) {
    decision = trackedTp1Reached ? "MANAGE LONG RUNNER" : "HOLD LONG PLAN";
    reason = trackedTp1Reached ? "2R REACHED WAIT 4R OR BE" : "LONG TRADE ACTIVE";
} else if (activeSide == -1) {
    decision = trackedTp1Reached ? "MANAGE SHORT RUNNER" : "HOLD SHORT PLAN";
    reason = trackedTp1Reached ? "2R REACHED WAIT 4R OR BE" : "SHORT TRADE ACTIVE";
} else if (manualBlocked) {
    decision = "NO TRADE";
    reason = "MANUAL RISK BLOCK ACTIVE";
} else if (shortCandidate) {
    decision = isLiveUpdate ? "SHORT CANDIDATE WAIT CLOSE" : "ENTER SHORT";
    reason = "FAILED RETEST AND ASKS CONFIRM";
} else if (longCandidate) {
    decision = isLiveUpdate ? "LONG CANDIDATE WAIT CLOSE" : "ENTER LONG";
    reason = "ACCUMULATION THEN BULL RETEST";
} else if (shortStage == 1) {
    decision = "WATCH SHORT";
    reason = "BOOK DISTRIBUTION ARMED";
} else if (shortStage == 2) {
    decision = "WATCH SHORT";
    reason = shortBookAtEntry ? "WAIT FAILED RETEST" : "WAIT RETEST ASK CONFIRM";
} else if (longStage == 1) {
    decision = "WATCH LONG";
    reason = "BOOK ACCUMULATION ARMED";
} else if (longStage == 2) {
    decision = "WATCH LONG";
    reason = "WAIT PRICE RETEST CONFIRM";
}

var bookState = "UNAVAILABLE";
if (bookAvailable) {
    if (ratio1 <= shortEntryRatio1 && ratio2 <= shortEntryRatio2) {
        bookState = "ASK PRESSURE";
    } else if (ratio1 >= longSetupRatio1 && ratio2 >= longSetupRatio2) {
        bookState = "BID PRESSURE";
    } else {
        bookState = "MIXED";
    }
}

var lockedR = (0 - totalStops) + totalBeExits + (totalRunnerHits * 3) + (activeSide != 0 && trackedTp1Reached ? 1 : 0);

// ==================== DISPLAY ====================
if (showEma) {
    plotLine(value=ema21, width=2, colors=["#38bdf8"], label=["EMA 21"], desc=["Entry/retest reference"]);
    plotLine(value=ema55, width=2, colors=["#f59e0b"], label=["EMA 55"], desc=["Regime reference"]);
}

if (showEntryLabels && enterLong) {
    plotPriceLabel(price=price.low, text="ENTER LONG", type="callout", color="#ffffff", backgroundColor="#16a34a", size=12, fontWeight=700);
}

if (showEntryLabels && enterShort) {
    plotPriceLabel(price=price.high, text="ENTER SHORT", type="callout", color="#ffffff", backgroundColor="#dc2626", size=12, fontWeight=700);
}

if (showManagementLabels && tp1Event && !isLiveUpdate && eventSide == 1) {
    plotPriceLabel(price=price.high, text="LONG TP1 2R", type="callout", color="#ffffff", backgroundColor="#0369a1", size=10, fontWeight=700);
}

if (showManagementLabels && tp1Event && !isLiveUpdate && eventSide == -1) {
    plotPriceLabel(price=price.low, text="SHORT TP1 2R", type="callout", color="#ffffff", backgroundColor="#0369a1", size=10, fontWeight=700);
}

if (showManagementLabels && runnerEvent && !isLiveUpdate && eventSide == 1) {
    plotPriceLabel(price=price.high, text="LONG RUNNER 4R", type="callout", color="#ffffff", backgroundColor="#0f766e", size=10, fontWeight=700);
}

if (showManagementLabels && runnerEvent && !isLiveUpdate && eventSide == -1) {
    plotPriceLabel(price=price.low, text="SHORT RUNNER 4R", type="callout", color="#ffffff", backgroundColor="#0f766e", size=10, fontWeight=700);
}

if (showManagementLabels && beExitEvent && !isLiveUpdate && eventSide == 1) {
    plotPriceLabel(price=price.low, text="LONG RUNNER BE EXIT", type="callout", color="#ffffff", backgroundColor="#475569", size=10, fontWeight=700);
}

if (showManagementLabels && beExitEvent && !isLiveUpdate && eventSide == -1) {
    plotPriceLabel(price=price.high, text="SHORT RUNNER BE EXIT", type="callout", color="#ffffff", backgroundColor="#475569", size=10, fontWeight=700);
}

if (showManagementLabels && lossEvent && !isLiveUpdate && eventSide == 1) {
    plotPriceLabel(price=price.low, text="LONG STOPPED", type="callout", color="#ffffff", backgroundColor="#475569", size=10, fontWeight=700);
}

if (showManagementLabels && lossEvent && !isLiveUpdate && eventSide == -1) {
    plotPriceLabel(price=price.high, text="SHORT STOPPED", type="callout", color="#ffffff", backgroundColor="#475569", size=10, fontWeight=700);
}

if (showDiagnosticMarkers && longArmEvent) {
    plotPriceLabel(price=price.low, text="LONG ACCUM ARMED", type="callout", color="#ffffff", backgroundColor="#7c3aed", size=9, fontWeight=700);
}

if (showDiagnosticMarkers && longReclaimEvent) {
    plotPriceLabel(price=price.low, text="LONG RECLAIMED", type="callout", color="#ffffff", backgroundColor="#16a34a", size=9, fontWeight=700);
}

if (showDiagnosticMarkers && shortArmEvent) {
    plotPriceLabel(price=price.high, text="SHORT DIST ARMED", type="callout", color="#ffffff", backgroundColor="#7c3aed", size=9, fontWeight=700);
}

if (showDiagnosticMarkers && shortBreakEvent) {
    plotPriceLabel(price=price.high, text="SHORT BREAK", type="callout", color="#ffffff", backgroundColor="#d97706", size=9, fontWeight=700);
}

// ==================== SIMPLE DASHBOARD ====================
// Presentation controls only. No signal, risk, or lifecycle logic changes.
var displayEntry = activeSide != 0 ? trackedEntry : (shortCandidate || longCandidate ? price.close : na);
var displayStop = activeSide != 0 ? trackedActiveStop : (shortCandidate ? shortStop : (longCandidate ? longStop : na));
var displayTarget = activeSide != 0 ? trackedTp1 : (shortCandidate ? shortTarget2 : (longCandidate ? longTarget2 : na));
var displayRunner = activeSide != 0 ? trackedRunner : (shortCandidate ? shortTarget4 : (longCandidate ? longTarget4 : na));

var dashboardBg = transparency("#0f172a", dashboardTransparency);
var dashboardHeaderBg = transparency("#1e293b", dashboardTransparency);
var dashboardBorder = transparency("#334155", dashboardTransparency);

if (showDashboard && compactDashboard && isLastBar) {
    plotTable(
        data=[
            ["BTC Swing Intelligence", "V5.3e COMPACT"],
            ["Decision", decision],
            ["Reason", reason],
            ["Trade State", tradeState],
            ["Setup State", setupState],
            ["Book State", bookState],
            ["Entry", displayEntry],
            ["Stop", displayStop],
            ["Target 2R", displayTarget],
            ["Runner 4R", displayRunner],
            ["Locked R Approx", lockedR]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=dashboardBg,
        headerBackgroundColor=dashboardHeaderBg,
        borderColor=dashboardBorder,
        borderWidth=1,
        fontSize=10,
        cellPadding=5
    );
}

if (showDashboard && !compactDashboard && isLastBar) {
    plotTable(
        data=[
            ["BTC Swing Intelligence", "V5.3e FULL"],
            ["Decision", decision],
            ["Reason", reason],
            ["Trade State", tradeState],
            ["Setup State", setupState],
            ["Book State", bookState],
            ["Funding", fundingState],
            ["Short Stop Cap Percent", maxShortStopPct],
            ["Long Stop Cap Percent", maxLongStopPct],
            ["Entry Candle Management", "OFF - START NEXT BAR"],
            ["Entry", displayEntry],
            ["Active Stop", displayStop],
            ["Target 2R", displayTarget],
            ["Runner 4R", displayRunner],
            ["Tracked Entries", totalEntries],
            ["Tracked Stops", totalStops],
            ["Tracked TP1 Hits", totalTp1Hits],
            ["Tracked 4R Hits", totalRunnerHits],
            ["Tracked BE Exits", totalBeExits],
            ["Locked R Approx", lockedR]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=dashboardBg,
        headerBackgroundColor=dashboardHeaderBg,
        borderColor=dashboardBorder,
        borderWidth=1,
        fontSize=10,
        cellPadding=5
    );
}