TEStructure PivotSwings Clusters RowProfile

TradersEdgeUSA · library · 825 行 · 点赞 2 · TradingView 原页

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

Pine Script

//@version=6
// This source code is subject to the terms of the TRADERS EDGE USA license. Published on TradingView as an open-source library: you may import it,
// and reuse or adapt its code in your own open-source scripts, with credit to TRADERS EDGE USA; reuse in closed-source (protected or invite-only) scripts requires our permission.
// TE STRUCTURE — PIVOT SWINGS, WEIGHTED 1-D CLUSTERING, PRIOR-SESSION AND DAILY EXTREMES, TRADING-DATE AND WEEK KEYS,
// STRICT SWINGS, A ROW-DEPOSIT VOLUME PROFILE, AN ATR DISTANCE AND AN EMA/ATR STEPPER, AS AN IMPORTABLE LIBRARY
//
// WHAT IT IS: a Pine library of TEXTBOOK PRICE-STRUCTURE MATHS. It carries no trading rule of any kind: no entry, no
// exit, no score, no ordering of levels by importance and no level-selection logic. Pivot widths, the clustering
// tolerance and weights, the session clock and time zone, the skipped weekdays, the profile row size and window, the ATR
// multiple, and the tag codes written next to each price are ARGUMENTS. The fixed constants are the ones the name of each function states (4 bars each side, 2 bars each
// side, EMA 20 and 50, ATR 14, rings of 6 and 20, a 20-bar ATR and a 5-bar daily range) and runtime guards (10 calendar
// steps), all stated below.
//
// ── THE EXPORTS ─────────────────────────────────────────────────────────────────────────────────
// swings     pivotSwingsInto · strictPivot4At · strictSwing2Prices
// clusters   weightedClusters
// sessions   sessionExtremesInto · dailyLevelsInto
// calendar   prevTradingDate · weekMondayOf · weeklyHighLow
// distance   atrBuffer
// profile    rowDepositProfile
// stepper    RegState (type) · regStateNew · regStep
//
// ── THE MATHS, STATED ONCE ──────────────────────────────────────────────────────────────────────
// PIVOT      bar i is a pivot LOW when no bar in [i − left, i + right] has a lower low AND at least one other bar in it has
//            a higher low (so equal lows inside the window are allowed, but a completely flat window is not a pivot);
//            a pivot HIGH is the mirror. The low is written before the high for the same bar. Each price is written with
//            its type code and the label code lowL (or highL) + pack × (ts[i] + dur), the end time of the pivot's bar.
// STRICT     strictPivot4At: the value at p is strictly below (side 1, lows) or strictly above (side −1, highs) each of
//            the 4 values on either side. strictSwing2Prices: every strict 2-and-2 swing low and high over the last lb
//            values; an na anywhere in the five values kills that swing. Worked example: lows 5, 4, 3, 4, 5 with highs
//            9, 9, 8, 9, 9 → one swing low, 3 (the high 8 is a minimum, not a maximum).
// CLUSTER    sort the prices ascending (a stable insertion sort, so equal prices keep their input order), then walk them:
//            a price within tol of the LAST zone's current price joins it, otherwise it starts a new zone. A zone's price
//            is its first member's price until a second member joins, then Σ(p × w) / Σ w over its members, w looked up
//            by each member's type code in the caller's weight array. Worked example: prices 100, 100.4, 101, weights
//            1, 1, 2, tol 0.5 → zone 1 = (100 + 100.4) / 2 = 100.2; 101 is 0.8 from it → zone 2 = 101.
// SESSIONS   sessionExtremesInto keys each bar to a trading date (its date in tz after adding rollMs) and calls it
//            regular-session when its minute of day in tz is in [rthOpen, rthClose) (and, when asked, the date is not in
//            TE Math's CME holiday table). It writes the low and high of the newest two COMPLETED regular sessions and of
//            the newest two out-of-session periods; today's session counts once the last bar's minute is in
//            [rthClose, rollMin). The defaults are an 18:00 New York date roll and a 09:30-16:00 New York session.
//            dailyLevelsInto writes daily pivots (pivotSwingsInto) and the low and high of the last five daily bars.
// DISTANCE   atrBuffer = max(tick, roundToTick(mult × mean of the last 20 true ranges)), 4 ticks when fewer than 21 bars.
//            Worked example: 20 true ranges averaging 7.10, mult 0.3, tick 0.25 → 2.13 → 2.25.
// CALENDAR   dates are yyyymmdd integers. prevTradingDate steps back one calendar day at a time (up to 10) past the two
//            skipped weekdays and, when asked, TE Math's CME holiday table. weekMondayOf returns the Monday of the
//            date's week. weeklyHighLow folds daily rows into one high/low per Monday-keyed week, leaving out the
//            week of `key`; a row with an na high makes its own week na and no other.
// PROFILE    over the last `lookback` rows: row index r = floor(price / rowH); each row's volume is spread EVENLY over
//            the price rows from floor(low / rowH) to floor(high / rowH), and a second array receives the same share
//            times the close location (close − low) / (high − low) (TE Math's closeLocation, 0.5 on a zero-range row).
//            Worked example: rowH 1, one row high 102.5, low 100.2, close 102, volume 300 → rows 100, 101, 102 get 100
//            each and the second array gets 100 × 1.8 / 2.3 ≈ 78.26 each.
// STEPPER    per completed bucket: true range through TE Math (high − low on the first bucket), EMA 20 and EMA 50
//            (α = 2 / 21 and 2 / 51, seeded with the first close), Wilder ATR 14 through TE Math's Atr, and rings of
//            the last 6 EMA-20 values and the last 20 highs and lows. It stores readings; it classifies nothing.
//
// ── WHAT IT DOES NOT DO ─────────────────────────────────────────────────────────────────────────
// • Nothing here forecasts or selects. A pivot, a cluster or a heavy row describes bars already given.
// • The calendar knows no exchange: the weekdays to skip and the optional CME holiday table are the caller's arguments
//   (the defaults describe a Monday-to-Friday market that closes on CME holidays). A market that trades every day
//   passes -1, -1, false. TE Math's CME table covers 2026 and 2027 only; no date in any other year is a holiday.
//   sessionExtremesInto is the same: the session clock is yours. A market that trades around the clock can pass its own
//   time zone, a roll of 0 with rollMin 1440, useCmeHolidays false, and whatever window it treats as its main session.
// • weeklyHighLow treats a missing day as a hole in its own week: that week is na rather than a partial high and low.
//   It never reaches into the neighbouring week, and a missing day in the excluded current week changes nothing.
// • strictPivot4At reads p − 4 to p + 4 without a bounds check: the caller must pass 4 ≤ p ≤ size − 5.
// • rowDepositProfile needs at least one row and lookback ≥ 1; a row with no volume adds nothing.
// • The seven-row table appears only when the library itself is added to a chart; an importing script receives the
//   exported functions and none of the readout.
//
// ── REPAINT CONTRACT ────────────────────────────────────────────────────────────────────────────
// No request.*() call, no lookahead and no bar-history index appear anywhere in this library. Every function is a
// pure function of its arguments, except regStep, which updates the state object it is given. Step it once per
// COMPLETED bucket, oldest first; stepping a forming bucket repaints.
//
// IP PROVENANCE
// PUBLIC MATH — fractal-style pivot highs and lows; a strict n-and-n swing; single-pass 1-D clustering with a weighted
//   mean; session and daily highs and lows; an average-true-range multiple; calendar arithmetic; a volume profile
//   that spreads each bar's volume over the rows it spans; the close location value; exponential moving averages; Wilder's average true range (through the published TE Math library).
// REUSED from our own work — every function body is moved from our own earlier source; the signatures take arrays
//   where that source passed its own record types, and gain the arguments that replaced fixed choices. Two bodies differ
//   from that source on purpose: weightedClusters drops two outputs nothing read (as our newer source does) and cannot
//   raise an index error, which that source could on TradingView (every array access is checked against its own size, and
//   a type code outside the weight array or a weight that is not positive counts as weight 0; wherever that source
//   completed with valid codes and positive weights, the zones are the same), and weeklyHighLow's handling of
//   a missing day follows our own corrected reference implementation. Each is held to its source, or to that
//   reference, by a test.
// INDEPENDENTLY DERIVED — nothing. No third-party script was read or ported.
//
// This library is for education and analysis. It is not financial advice and it places no orders.
 
// @description Price-structure maths for Pine arrays: pivot swings with tie handling, strict 4-and-4 and 2-and-2 swings, a weighted single-pass 1-D clustering, trading-date and week keys with the calendar as arguments, a rolling volume profile that spreads each bar over its rows with a close-location share, and an EMA 20/50 plus ATR 14 stepper. No trading rules.
library("TEStructure_PivotSwings_Clusters_RowProfile", overlay = true)
 
import TradersEdgeUSA/TEMath_WilderSuperTrend_TickGridValueArea/1 as tem
 
// ── TE DESIGN KIT v3 ── the shared visual grammar (generated; do not hand-edit)
//
// The Trader's Edge visual grammar. Every indicator in the fleet reads the SAME meanings:
//   solid = confirmed · dashed = projected/conditional · dotted = historical/reference
//   gold  = brand and selection ONLY. It never means good, bullish, or high confidence.
//   risk outranks opportunity: a blocker always dominates positive styling.
 
teKitDark = input.string("Dark", "Theme", options = ["Dark", "Light"], group = "APPEARANCE", tooltip = "Which chart background this is drawn for. Changing it re-picks every colour so text and lines stay legible. It cannot detect your theme automatically, so set it to match your chart.") == "Dark"
 
// THE HOVER TOGGLE — shows or hides the on-chart explanations. Default ON.
// Display only: it switches teTeach (below), so every explanation composed through it goes at once.
teTips = input.bool(true, "Hover tooltips (on-chart explanations)", group = "APPEARANCE", tooltip = "Shows or hides the explanation that appears when you hover a table cell or a label on the chart. Off removes that hover text only: every printed value, line, zone and alert is unchanged, and nothing is recomputed. Explanations in this settings dialog are not affected.")
 
// TE_CANVAS: TE-owned surface; the TV canvas belongs to the user
TE_CANVAS = teKitDark ? #0B0F14 : #FFFFFF
// TE_SURFACE: status card / table background
TE_SURFACE = teKitDark ? #111820 : #F4F6F8
// TE_SURFACE_HI: elevated or selected row
TE_SURFACE_HI = teKitDark ? #17212B : #E9EDF1
// TE_TEXT: primary text
TE_TEXT = teKitDark ? #E6EDF3 : #0B0F14
// TE_TEXT_2: secondary text
TE_TEXT_2 = teKitDark ? #A3AFBA : #3F4A54
// TE_TEXT_MUTED: muted text — provenance, units, secondary detail
TE_TEXT_MUTED = teKitDark ? #7F8A93 : #5A6570
// TE_BORDER: divider
TE_BORDER = teKitDark ? #2A3540 : #C7D0D8
// TE_BRAND: BRAND AND SELECTION ONLY
TE_BRAND = teKitDark ? #C9A55B : #AD8E4E
// TE_BRAND_MUTED: brand, de-emphasised
TE_BRAND_MUTED = teKitDark ? #8D7441 : #8D7441
// TE_BULL: bullish direction
TE_BULL = teKitDark ? #00D28B : #00A86F
// TE_BEAR: bearish direction
TE_BEAR = teKitDark ? #DE384E : #DE384E
// TE_DEVELOPING: developing / building / monitor
TE_DEVELOPING = teKitDark ? #5B9EF7 : #5695E8
// TE_ATTENTION: needs attention / selected
TE_ATTENTION = teKitDark ? #D7B45C : #AC904A
// TE_CAUTION: caution / degraded
TE_CAUTION = teKitDark ? #E9B949 : #B18D37
// TE_BLOCKED: blocked / no action
TE_BLOCKED = teKitDark ? #F28C45 : #D57B3D
// TE_INVALID: invalidated / critical risk
TE_INVALID = teKitDark ? #F0525F : #F0525F
// TE_INACTIVE: inactive / dormant / expired
TE_INACTIVE = teKitDark ? #999BAC : #9092A2
// TE_STRUCTURE: neutral structure — a level with no direction of its own
TE_STRUCTURE = teKitDark ? #B6C0C9 : #8A9299
// TE_STRUCTURE_2: secondary structure
TE_STRUCTURE_2 = teKitDark ? #7F8B95 : #7F8B95
// TE_TARGET: target / destination
TE_TARGET = teKitDark ? #77BDFB : #5F97C9
// TE_STOP: explicit stop / invalidation
TE_STOP = teKitDark ? #F0525F : #F0525F
// TE_ENTRY: planned entry
TE_ENTRY = teKitDark ? #D7B45C : #AC904A
// TE_PIVOT: a confirmed pivot marker. Never told apart from TE_POC by colour alone (deuteranope dE 8.1)
TE_PIVOT = teKitDark ? #F9D545 : #A9912F
// TE_EST_BUY: volume ESTIMATED as buying from close location in the bar range, never bid/ask or order flow
TE_EST_BUY = teKitDark ? #2EA49C : #2EA49C
// TE_EST_SELL: volume ESTIMATED as selling from close location in the bar range, never bid/ask or order flow
TE_EST_SELL = teKitDark ? #676ACC : #676ACC
// TE_POC: point of control, the most-traded row of a profile
TE_POC = teKitDark ? #FF9A1C : #D17E17
 
// the line grammar, as one call — so "dashed" can never quietly come to mean "minor"
 
// weight carries priority; it is what "minor" uses instead of a dash.
// These are CONSTANTS because plot(linewidth=) refuses a function's series return.
TE_W_CONTEXT = 1  // context / secondary
TE_W_STANDARD = 2  // active primary structure
TE_W_EMPHASIS = 3  // decision boundary / invalidation / selected
 
// the same grammar for a weight chosen at RUNTIME — line.new(width=) takes series, plot() does not
 
// zone fills, in perceived-opacity bands (Pine takes transparency = 100 - opacity)
 
// THE TE TAG — the house label. One state, one number, one separator, monospace, and a
// tooltip that is not optional. Everything else belongs in the hover layer, not on the chart.
// `style_label_left` puts the tag's pointer ON the price, so it is attached, not floating.
 
// ...and the plateless variant, for dense areas where a plate would cover the tape.
// Same typeface, same hover contract, no box.
 
// THE TEACHING LAYER — the hover is a learning tool, and this is its schema as CODE.
// Four arguments, so a product cannot quietly ship three: reads -> computed -> matters -> limit
// Plain language opens, the maths is second, and the limit clause is never optional.
// PASS COMPOSED STRINGS: a tooltip is built at runtime, so "reads" can carry THIS BAR's
// number and the lesson is about the chart in front of them, not about the concept.
// OFF (teTips false) returns na: no tooltip at any site composed through this helper.
teTeach(string reads, string computed, string matters, string limit) =>
    teTips ? reads + "  ·  " + computed + "  ·  " + matters + "  ·  " + limit : na
 
// THE HOVER LAYER — every on-chart value explains itself on hover, in this order:
//   what it reads .................. [plain]
//   how it is computed ............. [maths]
//   why that information matters ... [plain]
//   what it does not tell you ...... [plain]
//   hoverable: table.cell · label.new   NOT hoverable: box.new · line.new · plot
// ── END TE DESIGN KIT ──
 
// ═══ PRIVATE HELPERS ═══
// Small helpers the exports below call. All are private: they are not part of the importable API. The sort, the slice,
// the two time-zone keys and the tick rounding are the same bodies TE Core exports (stableIsortIdx, sliceF, dateKeyIn,
// minuteOfDayIn, tickDecimals, roundToTick); they are copied here so this library imports nothing but TE Math. The slice returns
// an empty array where array.slice would throw a runtime error.
 
isortIdx(array<int> idx, array<float> key, bool desc) =>
    int n = array.size(idx)
    int nk = array.size(key)
    bool ok = true
    if n > 0
        for q = 0 to n - 1
            int e = array.get(idx, q)
            if e < 0 or e >= nk
                ok := false
    if ok and n > 1
        for i = 1 to n - 1
            int cur = array.get(idx, i)
            float kc = array.get(key, cur)
            int j = i - 1
            bool go = true
            while go and j >= 0
                float kp = array.get(key, array.get(idx, j))
                bool move = desc ? kp < kc : kp > kc
                if move
                    array.set(idx, j + 1, array.get(idx, j))
                    j -= 1
                else
                    go := false
            array.set(idx, j + 1, cur)
    idx
 
f_sliceF(array<float> a, int i0, int i1) =>
    array.size(a) > 0 and i0 >= 0 and i0 < i1 and i1 <= array.size(a) ? array.slice(a, i0, i1) : array.new_float(0)
 
dateKeyIn(int t, string tz) =>
    year(t, tz) * 10000 + month(t, tz) * 100 + dayofmonth(t, tz)
 
minuteOfDayIn(int t, string tz) =>
    hour(t, tz) * 60 + minute(t, tz)
 
tickDecimals(float t) =>
    int d = 0
    while d < 10 and math.abs(t * math.pow(10, d) - math.round(t * math.pow(10, d))) > 1e-9
        d += 1
    d
 
roundToTick(float px, float tick) =>
    float t = tick > 0 ? tick : 0.01
    int d = tickDecimals(t)
    float pw10 = math.pow(10, d)
    float units = math.round(t * pw10)
    float k = math.round(px / t)
    (k * units) / pw10
 
pushTagged(array<float> cP, array<int> cT, array<int> cL, float price, int ty, int lb) =>
    if not na(price)
        array.push(cP, price)
        array.push(cT, ty)
        array.push(cL, lb)
    true
 
// ═══ SWINGS ═══
 
// @function writes every pivot low and pivot high of the arrays into three parallel output arrays. Bar i is a pivot low when no bar in [i − left, i + right] has a lower low and at least one other bar there has a higher low (equal lows are allowed; a flat window is not a pivot); a pivot high is the mirror. The low is written before the high for the same bar.
// @param h highs, oldest first
// @param l lows, oldest first (the scan covers min(size(h), size(l)) bars)
// @param left bars to the left of a pivot
// @param right bars to the right of a pivot (the last `right` bars can never be pivots)
// @param lowT the type code written next to each pivot low
// @param highT the type code written next to each pivot high
// @param lowL the label code for a pivot low; pack × (ts[i] + dur) is added to it
// @param highL the label code for a pivot high; pack × (ts[i] + dur) is added to it
// @param cP output: prices are pushed here
// @param cT output: type codes are pushed here
// @param cL output: label codes are pushed here
// @param ts each bar's start time (at least as many entries as bars); pass zeros to write no time
// @param dur the bar length in milliseconds, so ts[i] + dur is the end of the pivot's bar
// @param pack the multiplier that packs the end time into the label code (32 keeps five bits for the label)
// @returns true
export pivotSwingsInto(array<float> h, array<float> l, int left, int right, int lowT, int highT, int lowL, int highL, array<float> cP, array<int> cT, array<int> cL, array<int> ts, int dur, int pack = 32) =>
    int n = math.min(array.size(h), array.size(l))
    int firstI = left
    int lastI = n - right - 1
    if firstI <= lastI
        for i = firstI to lastI
            float li = array.get(l, i)
            float hi = array.get(h, i)
            bool allLo = true
            bool anyLo = false
            bool allHi = true
            bool anyHi = false
            for j = i - left to i + right
                float lj = array.get(l, j)
                float hj = array.get(h, j)
                if lj < li
                    allLo := false
                if j != i and lj > li
                    anyLo := true
                if hj > hi
                    allHi := false
                if j != i and hj < hi
                    anyHi := true
            int b = array.get(ts, i) + dur
            if allLo and anyLo
                pushTagged(cP, cT, cL, li, lowT, lowL + pack * b)
            if allHi and anyHi
                pushTagged(cP, cT, cL, hi, highT, highL + pack * b)
    true
 
// @function whether the value at p is a strict 4-and-4 swing: for side 1 the low at p is strictly below each of the 4 lows on either side, for side −1 the high at p is strictly above each of the 4 highs on either side
// @param hs highs, oldest first
// @param ls lows, oldest first
// @param p the index to test; it is read without a bounds check, so 4 ≤ p ≤ size − 5 is the caller's to guarantee
// @param side 1 tests the lows, −1 tests the highs
// @returns true when the value at p is a strict swing on that side
export strictPivot4At(array<float> hs, array<float> ls, int p, int side) =>
    float x = side == 1 ? array.get(ls, p) : array.get(hs, p)
    bool ok = true
    for i = 1 to 4
        float a = side == 1 ? array.get(ls, p - i) : array.get(hs, p - i)
        float b = side == 1 ? array.get(ls, p + i) : array.get(hs, p + i)
        ok := ok and (side == 1 ? x < a and x < b : x > a and x > b)
    ok
 
// @function every strict 2-and-2 swing over the last lb values: a low strictly below the 2 lows on each side, a high strictly above the 2 highs on each side. An na anywhere in the five values of a window kills that window's swings. For each index the low (if any) is written before the high.
// @param hs highs, oldest first (one per row; na marks a missing row)
// @param ls lows, oldest first, the same length as hs
// @param lb how many of the most recent rows to scan
// @returns a new array of the swing prices in index order
export strictSwing2Prices(array<float> hs, array<float> ls, int lb) =>
    array<float> out = array.new_float(0)
    int n = array.size(hs)
    int s0 = math.max(0, n - lb)
    if n - s0 >= 5
        for i = s0 + 2 to n - 3
            float ml = array.get(ls, i)
            float mh = array.get(hs, i)
            bool okL = not na(ml)
            bool okH = not na(mh)
            for j = i - 2 to i + 2
                if j != i
                    okL := okL and array.get(ls, j) > ml
                    okH := okH and array.get(hs, j) < mh
            if okL
                array.push(out, ml)
            if okH
                array.push(out, mh)
    out
 
// ═══ SESSION AND DAILY LEVELS ═══
 
// @function writes the prior-session extremes of a bar series into three parallel output arrays: the low and high of the newest two COMPLETED regular sessions ("prior" and "two sessions back") and of the newest two out-of-session periods ("overnight" and the one before it). Each bar is keyed to a trading date = its date in tz after adding rollMs; it is in the regular session when its minute of day in tz is in [rthOpen, rthClose) and, when useCmeHolidays is true, its trading date is not in TE Math's CME holiday table. Today's regular session counts as prior only once the last bar's minute is in [rthClose, rollMin). Each extreme's label code carries pack × (its bar's time + 1), the first bar that printed it.
// @param ts bar start times, oldest first
// @param h bar highs
// @param l bar lows
// @param cP output: prices are pushed here (an extreme that does not exist is not pushed)
// @param cT output: type codes are pushed here
// @param cL output: label codes are pushed here
// @param tys eight type codes, in order: prior low, prior high, two-back low, two-back high, overnight low, overnight high, earlier out-of-session low, earlier out-of-session high
// @param lbs eight label codes, in the same order as tys
// @param tz the time zone the session clock is read in
// @param rollMs milliseconds added to a bar's time before its trading date is read (6 hours makes an 18:00 open start the next date)
// @param rthOpen the regular session's first minute of day
// @param rthClose the minute of day the regular session ends (exclusive)
// @param rollMin the minute of day the next trading date begins (it should equal 1440 − rollMs / 60000)
// @param useCmeHolidays true treats a trading date in TE Math's CME holiday table as having no regular session
// @param pack the multiplier that packs a bar time into a label code
// @returns true
export sessionExtremesInto(array<int> ts, array<float> h, array<float> l, array<float> cP, array<int> cT, array<int> cL, array<int> tys, array<int> lbs, string tz = "America/New_York", int rollMs = 21600000, int rthOpen = 570, int rthClose = 960, int rollMin = 1080, bool useCmeHolidays = true, int pack = 32) =>
    int n = math.min(array.size(ts), math.min(array.size(h), array.size(l)))
    if n > 0
        array<int> keys = array.new_int(n, 0)
        array<bool> rth = array.new_bool(n, false)
        int r1 = -1
        int r2 = -1
        int r3 = -1
        int o1 = -1
        int o2 = -1
        bool done = false
        for i = 0 to n - 1
            int tt = array.get(ts, i)
            int k = dateKeyIn(tt + rollMs, tz)
            int mnt = minuteOfDayIn(tt, tz)
            bool isR = mnt >= rthOpen and mnt < rthClose and not (useCmeHolidays and tem.cmeHoliday(k))
            array.set(keys, i, k)
            array.set(rth, i, isR)
            done := mnt >= rthClose and mnt < rollMin
            if isR
                if k > r1
                    r3 := r2
                    r2 := r1
                    r1 := k
            else if k > o1
                o2 := o1
                o1 := k
        // today (the last bar's key) is not a PRIOR RTH until its cash session has closed
        if r1 == array.get(keys, n - 1) and not done
            r1 := r2
            r2 := r3
        float r1lo = na
        float r1hi = na
        float r2lo = na
        float r2hi = na
        float o1lo = na
        float o1hi = na
        float o2lo = na
        float o2hi = na
        int r1lb = 0
        int r1hb = 0
        int r2lb = 0
        int r2hb = 0
        int o1lb = 0
        int o1hb = 0
        int o2lb = 0
        int o2hb = 0
        for i = 0 to n - 1
            int k = array.get(keys, i)
            float lo = array.get(l, i)
            float hi = array.get(h, i)
            int b = array.get(ts, i) + 1
            if array.get(rth, i)
                if k == r1
                    if na(r1lo) or lo < r1lo
                        r1lo := lo
                        r1lb := b
                    if na(r1hi) or hi > r1hi
                        r1hi := hi
                        r1hb := b
                if k == r2
                    if na(r2lo) or lo < r2lo
                        r2lo := lo
                        r2lb := b
                    if na(r2hi) or hi > r2hi
                        r2hi := hi
                        r2hb := b
            else
                if k == o1
                    if na(o1lo) or lo < o1lo
                        o1lo := lo
                        o1lb := b
                    if na(o1hi) or hi > o1hi
                        o1hi := hi
                        o1hb := b
                if k == o2
                    if na(o2lo) or lo < o2lo
                        o2lo := lo
                        o2lb := b
                    if na(o2hi) or hi > o2hi
                        o2hi := hi
                        o2hb := b
        pushTagged(cP, cT, cL, r1lo, array.get(tys, 0), array.get(lbs, 0) + pack * r1lb)
        pushTagged(cP, cT, cL, r1hi, array.get(tys, 1), array.get(lbs, 1) + pack * r1hb)
        pushTagged(cP, cT, cL, r2lo, array.get(tys, 2), array.get(lbs, 2) + pack * r2lb)
        pushTagged(cP, cT, cL, r2hi, array.get(tys, 3), array.get(lbs, 3) + pack * r2hb)
        pushTagged(cP, cT, cL, o1lo, array.get(tys, 4), array.get(lbs, 4) + pack * o1lb)
        pushTagged(cP, cT, cL, o1hi, array.get(tys, 5), array.get(lbs, 5) + pack * o1hb)
        pushTagged(cP, cT, cL, o2lo, array.get(tys, 6), array.get(lbs, 6) + pack * o2lb)
        pushTagged(cP, cT, cL, o2hi, array.get(tys, 7), array.get(lbs, 7) + pack * o2hb)
    true
 
// @function writes daily pivot lows and highs (pivotSwingsInto with pivotStrength bars each side) and the low and high of the last five daily bars into three parallel output arrays; nothing when fewer than 12 daily bars are given
// @param dH daily highs, oldest first
// @param dL daily lows, oldest first
// @param pivotStrength bars on each side of a daily pivot
// @param cP output: prices are pushed here
// @param cT output: type codes are pushed here
// @param cL output: label codes are pushed here
// @param tys four type codes, in order: pivot low, pivot high, five-day low, five-day high
// @param lbs four label codes, in the same order as tys
// @param pack the pivot label packing multiplier, passed to pivotSwingsInto (daily pivots are written with no bar time, so the packed part is 0; it keeps the label form the same as pivotSwingsInto's)
// @returns true
export dailyLevelsInto(array<float> dH, array<float> dL, int pivotStrength, array<float> cP, array<int> cT, array<int> cL, array<int> tys, array<int> lbs, int pack = 32) =>
    int n = math.min(array.size(dH), array.size(dL))
    if n >= 12
        pivotSwingsInto(dH, dL, pivotStrength, pivotStrength, array.get(tys, 0), array.get(tys, 1), array.get(lbs, 0), array.get(lbs, 1), cP, cT, cL, array.new_int(n, 0), 0, pack)
        int start = math.max(0, n - 5)
        if n - start >= 3
            float lo = array.get(dL, start)
            float hi = array.get(dH, start)
            for i = start to n - 1
                lo := math.min(lo, array.get(dL, i))
                hi := math.max(hi, array.get(dH, i))
            pushTagged(cP, cT, cL, lo, array.get(tys, 2), array.get(lbs, 2))
            pushTagged(cP, cT, cL, hi, array.get(tys, 3), array.get(lbs, 3))
    true
 
// ═══ VOLATILITY ═══
 
// @function a price distance of mult × the average true range of the last 20 bars (true range against each bar's previous close), rounded to the tick and never below one tick; 4 ticks when fewer than 21 bars are given
// @param h highs, oldest first
// @param l lows, oldest first
// @param c closes, oldest first
// @param tick the tick size
// @param mult the multiple of the 20-bar average true range (no default: the caller chooses it)
// @returns the distance in price units
export atrBuffer(array<float> h, array<float> l, array<float> c, float tick, float mult) =>
    int n = math.min(array.size(h), math.min(array.size(l), array.size(c)))
    float buf = tick * 4
    if n >= 21
        int s = n - 21
        float sum = 0.0
        for i = 1 to 20
            int k = s + i
            float pc = array.get(c, k - 1)
            float hk = array.get(h, k)
            float lk = array.get(l, k)
            sum := sum + math.max(hk - lk, math.abs(hk - pc), math.abs(lk - pc))
        buf := math.max(tick, roundToTick(sum / 20 * mult, tick))
    buf
 
// ═══ CLUSTERS ═══
 
// @function single-pass 1-D clustering of prices in ascending order. Each price joins the last zone when it is within tol of that zone's current price, else it starts a new zone. A zone's price is its first member's price until a member with a positive weight joins, then Σ(price × w) / Σ w over its members, with w = wClust[type code]. A type code that is na or not a valid index into wClust, and a weight that is na or not positive, count as weight 0: the price still joins or starts a zone but does not move a weighted mean, and a zone whose weights are all 0 keeps its first member's price. Every array read and write is checked against that array's own size, so it cannot raise an index error. All four output arrays are cleared first; they must be four distinct arrays, none of them cP. A zone's lowest and highest member prices are cP[ord[zStart]] and cP[ord[zStart + zCount − 1]], because ord is in ascending price order.
// @param cP the prices
// @param cT each price's type code, an index into wClust
// @param tol the join distance, in price units
// @param wClust one weight per type code
// @param ord output: the price indices in ascending price order (equal prices keep their input order)
// @param zPrice output: each zone's price
// @param zStart output: the position in ord of each zone's first member
// @param zCount output: each zone's member count (its members are ord[zStart] … ord[zStart + zCount − 1])
// @returns the number of zones
export weightedClusters(array<float> cP, array<int> cT, float tol, array<float> wClust, array<int> ord, array<float> zPrice, array<int> zStart, array<int> zCount) =>
    array.clear(ord)
    array.clear(zPrice)
    array.clear(zStart)
    array.clear(zCount)
    int m = math.min(array.size(cP), array.size(cT))
    int nw = array.size(wClust)
    // the running totals and the zone's current price live in these locals, pushed and read together, so no index into
    // them can pass their size; the output arrays are written from them and never read back
    array<float> zTw = array.new_float(0)
    array<float> zPw = array.new_float(0)
    array<float> zCur = array.new_float(0)
    if m > 0
        for i = 0 to m - 1
            array.push(ord, i)
        isortIdx(ord, cP, false)
        for k = 0 to m - 1
            int i = array.get(ord, k)
            float p = array.get(cP, i)
            int ty = array.get(cT, i)
            float w0 = (not na(ty) and ty >= 0 and ty < nw) ? array.get(wClust, ty) : 0.0
            float w = (na(w0) or w0 <= 0) ? 0.0 : w0
            int zc = array.size(zCur)
            bool joins = false
            if zc > 0
                joins := math.abs(p - array.get(zCur, zc - 1)) <= tol
            if joins
                int z = zc - 1
                // every read and write below is checked against THAT array's own size, so the call cannot raise an index
                // error even if one array fell out of step with zCur; a missing total reads as 0
                float tw = (z < array.size(zTw) ? array.get(zTw, z) : 0.0) + w
                float pw = (z < array.size(zPw) ? array.get(zPw, z) : 0.0) + p * w
                if z < array.size(zTw)
                    array.set(zTw, z, tw)
                if z < array.size(zPw)
                    array.set(zPw, z, pw)
                if tw > 0
                    array.set(zCur, z, pw / tw)
                if z < array.size(zPrice)
                    array.set(zPrice, z, array.get(zCur, z))
                if z < array.size(zCount)
                    array.set(zCount, z, array.get(zCount, z) + 1)
            else
                // the locals are pushed BEFORE the outputs: measured on TradingView's runtime, the reverse order left the
                // totals array empty at the first join and raised an array index error
                array.push(zCur, p)
                array.push(zTw, w)
                array.push(zPw, p * w)
                array.push(zPrice, p)
                array.push(zStart, k)
                array.push(zCount, 1)
    array.size(zCur)
 
// ═══ CALENDAR ═══
 
// @function the date before k that is neither of the two skipped weekdays and, when useCmeHolidays is true, not in TE Math's CME holiday table; it steps back at most 10 calendar days
// @param k a date as yyyymmdd
// @param skipA a weekday to step over (dayofweek.*), or -1 for none
// @param skipB a second weekday to step over, or -1 for none
// @param useCmeHolidays true also steps over the dates in TE Math's CME holiday table
// @returns the earlier date as yyyymmdd
export prevTradingDate(int k, int skipA = dayofweek.saturday, int skipB = dayofweek.sunday, bool useCmeHolidays = true) =>
    int t = timestamp("UTC", int(math.floor(k / 10000)), int(math.floor(k / 100)) % 100, k % 100, 12, 0) - 86400000
    int g = 0
    while g < 10 and (dayofweek(t, "UTC") == skipA or dayofweek(t, "UTC") == skipB or useCmeHolidays and tem.cmeHoliday(year(t, "UTC") * 10000 + month(t, "UTC") * 100 + dayofmonth(t, "UTC")))
        t -= 86400000
        g += 1
    year(t, "UTC") * 10000 + month(t, "UTC") * 100 + dayofmonth(t, "UTC")
 
// @function the Monday of the week that contains a date, both as yyyymmdd (a Sunday belongs to the week that began six days earlier)
// @param k a date as yyyymmdd
// @returns that week's Monday as yyyymmdd
export weekMondayOf(int k) =>
    int t = timestamp("UTC", int(math.floor(k / 10000)), int(math.floor(k / 100)) % 100, k % 100, 12, 0)
    t -= ((dayofweek(t, "UTC") + 5) % 7) * 86400000
    year(t, "UTC") * 10000 + month(t, "UTC") * 100 + dayofmonth(t, "UTC")
 
// @function one high and one low per completed week, folded from daily rows in order and keyed by each row's Monday; every row in the week containing `key` is left out. A row with an na high is a missing day: it makes ITS OWN week na (high and low), and no other week. A missing day must have both its high and low na; sesK must hold no na and be as long as sesH and sesL.
// @param key the current date as yyyymmdd (its week is excluded), or na to include every week
// @param sesK each daily row's date as yyyymmdd, oldest first
// @param sesH each daily row's high (na marks a missing day)
// @param sesL each daily row's low
// @returns a tuple of two new arrays: the weekly highs and the weekly lows, oldest first
export weeklyHighLow(int key, array<int> sesK, array<float> sesH, array<float> sesL) =>
    array<float> wH = array.new_float(0)
    array<float> wL = array.new_float(0)
    array<bool> wGap = array.new_bool(0)
    int wk = na
    int cw = na(key) ? na : weekMondayOf(key)
    for [i, sk] in sesK
        int w = weekMondayOf(sk)
        if na(cw) or w != cw
            if na(wk) or w != wk
                array.push(wH, na)
                array.push(wL, na)
                array.push(wGap, false)
                wk := w
            int z = array.size(wH) - 1
            float sh = array.get(sesH, i)
            if na(sh)
                array.set(wGap, z, true)
                array.set(wH, z, na)
                array.set(wL, z, na)
            else if not array.get(wGap, z)
                float hz = array.get(wH, z)
                float lz = array.get(wL, z)
                array.set(wH, z, na(hz) ? sh : math.max(hz, sh))
                array.set(wL, z, na(lz) ? array.get(sesL, i) : math.min(lz, array.get(sesL, i)))
    [wH, wL]
 
// ═══ PROFILE ═══
 
// @function a volume profile of the last `lookback` rows in which each row's volume is spread EVENLY over the price rows it spans (row r covers [r × rowH, (r + 1) × rowH)), with a second array receiving the same shares times the close location (close − low) / (high − low)
// @param rH row highs, oldest first
// @param rL row lows, oldest first
// @param rC row closes, oldest first
// @param rV row volumes, oldest first (a row with no volume adds nothing)
// @param rowH the height of one price row, in price units (> 0)
// @param lookback how many of the most recent rows to use (≥ 1; at least one row must exist)
// @returns a tuple: the lowest row number, the volume per row, and the close-location-weighted volume per row
export rowDepositProfile(array<float> rH, array<float> rL, array<float> rC, array<float> rV, float rowH, int lookback = 192) =>
    int nB = array.size(rH)
    int s0 = math.max(0, nB - lookback)
    int lo = int(math.floor(array.min(f_sliceF(rL, s0, nB)) / rowH))
    int hi = int(math.floor(array.max(f_sliceF(rH, s0, nB)) / rowH))
    array<float> vol = array.new_float(hi - lo + 1, 0.0)
    array<float> buy = array.new_float(hi - lo + 1, 0.0)
    for j = s0 to nB - 1
        float bv = array.get(rV, j)
        if bv > 0
            float bh = array.get(rH, j)
            float bl = array.get(rL, j)
            int a = int(math.floor(bl / rowH)) - lo
            int z = int(math.floor(bh / rowH)) - lo
            float per = bv / (z - a + 1)
            float pb = per * tem.closeLocation(bh, bl, array.get(rC, j))
            for k = a to z
                array.set(vol, k, array.get(vol, k) + per)
                array.set(buy, k, array.get(buy, k) + pb)
    [lo, vol, buy]
 
// ═══ STEPPER ═══
 
// @type the running state of an EMA 20 / EMA 50 / ATR 14 stepper over completed buckets. Create it with regStateNew().
// @field emaF EMA 20 of the closes
// @field emaS EMA 50 of the closes
// @field atr Wilder ATR 14 (na for the first 13 buckets)
// @field prevC the last close stepped
// @field tr the last true range
// @field n the number of buckets stepped
// @field w TE Math's Wilder ATR state behind atr
// @field emaFHist the last 6 EMA 20 values, newest last
// @field hi20 the last 20 highs, newest last
// @field lo20 the last 20 lows, newest last
export type RegState
    float emaF = na
    float emaS = na
    float atr = na
    float prevC = na
    float tr = na
    int n = 0
    tem.Atr w
    array<float> emaFHist
    array<float> hi20
    array<float> lo20
 
// @function a new, empty stepper state with an ATR length of 14 and empty rings
// @returns a RegState
export regStateNew() =>
    RegState.new(w = tem.Atr.new(14), emaFHist = array.new<float>(), hi20 = array.new<float>(), lo20 = array.new<float>())
 
// @function steps the state by one COMPLETED bucket: true range (high − low on the first bucket), EMA 20 and EMA 50 seeded with the first close, Wilder ATR 14, and the 6 / 20 / 20 rings. Call it once per completed bucket, oldest first.
// @param s the state, updated in place
// @param h the bucket's high
// @param l the bucket's low
// @param c the bucket's close
// @returns s
export regStep(RegState s, float h, float l, float c) =>
    float tr = tem.trueRange(h, l, s.prevC)
    if s.n == 0
        s.emaF := c
        s.emaS := c
    else
        float aF = 2.0 / 21.0
        float aS = 2.0 / 51.0
        s.emaF := aF * c + (1.0 - aF) * s.emaF
        s.emaS := aS * c + (1.0 - aS) * s.emaS
    s.atr := tem.atrStepTR(s.w, tr, c)
    s.tr := tr
    s.prevC := c
    s.n += 1
    array.push(s.emaFHist, s.emaF)
    if array.size(s.emaFHist) > 6
        array.shift(s.emaFHist)
    array.push(s.hi20, h)
    if array.size(s.hi20) > 20
        array.shift(s.hi20)
    array.push(s.lo20, l)
    if array.size(s.lo20) > 20
        array.shift(s.lo20)
    s
 
// ═══ THE ON-CHART READOUT ═══
// Runs only when the library itself is added to a chart. A script that IMPORTS the library gets the exported functions
// above and none of this. It exists so the maths can be seen doing its job on any symbol: the exports applied to this
// chart's own closed bars. Bars are folded on barstate.isconfirmed and the table is written on the last bar from the
// arrays of closed bars, so nothing here repaints. It works on any market: the calendar row uses the symbol's own
// exchange time zone and a plain Monday-to-Friday calendar (no exchange holiday table), the profile rows are one fiftieth
// of the held range on the tick grid (so never more than about 75), and a symbol with no volume is
// said to have none rather than given a profile.
 
const int DEMO_N = 200
const int DEMO_PIV = 3
const int DEMO_SW_LB = 30
 
var RegState demoReg = regStateNew()
var array<float> dH = array.new_float(0)
var array<float> dL = array.new_float(0)
var array<float> dC = array.new_float(0)
var array<float> dV = array.new_float(0)
var int demoLastT = na
 
if barstate.isconfirmed
    regStep(demoReg, high, low, close)
    array.push(dH, high)
    array.push(dL, low)
    array.push(dC, close)
    array.push(dV, nz(volume))
    if array.size(dH) > DEMO_N
        array.shift(dH)
        array.shift(dL)
        array.shift(dC)
        array.shift(dV)
    demoLastT := time
 
var table demoTbl = table.new(position.top_right, 2, 7, bgcolor = TE_SURFACE, border_color = TE_BORDER, border_width = 1)
if barstate.islast and array.size(dH) > 0
    int nb = array.size(dH)
    float atr = demoReg.atr
    // pivots, then the pivots clustered at a quarter of an ATR with equal weights for lows and highs
    array<float> cP = array.new_float(0)
    array<int> cT = array.new_int(0)
    array<int> cL = array.new_int(0)
    pivotSwingsInto(dH, dL, DEMO_PIV, DEMO_PIV, 0, 1, 0, 0, cP, cT, cL, array.new_int(nb, 0), 0)
    int nLo = 0
    for x in cT
        nLo += x == 0 ? 1 : 0
    int nHi = array.size(cT) - nLo
    array<int> ord = array.new_int(0)
    array<float> zP = array.new_float(0)
    array<int> zS = array.new_int(0)
    array<int> zN = array.new_int(0)
    float tol = na(atr) ? na : 0.25 * atr
    int nZones = na(tol) ? 0 : weightedClusters(cP, cT, tol, array.from(1.0, 1.0), ord, zP, zS, zN)
    // strict swings
    int nSw = array.size(strictSwing2Prices(dH, dL, DEMO_SW_LB))
    string p4Txt = "warming"
    if nb >= 9
        bool pl = strictPivot4At(dH, dL, nb - 5, 1)
        bool ph = strictPivot4At(dH, dL, nb - 5, -1)
        p4Txt := pl and ph ? "low and high" : pl ? "low" : ph ? "high" : "neither"
    // the row-deposit profile on rows of one fiftieth of the held range (on the tick grid): at most about 75 rows
    string rowTxt = "flat range"
    string shareTxt = ""
    float span = array.max(dH) - array.min(dL)
    if span > 0
        float rowH = math.max(syminfo.mintick, math.round(span / 50 / syminfo.mintick) * syminfo.mintick)
        [pLo, pVol, pUp] = rowDepositProfile(dH, dL, dC, dV, rowH, DEMO_N)
        float mx = array.max(pVol)
        if mx > 0
            int k = array.indexof(pVol, mx)
            rowTxt := str.tostring((pLo + k + 0.5) * rowH, format.mintick)
            shareTxt := str.tostring(math.round(100 * array.get(pUp, k) / mx)) + "%"
        else
            rowTxt := "no volume data"
    // the stepper's EMA spread in ATRs, and the calendar keys of the last closed bar
    string emaTxt = na(atr) or atr == 0 ? "warming" : str.tostring((demoReg.emaF - demoReg.emaS) / atr, "+#.##;-#.##") + " ATR"
    int dKey = year(demoLastT, syminfo.timezone) * 10000 + month(demoLastT, syminfo.timezone) * 100 + dayofmonth(demoLastT, syminfo.timezone)
    int prevD = prevTradingDate(dKey, dayofweek.saturday, dayofweek.sunday, false)
    int monD = weekMondayOf(dKey)
    string calTxt = str.tostring(prevD) + " · " + str.tostring(monD)
    tipPiv = teTeach("Over the last " + str.tostring(nb) + " closed bars there are " + str.tostring(nLo) + " pivot lows and " + str.tostring(nHi) + " pivot highs with 3 bars on each side.", "pivotSwingsInto: a low is a pivot when no bar within 3 on either side is lower and at least one of them is higher; a high is the mirror, so equal extremes inside the window still count.", "Pivots are where a run of bars turned, found by rule rather than by eye, so two scripts reading the same bars mark the same turns.", "A pivot is only known 3 bars after it prints; it is a record of a turn, not a level price will respect.")
    table.cell(demoTbl, 0, 0, "Pivots 3-and-3", text_color = TE_TEXT_2, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipPiv)
    table.cell(demoTbl, 1, 0, str.tostring(nLo) + " lows · " + str.tostring(nHi) + " highs", text_color = TE_TEXT, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipPiv)
    string zTxt = na(tol) ? "warming" : str.tostring(nZones)
    tipZ = teTeach("Those " + str.tostring(array.size(cP)) + " pivot prices group into " + zTxt + " zones when prices within " + (na(tol) ? "a quarter ATR (still warming)" : str.tostring(tol, format.mintick)) + " of each other are joined.", "weightedClusters: sort ascending, then each price joins the last zone if it is within the tolerance of that zone's current price, whose value is the weighted mean Σ(p × w) / Σ w of its members.", "Nearby prices that differ by a few ticks usually describe one area; merging them turns a crowd of lines into a short list of places.", "Zones are counted, not ranked; a zone with many pivots is not claimed to be stronger than one with few.")
    table.cell(demoTbl, 0, 1, "Pivot zones", text_color = TE_TEXT_2, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipZ)
    table.cell(demoTbl, 1, 1, zTxt, text_color = TE_TEXT, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipZ)
    tipSw = teTeach("In the last " + str.tostring(DEMO_SW_LB) + " closed bars there are " + str.tostring(nSw) + " strict 2-and-2 swings.", "strictSwing2Prices: a low strictly below the two lows on each side, or a high strictly above the two highs on each side; any missing value in the five kills that swing.", "Strict inequality ignores double bottoms and flat tops, which gives a sparser, unambiguous list of turns than the tie-tolerant pivot above.", "A swing needs two bars after it, so the newest two bars can never qualify; it says nothing about whether the swing holds.")
    table.cell(demoTbl, 0, 2, "Strict swings 2-and-2", text_color = TE_TEXT_2, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipSw)
    table.cell(demoTbl, 1, 2, str.tostring(nSw), text_color = TE_TEXT, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipSw)
    tipP4 = teTeach("The closed bar 4 back from the latest is a strict 4-and-4 swing: " + p4Txt + ".", "strictPivot4At: its low is strictly below each of the 4 lows on either side (a swing low), or its high strictly above each of the 4 highs on either side (a swing high).", "Four bars is the earliest this test can be answered, so this row shows the newest turn that the rule can confirm right now.", "Both can be true on one wide bar and neither on most bars; a confirmed swing is history, not a forecast.")
    table.cell(demoTbl, 0, 3, "Swing 4 bars back", text_color = TE_TEXT_2, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipP4)
    table.cell(demoTbl, 1, 3, p4Txt, text_color = TE_TEXT, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipP4)
    tipRow = teTeach("Across the last " + str.tostring(nb) + " closed bars the heaviest price row is centred at " + rowTxt + (shareTxt == "" ? "" : ", and its close-location share is " + shareTxt + " (100% would mean every bar that built it closed at its high)") + ".", "rowDepositProfile: each bar's volume is split evenly over the rows it spans, each row one fiftieth of the held range; a second array adds the same share times (close − low) / (high − low), and the share is that array over the volume.", "Where volume piled up is information a price line alone does not carry, and the close-location share adds whether those bars tended to finish near their highs or their lows.", "Volume is spread evenly across each bar's range because the bars do not say where inside the range it traded; the share is a candle-shape estimate, not a count of buyers.")
    table.cell(demoTbl, 0, 4, "Heaviest volume row", text_color = TE_TEXT_2, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipRow)
    table.cell(demoTbl, 1, 4, rowTxt + (shareTxt == "" ? "" : " · " + shareTxt), text_color = TE_TEXT, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipRow)
    tipEma = teTeach("EMA 20 minus EMA 50 of the closes, divided by the ATR 14, after " + str.tostring(demoReg.n) + " closed bars: " + emaTxt + ".", "regStep: EMA 20 and EMA 50 with α = 2 / 21 and 2 / 51 seeded on the first close, and Wilder's ATR 14 of the true range, stepped once per closed bar.", "Dividing the gap between two averages by the ATR puts it in units of a typical bar, so the same reading means the same thing on any symbol and timeframe.", "The stepper stores readings and names no regime; no threshold on this number is part of the library.")
    table.cell(demoTbl, 0, 5, "EMA 20 − 50 / ATR", text_color = TE_TEXT_2, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipEma)
    table.cell(demoTbl, 1, 5, emaTxt, text_color = TE_TEXT, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipEma)
    tipCal = teTeach("The last closed bar's exchange date is " + str.tostring(dKey) + "; the weekday before it is " + str.tostring(prevD) + " and its week began on Monday " + str.tostring(monD) + ".", "prevTradingDate steps back one calendar day at a time past Saturday and Sunday (the optional CME holiday table is off here); weekMondayOf subtracts (weekday + 5) mod 7 days.", "Integer date keys make it cheap to group bars into days and weeks, and to find the day before, without string handling.", "This row uses a plain weekday calendar; it does not know this market's holidays or whether it trades on weekends.")
    table.cell(demoTbl, 0, 6, "Prior weekday · Monday", text_color = TE_TEXT_2, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipCal)
    table.cell(demoTbl, 1, 6, calTxt, text_color = TE_TEXT, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipCal)

← 返回列表