本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RafaelZioni — High/Low Linear Regression Channel
//
// Upper line = least-squares regression of HIGHS, lower line = regression of LOWS.
// Fit on "Bars" : every bar's high / low over the lookback
// Fit on "Pivots" : only the last N swing highs / swing lows (cleaner, structure-based)
// Placement:
// "Regression" : pure best-fit lines (price can trade outside them)
// "Envelope (touch extremes)": same slopes, shifted so the upper line touches the highest high
// and the lower line the lowest low -> nothing is outside the channel
//@version=6
indicator("High/Low Regression Channel+ Next Pivot Projection", "HL-RegCh", overlay=true, max_bars_back=5000, max_lines_count=40, max_labels_count=150, max_boxes_count=20)
// ───────── Inputs
mode = input.string("Bars", "Fit on", options=["Bars", "Pivots"])
len = input.int(100, "Lookback bars (Bars mode)", minval=5, maxval=4900)
pvL = input.int(5, "Pivot left bars", minval=1, group="Pivots")
pvR = input.int(5, "Pivot right bars", minval=1, group="Pivots")
pvN = input.int(5, "Pivots used per line", minval=2, maxval=50, group="Pivots")
showPv = input.bool(true, "Mark all pivots (any mode)", group="Pivots")
showUsd = input.bool(true, "Label last N pivots (H1.. / L1..)", group="Pivots", tooltip="In Pivots mode these are the points used in the fit")
fit = input.string("Deviation", "Line placement", options=["Deviation", "Regression", "Envelope (touch extremes)"],
tooltip="Deviation: best-fit line pushed out by N x std-dev of residuals (like the built-in Linear Regression Channel). Regression: pure best-fit. Envelope: touches the extreme high/low.")
devU = input.float(1.0, "Upper deviation (x σ of high residuals)", step=0.25, minval=0)
devL = input.float(1.0, "Lower deviation (x σ of low residuals)", step=0.25, minval=0)
midSrc = input.source(close, "Mid line source (Bars mode)")
extR = input.bool(true, "Extend lines right")
showMid = input.bool(true, "Show mid line")
showLbl = input.bool(true, "Show stats table")
tPos = input.string("top_right", "Table position", options=["top_right", "bottom_right", "top_left", "bottom_left"])
gJ = "Next pivot projection"
projOn = input.bool(true, "Project next pivot", group=gJ)
proj2 = input.bool(true, "Also project the one after", group=gJ)
showZn = input.bool(true, "Show uncertainty zone", group=gJ)
cJ = input.color(#FF9800, "Projection colour", group=gJ)
cU = input.color(#2962FF, "Upper (highs)", group="Style")
cL = input.color(#F23645, "Lower (lows)", group="Style")
cM = input.color(#F23645, "Mid", group="Style")
lw = input.int(2, "Line width", minval=1, maxval=5, group="Style")
fillT = input.int(92, "Fill transparency (100 = off)", minval=0, maxval=100, group="Style")
// ───────── Least squares: y = a + b*x, x = bar offset from the current bar (<= 0)
// returns slope b, value at current bar a, R², max and min residual
f_reg(array<float> xs, array<float> ys) =>
n = xs.size()
float b = na
float a = na
float r2 = na
float rMax = na
float rMin = na
float ssResOut = 0.0
if n >= 2
float sx = 0.0
float sy = 0.0
float sxx = 0.0
float sxy = 0.0
float syy = 0.0
for i = 0 to n - 1
x = xs.get(i)
y = ys.get(i)
sx += x
sy += y
sxx += x * x
sxy += x * y
syy += y * y
den = n * sxx - sx * sx
b := den != 0 ? (n * sxy - sx * sy) / den : 0.0
a := (sy - b * sx) / n
float ssRes = 0.0
rMax := -1e300
rMin := 1e300
for i = 0 to n - 1
r = ys.get(i) - (a + b * xs.get(i))
ssRes += r * r
rMax := math.max(rMax, r)
rMin := math.min(rMin, r)
ssTot = syy - sy * sy / n
r2 := ssTot > 0 ? 1 - ssRes / ssTot : 0.0
ssResOut := ssRes
sd = n >= 2 ? math.sqrt(ssResOut / n) : na
[b, a, r2, rMax, rMin, sd]
// ───────── Collect points
var array<int> phX = array.new<int>() // absolute bar index of swing highs
var array<float> phY = array.new<float>()
var array<int> plX = array.new<int>()
var array<float> plY = array.new<float>()
ph = ta.pivothigh(high, pvL, pvR)
pl = ta.pivotlow(low, pvL, pvR)
if not na(ph)
phX.push(bar_index - pvR)
phY.push(ph)
if phX.size() > pvN
phX.shift()
phY.shift()
if not na(pl)
plX.push(bar_index - pvR)
plY.push(pl)
if plX.size() > pvN
plX.shift()
plY.shift()
xsU = array.new_float()
ysU = array.new_float()
xsL = array.new_float()
ysL = array.new_float()
ysM = array.new_float()
xsM = array.new_float()
int startU = na
int startL = na
if mode == "Bars"
n = math.min(len, bar_index + 1)
for i = 0 to n - 1
xsU.push(-i)
ysU.push(high[i])
xsL.push(-i)
ysL.push(low[i])
ysM.push(midSrc[i])
xsM.push(-i)
startU := bar_index - (n - 1)
startL := startU
else
// note: "for i = 0 to -1" runs backwards in Pine, so guard empty arrays
if phX.size() > 0
for i = 0 to phX.size() - 1
xsU.push(phX.get(i) - bar_index)
ysU.push(phY.get(i))
if plX.size() > 0
for i = 0 to plX.size() - 1
xsL.push(plX.get(i) - bar_index)
ysL.push(plY.get(i))
startU := phX.size() > 0 ? phX.first() : na
startL := plX.size() > 0 ? plX.first() : na
[bU, aU, r2U, rMaxU, rMinU, sdU] = f_reg(xsU, ysU)
[bL, aL, r2L, rMaxL, rMinL, sdL] = f_reg(xsL, ysL)
[bM, aM, r2M, rMaxM, rMinM, sdM] = f_reg(xsM, ysM)
env = fit == "Envelope (touch extremes)"
dev = fit == "Deviation"
aU2 = env ? aU + rMaxU : dev ? aU + devU * sdU : aU
aL2 = env ? aL + rMinL : dev ? aL - devL * sdL : aL
// mid: regression of the mid source in Bars mode, otherwise halfway between the lines
useM = mode == "Bars" and not na(bM)
bMid = useM ? bM : (bU + bL) / 2
aMid = useM ? aM : (aU2 + aL2) / 2
upNow = aU2 // channel values at the current bar
loNow = aL2
midNow = aMid
// data window / alerts (current channel; it is refit every bar)
plot(upNow, "Upper now", cU, display=display.data_window)
plot(loNow, "Lower now", cL, display=display.data_window)
plot(midNow, "Mid now", cM, display=display.data_window)
plot(bU, "Upper slope / bar", display=display.data_window)
plot(bL, "Lower slope / bar", display=display.data_window)
// ───────── Pivot marks (all detected swings, placed on the pivot bar)
isPv = showPv
plotshape(isPv and not na(ph), "Pivot high", shape.triangledown, location.abovebar, color.new(cU, 20), offset=-pvR, size=size.tiny, display=display.pane)
plotshape(isPv and not na(pl), "Pivot low", shape.triangleup, location.belowbar, color.new(cL, 20), offset=-pvR, size=size.tiny, display=display.pane)
// ───────── Draw
var array<label> pvLbls = array.new<label>()
var line lnU = na
var line lnL = na
var line lnM = na
var linefill lfU = na
var linefill lfL = na
var label lb = na
f_y(float a, float b, int x) => a + b * (x - bar_index)
if barstate.islast
lnU.delete()
lnL.delete()
lnM.delete()
lb.delete()
for l_ in pvLbls
l_.delete()
pvLbls.clear()
if showUsd
if phX.size() > 0
for i = 0 to phX.size() - 1
pvLbls.push(label.new(phX.get(i), phY.get(i), "H" + str.tostring(i + 1), style=label.style_label_down,
color=cU, textcolor=color.white, size=size.tiny, tooltip=str.tostring(phY.get(i), format.mintick)))
if plX.size() > 0
for i = 0 to plX.size() - 1
pvLbls.push(label.new(plX.get(i), plY.get(i), "L" + str.tostring(i + 1), style=label.style_label_up,
color=cL, textcolor=color.white, size=size.tiny, tooltip=str.tostring(plY.get(i), format.mintick)))
ex = extR ? extend.right : extend.none
if not na(bU) and not na(startU)
lnU := line.new(startU, f_y(aU2, bU, startU), bar_index, aU2, color=cU, width=lw, extend=ex)
if not na(bL) and not na(startL)
lnL := line.new(startL, f_y(aL2, bL, startL), bar_index, aL2, color=cL, width=lw, extend=ex)
if not na(lnU) and not na(lnL)
s0 = math.min(startU, startL)
lnM := line.new(s0, f_y(aMid, bMid, s0), bar_index, aMid, color=showMid ? cM : color.new(cM, 100), width=1, extend=ex)
if fillT < 100
lfU := linefill.new(lnU, lnM, color.new(cU, fillT))
lfL := linefill.new(lnM, lnL, color.new(cL, fillT))
// ───────── Next pivot projection
// Alternating swing list: consecutive same-type pivots are merged (keep the more extreme one)
var array<int> swX = array.new<int>()
var array<float> swY = array.new<float>()
var array<int> swT = array.new<int>() // +1 high, -1 low
f_addSwing(int x, float y, int t) =>
int st = -1
if swT.size() > 0 and swT.last() == t
if (t == 1 and y > swY.last()) or (t == -1 and y < swY.last())
swX.set(swX.size() - 1, x)
swY.set(swY.size() - 1, y)
st := 0 // replaced
else
swX.push(x)
swY.push(y)
swT.push(t)
if swX.size() > 200
swX.shift()
swY.shift()
swT.shift()
st := 1 // new swing
st
// project the pivot that follows a swing at (fromX, fromY, fromT)
f_proj(int fromX, float fromY, int fromT) =>
nt = -fromT
durs = array.new_float()
amps = array.new_float()
xs = array.new_float()
ys = array.new_float()
n = swX.size()
if n >= 2
for i = n - 1 to 1
if swT.get(i) == nt and durs.size() < pvN
durs.push(swX.get(i) - swX.get(i - 1))
amps.push(math.abs(swY.get(i) - swY.get(i - 1)))
if n >= 1
for i = n - 1 to 0
if swT.get(i) == nt and xs.size() < pvN
xs.push(swX.get(i) - bar_index)
ys.push(swY.get(i))
int px = na
float targ = na
float chY = na
float swYv = na
float dSd = na
float zone = na
if durs.size() >= 2
px := fromX + math.round(durs.median())
dSd := durs.stdev()
swYv := fromY + (nt == 1 ? 1 : -1) * amps.median()
[b, a, r2, rMax, rMin, sd] = f_reg(xs, ys)
if not na(b)
chY := a + b * (px - bar_index)
targ := na(chY) ? swYv : (chY + swYv) / 2
zone := math.max(nz(sd), na(chY) ? amps.stdev() / 2 : math.abs(chY - swYv) / 2)
[px, targ, chY, swYv, dSd, zone, nt]
// feed confirmed pivots into the swing list, score the standing projection, re-project
var int pjX = na
var float pjY = na
var int pjT = na
var float pjZ = na
var float pjD = na
var float scN = 0.0
var float scB = 0.0
var float scP = 0.0
var float scIn = 0.0
f_upd(int st, int x, float y, int t) =>
// returns true when a NEW swing of the projected type arrived (to be scored)
st == 1 and not na(pjT) and t == pjT and not na(pjX) and not na(pjY) and not na(pjZ)
if not na(ph)
st = f_addSwing(bar_index - pvR, ph, 1)
if f_upd(st, bar_index - pvR, ph, 1)
scN += 1
scB += math.abs((bar_index - pvR) - pjX)
scP += math.abs(ph - pjY) / ph * 100
scIn += math.abs((bar_index - pvR) - pjX) <= math.max(pjD, 1) and math.abs(ph - pjY) <= pjZ ? 1 : 0
if st >= 0
[a1, b1, c1, d1, e1, f1, g1] = f_proj(swX.last(), swY.last(), swT.last())
pjX := a1
pjY := b1
pjD := e1
pjZ := f1
pjT := g1
if not na(pl)
st = f_addSwing(bar_index - pvR, pl, -1)
if f_upd(st, bar_index - pvR, pl, -1)
scN += 1
scB += math.abs((bar_index - pvR) - pjX)
scP += math.abs(pl - pjY) / pl * 100
scIn += math.abs((bar_index - pvR) - pjX) <= math.max(pjD, 1) and math.abs(pl - pjY) <= pjZ ? 1 : 0
if st >= 0
[a1, b1, c1, d1, e1, f1, g1] = f_proj(swX.last(), swY.last(), swT.last())
pjX := a1
pjY := b1
pjD := e1
pjZ := f1
pjT := g1
var array<line> pjLines = array.new<line>()
var array<box> pjBoxes = array.new<box>()
var array<label> pjLabels = array.new<label>()
f_t(int x) => str.format_time(time + (x - bar_index) * timeframe.in_seconds() * 1000, "dd/MM HH:mm")
f_drawProj(int fx, float fy, int px, float py, float chY, float swYv, float dSd, float zone, int nt, string tag, string extra) =>
lc = nt == 1 ? cU : cL
pjLines.push(line.new(fx, fy, px, py, color=cJ, style=line.style_dashed, width=2))
if showZn
dx = math.max(1, math.round(nz(dSd, 1)))
pjBoxes.push(box.new(px - dx, py + zone, px + dx, py - zone, border_color=color.new(cJ, 60),
bgcolor=color.new(cJ, 94), border_style=line.style_dotted))
tip = tag + (nt == 1 ? " HIGH" : " LOW") + " ≈ " + str.tostring(py, format.mintick) +
"\n" + f_t(px) + " (bar " + (px - bar_index >= 0 ? "+" : "") + str.tostring(px - bar_index) + " ±" + str.tostring(nz(dSd), "0") + ")" +
"\nchannel " + (na(chY) ? "-" : str.tostring(chY, format.mintick)) + " | swing " + str.tostring(swYv, format.mintick) + extra
pjLabels.push(label.new(px, py + (nt == 1 ? zone * 1.15 : -zone * 1.15), tag + (nt == 1 ? " H " : " L ") + str.tostring(py, format.mintick), style=label.style_none,
textcolor=lc, size=size.small, tooltip=tip))
pjLabels.push(label.new(px, py, "", style=label.style_circle, color=cJ, size=size.tiny, tooltip=tip))
if barstate.islast
for o in pjLines
o.delete()
for o in pjBoxes
o.delete()
for o in pjLabels
o.delete()
pjLines.clear()
pjBoxes.clear()
pjLabels.clear()
if projOn and swX.size() >= 3 and not na(pjX)
// live candidate: extreme since the last confirmed swing (not confirmed yet)
lastX = swX.last()
nb = math.min(bar_index - lastX, 499)
float cand = na
int candX = na
if nb >= 1
for i = 0 to nb - 1
v = pjT == 1 ? high[i] : low[i]
if na(cand) or (pjT == 1 ? v > cand : v < cand)
cand := v
candX := bar_index - i
late = pjX < bar_index - pvR
sc = scN > 0 ? "\nhistory n=" + str.tostring(scN, "#") + ": err " + str.tostring(scB / scN, "0.0") + " bars, " +
str.tostring(scP / scN, "0.00") + "% | in zone " + str.tostring(scIn / scN * 100, "0") + "%" : ""
extra = (late ? "\nOVERDUE – watch candidate" : "") + sc
[p0, t0, ch0, sw0, d0, z0, n0] = f_proj(swX.last(), swY.last(), swT.last())
f_drawProj(swX.last(), swY.last(), p0, t0, ch0, sw0, d0, z0, n0, "NEXT", extra)
if not na(candX)
pjLabels.push(label.new(candX, cand, "?", style=pjT == 1 ? label.style_label_down : label.style_label_up,
color=color.new(cJ, 0), textcolor=color.black, size=size.tiny,
tooltip="Unconfirmed extreme since the last swing - becomes a pivot after " + str.tostring(pvR) + " bars without a new extreme"))
if proj2 and not na(p0)
// second step: temporarily add the projected pivot, project again, remove it
swX.push(p0)
swY.push(t0)
swT.push(n0)
[p1, t1, ch1, sw1, d1, z1, n1] = f_proj(p0, t0, n0)
swX.pop()
swY.pop()
swT.pop()
if not na(p1)
f_drawProj(p0, t0, p1, t1, ch1, sw1, d1, z1, n1, "THEN", "")
// ───────── Stats table (keeps the chart clear)
var table st_ = table.new(tPos == "top_right" ? position.top_right : tPos == "bottom_right" ? position.bottom_right : tPos == "top_left" ? position.top_left : position.bottom_left,
2, 14, bgcolor=color.new(#131722, 15), frame_color=color.new(#787B86, 50), frame_width=1, border_width=1, border_color=color.new(#2A2E39, 0))
f_tc(int r, string a, string b, color cb) =>
st_.cell(0, r, a, text_color=#B2B5BE, text_size=size.small, text_halign=text.align_left)
st_.cell(1, r, b, text_color=cb, text_size=size.small, text_halign=text.align_right)
if barstate.islast and showLbl
st_.clear(0, 0, 1, 13)
if mode == "Pivots" and (phX.size() < 2 or plX.size() < 2)
f_tc(0, "Need 2+ pivot highs & lows", str.tostring(phX.size()) + " / " + str.tostring(plX.size()), color.orange)
else if not na(bU) and not na(bL)
conv = bU - bL
shp = math.abs(conv) < 0.1 * math.max(math.abs(bU), math.abs(bL), syminfo.mintick) ? "parallel" : conv > 0 ? "widening" : "narrowing"
dir = bU > 0 and bL > 0 ? "UP" : bU < 0 and bL < 0 ? "DOWN" : "mixed"
pos = upNow > loNow ? (close - loNow) / (upNow - loNow) * 100 : 50
f_tc(0, "Trend", dir + " · " + shp, dir == "UP" ? #26A69A : dir == "DOWN" ? #EF5350 : color.white)
f_tc(1, "High slope / R²", str.tostring(bU, format.mintick) + " · " + str.tostring(r2U, "0.00"), color.white)
f_tc(2, "Low slope / R²", str.tostring(bL, format.mintick) + " · " + str.tostring(r2L, "0.00"), color.white)
f_tc(3, "Width", str.tostring(upNow - loNow, format.mintick), color.white)
f_tc(4, "Position in channel", str.tostring(pos, "0") + "%", color.white)
if projOn and swX.size() >= 3
[q0, qy, qc, qs, qd, qz, qn] = f_proj(swX.last(), swY.last(), swT.last())
if not na(q0)
f_tc(6, "NEXT " + (qn == 1 ? "HIGH" : "LOW"), str.tostring(qy, format.mintick), qn == 1 ? cU : cL)
f_tc(7, " when", f_t(q0) + " (" + (q0 - bar_index >= 0 ? "+" : "") + str.tostring(q0 - bar_index) + " ±" + str.tostring(nz(qd), "0") + " bars)", color.white)
f_tc(8, " channel / swing", (na(qc) ? "-" : str.tostring(qc, format.mintick)) + " / " + str.tostring(qs, format.mintick), color.white)
f_tc(9, " zone ±", str.tostring(qz, format.mintick), color.white)
if q0 < bar_index - pvR
f_tc(10, " status", "OVERDUE", color.orange)
if scN > 0
f_tc(11, "History n", str.tostring(scN, "#"), color.white)
f_tc(12, " avg error", str.tostring(scB / scN, "0.0") + " bars · " + str.tostring(scP / scN, "0.00") + "%", color.white)
f_tc(13, " landed in zone", str.tostring(scIn / scN * 100, "0") + "%", color.white)
// ───────── Alerts
alertcondition(ta.crossover(close, upNow), "Close above upper", "Close broke above the highs regression line")
alertcondition(ta.crossunder(close, loNow), "Close below lower", "Close broke below the lows regression line")
alertcondition(high >= upNow and close < upNow, "Rejected at upper", "Wicked into upper line and closed back inside")
alertcondition(low <= loNow and close > loNow, "Rejected at lower", "Wicked into lower line and closed back inside")