MM Flow
FlowScripts

Perfected FlowScript

Asia spring load

Asia Spring Load — Perfected Edition is indexed as 289_asia_spring_load.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

18.8 KB

Lines

593

Native Signal Candidates

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

6/6 guarded

Unlabeled shape

line 495:9

Trigger

(showBreakoutShapes) && (longBreak)

Value

close

Deps

longBreak:var, showBreakoutShapes:input

Unlabeled shape

line 505:9

Trigger

(showBreakoutShapes) && (shortBreak)

Value

close

Deps

shortBreak:var, showBreakoutShapes:input

False Long

line 518:9

Trigger

(showFalseBreakShapes) && (falseBreakLong)

Value

close

Deps

falseBreakLong:var, showFalseBreakShapes:input

False Short

line 528:9

Trigger

(showFalseBreakShapes) && (falseBreakShort)

Value

close

Deps

falseBreakShort:var, showFalseBreakShapes:input

Retest Long

line 541:9

Trigger

(showRetestShapes) && (retestLong)

Value

close

Deps

retestLong:var, showRetestShapes:input

Retest Short

line 551:9

Trigger

(showRetestShapes) && (retestShort)

Value

close

Deps

retestShort:var, showRetestShapes:input

289_asia_spring_load.flowscript

source path: kscripts/perfected/289_asia_spring_load.flowscript · sha256:aaf63e123c66145ce799293638829dd83e86122da6ae2e0936986dfd5e4f1a52

hash verified
//@version=2
// ============================================================================
// Asia Spring Load — Perfected Edition
// Author: P (@Petar Petrov_5685) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #asia, #session, #range, #accumulation, #springload, #breakout
//
// Production-quality session-aware Asian range accumulation and spring-load
// breakout detector. Tracks the Asian session (Tokyo-dominated) high/low range,
// computes a compression score (spring load), and detects London/NY-driven
// expansion breakouts with strength classification.
//
// Research papers underpinning this design:
//  1. Harris (1986), "A Transaction Data Study of Weekly and Intradaily
//     Patterns in Stock Returns": documents distinct intraday seasonality.
//     Asian session exhibits lower volatility and range-bound conditions.
//  2. Ito & Hashimoto (2006), "Intraday Seasonality in Activities of the
//     Foreign Exchange Markets": U-shaped activity in Tokyo; overlapping hours
//     (London/NY) drive expansion. Asian session = accumulation phase.
//  3. Cercle PPM (2025), "ICT Killzone Pro Suite and Time-Based Trading":
//     Asian Killzone (00:00–05:00 UTC) as range-bound accumulation window;
//     London open (07:00–10:00 UTC) often breaks the Asian range.
//  4. Lo & MacKinlay (1990), "An Econometric Analysis of Nonsynchronous
//     Trading": non-trading periods create information accumulation; the
//     "spring load" effect mirrors price pressure building during low-activity
//     sessions before release at session open.
//  5. Bloomfield, O'Hara & Saar (2005), "The 'Make' or 'Take' Decision in
//     Electronic Markets": passive liquidity provision during low-volatility
//     periods (Asia) creates the inventory imbalance that drives breakouts.
//  6. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules
//     and the Stochastic Properties of Stock Returns": range breakout
//     strategies have significant predictive power; Asian range breakouts
//     carry directional edge due to information accumulation.
// ============================================================================

define(
    title="Asia Spring Load — Perfected Edition",
    position="onchart",
    axis=false
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- Session Timing ---
var asiaStartHour = input(
    name="asiaStartHour",
    type="number",
    defaultValue=0,
    label="Asia Session Start (UTC hour)",
    constraints={min: 0, max: 23, step: 1},
    group="Session Timing"
)
var asiaEndHour = input(
    name="asiaEndHour",
    type="number",
    defaultValue=8,
    label="Asia Session End (UTC hour)",
    constraints={min: 0, max: 23, step: 1},
    group="Session Timing"
)
var londonStartHour = input(
    name="londonStartHour",
    type="number",
    defaultValue=8,
    label="London Session Start (UTC hour)",
    constraints={min: 0, max: 23, step: 1},
    group="Session Timing"
)
var nyStartHour = input(
    name="nyStartHour",
    type="number",
    defaultValue=13,
    label="New York Session Start (UTC hour)",
    constraints={min: 0, max: 23, step: 1},
    group="Session Timing"
)

// --- Breakout Settings ---
var breakoutMode = input(
    name="breakoutMode",
    type="select",
    defaultValue="Both",
    label="Breakout Direction",
    options=["Long", "Short", "Both"],
    group="Breakout Settings"
)
var requireSpringLoad = input(
    name="requireSpringLoad",
    type="boolean",
    defaultValue=true,
    label="Require Spring Load (compression)",
    group="Breakout Settings"
)
var springLoadThreshold = input(
    name="springLoadThreshold",
    type="number",
    defaultValue=0.5,
    label="Spring Load Threshold (ATR multiple)",
    constraints={min: 0.1, max: 3.0, step: 0.1},
    group="Breakout Settings"
)
var compressionLookback = input(
    name="compressionLookback",
    type="number",
    defaultValue=20,
    label="Compression History Lookback (days)",
    constraints={min: 5, max: 100, step: 1},
    group="Breakout Settings"
)

// --- Range Display ---
var showAsiaRange = input(
    name="showAsiaRange",
    type="boolean",
    defaultValue=true,
    label="Show Asia Range Lines",
    group="Range Display"
)
var showAsiaFill = input(
    name="showAsiaFill",
    type="boolean",
    defaultValue=true,
    label="Show Asia Range Fill",
    group="Range Display"
)
var showMidLine = input(
    name="showMidLine",
    type="boolean",
    defaultValue=true,
    label="Show Asia Midpoint",
    group="Range Display"
)
var showSpringLoad = input(
    name="showSpringLoad",
    type="boolean",
    defaultValue=true,
    label="Show Spring Load Score (offchart)",
    group="Range Display"
)

// --- Signals ---
var showBreakoutShapes = input(
    name="showBreakoutShapes",
    type="boolean",
    defaultValue=true,
    label="Show Breakout Shapes",
    group="Signals"
)
var showFalseBreakShapes = input(
    name="showFalseBreakShapes",
    type="boolean",
    defaultValue=true,
    label="Show False Breakout Shapes",
    group="Signals"
)
var showRetestShapes = input(
    name="showRetestShapes",
    type="boolean",
    defaultValue=true,
    label="Show Retest Shapes",
    group="Signals"
)

// --- Colors ---
var asiaColor = input(
    name="asiaColor",
    type="color",
    defaultValue="#9c27b0",
    label="Asia Range Color",
    group="Colors"
)
var upColor = input(
    name="upColor",
    type="color",
    defaultValue="#00e676",
    label="Long Breakout Color",
    group="Colors"
)
var dnColor = input(
    name="dnColor",
    type="color",
    defaultValue="#ff5252",
    label="Short Breakout Color",
    group="Colors"
)
var falseBreakColor = input(
    name="falseBreakColor",
    type="color",
    defaultValue="#ff9800",
    label="False Breakout Color",
    group="Colors"
)
var retestColor = input(
    name="retestColor",
    type="color",
    defaultValue="#42a5f5",
    label="Retest Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries price = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = price.close
timeseries high = price.high
timeseries low = price.low
timeseries t = price.time
timeseries volume = price.volume

if (isnan(close[0])) {
    return
}

// Hour of day and session flags
timeseries hourOfDay = (t / 3600000) % 24
timeseries dayId = math.floor(t / 86400000)

timeseries inAsia = hourOfDay >= asiaStartHour && hourOfDay < asiaEndHour
timeseries inLondon = hourOfDay >= londonStartHour && hourOfDay < (londonStartHour + 8)
timeseries inNY = hourOfDay >= nyStartHour && hourOfDay < (nyStartHour + 8)
timeseries inOverlap = inLondon && inNY

// -----------------------------------------------------------------------------
// 3. SESSION STATE — static variables for daily tracking
// -----------------------------------------------------------------------------
// Per Harris (1986) and Ito & Hashimoto (2006), the Asian session serves as
// an accumulation phase. We track daily range, midpoint, and volume to
// compute a spring-load score.

static asiaHigh = 0.0
static asiaLow = 1e18
static asiaMid = 0.0
static asiaRange = 0.0
static asiaVolume = 0.0
static lastDay = -1
static stillAsia = false
static priorAsiaHigh = 0.0
static priorAsiaLow = 0.0
static priorAsiaMid = 0.0
static priorAsiaRange = 0.0
static springLoadScore = 0.0

var currentDay = dayId[0]

if (lastDay != currentDay) {
    // New day — save prior session stats before reset
    priorAsiaHigh = asiaHigh
    priorAsiaLow = asiaLow
    priorAsiaMid = asiaMid
    priorAsiaRange = asiaRange

    lastDay = currentDay
    asiaHigh = 0.0
    asiaLow = 1e18
    asiaMid = 0.0
    asiaRange = 0.0
    asiaVolume = 0.0
    stillAsia = false
}

// Accumulate Asia session data
if (inAsia) {
    if (!stillAsia) {
        asiaHigh = high[0]
        asiaLow = low[0]
        asiaVolume = volume[0]
        stillAsia = true
    } else {
        asiaHigh = math.max(asiaHigh, high[0])
        asiaLow = math.min(asiaLow, low[0])
        asiaVolume = asiaVolume + volume[0]
    }
    asiaMid = (asiaHigh + asiaLow) / 2.0
    asiaRange = asiaHigh - asiaLow
}

// Guard: if Asia range is invalid, skip plotting for this day
var validAsiaRange = asiaRange > 0 && asiaHigh > 0 && asiaLow < 1e18

// -----------------------------------------------------------------------------
// 4. ATR & SPRING LOAD SCORE
// -----------------------------------------------------------------------------
// The spring load measures how compressed today's Asia range is relative to
// recent history. A range narrower than 0.5x the 20-day median ATR implies
// strong compression (coiled spring). Per Lo & MacKinlay (1990), information
// accumulates during non-trading/low-activity periods, creating pressure.

timeseries atr14 = atr(period=14)
timeseries atrMedian = sma(source=atr14, period=compressionLookback)

var springLoad = 0.0
if (validAsiaRange && atrMedian > 0) {
    springLoad = atrMedian / math.max(asiaRange, atr14 * 0.1)  // compression ratio
    springLoad = math.min(springLoad, 10.0)  // cap at 10x
} else {
    springLoad = 0.0
}

var isCompressed = validAsiaRange && springLoad >= springLoadThreshold
var isVeryCompressed = validAsiaRange && springLoad >= springLoadThreshold * 2.0

// Smooth spring load for offchart display
timeseries springLoadSmooth = ema(source=springLoad, period=5)

// -----------------------------------------------------------------------------
// 5. BREAKOUT DETECTION
// -----------------------------------------------------------------------------
// Breakout logic: price must trade outside the Asia range AFTER the session
// ends. Per Brock et al. (1992), range breakouts have directional edge.
// We also detect false breakouts (price re-enters within 3 bars) and retests.

var isPostAsia = !inAsia && stillAsia && validAsiaRange

var longBreak = isPostAsia && close[0] > asiaHigh && (breakoutMode == "Long" || breakoutMode == "Both")
var shortBreak = isPostAsia && close[0] < asiaLow && (breakoutMode == "Short" || breakoutMode == "Both")

if (requireSpringLoad) {
    longBreak = longBreak && isCompressed
    shortBreak = shortBreak && isCompressed
}

// Breakout strength = distance beyond range as % of ATR
var breakStrength = 0.0
if (longBreak && atr14 > 0) {
    breakStrength = (close[0] - asiaHigh) / atr14 * 100.0
} else if (shortBreak && atr14 > 0) {
    breakStrength = (asiaLow - close[0]) / atr14 * 100.0
}

var strongBreak = breakStrength > 50.0
var weakBreak = breakStrength > 0 && breakStrength <= 20.0

// -----------------------------------------------------------------------------
// 6. FALSE BREAKOUT & RETEST DETECTION (stateful via static)
// -----------------------------------------------------------------------------
// Track the last breakout direction and whether price re-entered the range.
// Per Bloomfield et al. (2005), liquidity providers may pull orders during
// false breaks, causing rapid reversals.

static lastBreakoutDir = 0   // 1 = long, -1 = short, 0 = none
static breakBarIndex = -1
static breakHigh = 0.0
static breakLow = 0.0

var currentBar = bar_index[0]

if (longBreak) {
    lastBreakoutDir = 1
    breakBarIndex = currentBar
    breakHigh = close[0]
    breakLow = asiaLow
}
if (shortBreak) {
    lastBreakoutDir = -1
    breakBarIndex = currentBar
    breakLow = close[0]
    breakHigh = asiaHigh
}

var barsSinceBreak = currentBar - breakBarIndex
var falseBreakLong = false
var falseBreakShort = false
var retestLong = false
var retestShort = false

if (lastBreakoutDir == 1 && barsSinceBreak > 0 && barsSinceBreak <= 5) {
    // Price re-entered Asia range after long breakout = false break
    falseBreakLong = close[0] < asiaHigh && close[0] > asiaLow
    // Price touched Asia high from above = retest
    retestLong = close[0] >= asiaHigh * 0.998 && close[0] <= asiaHigh * 1.002
}
if (lastBreakoutDir == -1 && barsSinceBreak > 0 && barsSinceBreak <= 5) {
    falseBreakShort = close[0] > asiaLow && close[0] < asiaHigh
    retestShort = close[0] <= asiaLow * 1.002 && close[0] >= asiaLow * 0.998
}

// Reset breakout tracking if we enter a new Asia session
if (inAsia && stillAsia && barsSinceBreak > 5) {
    lastBreakoutDir = 0
    breakBarIndex = -1
}

// -----------------------------------------------------------------------------
// 7. REGIME DETECTION
// -----------------------------------------------------------------------------
// Classify current market regime: trending up, trending down, ranging,
// or breakout. Uses position relative to Asia midpoint and ATR slope.

timeseries atrSlope = atr14[0] - atr14[5]

var regime = "RANGING"
if (close[0] > asiaMid && atrSlope > 0 && isPostAsia) {
    regime = "BULL_BREAK"
} else if (close[0] < asiaMid && atrSlope > 0 && isPostAsia) {
    regime = "BEAR_BREAK"
} else if (close[0] > asiaMid + atr14 * 0.5) {
    regime = "BULL_TREND"
} else if (close[0] < asiaMid - atr14 * 0.5) {
    regime = "BEAR_TREND"
}

var regimeColor = asiaColor
if (regime == "BULL_BREAK" || regime == "BULL_TREND") {
    regimeColor = upColor
} else if (regime == "BEAR_BREAK" || regime == "BEAR_TREND") {
    regimeColor = dnColor
}

// -----------------------------------------------------------------------------
// 8. PLOTTING — Asia Range
// -----------------------------------------------------------------------------

if (showAsiaRange && validAsiaRange) {
    plotLine(
        value=asiaHigh,
        width=1,
        colors=[asiaColor],
        label=["Asia High"],
        desc=["Asian session high (" + asiaStartHour + ":00–" + asiaEndHour + ":00 UTC)"]
    )
    plotLine(
        value=asiaLow,
        width=1,
        colors=[asiaColor],
        label=["Asia Low"],
        desc=["Asian session low (" + asiaStartHour + ":00–" + asiaEndHour + ":00 UTC)"]
    )
}

if (showMidLine && validAsiaRange) {
    plotLine(
        value=asiaMid,
        width=1,
        colors=[transparency(asiaColor, 50)],
        label=["Asia Mid"],
        desc=["Asian session midpoint (accumulation equilibrium)"]
    )
}

if (showAsiaFill && validAsiaRange) {
    plotLine(
        value=[asiaHigh, asiaLow],
        width=1,
        colors=[transparency(asiaColor, 20), transparency(asiaColor, 20)],
        colorIndex=0,
        fill=true,
        label=["Asia High", "Asia Low"],
        desc=["Asian session range fill", "Asian session range fill"]
    )
}

// -----------------------------------------------------------------------------
// 9. PLOTTING — Spring Load Score (offchart)
// -----------------------------------------------------------------------------
if (showSpringLoad) {
    // Spring load compression line
    plotLine(
        value=springLoadSmooth,
        width=2,
        colors=[isCompressed ? upColor : neutralColor],
        label=["Spring Load"],
        desc=["Asia range compression score (higher = more compressed / spring loaded)"]
    )

    // Threshold line
    hline(value=springLoadThreshold, color=transparency(upColor, 50), width=1)
    hline(value=0, color=transparency("#ffffff", 30), width=1)

    // Compression fill
    var compressed = springLoadSmooth >= springLoadThreshold
    plotBar(
        value=springLoadSmooth,
        colors=[transparency(upColor, 60), transparency(dnColor, 10)],
        colorIndex=compressed ? 0 : 1,
        width=1,
        label=["Spring Load Hist"],
        desc=["Spring load histogram — green bars indicate compression above threshold"]
    )
}

// -----------------------------------------------------------------------------
// 10. PLOTTING — Breakout Shapes
// -----------------------------------------------------------------------------
if (showBreakoutShapes) {
    if (longBreak) {
        plotShape(
            value=close,
            shape=strongBreak ? "triangleup" : "arrowup",
            colorIndex=strongBreak ? upColor : transparency(upColor, 60),
            width=strongBreak ? 4 : 3,
            label=[strongBreak ? "Strong Long" : "Long Break"],
            desc=["Long breakout above Asia high (spring load: " + springLoad + ")"]
        )
    }
    if (shortBreak) {
        plotShape(
            value=close,
            shape=strongBreak ? "triangledown" : "arrowdown",
            colorIndex=strongBreak ? dnColor : transparency(dnColor, 60),
            width=strongBreak ? 4 : 3,
            label=[strongBreak ? "Strong Short" : "Short Break"],
            desc=["Short breakout below Asia low (spring load: " + springLoad + ")"]
        )
    }
}

if (showFalseBreakShapes) {
    if (falseBreakLong) {
        plotShape(
            value=close,
            shape="xcross",
            colorIndex=falseBreakColor,
            width=3,
            label=["False Long"],
            desc=["False long breakout — price re-entered Asia range after breaking above"]
        )
    }
    if (falseBreakShort) {
        plotShape(
            value=close,
            shape="xcross",
            colorIndex=falseBreakColor,
            width=3,
            label=["False Short"],
            desc=["False short breakout — price re-entered Asia range after breaking below"]
        )
    }
}

if (showRetestShapes) {
    if (retestLong) {
        plotShape(
            value=close,
            shape="circle",
            colorIndex=retestColor,
            width=2,
            label=["Retest Long"],
            desc=["Asia high retest from above — support confirmation"]
        )
    }
    if (retestShort) {
        plotShape(
            value=close,
            shape="circle",
            colorIndex=retestColor,
            width=2,
            label=["Retest Short"],
            desc=["Asia low retest from below — resistance confirmation"]
        )
    }
}

// -----------------------------------------------------------------------------
// 11. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regime
    var regimeTextColor = regimeColor

    plotTable(
        data=[
            ["Asia Spring Load", regimeText],
            ["Asia High", asiaHigh],
            ["Asia Low", asiaLow],
            ["Asia Range", asiaRange],
            ["Spring Load", springLoad],
            ["Compressed?", isCompressed ? "YES" : "NO"],
            ["ATR(14)", atr14[0]],
            ["Session", inAsia ? "ASIA" : (inLondon ? "LONDON" : (inNY ? "NY" : "OFF"))]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=transparency("#0f172a", 40),
        headerBackgroundColor=transparency("#1e293b", 40),
        borderColor=transparency("#334155", 40),
        borderWidth=1,
        fontSize=10,
        cellPadding=4
    )
}