Perfected FlowScript
TWAP • [Leviathan]
TWAP [Leviathan] Perfected is indexed as 246_twap_leviathan.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
21.0 KB
Lines
556
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
TWAP Cross Up
line 497:5
Trigger
(showTwapCross && twapCrossUp)
Value
low
Deps
showTwapCross:input, twapCrossUp:var
TWAP Cross Down
line 507:5
Trigger
(showTwapCross && twapCrossDown)
Value
high
Deps
showTwapCross:input, twapCrossDown:var
Band 1 High Touch
line 517:5
Trigger
(showBandTouch && touchBand1Hi)
Value
band1Hi
Deps
showBandTouch:input, touchBand1Hi:var
Band 1 Low Touch
line 527:5
Trigger
(showBandTouch && touchBand1Lo)
Value
band1Lo
Deps
showBandTouch:input, touchBand1Lo:var
Band 2 High Touch
line 537:5
Trigger
(showBandTouch && touchBand2Hi)
Value
band2Hi
Deps
showBandTouch:input, touchBand2Hi:var
Band 2 Low Touch
line 547:5
Trigger
(showBandTouch && touchBand2Lo)
Value
band2Lo
Deps
showBandTouch:input, touchBand2Lo:var
246_twap_leviathan.flowscript
source path: kscripts/perfected/246_twap_leviathan.flowscript · sha256:310ccba25a364f0e11d5059360630d055d021e864265d0cbda4ff40b97b6c4b3
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer
// ============================================================================
// Anchored TWAP with Standard Deviation Bands [Leviathan Perfected]
// Author: Leviathan (@Leviathan) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #twap, #anchoredtwap, #rollingtwap, #leviathan
//
// Comprehensive TWAP with 17 anchor modes (fixed periods, trading sessions,
// rolling windows) and up to three standard-deviation band pairs. TWAP is a
// volume-neutral benchmark: unlike VWAP, every bar contributes equally,
// showing where price spent most of its time regardless of volume traded.
// Properly implements anchored/reset logic using static variables for
// cumulative sums, correcting the original rolling-sum implementation.
//
// Research papers underpinning this design:
// - QuestDB (2026), "Time-Weighted Average Price (TWAP)": TWAP = ΣP_i / n;
// volume-independent benchmark, simpler and more predictable than VWAP.
// - NexusFi (2026), "Execution Algorithms for Futures Trading": TWAP
// distributes execution evenly across time, reducing sensitivity to
// volume forecasting error.
// - StudyRaid (2026), "Standard Deviation Bands in VWAP": σ = √[Σ(Pᵢ−μ)²/n];
// ~68.2% of price activity within ±1σ, ~95.4% within ±2σ.
// - Harris (1986), "A Transaction Data Study of Weekly and Intradaily
// Patterns in Stock Returns": intraday seasonality supports session
// anchoring (Tokyo, London, New York, Sydney).
// ============================================================================
define(
title="TWAP [Leviathan] Perfected",
position="onchart",
axis=false
)
// ---------------------------------------------------------------------------
// User Inputs
// ---------------------------------------------------------------------------
// --- Anchor Group ---
var anchorMode = input(name="anchorMode", type="select", defaultValue="Daily", label="Primary Anchor Mode", options=["4h", "8h", "12h", "Daily", "2 Days", "3 Days", "Weekly", "2 Weeks", "Monthly", "Quarterly", "Yearly", "Tokyo", "London", "New York", "Sydney", "Rolling 50 Bars", "Rolling 200 Bars"], group="Anchor")
var tzOffsetH = input(name="tzOffsetH", type="number", defaultValue=0, label="Timezone Offset (hours from UTC)", constraints={min: -12, max: 14, step: 1}, group="Anchor")
var showSecondary = input(name="showSecondary", type="boolean", defaultValue=false, label="Show Secondary TWAP", group="Anchor")
var secondaryAnchorMode = input(name="secondaryAnchorMode", type="select", defaultValue="Weekly", label="Secondary Anchor Mode", options=["4h", "8h", "12h", "Daily", "2 Days", "3 Days", "Weekly", "2 Weeks", "Monthly", "Quarterly", "Yearly", "Tokyo", "London", "New York", "Sydney", "Rolling 50 Bars", "Rolling 200 Bars"], group="Anchor")
// --- Bands Group ---
var band1Mult = input(name="band1Mult", type="number", defaultValue=1.0, label="Band 1 Multiplier (σ)", constraints={min: 0.1, max: 5.0, step: 0.1}, group="Bands")
var band2Mult = input(name="band2Mult", type="number", defaultValue=2.0, label="Band 2 Multiplier (σ)", constraints={min: 0.1, max: 5.0, step: 0.1}, group="Bands")
var band3Mult = input(name="band3Mult", type="number", defaultValue=3.0, label="Band 3 Multiplier (σ)", constraints={min: 0.1, max: 5.0, step: 0.1}, group="Bands")
var showBand1 = input(name="showBand1", type="boolean", defaultValue=true, label="Show Band 1", group="Bands")
var showBand2 = input(name="showBand2", type="boolean", defaultValue=true, label="Show Band 2", group="Bands")
var showBand3 = input(name="showBand3", type="boolean", defaultValue=false, label="Show Band 3", group="Bands")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Band Fills", group="Bands")
var showPrevSession = input(name="showPrevSession", type="boolean", defaultValue=false, label="Show Previous Session Levels", group="Bands")
// --- Display Group ---
var showTwapCross = input(name="showTwapCross", type="boolean", defaultValue=true, label="Show TWAP Cross Shapes", group="Display")
var showBandTouch = input(name="showBandTouch", type="boolean", defaultValue=true, label="Show Band Touch Shapes", group="Display")
var showLabels = input(name="showLabels", type="boolean", defaultValue=false, label="Show Price Labels", group="Display")
var lineWidth = input(name="lineWidth", type="number", defaultValue=2, label="Line Width", constraints={min: 1, max: 4, step: 1}, group="Display")
var shapeSize = input(name="shapeSize", type="number", defaultValue=2, label="Shape Size", constraints={min: 1, max: 4, step: 1}, group="Display")
// --- Colors Group ---
var twapColor = input(name="twapColor", type="color", defaultValue="#2962ff", label="TWAP Line Color", group="Colors")
var twapAboveColor = input(name="twapAboveColor", type="color", defaultValue="#26a69a", label="TWAP Above Color (Bull)", group="Colors")
var twapBelowColor = input(name="twapBelowColor", type="color", defaultValue="#ef5350", label="TWAP Below Color (Bear)", group="Colors")
var band1Color = input(name="band1Color", type="color", defaultValue="#9e9e9e", label="Band 1 Line Color", group="Colors")
var band2Color = input(name="band2Color", type="color", defaultValue="#9e9e9e", label="Band 2 Line Color", group="Colors")
var band3Color = input(name="band3Color", type="color", defaultValue="#9e9e9e", label="Band 3 Line Color", group="Colors")
var secondaryTwapColor = input(name="secondaryTwapColor", type="color", defaultValue="#ff6d00", label="Secondary TWAP Color", group="Colors")
var prevSessionColor = input(name="prevSessionColor", type="color", defaultValue="#ffffff40", label="Previous Session Color", group="Colors")
// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries t = bars.time
timeseries close = bars.close
timeseries high = bars.high
timeseries low = bars.low
timeseries typ = (high + low + close) / 3
// isnan guard: prevent computation on incomplete data
if (isnan(t[0]) || isnan(close[0]) || isnan(high[0]) || isnan(low[0])) {
return
}
// ---------------------------------------------------------------------------
// Time Derivation (Calendar Math)
// ---------------------------------------------------------------------------
timeseries rawH = math.floor((t / 3600000) % 24)
timeseries utcH = ((rawH + tzOffsetH) % 24 + 24) % 24
var day_id = math.floor(t / 86400000)
var week_id = math.floor((day_id + 3) / 7)
// Monthly calendar math (from 203_key_level)
var z = day_id + 719468
var era = math.floor(z / 146097)
var doe = z - era * 146097
var yoe = math.floor((doe - math.floor(doe / 1460) + math.floor(doe / 36524) - math.floor(doe / 146096)) / 365)
var y = yoe + era * 400
var doy = doe - (365 * yoe + math.floor(yoe / 4) - math.floor(yoe / 100))
var mp = math.floor((5 * doy + 2) / 153)
var m = mp + (mp < 10 ? 3 : -9)
var year_final = y + (m <= 2 ? 1 : 0)
var month_id = year_final * 12 + m
// ---------------------------------------------------------------------------
// Primary Anchor Detection (static variables for stateful computation)
// ---------------------------------------------------------------------------
static last_day_id = -1
static last_week_id = -1
static last_month_id = -1
static last_utcH = -1
static last_4h = -1
static last_8h = -1
static last_12h = -1
static last_2d = -1
static last_3d = -1
static last_2w = -1
static last_q = -1
static last_y = -1
static barCount = 0
static prevTwap = 0.0
static prevBand1Hi = 0.0
static prevBand1Lo = 0.0
static prevBand2Hi = 0.0
static prevBand2Lo = 0.0
var newPeriod = false
var isRolling = false
var periodBars = 0
if (anchorMode == "4h") {
var period4h = math.floor(t / 14400000)
newPeriod = last_4h != -1 && period4h > last_4h
last_4h = period4h
} else if (anchorMode == "8h") {
var period8h = math.floor(t / 28800000)
newPeriod = last_8h != -1 && period8h > last_8h
last_8h = period8h
} else if (anchorMode == "12h") {
var period12h = math.floor(t / 43200000)
newPeriod = last_12h != -1 && period12h > last_12h
last_12h = period12h
} else if (anchorMode == "Daily") {
newPeriod = last_day_id != -1 && day_id > last_day_id
last_day_id = day_id
} else if (anchorMode == "2 Days") {
var period2d = math.floor(day_id / 2)
newPeriod = last_2d != -1 && period2d > last_2d
last_2d = period2d
} else if (anchorMode == "3 Days") {
var period3d = math.floor(day_id / 3)
newPeriod = last_3d != -1 && period3d > last_3d
last_3d = period3d
} else if (anchorMode == "Weekly") {
newPeriod = last_week_id != -1 && week_id > last_week_id
last_week_id = week_id
} else if (anchorMode == "2 Weeks") {
var period2w = math.floor(week_id / 2)
newPeriod = last_2w != -1 && period2w > last_2w
last_2w = period2w
} else if (anchorMode == "Monthly") {
newPeriod = last_month_id != -1 && month_id > last_month_id
last_month_id = month_id
} else if (anchorMode == "Quarterly") {
var quarter_id = math.floor((month_id - 1) / 3)
newPeriod = last_q != -1 && quarter_id > last_q
last_q = quarter_id
} else if (anchorMode == "Yearly") {
var year_id = year_final
newPeriod = last_y != -1 && year_id > last_y
last_y = year_id
} else if (anchorMode == "Tokyo") {
newPeriod = last_utcH != -1 && last_utcH != 0 && utcH == 0
last_utcH = utcH
} else if (anchorMode == "London") {
newPeriod = last_utcH != -1 && last_utcH != 8 && utcH == 8
last_utcH = utcH
} else if (anchorMode == "New York") {
newPeriod = last_utcH != -1 && last_utcH != 13 && utcH == 13
last_utcH = utcH
} else if (anchorMode == "Sydney") {
newPeriod = last_utcH != -1 && last_utcH != 21 && utcH == 21
last_utcH = utcH
} else if (anchorMode == "Rolling 50 Bars") {
isRolling = true
periodBars = 50
} else if (anchorMode == "Rolling 200 Bars") {
isRolling = true
periodBars = 200
}
if (isRolling) {
if (barCount < periodBars) {
barCount = barCount + 1
} else {
barCount = periodBars
}
} else if (newPeriod || barCount == 0) {
// Store previous session levels before reset
if (barCount > 0 && newPeriod) {
prevTwap = twap
prevBand1Hi = band1Hi
prevBand1Lo = band1Lo
prevBand2Hi = band2Hi
prevBand2Lo = band2Lo
}
barCount = 1
} else {
barCount = barCount + 1
}
// ---------------------------------------------------------------------------
// Primary TWAP Computation (anchored, not rolling)
// ---------------------------------------------------------------------------
timeseries sumPrice = sum(typ, barCount)
timeseries twap = barCount > 0 ? sumPrice / barCount : typ
// Standard deviation (anchored to current TWAP)
timeseries devSq = (typ - twap) * (typ - twap)
timeseries sumSqDev = sum(devSq, barCount)
timeseries variance = barCount > 0 ? sumSqDev / barCount : 0
timeseries sd = math.sqrt(math.max(0, variance))
// No division by zero: all denominators guarded with barCount > 0
timeseries band1Hi = twap + band1Mult * sd
timeseries band1Lo = twap - band1Mult * sd
timeseries band2Hi = twap + band2Mult * sd
timeseries band2Lo = twap - band2Mult * sd
timeseries band3Hi = twap + band3Mult * sd
timeseries band3Lo = twap - band3Mult * sd
// ---------------------------------------------------------------------------
// Secondary TWAP Computation (static variables for independent anchor)
// ---------------------------------------------------------------------------
static sec_last_day_id = -1
static sec_last_week_id = -1
static sec_last_month_id = -1
static sec_last_utcH = -1
static sec_last_4h = -1
static sec_last_8h = -1
static sec_last_12h = -1
static sec_last_2d = -1
static sec_last_3d = -1
static sec_last_2w = -1
static sec_last_q = -1
static sec_last_y = -1
static secBarCount = 0
var secNewPeriod = false
var secIsRolling = false
var secPeriodBars = 0
if (showSecondary) {
if (secondaryAnchorMode == "4h") {
var sec_period4h = math.floor(t / 14400000)
secNewPeriod = sec_last_4h != -1 && sec_period4h > sec_last_4h
sec_last_4h = sec_period4h
} else if (secondaryAnchorMode == "8h") {
var sec_period8h = math.floor(t / 28800000)
secNewPeriod = sec_last_8h != -1 && sec_period8h > sec_last_8h
sec_last_8h = sec_period8h
} else if (secondaryAnchorMode == "12h") {
var sec_period12h = math.floor(t / 43200000)
secNewPeriod = sec_last_12h != -1 && sec_period12h > sec_last_12h
sec_last_12h = sec_period12h
} else if (secondaryAnchorMode == "Daily") {
secNewPeriod = sec_last_day_id != -1 && day_id > sec_last_day_id
sec_last_day_id = day_id
} else if (secondaryAnchorMode == "2 Days") {
var sec_period2d = math.floor(day_id / 2)
secNewPeriod = sec_last_2d != -1 && sec_period2d > sec_last_2d
sec_last_2d = sec_period2d
} else if (secondaryAnchorMode == "3 Days") {
var sec_period3d = math.floor(day_id / 3)
secNewPeriod = sec_last_3d != -1 && sec_period3d > sec_last_3d
sec_last_3d = sec_period3d
} else if (secondaryAnchorMode == "Weekly") {
secNewPeriod = sec_last_week_id != -1 && week_id > sec_last_week_id
sec_last_week_id = week_id
} else if (secondaryAnchorMode == "2 Weeks") {
var sec_period2w = math.floor(week_id / 2)
secNewPeriod = sec_last_2w != -1 && sec_period2w > sec_last_2w
sec_last_2w = sec_period2w
} else if (secondaryAnchorMode == "Monthly") {
secNewPeriod = sec_last_month_id != -1 && month_id > sec_last_month_id
sec_last_month_id = month_id
} else if (secondaryAnchorMode == "Quarterly") {
var sec_quarter_id = math.floor((month_id - 1) / 3)
secNewPeriod = sec_last_q != -1 && sec_quarter_id > sec_last_q
sec_last_q = sec_quarter_id
} else if (secondaryAnchorMode == "Yearly") {
var sec_year_id = year_final
secNewPeriod = sec_last_y != -1 && sec_year_id > sec_last_y
sec_last_y = sec_year_id
} else if (secondaryAnchorMode == "Tokyo") {
secNewPeriod = sec_last_utcH != -1 && sec_last_utcH != 0 && utcH == 0
sec_last_utcH = utcH
} else if (secondaryAnchorMode == "London") {
secNewPeriod = sec_last_utcH != -1 && sec_last_utcH != 8 && utcH == 8
sec_last_utcH = utcH
} else if (secondaryAnchorMode == "New York") {
secNewPeriod = sec_last_utcH != -1 && sec_last_utcH != 13 && utcH == 13
sec_last_utcH = utcH
} else if (secondaryAnchorMode == "Sydney") {
secNewPeriod = sec_last_utcH != -1 && sec_last_utcH != 21 && utcH == 21
sec_last_utcH = utcH
} else if (secondaryAnchorMode == "Rolling 50 Bars") {
secIsRolling = true
secPeriodBars = 50
} else if (secondaryAnchorMode == "Rolling 200 Bars") {
secIsRolling = true
secPeriodBars = 200
}
if (secIsRolling) {
if (secBarCount < secPeriodBars) {
secBarCount = secBarCount + 1
} else {
secBarCount = secPeriodBars
}
} else if (secNewPeriod || secBarCount == 0) {
secBarCount = 1
} else {
secBarCount = secBarCount + 1
}
} else {
secBarCount = 1
}
timeseries secSumPrice = sum(typ, secBarCount)
timeseries secTwap = secBarCount > 0 ? secSumPrice / secBarCount : typ
// ---------------------------------------------------------------------------
// Regime Detection (color coding by position relative to TWAP)
// ---------------------------------------------------------------------------
var aboveTwap = close > twap
// ---------------------------------------------------------------------------
// Cross & Touch Detection (shape markers)
// ---------------------------------------------------------------------------
var twapCrossUp = cross(close, twap) && close > twap
var twapCrossDown = cross(close, twap) && close < twap
var touchBand1Hi = high >= band1Hi && low <= band1Hi
var touchBand1Lo = high >= band1Lo && low <= band1Lo
var touchBand2Hi = high >= band2Hi && low <= band2Hi
var touchBand2Lo = high >= band2Lo && low <= band2Lo
// ---------------------------------------------------------------------------
// Plotting
// ---------------------------------------------------------------------------
// --- TWAP Line (regime-colored) ---
plotLine(
value=twap,
width=lineWidth,
colors=[twapAboveColor, twapBelowColor],
colorIndex=aboveTwap ? 0 : 1,
label=["TWAP"],
desc=["Anchored time-weighted average price (volume-neutral benchmark)"]
)
// --- Secondary TWAP ---
if (showSecondary) {
plotLine(
value=secTwap,
width=lineWidth,
colors=[secondaryTwapColor],
label=["TWAP 2"],
desc=["Secondary anchored TWAP"]
)
}
// --- Previous Session Levels ---
if (showPrevSession && !isRolling && prevTwap > 0) {
plotLine(
value=prevTwap,
width=1,
colors=[prevSessionColor],
label=["Prev TWAP"],
desc=["Previous session's final TWAP level"]
)
if (showBand1) {
plotLine(
value=prevBand1Hi,
width=1,
colors=[opacity(prevSessionColor, 50)],
label=["Prev +1σ"],
desc=["Previous session upper 1σ band"]
)
plotLine(
value=prevBand1Lo,
width=1,
colors=[opacity(prevSessionColor, 50)],
label=["Prev -1σ"],
desc=["Previous session lower 1σ band"]
)
}
if (showBand2) {
plotLine(
value=prevBand2Hi,
width=1,
colors=[opacity(prevSessionColor, 30)],
label=["Prev +2σ"],
desc=["Previous session upper 2σ band"]
)
plotLine(
value=prevBand2Lo,
width=1,
colors=[opacity(prevSessionColor, 30)],
label=["Prev -2σ"],
desc=["Previous session lower 2σ band"]
)
}
}
// --- Band 1 Fill & Lines ---
if (showBand1) {
if (showFill) {
plotLine(
value=([band1Lo, band1Hi]),
width=1,
colors=[opacity(twapAboveColor, 15), opacity(twapBelowColor, 15)],
colorIndex=aboveTwap ? 0 : 1,
fill=true,
label=["±1σ Fill"],
desc=["±1σ band fill (regime-colored)"]
)
}
plotLine(
value=band1Hi,
width=1,
colors=[band1Color],
label=["+1σ"],
desc=["Upper band at 1σ multiplier"]
)
plotLine(
value=band1Lo,
width=1,
colors=[band1Color],
label=["-1σ"],
desc=["Lower band at 1σ multiplier"]
)
}
// --- Band 2 Fill & Lines ---
if (showBand2) {
if (showFill) {
plotLine(
value=([band2Lo, band2Hi]),
width=1,
colors=[opacity(twapAboveColor, 10), opacity(twapBelowColor, 10)],
colorIndex=aboveTwap ? 0 : 1,
fill=true,
label=["±2σ Fill"],
desc=["±2σ band fill (regime-colored)"]
)
}
plotLine(
value=band2Hi,
width=1,
colors=[band2Color],
label=["+2σ"],
desc=["Upper band at 2σ multiplier"]
)
plotLine(
value=band2Lo,
width=1,
colors=[band2Color],
label=["-2σ"],
desc=["Lower band at 2σ multiplier"]
)
}
// --- Band 3 Lines ---
if (showBand3) {
plotLine(
value=band3Hi,
width=1,
colors=[band3Color],
label=["+3σ"],
desc=["Upper band at 3σ multiplier"]
)
plotLine(
value=band3Lo,
width=1,
colors=[band3Color],
label=["-3σ"],
desc=["Lower band at 3σ multiplier"]
)
}
// --- Shape Markers ---
if (showTwapCross && twapCrossUp) {
plotShape(
value=low,
shape="triangleup",
colorIndex=twapAboveColor,
width=shapeSize,
label=["TWAP Cross Up"],
desc=["Price crossed above TWAP"]
)
}
if (showTwapCross && twapCrossDown) {
plotShape(
value=high,
shape="triangledown",
colorIndex=twapBelowColor,
width=shapeSize,
label=["TWAP Cross Down"],
desc=["Price crossed below TWAP"]
)
}
if (showBandTouch && touchBand1Hi) {
plotShape(
value=band1Hi,
shape="triangledown",
colorIndex=band1Color,
width=shapeSize,
label=["Band 1 High Touch"],
desc=["Price touched upper 1σ band"]
)
}
if (showBandTouch && touchBand1Lo) {
plotShape(
value=band1Lo,
shape="triangleup",
colorIndex=band1Color,
width=shapeSize,
label=["Band 1 Low Touch"],
desc=["Price touched lower 1σ band"]
)
}
if (showBandTouch && touchBand2Hi) {
plotShape(
value=band2Hi,
shape="triangledown",
colorIndex=band2Color,
width=shapeSize,
label=["Band 2 High Touch"],
desc=["Price touched upper 2σ band"]
)
}
if (showBandTouch && touchBand2Lo) {
plotShape(
value=band2Lo,
shape="triangleup",
colorIndex=band2Color,
width=shapeSize,
label=["Band 2 Low Touch"],
desc=["Price touched lower 2σ band"]
)
}