本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@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 CORE — STABLE INSERTION SORT, TICK ROUNDING, TIME-ZONE KEYS, PRICE-TEXT SCAN AND RANK/MEDIAN HELPERS, AS AN
// IMPORTABLE LIBRARY
//
// WHAT IT IS: a Pine library of TEXTBOOK MATHS AND UTILITIES. It carries no trading rule of any kind: no entry, no
// exit, no score, no ordering of levels and no level-selection logic. The timezone, the session open, the ladder of
// round-number steps, the ring size and the minimum count are ARGUMENTS; the only fixed constants are the 0.65-1.35
// plausibility band in withinBand and runtime guards (2,000 values, 60 steps, the 20-hour step), all stated below.
//
// ── THE EXPORTS ─────────────────────────────────────────────────────────────────────────────────
// arrays stableIsortIdx · sliceF · sliceI
// price grid tickDecimals · roundToTick · withinBand · roundStepFor · roundNumbersInto
// time dateKeyIn · minuteOfDayIn · sessionWindowStart
// text isDigit · isLetter · charAt · pricesFromText
// units unitsForRisk · trancheAlloc
// series wilderAtrOf · medianVolumeRatio · percentileOfLast
//
// ── THE MATHS, STATED ONCE ──────────────────────────────────────────────────────────────────────
// SORT insertion sort of an index array by key[index]: shift while key[prev] > key[cur] (ascending) or
// key[prev] < key[cur] (descending). The comparison is STRICT, so equal keys keep their input order (a
// stable sort). array.sort_indices is not used because its tie order is unspecified.
// TICK d = the fewest decimals (≤ 10) at which tick × 10^d is an integer within 1e-9; units = round(tick × 10^d);
// roundToTick(px) = round(px / tick) × units / 10^d. k × units and 10^d are exact integers, so the one
// division is the correctly rounded decimal. Worked example: tick 0.25 → d = 2, units = 25;
// px 4321.13 → round(17284.52) = 17285 → 17285 × 25 / 100 = 4321.25.
// BAND withinBand(p, ref) = p > 0 and (ref is na or ≤ 0, or 0.65 × ref ≤ p ≤ 1.35 × ref).
// ROUND STEP the first rung s of the caller's ladder with (hi − lo) / s ≤ maxLevels, else the last rung. Worked example:
// ladder 0.05 … 1000, lo 4300, hi 4420, maxLevels 8 → 120 / 25 = 4.8 ≤ 8 and 120 / 10 = 12 > 8 → step 25;
// roundNumbersInto then writes 4300, 4325, 4350, 4375, 4400.
// TIME dateKeyIn(t, tz) = year × 10000 + month × 100 + day in tz; minuteOfDayIn(t, tz) = hour × 60 + minute in tz,
// both resolved by the timezone database (correct through daylight-saving changes).
// WINDOW sessionWindowStart walks back from a session open: each step goes 20 hours back, re-anchors to the open
// hour on THAT calendar date in tz, and counts the step unless the new open falls on either skipped weekday.
// TEXT pricesFromText scans left to right for digit runs, each with optional thousands groups ("7,125": a comma
// then exactly three digits, after a head of at most three) and an optional decimal part. A number
// written straight after the previous one with a "-" between them is a RANGE TAIL, kept only if it has at
// least as many integer digits as that previous number and the previous number was not itself a tail:
// "7100-7120" keeps both, "7100-05" keeps 7100 alone. A number is refused when a letter, "." or ":" sits
// before it, when a letter, ":" or "%" sits after it, or when a "-" before it is not a range tail.
// Duplicates and non-positive values are dropped; at most maxOut values are returned, in text order.
// UNITS unitsForRisk = floor(budget / (points × point value) + 1e-9), 0 unless all three are positive.
// trancheAlloc splits N whole units: a1 = min(N, max(1, round(s1 × N))); a2 = min(round or floor(s2 × N),
// N − a1); a3 = min(floor(s3 × N), N − a1 − a2); the remainder N − a1 − a2 − a3 is the fourth value.
// Worked example: N = 7, fractions 0.5 / 0.3 / 0 → a1 = round(3.5) = 4, a2 = floor(2.1) = 2, a3 = 0,
// remainder 1.
// ATR wilderAtrOf folds whole arrays through TE Math's Wilder ATR (the mean of the first n true ranges, then
// (ATR × (n − 1) + TR) / n); na unless at least n + 1 bars are given.
// MEDIAN medianVolumeRatio = median(last `lookback` values) / median(all values), na unless there are at least
// 2 × lookback values and the overall median is positive.
// PERCENTILE percentileOfLast = 100 × the mid-rank of the last value among up to `cap` values before it (TE Math's Rank:
// (count strictly below + half the exact ties) / n), na until `minN` values are held. Worked example: held
// 10, 20, 20, 30, last value 20 → (1 + 2 / 2) / 4 = 0.50 → 50.
//
// ── WHAT IT DOES NOT DO ─────────────────────────────────────────────────────────────────────────
// • Nothing here forecasts or selects. A rank, a median ratio or a round number describes values already given.
// • sessionWindowStart knows no exchange calendar: the session open, the timezone and the two skipped weekdays are the
// caller's arguments (the defaults describe a 18:00 New York open that never starts on a Friday or Saturday).
// Its 20-hour step reaches the previous calendar date only for an open hour from 0 to 19.
// • pricesFromText reads numbers out of text; it cannot tell a price from any other number the text contains.
// • An na in an array passed to wilderAtrOf makes the result na; filter first.
// • The six-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.
//
// IP PROVENANCE
// PUBLIC MATH — insertion sort; decimal tick rounding; the median; the mid-rank percentile; Wilder's average true
// range (through the published TE Math library); calendar keys from the timezone database.
// ORIGINAL — the price-text scan rules, the range-tail rule and the whole-unit allocation rounding, written by us.
// REUSED from our own work — every function is moved unchanged from our own earlier source, held equal to it by a
// test (a normalised body comparison plus a JavaScript mirror per export).
// 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 Utility maths for Pine arrays and prices: a stable insertion sort, bounds-checked slices, decimal tick rounding, round-number steps, timezone date and minute keys, a session-open walk, a price-from-text scanner, whole-unit sizing arithmetic, a Wilder ATR over arrays, a median volume ratio and a trailing percentile. No trading rules.
library("TECore_StableSort_TickRound_TextScan", 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 ──
// ═══ ARRAYS ═══
// @function stable insertion sort of an index array by key[element], in place. Strict comparison, so equal keys keep their input order (the same order as a stable sort). If any element is not a valid index into key, the array is returned UNSORTED rather than throwing.
// @param idx the indices to order (each must satisfy 0 ≤ idx[q] < array.size(key))
// @param key the values the indices point into
// @param desc true sorts by descending key, false by ascending key
// @returns idx, reordered in place
export stableIsortIdx(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
// @function a bounds-checked copy of a[i0 .. i1 − 1]: an empty array when the window is empty or out of range, where array.slice would throw a runtime error
// @param a the source array
// @param i0 the first index, inclusive
// @param i1 the end index, exclusive
// @returns a new float array
export 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)
// @function a bounds-checked copy of a[i0 .. i1 − 1]: an empty array when the window is empty or out of range, where array.slice would throw a runtime error
// @param a the source array
// @param i0 the first index, inclusive
// @param i1 the end index, exclusive
// @returns a new int array
export sliceI(array<int> 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_int(0)
// ═══ PRICE GRID ═══
// @function the fewest decimals d (0 to 10) at which t × 10^d is an integer within 1e-9. 0.25 → 2, 0.1 → 1, 0.005 → 3, 1 → 0
// @param t a tick size
// @returns d
export 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
// @function round a price to the nearest multiple of the tick as round(px / tick) × units / 10^d, with units = round(tick × 10^d): integers and one division, so the result is the correctly rounded decimal. A tick ≤ 0 is treated as 0.01
// @param px the price
// @param tick the tick size
// @returns the rounded price
export 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
// @function whether a price is positive and, when the reference is a positive number, within 0.65 × to 1.35 × of it
// @param price the price to test
// @param reference the reference price, or na (or ≤ 0) for no band
// @returns true when the price passes
export withinBand(float price, float reference) =>
bool ok = false
if not na(price)
if price > 0
if na(reference) or reference <= 0
ok := true
else
ok := price >= reference * 0.65 and price <= reference * 1.35
ok
// @function the first rung s of the ladder (ascending) at which (hi − lo) / s ≤ maxLevels; the last rung when none qualifies; na when hi ≤ lo. The ladder must not be empty
// @param lo the low of the span
// @param hi the high of the span
// @param maxLevels the most multiples of the rung the span may hold
// @param ladder the candidate steps, ascending
// @returns the step, or na
export roundStepFor(float lo, float hi, int maxLevels, array<float> ladder) =>
float span = hi - lo
float out = na
if span > 0
int nl = array.size(ladder)
out := array.get(ladder, nl - 1)
bool found = false
for i = 0 to nl - 1
if not found and span / array.get(ladder, i) <= maxLevels
out := array.get(ladder, i)
found := true
out
// one tagged price appended to three parallel arrays (skipped when the price is na)
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
// @function append every multiple of rStep from ceil(lo / rStep) × rStep up to hi to three parallel arrays, each tagged with the caller's two codes. At most 2,000 values, a guard that cannot bind when rStep comes from roundStepFor
// @param lo the low of the span
// @param hi the high of the span
// @param rStep the step, > 0
// @param cP receives the prices
// @param cT receives ty once per price
// @param cL receives lb once per price
// @param ty the caller's first tag code
// @param lb the caller's second tag code
// @returns true
export roundNumbersInto(float lo, float hi, float rStep, array<float> cP, array<int> cT, array<int> cL, int ty, int lb) =>
if hi > lo and rStep > 0
float p = math.ceil(lo / rStep) * rStep
int guard = 0
while p <= hi and guard < 2000
pushTagged(cP, cT, cL, p, ty, lb)
p := p + rStep
guard += 1
true
// ═══ TIME ═══
// the hour in milliseconds
const int H1_MS = 3600000
// @function the calendar date of t in a timezone as one integer, year × 10000 + month × 100 + day
// @param t a UNIX time in milliseconds
// @param tz an IANA timezone name
// @returns the date key, e.g. 20260308
export dateKeyIn(int t, string tz = "America/New_York") =>
year(t, tz) * 10000 + month(t, tz) * 100 + dayofmonth(t, tz)
// @function the minute of the day of t in a timezone, hour × 60 + minute
// @param t a UNIX time in milliseconds
// @param tz an IANA timezone name
// @returns 0 to 1439
export minuteOfDayIn(int t, string tz = "America/New_York") =>
hour(t, tz) * 60 + minute(t, tz)
// @function walk back from one session open to the open `sessions − 1` sessions earlier. Each step goes 20 hours back, re-anchors to openHour:openMinute on that calendar date in tz, and counts unless the new open falls on skipA or skipB; at most 60 steps. The 20-hour step reaches the previous date only for openHour 0 to 19
// @param firstOpen the session open to start from, in milliseconds
// @param sessions how many sessions the window holds, counting the first
// @param tz an IANA timezone name
// @param openHour the session-open hour in tz, 0 to 19
// @param openMinute the session-open minute in tz
// @param skipA a weekday (dayofweek.*) on which no session opens, or −1 for none
// @param skipB a second such weekday, or −1 for none
// @returns the open of the earliest session in the window, in milliseconds
export sessionWindowStart(int firstOpen, int sessions, string tz = "America/New_York", int openHour = 18, int openMinute = 0, int skipA = dayofweek.friday, int skipB = dayofweek.saturday) =>
int openT = firstOpen
int stepsLeft = sessions - 1
int guard = 0
while stepsLeft > 0 and guard < 60
int p = openT - 20 * H1_MS
openT := timestamp(tz, year(p, tz), month(p, tz), dayofmonth(p, tz), openHour, openMinute)
int dw = dayofweek(openT, tz)
if dw != skipA and dw != skipB
stepsLeft -= 1
guard += 1
openT
// ═══ TEXT ═══
// @function whether ch is exactly one character from 0 to 9
// @param ch a string
// @returns true for a single digit
export isDigit(string ch) =>
str.length(ch) == 1 and str.contains("0123456789", ch)
// @function whether ch is exactly one ASCII letter
// @param ch a string
// @returns true for a single letter a-z or A-Z
export isLetter(string ch) =>
str.length(ch) == 1 and str.contains("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", ch)
// @function the character of s at index i, or "" when i is outside 0 .. n − 1
// @param s the text
// @param i the index
// @param n the length of s (passed so a loop computes it once)
// @returns one character or ""
export charAt(string s, int i, int n) =>
string ch = ""
if i >= 0 and i < n
ch := str.substring(s, i, i + 1)
ch
// @function every positive number written in free text, in text order and without duplicates, under the scan rules in the header (thousands groups, one decimal part, range tails; a number touching a letter, ".", ":", "%" or a lone "-" is refused)
// @param s the text
// @param maxOut the most values to return
// @returns a float array of at most maxOut values
export pricesFromText(string s, int maxOut = 40) =>
array<float> out = array.new_float(0)
int n = str.length(s)
int lastEnd = -2
int lastIntDigits = 0
bool lastWasTail = false
int i = 0
while i < n and array.size(out) < maxOut
if not isDigit(charAt(s, i, n))
i += 1
else
int start = i
string prev = charAt(s, start - 1, n)
string intStr = ""
int run = 0
int j = i
bool more = true
while more
while j < n and isDigit(charAt(s, j, n))
intStr := intStr + charAt(s, j, n)
run += 1
j += 1
more := false
if j + 3 < n and run <= 3
if charAt(s, j, n) == "," and isDigit(charAt(s, j + 1, n)) and isDigit(charAt(s, j + 2, n)) and isDigit(charAt(s, j + 3, n))
if j + 4 >= n or not isDigit(charAt(s, j + 4, n))
j += 1
run := 0
more := true
string frac = ""
if j + 1 < n
if charAt(s, j, n) == "." and isDigit(charAt(s, j + 1, n))
j += 1
while j < n and isDigit(charAt(s, j, n))
frac := frac + charAt(s, j, n)
j += 1
string nxt = charAt(s, j, n)
bool isTail = prev == "-" and lastEnd == start - 1
bool valid = true
if isLetter(prev) or prev == "." or prev == ":"
valid := false
if isLetter(nxt) or nxt == ":" or nxt == "%"
valid := false
if prev == "-" and not isTail
valid := false
if isTail and (lastWasTail or str.length(intStr) < lastIntDigits)
valid := false
float value = str.tonumber(str.length(frac) > 0 ? intStr + "." + frac : intStr)
if valid and not na(value)
if value > 0 and value <= 1.7976931348623157e308 and not array.includes(out, value)
array.push(out, value)
lastEnd := j
lastIntDigits := str.length(intStr)
lastWasTail := isTail
i := j
out
// ═══ UNITS ═══
// @function how many whole units fit a currency budget when each unit risks `pts` points at `pv` currency per point: floor(usd / (pts × pv) + 1e-9); 0 unless all three are positive
// @param usd the currency budget
// @param pts the points at risk per unit
// @param pv the currency value of one point for one unit
// @returns a non-negative integer
export unitsForRisk(float usd, float pts, float pv) =>
int ct = 0
if pts > 0 and pv > 0 and usd > 0
ct := int(math.floor(usd / (pts * pv) + 1e-9))
ct
// @function split N whole units into three tranches and a remainder: a1 = min(N, max(1, round(s1 × N))); a2 = min(round (t2Round) or floor(s2 × N), N − a1); a3 = min(floor(s3 × N), N − a1 − a2); remainder = N − a1 − a2 − a3. A negative N counts as 0
// @param N the whole units
// @param s1 the first fraction
// @param s2 the second fraction
// @param s3 the third fraction
// @param t2Round true rounds the second tranche, false floors it
// @returns [a1, a2, a3, remainder]
export trancheAlloc(int N, float s1, float s2, float s3, bool t2Round) =>
int n = math.max(0, N)
int a1 = 0
int a2 = 0
int a3 = 0
if n > 0
a1 := math.min(n, math.max(1, int(math.round(s1 * n))))
a2 := math.min(int(t2Round ? math.round(s2 * n) : math.floor(s2 * n)), n - a1)
a3 := math.min(int(math.floor(s3 * n)), n - a1 - a2)
[a1, a2, a3, n - a1 - a2 - a3]
// ═══ SERIES ═══
// @function Wilder's ATR (TE Math's Atr: the mean of the first nAtr true ranges, then (ATR × (nAtr − 1) + TR) / nAtr) folded over whole arrays, oldest first; na unless at least nAtr + 1 bars are given and nAtr ≥ 1
// @param h the highs
// @param l the lows
// @param c the closes
// @param nAtr the ATR length
// @returns the ATR after the last bar, or na
export wilderAtrOf(array<float> h, array<float> l, array<float> c, int nAtr) =>
int len = math.min(array.size(h), math.min(array.size(l), array.size(c)))
float a = na
if len >= nAtr + 1 and nAtr >= 1
tem.Atr w = tem.Atr.new(nAtr)
for i = 0 to len - 1
tem.atrStep(w, array.get(h, i), array.get(l, i), array.get(c, i))
a := w.value
a
// @function the median of the last `lookback` values divided by the median of all of them; na unless there are at least 2 × lookback values and the overall median is positive
// @param vols the values, oldest first (volumes, for a relative-volume reading)
// @param lookback how many recent values form the numerator
// @returns the ratio, or na
export medianVolumeRatio(array<float> vols, int lookback) =>
float r = na
int n = array.size(vols)
if n >= lookback * 2
float base = array.median(vols)
if base > 0
r := array.median(sliceF(vols, n - lookback, n)) / base
r
// @function 100 × the mid-rank of the LAST value among up to `cap` values before it, by TE Math's Rank ((count strictly below + half the exact ties) / n); na until `minN` values are held or when the last value is na. The last value is rated before it would join, never against itself
// @param atrs the values, oldest first (per-bucket ATR readings, for a volatility percentile)
// @param cap the most earlier values to compare against, ≥ 1
// @param minN the fewest earlier values a rank needs
// @returns 0 to 100, or na
export percentileOfLast(array<float> atrs, int cap, int minN) =>
float pct = na
int na0 = array.size(atrs)
if na0 > 0
tem.Rank r = tem.rankNew(math.min(cap, na0), minN)
if na0 > 1 and cap >= 1
for i = math.max(0, na0 - cap - 1) to na0 - 2
tem.rankPush(r, array.get(atrs, i))
float q = tem.rankOf(r, array.get(atrs, na0 - 1))
if not na(q)
pct := q * 100
pct
// ═══ 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: six of the exports applied to
// this chart's own closed bars. Everything is folded on barstate.isconfirmed and read from the arrays of closed bars, so
// nothing here repaints; the table is written on the last bar. It works on any market: the round-number ladder spans
// 0.0001 to 10,000, the calendar keys use the symbol's own exchange time zone, and a symbol with no volume is said to
// have none rather than given a ratio.
const int DEMO_N = 200
const int DEMO_ATR_N = 14
const int DEMO_RVOL_N = 30
var array<float> DEMO_LADDER = array.from(0.0001, 0.001, 0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 2500.0, 5000.0, 10000.0)
var tem.Atr demoAtr = tem.Atr.new(DEMO_ATR_N)
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 array<float> dA = array.new_float(0)
var int demoLastT = na
if barstate.isconfirmed
tem.atrStep(demoAtr, high, low, close)
array.push(dH, high)
array.push(dL, low)
array.push(dC, close)
array.push(dV, nz(volume))
if not na(demoAtr.value)
array.push(dA, demoAtr.value)
if array.size(dH) > DEMO_N
array.shift(dH)
array.shift(dL)
array.shift(dC)
array.shift(dV)
if array.size(dA) > 500
array.shift(dA)
demoLastT := time
var table demoTbl = table.new(position.top_right, 2, 6, bgcolor = TE_SURFACE, border_color = TE_BORDER, border_width = 1)
if barstate.islast and array.size(dH) > 0
int nb = array.size(dH)
float lastMid = roundToTick((array.last(dH) + array.last(dL)) / 2, syminfo.mintick)
float lo = array.min(dL)
float hi = array.max(dH)
float rStep = roundStepFor(lo, hi, 8, DEMO_LADDER)
array<float> rP = array.new_float(0)
array<int> rT = array.new_int(0)
array<int> rL = array.new_int(0)
roundNumbersInto(lo, hi, rStep, rP, rT, rL, 0, 0)
int dKey = dateKeyIn(demoLastT, syminfo.timezone)
int dMin = minuteOfDayIn(demoLastT, syminfo.timezone)
float wAtr = wilderAtrOf(dH, dL, dC, DEMO_ATR_N)
float pct = percentileOfLast(dA, 499, 50)
float rv = medianVolumeRatio(dV, DEMO_RVOL_N)
string midTxt = str.tostring(lastMid, format.mintick)
string stepTxt = na(rStep) ? "none" : str.tostring(rStep)
string keyTxt = str.tostring(dKey) + " " + str.tostring(math.floor(dMin / 60)) + ":" + (dMin % 60 < 10 ? "0" : "") + str.tostring(dMin % 60)
string atrTxt = na(wAtr) ? "warming" : str.tostring(wAtr, format.mintick)
string pctTxt = na(pct) ? "warming" : str.tostring(math.round(pct)) + " / 100"
string rvTxt = na(rv) ? (array.max(dV) == 0 or (array.size(dV) >= DEMO_RVOL_N * 2 and array.median(dV) == 0) ? "no volume data" : "warming") : str.tostring(rv, "#.##") + "×"
tipMid = teTeach("The midpoint of the last closed bar, (high + low) / 2, rounded to this symbol's tick of " + str.tostring(syminfo.mintick) + ": " + midTxt + ".", "roundToTick: d = the fewest decimals at which the tick is a whole number, then round(price / tick) × round(tick × 10^d) / 10^d, integers and one division.", "A price computed from other prices rarely lands on the grid a market actually trades on; this puts it back on that grid without leaving binary residue in the last digits.", "It is arithmetic on one bar; the midpoint is not a level and says nothing about what price does next.")
table.cell(demoTbl, 0, 0, "Midpoint on tick", text_color = TE_TEXT_2, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipMid)
table.cell(demoTbl, 1, 0, midTxt, text_color = TE_TEXT, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipMid)
tipStep = teTeach("Over the last " + str.tostring(nb) + " closed bars (" + str.tostring(lo, format.mintick) + " to " + str.tostring(hi, format.mintick) + ") the round-number step is " + stepTxt + ", giving " + str.tostring(array.size(rP)) + " multiples inside that span.", "roundStepFor takes the first rung of a ladder from 0.0001 to 10,000 at which (high − low) / rung ≤ 8; roundNumbersInto lists every multiple of it from ceil(low / step) × step up to the high.", "It scales round numbers to whatever the symbol trades at, so a 1.10 currency pair and a 60,000 coin both get a handful of lines rather than none or thousands.", "Round numbers are a reference grid, not support or resistance; nothing here says price reacts at them.")
table.cell(demoTbl, 0, 1, "Round-number step", text_color = TE_TEXT_2, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipStep)
table.cell(demoTbl, 1, 1, stepTxt, text_color = TE_TEXT, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipStep)
tipKey = teTeach("The last closed bar opened on " + keyTxt + " in this symbol's exchange time zone, " + syminfo.timezone + ".", "dateKeyIn = year × 10000 + month × 100 + day and minuteOfDayIn = hour × 60 + minute, both resolved by the time-zone database, so daylight-saving changes are handled.", "One integer per calendar date and per minute makes it cheap to group bars by day or by time of day in the market's own clock, whatever time zone the viewer is in.", "It is a calendar label; it knows nothing about holidays or which hours a market is open.")
table.cell(demoTbl, 0, 2, "Exchange date, time", text_color = TE_TEXT_2, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipKey)
table.cell(demoTbl, 1, 2, keyTxt, text_color = TE_TEXT, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipKey)
tipAtr = teTeach("Wilder's average true range over the last " + str.tostring(nb) + " closed bars, length " + str.tostring(DEMO_ATR_N) + ": " + atrTxt + ".", "wilderAtrOf folds the arrays oldest first: the mean of the first 14 true ranges, then ATR = (ATR × 13 + true range) / 14; true range = max(high − low, |high − prior close|, |low − prior close|).", "It is the same estimator as ta.atr, computed from stored arrays, which is what a script needs when its bars are aggregated rather than the chart's own.", "Seeded at the start of the window, it can differ slightly from an ATR run over the whole history; it measures how far bars travelled, not which way they go next.")
table.cell(demoTbl, 0, 3, "Wilder ATR 14", text_color = TE_TEXT_2, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipAtr)
table.cell(demoTbl, 1, 3, atrTxt, text_color = TE_TEXT, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipAtr)
tipPct = teTeach("Where the latest ATR 14 reading sits among up to 499 readings before it: " + pctTxt + ".", "percentileOfLast = 100 × (count strictly below + half the exact ties) / count, the latest reading rated before it joins; it waits for 50 earlier readings.", "It turns an ATR in points, which cannot be compared across symbols, into a position within this symbol's own recent history.", "A percentile describes the past readings it was given; it names no band and does not say whether volatility will rise or fall.")
table.cell(demoTbl, 0, 4, "ATR percentile", text_color = TE_TEXT_2, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipPct)
table.cell(demoTbl, 1, 4, pctTxt, text_color = TE_TEXT, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipPct)
tipRv = teTeach("The median volume of the last " + str.tostring(DEMO_RVOL_N) + " closed bars against the median of the last " + str.tostring(nb) + ": " + rvTxt + ".", "medianVolumeRatio = median(last 30 volumes) / median(all volumes held); it needs at least 60 bars and a positive overall median.", "Medians keep one enormous bar from dominating the comparison, so the ratio says whether recent bars are typically busier or quieter than usual.", "On a symbol whose feed carries no volume there is no ratio to show, and it says so; a ratio is not a direction.")
table.cell(demoTbl, 0, 5, "Median volume ratio", text_color = TE_TEXT_2, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipRv)
table.cell(demoTbl, 1, 5, rvTxt, text_color = TE_TEXT, text_font_family = font.family_monospace, text_size = size.small, tooltip = tipRv)