本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
// https://creativecommons.org/licenses/by-nc-sa/4.0/
// © AlgoNorth
//@version=6
indicator("Pullback Quantile Trend [AlgoNorth]", "P.Q.T", overlay = true)
// ─── Inputs ──────────────────────────────────────────────────────────────
string GRP_B = "Pullbacks"
int swingLen = input.int(5, "Swing length", minval = 2, maxval = 30, group = GRP_B, tooltip = "Bars on each side that confirm a swing high or low. A dip is measured from the most recent confirmed swing high down to the lowest close before price closes back above that high. A short bounce inside the dip does not end it unless it becomes a confirmed swing high itself. A rally is the mirror of that from a swing low.")
int sampleN = input.int(30, "Pullbacks in the sample", minval = 10, maxval = 100, group = GRP_B, tooltip = "How many of the most recent completed pullbacks on each side feed the trail distance and the panel.")
int pctl = input.int(80, "Trail percentile", minval = 50, maxval = 95, group = GRP_B, tooltip = "The trail sits this far behind the trend's extreme: the depth, in ATR (14), that this share of past completed pullbacks stayed inside. Higher = a wider trail that flips less often.")
string GRP_T = "Trend"
int smoothLen = input.int(10, "Line smoothing", minval = 1, maxval = 30, group = GRP_T, tooltip = "Two-pass smoothing on the drawn line, so it curves instead of stepping. 1 = no smoothing. Drawing only: the trend flips on the trail level itself, and the panel shows that level. The higher this is, the further the drawn line can sit from that level in a fast move, so a flip can come before price crosses the drawn line.")
bool colorBars = input.bool(true, "Colour candles", group = GRP_T, tooltip = "In the bull colour while the trend is bullish, the bear colour while it is bearish.")
string GRP_C = "Cloud"
bool showCloud = input.bool(true, "Show cloud", group = GRP_C, tooltip = "Six layers between the drawn line and the smoothed extreme of the trend, densest at the line. After a flip the cloud takes the new trend's colour straight away, then narrows and crosses over the line as the two ease toward each other. In a short trend it can flip again before it has crossed.")
int cloudTr = input.int(40, "Cloud transparency (inner)", minval = 0, maxval = 80, group = GRP_C, tooltip = "Transparency of the layer next to the line. The layers further out fade evenly toward 88.")
string GRP_P = "Panel"
bool showPanel = input.bool(true, "Show panel", group = GRP_P, tooltip = "Reads the trend, the level that flips it and how close each of the last 24 closes came to the trail.")
string panelPos = input.string("Top right", "Position", options = ["Top right", "Middle right", "Bottom right", "Top left", "Bottom left"], group = GRP_P)
string panelTxt = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = GRP_P)
string GRP_S = "Style"
color bullCol = input.color(#00E676, "Bull · Bear · Neutral", inline = "c1", group = GRP_S)
color bearCol = input.color(#FF1744, "", inline = "c1", group = GRP_S)
color neutCol = input.color(#787B86, "", inline = "c1", group = GRP_S)
color lineCol = input.color(#FFFFFF, "Trend line", group = GRP_S)
// ─── Helpers ─────────────────────────────────────────────────────────────
// two-pass EMA
ema2(float x, float len) =>
var float e1 = na
var float e2 = na
float al = 2.0 / (len + 1)
e1 := na(e1) ? x : e1 + (x - e1) * al
e2 := na(e2) ? e1 : e2 + (e1 - e2) * al
e2
// the trend's extreme, extended by the current bar
extFor(int tr, float e) =>
tr == 1 ? math.max(e, high) : math.min(e, low)
// the trail behind an extreme: the target distance, never moving away from price
trailFor(int tr, float e, float s, float dq, float rq, float a) =>
tr == 1 ? math.max(s, e - dq * a) : math.min(s, e + rq * a)
// how much of the room between the extreme and the trail a close has used, in percent (100 = the trail)
roomFor(int tr, float e, float s, float c) =>
(tr == 1 ? e - c : c - e) / math.max(math.abs(e - s), syminfo.mintick) * 100
// one colour channel's share of brightness, for the contrast test below
lin(float c) =>
float v = c / 255
v <= 0.03928 ? v / 12.92 : math.pow((v + 0.055) / 1.055, 2.4)
// black or white text, whichever has more contrast on a background colour
inkOn(color bg) =>
float l = 0.2126 * lin(color.r(bg)) + 0.7152 * lin(color.g(bg)) + 0.0722 * lin(color.b(bg))
(l + 0.05) / 0.05 >= 1.05 / (l + 0.05) ? color.rgb(0, 0, 0) : color.rgb(255, 255, 255)
fmtP(float v) => str.tostring(v, format.mintick)
fmtAtr(float v) => str.tostring(v, "0.0")
fmtPct(float v) => str.tostring(math.round(v)) + "%"
countText(int n, string one, string many) => str.tostring(n) + " " + (n == 1 ? one : many)
barsText(int n) => countText(n, "bar", "bars")
// 81st, 82nd, 83rd, 84th. Only used for the percentile, which runs from 50 to 95.
ordinal(int n) => str.tostring(n) + (n % 10 == 1 ? "st" : n % 10 == 2 ? "nd" : n % 10 == 3 ? "rd" : "th")
// share of the room to the trail used, as a block height
roomGlyph(float p) =>
p >= 100 ? "█" : p >= 85 ? "▇" : p >= 70 ? "▆" : p >= 55 ? "▅" : p >= 42 ? "▄" : p >= 30 ? "▃" : p >= 15 ? "▂" : "▁"
// ─── Pullback depths ─────────────────────────────────────────────────────
// A dip: after a confirmed swing high, how far below it the lowest close got before a bar closed back above it.
// A rally: after a confirmed swing low, how far above it the highest close got before a bar closed back below it.
// A newly confirmed swing replaces the one being watched, so a pullback is measured from the most recent confirmed
// swing. Depths are kept in ATR. Only completed pullbacks are recorded: one that price never recovers from is
// dropped when the next swing confirms. Everything updates on closed bars.
const int MIN_N = 10
float atr = ta.atr(14)
float ph = ta.pivothigh(high, swingLen, swingLen)
float pl = ta.pivotlow(low, swingLen, swingLen)
float loSince = ta.lowest(close, swingLen)
float hiSince = ta.highest(close, swingLen)
var float shPrice = na
var float shLowC = na
var float slPrice = na
var float slHighC = na
var array<float> dips = array.new<float>()
var array<float> rallies = array.new<float>()
var int dipBar = na
var int ralBar = na
var int lastSide = 0
var float lastDepth = na
var int lastBar = na
if barstate.isconfirmed
// the swing high being watched: track the lowest close, record the dip when a bar closes back above it
if not na(shPrice)
shLowC := math.min(shLowC, close)
if close > shPrice
if atr > 0
dips.push((shPrice - shLowC) / atr)
if dips.size() > sampleN
dips.shift()
dipBar := bar_index
lastSide := 1
lastDepth := dips.last()
lastBar := bar_index
shPrice := na
// the swing low being watched: track the highest close, record the rally when a bar closes back below it
if not na(slPrice)
slHighC := math.max(slHighC, close)
if close < slPrice
if atr > 0
rallies.push((slHighC - slPrice) / atr)
if rallies.size() > sampleN
rallies.shift()
ralBar := bar_index
lastSide := -1
lastDepth := rallies.last()
lastBar := bar_index
slPrice := na
// a newly confirmed swing replaces the one being watched
if not na(ph)
shPrice := ph
shLowC := loSince
if not na(pl)
slPrice := pl
slHighC := hiSince
// with at least 10 pullbacks and a percentile of 95 or less, the percentile is always within the sample
bool ready = dips.size() >= MIN_N and rallies.size() >= MIN_N
float dipQ = ready ? dips.percentile_linear_interpolation(pctl) : na
float rallyQ = ready ? rallies.percentile_linear_interpolation(pctl) : na
// ─── Trend ───────────────────────────────────────────────────────────────
// The trail sits behind the trend's extreme by the chosen percentile of past pullback depths. It follows each new
// extreme, tightens when ATR or the percentile falls, and never moves away from price. Each closed bar first extends
// the extreme and tightens the trail, then its close is tested against the trail as it now stands: a close beyond it
// flips the trend. The drawn line is the trail smoothed, so it is never part of the flip test.
// Each closed bar is also logged for the panel's tape: its trend, whether it flipped, whether it set a new extreme,
// and how much of the room between the extreme and the trail its close used.
const int COLS = 24
var int trend = 0
var float ext = na
var float stop = na
var int flipBar = na
var int extBar = na
var int flips = 0
var array<int> runs = array.new<int>()
var float curMax = 0.0
var int curMaxBar = na
var int prevDir = 0
var int prevLen = na
var float prevMax = na
var float prevExt = na
var float prevEnd = na
var array<int> hState = array.new<int>()
var array<bool> hFlip = array.new<bool>()
var array<bool> hNew = array.new<bool>()
var array<float> hRoom = array.new<float>()
bool flipUp = false
bool flipDn = false
if barstate.isconfirmed and ready
float extBefore = ext
if trend == 0
// starts on the side of the most recent completed pullback
trend := lastSide
ext := trend == 1 ? high : low
stop := trend == 1 ? high - dipQ * atr : low + rallyQ * atr
flipBar := bar_index
extBar := bar_index
curMaxBar := bar_index
else
// extend the extreme and tighten the trail, then test the close against it
ext := extFor(trend, ext)
stop := trailFor(trend, ext, stop, dipQ, rallyQ, atr)
flipDn := trend == 1 and close < stop
flipUp := trend == -1 and close > stop
if flipUp or flipDn
runs.push(bar_index - flipBar)
if runs.size() > 500
runs.shift()
// the trend that just ended
prevDir := trend
prevLen := bar_index - flipBar
prevMax := curMax
prevExt := ext
prevEnd := math.abs(close - ext) / atr
// the new one
trend := flipUp ? 1 : -1
ext := flipUp ? high : low
stop := flipUp ? high - dipQ * atr : low + rallyQ * atr
flipBar := bar_index
extBar := bar_index
curMax := 0.0
curMaxBar := bar_index
flips += 1
bool flipped = flipUp or flipDn
bool newExt = not flipped and not na(extBefore) and ext != extBefore
if newExt
extBar := bar_index
float room = na
if not flipped
room := roomFor(trend, ext, stop, close)
if room >= curMax
curMax := room
curMaxBar := bar_index
hState.push(trend)
hFlip.push(flipped)
hNew.push(newExt)
hRoom.push(room)
if hState.size() > COLS
hState.shift()
hFlip.shift()
hNew.shift()
hRoom.shift()
// the trail and the trend's extreme, smoothed for drawing
float trendLine = ema2(stop, smoothLen)
float farEdge = ema2(ext, smoothLen)
color stateCol = trend == 1 ? bullCol : trend == -1 ? bearCol : neutCol
barcolor(colorBars and trend != 0 ? stateCol : na)
// ─── Cloud ───────────────────────────────────────────────────────────────
// From the trend line out to the smoothed extreme, in the trend's colour. On a flip the trail jumps to the other
// side of price and the extreme resets, so the line and the far edge ease toward each other, cross, and the cloud
// reopens on the other side.
bool ribOn = showCloud and trend != 0
float ribW = farEdge - trendLine
float trStp = (88 - cloudTr) / 5.0
layer(int q) => ribOn ? trendLine + ribW * q / 6.0 : na
pL = plot(trendLine, "Trend line", lineCol, 2)
p1 = plot(layer(1), "Cloud 1", display = display.none)
p2 = plot(layer(2), "Cloud 2", display = display.none)
p3 = plot(layer(3), "Cloud 3", display = display.none)
p4 = plot(layer(4), "Cloud 4", display = display.none)
p5 = plot(layer(5), "Cloud 5", display = display.none)
p6 = plot(layer(6), "Cloud 6", display = display.none)
fill(pL, p1, color.new(stateCol, cloudTr), "Cloud fill 1")
fill(p1, p2, color.new(stateCol, cloudTr + trStp), "Cloud fill 2")
fill(p2, p3, color.new(stateCol, cloudTr + 2 * trStp), "Cloud fill 3")
fill(p3, p4, color.new(stateCol, cloudTr + 3 * trStp), "Cloud fill 4")
fill(p4, p5, color.new(stateCol, cloudTr + 4 * trStp), "Cloud fill 5")
fill(p5, p6, color.new(stateCol, 88), "Cloud fill 6")
// ─── Panel ───────────────────────────────────────────────────────────────
// Two headed sections side by side, split by an empty gap column. Left, under a grey STATS bar: the trend, the
// level that flips it and the pullback stats. Right, under a trend-coloured TRAIL TAPE bar and on its own shaded
// background: the last 24 bars, one table column per bar. While a bar is open it is the last column and updates
// live. The strip shows each bar's trend, the row above the blocks marks new extremes and flips, and the blocks and
// numbers show how much of the room between the extreme and the trail each close used.
const int LEFT = 2
const int P0 = LEFT + 1
const int NOW_S = COLS - 4
const int R_SEC = 4
const int R_READ = 5
const int R_TAGS = 6
const int R_TAPE = 7
const int R_EX = 8
const int R_DEPTH = 9
const int R_NUM = 10
const int R_PB = 11
const int R_AXIS = 12
const int R_SUM = 13
const int R_KEY = 14
const int R_END = 15
const int R_LAST = 16
color fg = chart.fg_color
color plotBg = color.new(fg, 91)
pSize = panelTxt == "Tiny" ? size.tiny : panelTxt == "Normal" ? size.normal : size.small
vSize = panelTxt == "Tiny" ? size.normal : panelTxt == "Normal" ? size.huge : size.large
gSize = panelTxt == "Tiny" ? size.small : panelTxt == "Normal" ? size.large : size.normal
nSize = panelTxt == "Tiny" ? size.tiny : size.small
pPos = panelPos == "Top left" ? position.top_left : panelPos == "Bottom left" ? position.bottom_left : panelPos == "Middle right" ? position.middle_right : panelPos == "Bottom right" ? position.bottom_right : position.top_right
wideRow(table t, int r, string s, color c, string sz, string tip = "", color bg = na, bool bold = false) =>
t.cell(0, r, s, text_color = c, bgcolor = bg, text_halign = text.align_left, text_size = sz, text_formatting = bold ? text.format_bold : text.format_none, tooltip = tip)
t.merge_cells(0, r, P0 + COLS - 1, r)
// a label and its value; the tooltip shows on both
dataRow(table t, int r, string l, string v, color c, string tip) =>
t.cell(0, r, l, text_color = fg, text_halign = text.align_left, text_size = pSize, tooltip = tip)
t.cell(1, r, v, text_color = c, text_halign = text.align_right, text_size = pSize, tooltip = tip)
// one text cell on the tape background, merged across `len` tape columns from `start`
span(table t, int r, int start, int len, string s, color c, string al, bool bold = false, color bg = na) =>
t.cell(P0 + start, r, s, text_color = c, bgcolor = na(bg) ? plotBg : bg, text_halign = al, text_size = pSize, text_formatting = bold ? text.format_bold : text.format_none)
t.merge_cells(P0 + start, r, P0 + start + len - 1, r)
// one tape cell on the tape background
tapeCell(table t, int c, int r, string s = "", color tc = na, string sz = size.small, color bg = na, string tip = "", string va = text.align_center) =>
t.cell(P0 + c, r, s, text_color = tc, bgcolor = na(bg) ? plotBg : bg, text_size = sz, text_valign = va, tooltip = tip)
var table panel = na
if barstate.islast and showPanel
// rebuilt on every update because the tape's tags move
table.delete(panel)
panel := table.new(pPos, P0 + COLS, R_LAST + 1, bgcolor = chart.bg_color, frame_color = color.new(fg, 70), frame_width = 1, border_color = color.new(fg, 85), border_width = 1)
wideRow(panel, 0, "Pullback Quantile Trend [AlgoNorth]", inkOn(stateCol), pSize, bg = stateCol, bold = true)
wideRow(panel, 1, "swing " + str.tostring(swingLen) + " · sample " + str.tostring(sampleN) + " · trail " + ordinal(pctl) + " percentile · smoothing " + str.tostring(smoothLen) + (colorBars ? " · candles on" : ""), fg, pSize, "Live settings: swing length · pullbacks in the sample · trail percentile · line smoothing · candle colouring.")
wideRow(panel, R_LAST, "Last bar " + str.format_time(time, "yyyy-MM-dd HH:mm", syminfo.timezone) + " exchange time · " + countText(bar_index + 1, "bar", "bars") + " calculated", fg, pSize, "Time of the last bar and how many bars this indicator has calculated, so you can see the panel has recalculated.")
if not ready
wideRow(panel, 2, "COLLECTING PULLBACKS", stateCol, vSize, bold = true)
wideRow(panel, 3, countText(dips.size(), "dip", "dips") + " and " + countText(rallies.size(), "rally", "rallies") + " measured · " + str.tostring(MIN_N) + " of each needed", fg, pSize)
else
float a = math.max(atr, syminfo.mintick)
bool up = trend == 1
bool live = not barstate.isconfirmed
string kind = up ? "dips" : "rallies"
color oppCol = up ? bearCol : bullCol
// the extreme and the trail as the current bar leaves them. On a closed bar these are the stored values;
// on an open bar they are what its close will be tested against. The extreme already includes this bar,
// so the pullback and the room used can never be negative.
float extL = extFor(trend, ext)
float stopL = trailFor(trend, extL, stop, dipQ, rallyQ, atr)
bool past = up ? close < stopL : close > stopL
// the sample the trend is using
array<float> smp = dips
if not up
smp := rallies
float qT = up ? dipQ : rallyQ
float q25 = smp.percentile_linear_interpolation(25)
float q50 = smp.percentile_linear_interpolation(50)
float q75 = smp.percentile_linear_interpolation(75)
float cur = (up ? extL - close : close - extL) / a
float gap = math.abs(extL - stopL) / a
float left = math.abs(close - stopL) / a
// the current pullback against past ones, and against the room to the trail (shown up to 100%, the trail)
int below = 0
for v in smp
if v < cur
below += 1
int rank = math.round(100.0 * below / smp.size())
float roomNow = math.min(100.0, roomFor(trend, extL, stopL, close))
bool callNow = roomNow >= curMax
float closest = math.max(curMax, roomNow)
string callAgo = callNow ? "now" : barsText(bar_index - curMaxBar) + " ago"
int extAgo = extL != ext ? 0 : bar_index - extBar
// verdict and read line
string runTxt = runs.size() > 0 ? " · typical run " + barsText(math.round(runs.median())) : ""
string verdict = past ? (up ? "BULL · PRICE BELOW THE TRAIL" : "BEAR · PRICE ABOVE THE TRAIL") : (up ? "BULL · ABOVE THE TRAIL" : "BEAR · BELOW THE TRAIL")
wideRow(panel, 2, verdict, stateCol, vSize, bold = true)
wideRow(panel, 3, barsText(bar_index - flipBar) + " in this trend · current pullback deeper than " + str.tostring(rank) + "% of the last " + str.tostring(smp.size()) + " " + kind, fg, pSize, "How long the trend has run since a bar last closed beyond the trail, and how the current pullback compares with past pullbacks of the same kind.")
// section bars, and the gap column between the two sections
panel.cell(0, R_SEC, "STATS", text_color = fg, bgcolor = color.new(neutCol, 55), text_halign = text.align_left, text_size = pSize, text_formatting = text.format_bold)
panel.merge_cells(0, R_SEC, LEFT - 1, R_SEC)
panel.cell(LEFT, R_SEC, "", bgcolor = chart.bg_color)
panel.merge_cells(LEFT, R_SEC, LEFT, R_END)
span(panel, R_SEC, 0, COLS, "TRAIL TAPE · last " + str.tostring(COLS) + " bars · how close each close came to the trail", inkOn(stateCol), text.align_left, true, color.new(stateCol, 10))
// stats
dataRow(panel, 5, up ? "Flips bear below" : "Flips bull above", fmtP(stopL) + (past ? " · price is past it" : " · " + fmtAtr(left) + " ATR away"), oppCol, "The trail level. A bar closing beyond it flips the trend. The white line eases toward this level, so the two can sit apart for some bars after a flip or a fast move. On the bar that flips, the new level is set from that bar's own high or low, so price may already have traded through it on that bar.")
dataRow(panel, 6, "Current pullback", fmtAtr(cur) + " ATR from the " + (up ? "high" : "low"), cur > q75 ? oppCol : fg, "How far price has pulled back from this trend's extreme, in ATR (14). It changes colour once it is deeper than three quarters of past pullbacks.")
dataRow(panel, 7, "Room used", past ? "past the trail" : fmtPct(roomNow) + " · " + fmtAtr(left) + " ATR left", roomNow >= 75 ? oppCol : fg, "How much of the gap between the trend's extreme and the trail the current pullback has used. 100% is the trail, where a close flips the trend. It changes colour at 75%.")
dataRow(panel, 8, "Trail distance", fmtAtr(gap) + " ATR · target " + fmtAtr(qT), fg, "How far the trail sits behind the extreme right now, in ATR (14), and its target: the depth that the chosen percentile of past pullbacks stayed inside. The trail never moves away from price, so the distance can be smaller than the target after ATR or the percentile has risen.")
dataRow(panel, 9, "Pullback depth 25 / 50 / 75", fmtAtr(q25) + " / " + fmtAtr(q50) + " / " + fmtAtr(q75) + " ATR", fg, "The 25th, 50th and 75th percentile of past pullback depths on the side this trend is using.")
dataRow(panel, 10, up ? "Trend high" : "Trend low", fmtP(extL) + " · " + (extAgo == 0 ? "set on this bar" : "set " + barsText(extAgo) + " ago"), fg, "The highest high of this uptrend or the lowest low of this downtrend, and when it was set. The trail is measured from it. The trail follows each new extreme, and also tightens when ATR or the pullback percentile falls.")
dataRow(panel, 11, "Pullbacks in the sample", countText(dips.size(), "dip", "dips") + " · " + countText(rallies.size(), "rally", "rallies"), fg, "The most recent completed pullbacks on each side, up to the sample setting. A dip is measured from the most recent confirmed swing high down to the lowest close before price closed back above it. A rally is the mirror of that from a swing low. A pullback that price never recovers from is not counted.")
dataRow(panel, 12, "Last pullback", (lastSide == 1 ? "▲ dip " : "▼ rally ") + fmtAtr(lastDepth) + " ATR · " + barsText(bar_index - lastBar) + " ago", lastSide == 1 ? bullCol : bearCol, "The most recent completed pullback: its kind, depth and age.")
dataRow(panel, 13, "Previous trend", prevDir == 0 ? "none completed yet" : (prevDir == 1 ? "bull · " : "bear · ") + barsText(prevLen) + " · " + (prevDir == 1 ? "high " : "low ") + fmtP(prevExt), prevDir == 1 ? bullCol : prevDir == -1 ? bearCol : fg, "The trend before this one: its direction, length and extreme.")
dataRow(panel, 14, "Closest call this trend", fmtPct(closest) + " of the room · " + callAgo, closest >= 75 ? oppCol : fg, "The most room to the trail any close in this trend has used, and when. It changes colour at 75%.")
dataRow(panel, 15, "Flips on this chart", str.tostring(flips) + runTxt, fg, "Trend flips across the calculated history, and the median length of the last 500 trends.")
// tape data: the logged closed bars, plus the open bar as the last column while it is forming
array<int> dState = hState.copy()
array<bool> dFlip = hFlip.copy()
array<bool> dNew = hNew.copy()
array<float> dRoom = hRoom.copy()
if live
dState.push(trend)
dFlip.push(false)
dNew.push(extL != ext)
dRoom.push(roomNow)
if dState.size() > COLS
dState.shift()
dFlip.shift()
dNew.shift()
dRoom.shift()
// tape: newest on the right
int n = dState.size()
int off = COLS - n
int fc = -1
for c = 0 to COLS - 1
int i = c - off
tapeCell(panel, c, R_TAGS)
tapeCell(panel, c, R_AXIS)
if i < 0
tapeCell(panel, c, R_TAPE)
tapeCell(panel, c, R_EX)
tapeCell(panel, c, R_DEPTH)
tapeCell(panel, c, R_NUM)
else
int st = dState.get(i)
bool fl = dFlip.get(i)
bool nx = dNew.get(i)
int rr = fl ? 100 : math.round(dRoom.get(i))
int ago = COLS - 1 - c
color tc = st == 1 ? bullCol : bearCol
if fl
fc := c
string tip = (ago == 0 ? (live ? "open bar" : "last closed bar") : barsText(ago) + (live ? " ago" : " before the last close")) + (fl ? " · flip" : " · " + str.tostring(rr) + "% of the room used at the close" + (nx ? " · new extreme" : ""))
tapeCell(panel, c, R_TAPE, bg = fl ? color.new(fg, 78) : color.new(tc, 55), tip = tip)
tapeCell(panel, c, R_EX, fl ? "◆" : nx ? (st == 1 ? "▲" : "▼") : "", fl ? fg : tc, pSize, tip = tip)
tapeCell(panel, c, R_DEPTH, roomGlyph(rr), fl ? fg : tc, gSize, tip = tip, va = text.align_bottom)
tapeCell(panel, c, R_NUM, fl ? "↯" : str.tostring(rr), fg, nSize, tip = tip)
// near misses, flips and the newest bar in bold
if rr >= 85 or c == COLS - 1
panel.cell_set_text_formatting(P0 + c, R_NUM, text.format_bold)
// readout
string pastTxt = live ? "PRICE IS PAST THE TRAIL · FLIPS IF THE BAR CLOSES HERE" : "PRICE IS PAST THE TRAIL · THE NEXT CLOSE PAST IT FLIPS"
span(panel, R_READ, 0, COLS, past ? pastTxt : fmtPct(roomNow) + " OF THE ROOM USED · " + (callNow ? "CLOSEST CALL THIS TREND IS NOW" : "CLOSEST CALL " + fmtPct(curMax) + " · " + str.upper(callAgo)), stateCol, text.align_left, true)
// tags on the right: the flip and the newest column, NOW while its bar is open and LAST once it has closed.
// A flip in the last few bars shares one tag with it.
string nowTxt = live ? "NOW" : "LAST"
int tagEnd = NOW_S
if fc >= NOW_S - 2
int fAgo = COLS - 1 - fc
tagEnd := NOW_S - 4
span(panel, R_TAGS, tagEnd, 8, "FLIP ◆ " + (fAgo == 0 ? nowTxt : str.upper(barsText(fAgo)) + " AGO · " + nowTxt), fg, text.align_right, true)
else
span(panel, R_TAGS, NOW_S, 4, nowTxt, stateCol, text.align_right, true)
if fc >= 0
tagEnd := math.max(0, fc - 1)
span(panel, R_TAGS, tagEnd, 4, "FLIP ◆", fg, text.align_center, true)
// tag on the left: the trend before the last flip, over its own bars only, or the current trend if no flip
// is in view. The arrow shows only when that trend runs off the left edge.
if fc >= 0
int pS = math.max(0, fc - prevLen)
int pN = tagEnd - pS
if pN >= 6
span(panel, R_TAGS, pS, pN, (fc - prevLen < 0 ? "◀ " : "") + (prevDir == 1 ? "BULL · " : "BEAR · ") + str.upper(barsText(prevLen)), prevDir == 1 ? bullCol : bearCol, text.align_center, true)
else
span(panel, R_TAGS, 0, NOW_S, "◀ " + (up ? "BULL · " : "BEAR · ") + str.upper(barsText(bar_index - flipBar)), stateCol, text.align_center, true)
// last completed dip and rally
span(panel, R_PB, 0, COLS / 2, "◉ last dip " + fmtAtr(dips.last()) + " ATR · " + barsText(bar_index - dipBar) + " ago", bullCol, text.align_left)
span(panel, R_PB, COLS / 2, COLS / 2, "◉ last rally " + fmtAtr(rallies.last()) + " ATR · " + barsText(bar_index - ralBar) + " ago", bearCol, text.align_left)
// axis: the left label is the age of the oldest bar on the tape
span(panel, R_AXIS, 0, 6, barsText(n - 1) + " back", fg, text.align_left)
span(panel, R_AXIS, 10, 3, "12", fg, text.align_center)
span(panel, R_AXIS, NOW_S, 4, live ? "now" : "last close", fg, text.align_right)
// the trend that ended at the last flip
string sumTxt = prevDir == 0 ? "Previous trend · none completed yet" : "Previous trend · " + (prevDir == 1 ? "bull " : "bear ") + barsText(prevLen) + " · deepest " + fmtPct(prevMax) + " of the room · ended " + fmtAtr(prevEnd) + " ATR " + (prevDir == 1 ? "below its high" : "above its low")
span(panel, R_SUM, 0, COLS, sumTxt, fg, text.align_left)
// key, filling the last two tape rows so the section ends level with the stats
panel.cell(P0, R_KEY, "strip = trend · ▲▼ new extreme · blocks, numbers = % of room used · ◆ ↯ flip", text_color = fg, bgcolor = plotBg, text_halign = text.align_left, text_valign = text.align_top, text_size = pSize, tooltip = "Blocks and numbers are measured at each bar's close, so a wick can reach closer to the trail than the number shows. Numbers in bold are 85% or more, a flip, or the newest bar.")
panel.merge_cells(P0, R_KEY, P0 + COLS - 1, R_END)
// ─── Alerts ──────────────────────────────────────────────────────────────
alertcondition(flipUp, "Trend flips bullish", "Pullback Quantile Trend: a bar closed above the pullback trail")
alertcondition(flipDn, "Trend flips bearish", "Pullback Quantile Trend: a bar closed below the pullback trail")