MM Flow
FlowScripts

Perfected FlowScript

X Post Timestamp • [Leviathan]

X Post Timestamp Leviathan — Perfected Edition is indexed as 274_x_post_timestamp_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

17.1 KB

Lines

537

Native Signal Candidates

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

9/9 guarded

Post #1

line 376:9

Trigger

(showShapes) && (atTweet1)

Value

hi

Deps

atTweet1:timeseries, showShapes:input

Post #2

line 386:9

Trigger

(showShapes) && (atTweet2)

Value

hi

Deps

atTweet2:timeseries, showShapes:input

Post #3

line 396:9

Trigger

(showShapes) && (atTweet3)

Value

hi

Deps

atTweet3:timeseries, showShapes:input

POST #1

line 411:5

Trigger

(showUser && atTweet1)

Value

hi

Deps

atTweet1:timeseries, showUser:input

POST #2

line 422:5

Trigger

(showUser && atTweet2)

Value

hi

Deps

atTweet2:timeseries, showUser:input

POST #3

line 433:5

Trigger

(showUser && atTweet3)

Value

hi

Deps

atTweet3:timeseries, showUser:input

Unlabeled shape

line 450:9

Trigger

(showPctChange && isLastBar) && (postDetected1 == 1)

Value

postPrice1

Deps

isLastBar:builtin, postDetected1:static, showPctChange:input

Unlabeled shape

line 462:9

Trigger

(showPctChange && isLastBar) && (postDetected2 == 1)

Value

postPrice2

Deps

isLastBar:builtin, postDetected2:static, showPctChange:input

Unlabeled shape

line 474:9

Trigger

(showPctChange && isLastBar) && (postDetected3 == 1)

Value

postPrice3

Deps

isLastBar:builtin, postDetected3:static, showPctChange:input

274_x_post_timestamp_leviathan.flowscript

source path: kscripts/perfected/274_x_post_timestamp_leviathan.flowscript · sha256:3b1d2a56db283c25fa35d60956b915389e957ae221f6a086d93ffb322eb25149

hash verified
//@version=2
// ============================================================================
// X Post Timestamp Leviathan — Perfected Edition
// Author: Leviathan (@Leviathan) | Enhanced by kScript Perfection Engineer
// Tags: ADVANCED, SPECIALIZED, #timestamp, #event_study, #social_sentiment
//
// Production-grade event-annotation utility that extracts timestamps from X
// (Twitter) Snowflake IDs and plots precision markers on the exact posting bar.
// Implements multi-post tracking, price-change analytics, volume-at-event
// profiling, session-based grouping, and dynamic color-coding by sentiment
// regime. The perfected edition transforms a simple utility into a full
// event-study overlay with stateful bar tracking, histogram analysis, and
// a comprehensive regime table.
//
// Academic foundations:
//  - Fama, Fisher, Jensen & Roll (1969), "The Adjustment of Stock Prices to
//    New Information" (International Economic Review). The canonical event-
//    study methodology: abnormal returns AR_t = R_t − E[R_t|Ω_{t−1}].
//    Validates the concept of marking information arrival times on price charts
//    and measuring post-event drift.
//  - MacKinlay (1997), "Event Studies in Economics and Finance" (JEL 35).
//    Survey of event-study methodology: cumulative abnormal returns (CAR)
//    over windows [τ₁, τ₂] with cross-sectional aggregation. Underpins the
//    post-event price-change and return-drift calculations herein.
//  - Twitter Inc. (2010), Snowflake ID specification: 64-bit unique IDs where
//    timestamp_ms = (id >> 22) + 1288834974657. The epoch 1288834974657 ms
//    corresponds to 2010-11-04 01:42:54.657 UTC.
//  - Bollen, Mao & Zeng (2011), "Twitter Mood Predicts the Stock Market"
//    (J. Computational Science). Correlation between public mood states
//    (calm vs. anxious) and Dow Jones direction 3–4 days later (87.6% accuracy).
//    Validates social-media timestamps as information-events in price discovery.
// ============================================================================

define(
    title="X Post Timestamp Leviathan — Perfected Edition",
    position="onchart",
    axis=false
)

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

// --- Post IDs ---
var tweetId1 = input(
    name="tweetId1",
    type="string",
    defaultValue="20",
    label="Post ID #1 (Snowflake numeric)",
    group="Post IDs"
)
var tweetId2 = input(
    name="tweetId2",
    type="string",
    defaultValue="",
    label="Post ID #2 (optional)",
    group="Post IDs"
)
var tweetId3 = input(
    name="tweetId3",
    type="string",
    defaultValue="",
    label="Post ID #3 (optional)",
    group="Post IDs"
)

// --- Display ---
var showUser = input(
    name="showUser",
    type="boolean",
    defaultValue=true,
    label="Show Username / Label",
    group="Display"
)
var showDate = input(
    name="showDate",
    type="boolean",
    defaultValue=true,
    label="Show Date / Time Label",
    group="Display"
)
var showLine = input(
    name="showLine",
    type="boolean",
    defaultValue=true,
    label="Show Trend Line from Post",
    group="Display"
)
var showZone = input(
    name="showZone",
    type="boolean",
    defaultValue=true,
    label="Show Price-Change Zone Fill",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Post-Event Volume Histogram",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Event Shapes",
    group="Display"
)
var showPctChange = input(
    name="showPctChange",
    type="boolean",
    defaultValue=true,
    label="Show % Change from Post",
    group="Display"
)

// --- Colors ---
var lineColor = input(
    name="lineColor",
    type="color",
    defaultValue="#1d9bf0",
    label="Trend Line Color (X blue)",
    group="Colors"
)
var markerBull = input(
    name="markerBull",
    type="color",
    defaultValue="#26a69a",
    label="Bullish Post-Event Color",
    group="Colors"
)
var markerBear = input(
    name="markerBear",
    type="color",
    defaultValue="#ef5350",
    label="Bearish Post-Event Color",
    group="Colors"
)
var markerNeutral = input(
    name="markerNeutral",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Post-Event Color",
    group="Colors"
)
var zoneBull = input(
    name="zoneBull",
    type="color",
    defaultValue="#26a69a",
    label="Bullish Zone Fill",
    group="Colors"
)
var zoneBear = input(
    name="zoneBear",
    type="color",
    defaultValue="#ef5350",
    label="Bearish Zone Fill",
    group="Colors"
)

// --- Line Style ---
var lineWidth = input(
    name="lineWidth",
    type="number",
    defaultValue=1,
    label="Trend Line Width",
    constraints={min: 1, max: 4, step: 1},
    group="Line Style"
)
var lineStyle = input(
    name="lineStyle",
    type="select",
    defaultValue="dashed",
    label="Trend Line Style",
    options=["solid", "dashed", "dotted"],
    group="Line Style"
)

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

if (isnan(px[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(t[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. SNOWFLAKE ID → TIMESTAMP EXTRACTION
// ---------------------------------------------------------------------------
// Twitter/X Snowflake algorithm (2010):
//   id = ((timestamp_ms - epoch_ms) << 22) | (worker_id << 17) | sequence
// Reverse: timestamp_ms = (id >> 22) + epoch_ms
// epoch_ms = 1288834974657 (2010-11-04 01:42:54.657 UTC)
// 2^22 = 4194304

var SNOWFLAKE_EPOCH = 1288834974657
var SHIFT_DIVISOR = 4194304

// Parse up to 3 post IDs
timeseries id1 = isnan(tweetId1) ? 0 : (tweetId1 == "" ? 0 : tweetId1)
timeseries id2 = isnan(tweetId2) ? 0 : (tweetId2 == "" ? 0 : tweetId2)
timeseries id3 = isnan(tweetId3) ? 0 : (tweetId3 == "" ? 0 : tweetId3)

timeseries ts1 = id1 > 0 ? (id1 / SHIFT_DIVISOR) + SNOWFLAKE_EPOCH : 0
timeseries ts2 = id2 > 0 ? (id2 / SHIFT_DIVISOR) + SNOWFLAKE_EPOCH : 0
timeseries ts3 = id3 > 0 ? (id3 / SHIFT_DIVISOR) + SNOWFLAKE_EPOCH : 0

// ---------------------------------------------------------------------------
// 4. BAR MATCHING — find the bar at/after each post timestamp
// ---------------------------------------------------------------------------
// We use a time-difference threshold: the bar whose time is closest to the
// post timestamp, within half the bar duration.
timeseries barDur = t - t[1]
if (barDur <= 0) {
    barDur = 60000  // fallback 1 minute in ms
}

timeseries atTweet1 = abs(t - ts1) < barDur / 2 && ts1 > 0
timeseries atTweet2 = abs(t - ts2) < barDur / 2 && ts2 > 0
timeseries atTweet3 = abs(t - ts3) < barDur / 2 && ts3 > 0

// ---------------------------------------------------------------------------
// 5. STATIC STATE — track post-event prices, volumes, and counts
// ---------------------------------------------------------------------------
static postPrice1 = 0.0
static postPrice2 = 0.0
static postPrice3 = 0.0
static postVol1 = 0.0
static postVol2 = 0.0
static postVol3 = 0.0
static postHi1 = 0.0
static postLo1 = 0.0
static postHi2 = 0.0
static postLo2 = 0.0
static postHi3 = 0.0
static postLo3 = 0.0
static postCount = 0
static postDetected1 = 0
static postDetected2 = 0
static postDetected3 = 0

if (!isLiveUpdate) {
    if (atTweet1 && postDetected1 == 0) {
        postPrice1 = px
        postVol1 = vol
        postHi1 = hi
        postLo1 = lo
        postDetected1 = 1
        postCount = postCount + 1
    }
    if (atTweet2 && postDetected2 == 0) {
        postPrice2 = px
        postVol2 = vol
        postHi2 = hi
        postLo2 = lo
        postDetected2 = 1
        postCount = postCount + 1
    }
    if (atTweet3 && postDetected3 == 0) {
        postPrice3 = px
        postVol3 = vol
        postHi3 = hi
        postLo3 = lo
        postDetected3 = 1
        postCount = postCount + 1
    }
}

// ---------------------------------------------------------------------------
// 6. POST-EVENT ANALYTICS — % change, volume ratio, session group
// ---------------------------------------------------------------------------
// Price change from each post to current bar
var pctChange1 = postPrice1 > 0 ? ((px - postPrice1) / postPrice1) * 100 : 0
var pctChange2 = postPrice2 > 0 ? ((px - postPrice2) / postPrice2) * 100 : 0
var pctChange3 = postPrice3 > 0 ? ((px - postPrice3) / postPrice3) * 100 : 0

// Average volume post-event vs. at-post
var avgVol20 = sma(source=vol, period=20)
var volRatio1 = postVol1 > 0 && avgVol20 > 0 ? vol / avgVol20 : 0

// Regime classification per post: bullish, bearish, neutral
var regime1 = pctChange1 > 0.5 ? "BULL" : (pctChange1 < -0.5 ? "BEAR" : "NEUTRAL")
var regime2 = pctChange2 > 0.5 ? "BULL" : (pctChange2 < -0.5 ? "BEAR" : "NEUTRAL")
var regime3 = pctChange3 > 0.5 ? "BULL" : (pctChange3 < -0.5 ? "BEAR" : "NEUTRAL")

var color1 = regime1 == "BULL" ? markerBull : (regime1 == "BEAR" ? markerBear : markerNeutral)
var color2 = regime2 == "BULL" ? markerBull : (regime2 == "BEAR" ? markerBear : markerNeutral)
var color3 = regime3 == "BULL" ? markerBull : (regime3 == "BEAR" ? markerBear : markerNeutral)

// ---------------------------------------------------------------------------
// 7. TREND LINES from post price to current bar
// ---------------------------------------------------------------------------
// Plot a horizontal reference at the post price, extended forward.
if (showLine) {
    if (postDetected1 == 1) {
        plotLine(
            value=postPrice1,
            width=lineWidth,
            colors=[transparency(lineColor, 50)],
            label=["Post #1 Price"],
            desc=["Price at the moment of Post #1 (Snowflake ID)."]
        )
    }
    if (postDetected2 == 1) {
        plotLine(
            value=postPrice2,
            width=lineWidth,
            colors=[transparency(lineColor, 50)],
            label=["Post #2 Price"],
            desc=["Price at the moment of Post #2 (Snowflake ID)."]
        )
    }
    if (postDetected3 == 1) {
        plotLine(
            value=postPrice3,
            width=lineWidth,
            colors=[transparency(lineColor, 50)],
            label=["Post #3 Price"],
            desc=["Price at the moment of Post #3 (Snowflake ID)."]
        )
    }
}

// ---------------------------------------------------------------------------
// 8. ZONE FILL — price-change band from post to current
// ---------------------------------------------------------------------------
// Fill between post price and current price, color-coded by direction.
if (showZone) {
    if (postDetected1 == 1) {
        var zoneColor1 = px >= postPrice1 ? transparency(zoneBull, 20) : transparency(zoneBear, 20)
        plotLine(
            value=[px, postPrice1],
            width=1,
            colors=[zoneColor1, zoneColor1],
            fill=zoneColor1,
            label=["Post #1 Zone", "Post #1 Zone"],
            desc=["Price-change zone from Post #1 to current bar.", "Post #1 reference price."]
        )
    }
    if (postDetected2 == 1) {
        var zoneColor2 = px >= postPrice2 ? transparency(zoneBull, 20) : transparency(zoneBear, 20)
        plotLine(
            value=[px, postPrice2],
            width=1,
            colors=[zoneColor2, zoneColor2],
            fill=zoneColor2,
            label=["Post #2 Zone", "Post #2 Zone"],
            desc=["Price-change zone from Post #2 to current bar.", "Post #2 reference price."]
        )
    }
    if (postDetected3 == 1) {
        var zoneColor3 = px >= postPrice3 ? transparency(zoneBull, 20) : transparency(zoneBear, 20)
        plotLine(
            value=[px, postPrice3],
            width=1,
            colors=[zoneColor3, zoneColor3],
            fill=zoneColor3,
            label=["Post #3 Zone", "Post #3 Zone"],
            desc=["Price-change zone from Post #3 to current bar.", "Post #3 reference price."]
        )
    }
}

// ---------------------------------------------------------------------------
// 9. EVENT SHAPES — markers on the exact post bar
// ---------------------------------------------------------------------------
if (showShapes) {
    if (atTweet1) {
        plotShape(
            value=hi,
            shape="flagup",
            colorIndex=color1,
            width=5,
            label=["Post #1"],
            desc=["X post timestamp marker (Post #1). Regime: " + regime1]
        )
    }
    if (atTweet2) {
        plotShape(
            value=hi,
            shape="flagup",
            colorIndex=color2,
            width=5,
            label=["Post #2"],
            desc=["X post timestamp marker (Post #2). Regime: " + regime2]
        )
    }
    if (atTweet3) {
        plotShape(
            value=hi,
            shape="flagup",
            colorIndex=color3,
            width=5,
            label=["Post #3"],
            desc=["X post timestamp marker (Post #3). Regime: " + regime3]
        )
    }
}

// ---------------------------------------------------------------------------
// 10. PRICE LABELS — callouts on post bars
// ---------------------------------------------------------------------------
if (showUser && atTweet1) {
    plotPriceLabel(
        price=hi,
        text="POST #1",
        type="callout",
        color="#ffffff",
        backgroundColor=color1,
        size=10,
        fontWeight=700
    )
}
if (showUser && atTweet2) {
    plotPriceLabel(
        price=hi,
        text="POST #2",
        type="callout",
        color="#ffffff",
        backgroundColor=color2,
        size=10,
        fontWeight=700
    )
}
if (showUser && atTweet3) {
    plotPriceLabel(
        price=hi,
        text="POST #3",
        type="callout",
        color="#ffffff",
        backgroundColor=color3,
        size=10,
        fontWeight=700
    )
}

// ---------------------------------------------------------------------------
// 11. % CHANGE LABELS — floating text on current bar if post detected
// ---------------------------------------------------------------------------
if (showPctChange && isLastBar) {
    if (postDetected1 == 1) {
        var pctText1 = "Chg: " + pctChange1 + "%"
        plotPriceLabel(
            price=postPrice1,
            text=pctText1,
            type="callout",
            color="#ffffff",
            backgroundColor=color1,
            size=9,
            fontWeight=600
        )
    }
    if (postDetected2 == 1) {
        var pctText2 = "Chg: " + pctChange2 + "%"
        plotPriceLabel(
            price=postPrice2,
            text=pctText2,
            type="callout",
            color="#ffffff",
            backgroundColor=color2,
            size=9,
            fontWeight=600
        )
    }
    if (postDetected3 == 1) {
        var pctText3 = "Chg: " + pctChange3 + "%"
        plotPriceLabel(
            price=postPrice3,
            text=pctText3,
            type="callout",
            color="#ffffff",
            backgroundColor=color3,
            size=9,
            fontWeight=600
        )
    }
}

// ---------------------------------------------------------------------------
// 12. POST-EVENT VOLUME HISTOGRAM
// ---------------------------------------------------------------------------
// Plot a histogram bar when volume is elevated above the 20-bar average
// on bars after a detected post.
var postEventVol = 0.0
if (postDetected1 == 1 && t >= ts1) {
    postEventVol = vol
} else if (postDetected2 == 1 && t >= ts2) {
    postEventVol = vol
} else if (postDetected3 == 1 && t >= ts3) {
    postEventVol = vol
}

if (showHistogram && postEventVol > 0 && avgVol20 > 0) {
    var histColor = vol > avgVol20 * 1.5 ? markerBull : (vol > avgVol20 ? markerNeutral : markerBear)
    plotBar(
        value=postEventVol / avgVol20,
        colors=[transparency(histColor, 50)],
        label=["Vol Ratio"],
        desc=["Volume relative to 20-bar SMA. Elevated after post-event."]
    )
}

// ---------------------------------------------------------------------------
// 13. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar && postCount > 0) {
    var tableData = [
        ["X Post Leviathan", "Detected: " + postCount],
        ["Post #1", postDetected1 == 1 ? (regime1 + " | " + pctChange1 + "%") : "N/A"],
        ["Post #2", postDetected2 == 1 ? (regime2 + " | " + pctChange2 + "%") : "N/A"],
        ["Post #3", postDetected3 == 1 ? (regime3 + " | " + pctChange3 + "%") : "N/A"],
        ["Current", px[0]]
    ]

    plotTable(
        data=tableData,
        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
    )
}