本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Millard Channels and Cycles", shorttitle = "Millard CC", overlay = false, max_bars_back = 5000, max_polylines_count = 50, max_boxes_count = 5)
// After B. J. Millard, "Channels and Cycles: A Tribute to J. M. Hurst" (1999), chapters 4 to 10.
// Price pane: constant-depth channels around centred averages, gap estimates, signals, status table.
// This pane: cycle highlighter (average minus average) or average difference, turning points and
// the chapter 4 prediction box. Centred values are exact up to half a span before the last bar;
// the section after that (the gap) and the projection are estimates recomputed on every bar.
// ---------------------------------------------------------------- inputs
grpC = "Channels"
src = input.source(close, "Source", group = grpC, tooltip = "Millard draws channels on closing prices on a linear price scale.")
innerSpanIn = input.int(41, "Inner span", minval = 5, maxval = 401, step = 2, group = grpC)
useMid = input.bool(true, "Middle", inline = "mid", group = grpC)
midSpanIn = input.int(101, "", minval = 5, maxval = 801, step = 2, inline = "mid", group = grpC)
useOut = input.bool(true, "Outer", inline = "out", group = grpC)
outSpanIn = input.int(201, "", minval = 5, maxval = 801, step = 2, inline = "out", group = grpC)
useSmooth = input.bool(false, "Smoothed averages", group = grpC, tooltip = "Chapter 7: a second simple average of about half the span applied to the first. Off reproduces the simple centred averages used in the chapter 9 and 10 examples. Even spans are raised by one so the average can be centred.")
outsidePct = input.float(3.5, "Points outside boundaries %", minval = 0.5, maxval = 20.0, step = 0.5, group = grpC, tooltip = "Chapter 7: boundaries are placed so that a set share of calculated points lies outside them. The book suggests 3 to 4%.")
depthLen = input.int(750, "Depth lookback, calculated points", minval = 100, maxval = 4000, group = grpC)
grpG = "Gap estimate"
gapMethod = input.string("Millard: curve fit + bending", "Method", options = ["Millard: curve fit + bending", "Curve fit only", "Drop-point (random walk)"], group = grpG, tooltip = "Applies to channels and highlighter. Millard: chapter 10 adjusted quadratic, then channels are bent or reversed when peaks or troughs in the gap break a boundary (the highlighter uses the curve fit). Drop-point: averages recomputed with every future close set to the last close, using the known prices that will leave the average.")
fitFrac = input.float(0.4, "Curve-fit window, share of gap", minval = 0.1, maxval = 1.0, step = 0.05, group = grpG, tooltip = "Chapter 10 fits the last 9 points of a 41-week average (gap of 20). 0.4 reproduces that ratio.")
tolFrac = input.float(0.15, "Penetration tolerance, share of half-depth", minval = 0.0, maxval = 1.0, step = 0.05, group = grpG)
useSym = input.bool(true, "Symmetry reversal", group = grpG, tooltip = "When bending cannot remove the breaks, the channel is reversed at the first breaking peak or trough (or at the extreme close in the gap) and mirrored about that point.")
projBars = input.int(20, "Projection beyond last bar", minval = 0, maxval = 250, group = grpG)
calcBars = input.int(1500, "Bars with per-bar estimates", minval = 100, maxval = 5000, group = grpG, tooltip = "Signals, the cycle filter and the scorecard need a full gap estimate on every bar. They are computed only over this many recent bars to stay inside execution limits.")
grpH = "Cycle highlighter"
hlSpanIn = input.int(53, "Span (wavelength to isolate)", minval = 5, maxval = 801, step = 2, group = grpH, tooltip = "Chapter 8: a highlighter of span N isolates cycles near N bars. Even spans are raised by one.")
calcMode = input.string("Cycle highlighter", "Calculation", options = ["Cycle highlighter", "Average difference"], group = grpH, tooltip = "Cycle highlighter: centred average of about half the span minus centred average of the span. Average difference: price minus the centred average of the span, which keeps every cycle shorter than the span.")
shortType = input.string("Weighted", "Short average", options = ["Weighted", "Simple"], group = grpH, tooltip = "Chapter 8: the hand method uses a simple average of half the span; the computer method uses a weighted average. Weighted here is triangular.")
pivIn = input.int(0, "Turn confirmation bars (0 = span / 8)", minval = 0, maxval = 100, group = grpH)
turnsUsed = input.int(6, "Half-waves used", minval = 2, maxval = 20, group = grpH, tooltip = "Chapter 4 prediction box: the next turn is expected between the shortest and longest recent half-wave after the last turn, at a distance between the smallest and largest recent swing.")
cvWaveMax = input.float(0.25, "Regular if half-wave CV below", minval = 0.05, maxval = 1.0, step = 0.05, group = grpH, tooltip = "Millard says to use a cycle only while it is regular, without giving a number. These thresholds are this script's operational choice.")
cvMagMax = input.float(0.5, "and swing CV below", minval = 0.05, maxval = 2.0, step = 0.05, group = grpH)
showBox = input.bool(true, "Prediction box", group = grpH)
grpS = "Signals"
showLong = input.bool(true, "Buy setups", group = grpS)
showShort = input.bool(false, "Short setups", group = grpS)
showExit = input.bool(true, "Exits", group = grpS)
colBuy = input.color(color.new(#089981, 0), "Buy colour", group = grpS)
colShort = input.color(color.new(#F23645, 0), "Short colour", group = grpS)
colExit = input.color(color.new(#FFD600, 0), "Exit colour", group = grpS)
nearZone = input.float(0.2, "Boundary zone, share of channel depth", minval = 0.05, maxval = 0.5, step = 0.05, group = grpS)
needOuter = input.bool(false, "Require outer channel in trade direction", group = grpS)
cycleFilter = input.string("Off", "Cycle filter", options = ["Off", "Cycle in trade direction", "Cycle in trade direction and regular"], group = grpS, tooltip = "Chapters 8 and 9: Millard acts when channel and cycle analysis agree. The filter requires the highlighter's estimated direction at the current bar to match the trade, and optionally the cycle to be regular. Off reproduces the chapter 6 rules.")
grpD = "Display"
showHist = input.bool(true, "Centred channels (exact section)", group = grpD)
showGap = input.bool(true, "Gap estimate and projection", group = grpD)
showPad = input.bool(false, "Drop-point estimate for comparison", group = grpD)
showTable = input.bool(false, "Status table", group = grpD)
scoreTarget = input.string("Inner", "Scorecard", options = ["Inner", "Middle", "Outer", "Highlighter", "Off"], group = grpD)
tablePos = input.string("Bottom right", "Table position", options = ["Top right", "Bottom right", "Bottom left", "Top left"], group = grpD)
colIn = input.color(color.new(#2962FF, 0), "Inner colour", group = grpD)
colMid = input.color(color.new(#FF9800, 0), "Middle colour", group = grpD)
colOut = input.color(color.new(#9C27B0, 0), "Outer colour", group = grpD)
// ---------------------------------------------------------------- spans
// spans are computed inline so they stay "simple" (plot offsets require it)
nI = innerSpanIn % 2 == 0 ? innerSpanIn + 1 : innerSpanIn
nM = midSpanIn % 2 == 0 ? midSpanIn + 1 : midSpanIn
nO = outSpanIn % 2 == 0 ? outSpanIn + 1 : outSpanIn
mI0 = int((nI + 1) / 2)
mM0 = int((nM + 1) / 2)
mO0 = int((nO + 1) / 2)
mI = useSmooth ? (mI0 % 2 == 1 ? mI0 : mI0 - 1) : 1
mM = useSmooth ? (mM0 % 2 == 1 ? mM0 : mM0 - 1) : 1
mO = useSmooth ? (mO0 % 2 == 1 ? mO0 : mO0 - 1) : 1
hI = int((nI - 1) / 2) + int((mI - 1) / 2)
hM = int((nM - 1) / 2) + int((mM - 1) / 2)
hO = int((nO - 1) / 2) + int((mO - 1) / 2)
hlN = hlSpanIn % 2 == 0 ? hlSpanIn + 1 : hlSpanIn
hlM0 = int((hlN + 1) / 2)
hlM = hlM0 % 2 == 1 ? hlM0 : hlM0 + 1
hlK = int((hlM + 1) / 2) // triangular span 2K-1 = hlM
hlH = int((hlN - 1) / 2)
hlHm = int((hlM - 1) / 2)
hlD = hlH - hlHm
isHL = calcMode == "Cycle highlighter"
isW = shortType == "Weighted"
pivLen = pivIn > 0 ? pivIn : math.max(2, int(math.round(hlN / 8)))
hlCurve = gapMethod != "Drop-point (random walk)"
// ---------------------------------------------------------------- channel averages and depth
// Trailing smoothed average at bar t equals the centred average at bar t - h.
s1I = ta.sma(src, nI)
s1M = ta.sma(src, nM)
s1O = ta.sma(src, nO)
avgI = ta.sma(s1I, mI)
avgM = ta.sma(s1M, mM)
avgO = ta.sma(s1O, mO)
// Half-depth: quantile of |price - centred average| over the calculated history.
devI = math.abs(src[hI] - avgI)
devM = math.abs(src[hM] - avgM)
devO = math.abs(src[hO] - avgO)
hdI = ta.percentile_nearest_rank(devI, depthLen, 100.0 - outsidePct)
hdM = ta.percentile_nearest_rank(devM, depthLen, 100.0 - outsidePct)
hdO = ta.percentile_nearest_rank(devO, depthLen, 100.0 - outsidePct)
// ---------------------------------------------------------------- highlighter
hlLong = ta.sma(src, hlN)
hlW1 = ta.sma(src, hlK)
hlShortW = ta.sma(hlW1, hlK)
hlShortP = ta.sma(src, hlM)
hlShort = isW ? hlShortW : hlShortP
// trailing value at bar t = centred value at bar t - hlH
hl = isHL ? hlShort[hlD] - hlLong : src[hlH] - hlLong
hlScale = ta.percentile_nearest_rank(math.abs(hl), 500, 95)
// ---------------------------------------------------------------- rolling buffers
maxSpan = math.max(nI, useMid ? nM : 0, useOut ? nO : 0, hlN)
maxH = math.max(hI, useMid ? hM : 0, useOut ? hO : 0, hlH)
bufLen = 2 * (maxSpan + maxH + projBars) + 10
pushBuf(array<float> b, float v, int maxLen) =>
b.push(v)
if b.size() > maxLen
b.shift()
true
// value i bars ago
ago(array<float> b, int i) =>
int sz = b.size()
i >= 0 and i < sz ? b.get(sz - 1 - i) : na
var array<float> bufC = array.new<float>()
var array<float> bufAI = array.new<float>()
var array<float> bufAM = array.new<float>()
var array<float> bufAO = array.new<float>()
var array<float> bufS1I = array.new<float>()
var array<float> bufS1M = array.new<float>()
var array<float> bufS1O = array.new<float>()
var array<float> bufHL = array.new<float>()
var array<float> bufSh = array.new<float>()
var array<float> bufW1 = array.new<float>()
pushBuf(bufC, src, bufLen)
pushBuf(bufAI, avgI, bufLen)
pushBuf(bufAM, avgM, bufLen)
pushBuf(bufAO, avgO, bufLen)
pushBuf(bufS1I, s1I, bufLen)
pushBuf(bufS1M, s1M, bufLen)
pushBuf(bufS1O, s1O, bufLen)
pushBuf(bufHL, hl, bufLen)
pushBuf(bufSh, hlShort, bufLen)
pushBuf(bufW1, hlW1, bufLen)
// ---------------------------------------------------------------- gap estimators
fitCount(int h, int avail) =>
math.max(3, math.min(math.max(5, int(math.round(fitFrac * h)) + 1), avail))
// Chapter 10: least-squares quadratic on the last F centred points, adjusted by a linear term
// so it passes through the first and last of them, evaluated k = 1..steps bars past the last point.
quadPath(array<float> ba, int F, int steps) =>
float S0 = F
float S1 = 0.0
float S2 = 0.0
float S3 = 0.0
float S4 = 0.0
float T0 = 0.0
float T1 = 0.0
float T2 = 0.0
for i = 0 to F - 1
float xv = i
float yv = ago(ba, F - 1 - i)
S1 += xv
S2 += xv * xv
S3 += xv * xv * xv
S4 += xv * xv * xv * xv
T0 += yv
T1 += xv * yv
T2 += xv * xv * yv
float det = S0 * (S2 * S4 - S3 * S3) - S1 * (S1 * S4 - S3 * S2) + S2 * (S1 * S3 - S2 * S2)
float c0 = (T0 * (S2 * S4 - S3 * S3) - S1 * (T1 * S4 - S3 * T2) + S2 * (T1 * S3 - S2 * T2)) / det
float c1 = (S0 * (T1 * S4 - S3 * T2) - T0 * (S1 * S4 - S3 * S2) + S2 * (S1 * T2 - T1 * S2)) / det
float c2 = (S0 * (S2 * T2 - T1 * S3) - S1 * (S1 * T2 - T1 * S2) + T0 * (S1 * S3 - S2 * S2)) / det
float y0 = ago(ba, F - 1)
float yL = ago(ba, 0)
float r0 = y0 - c0
float rL = yL - (c0 + c1 * (F - 1) + c2 * (F - 1) * (F - 1))
out = array.new<float>(steps, na)
for k = 1 to steps
float v = F - 1 + k
out.set(k - 1, c0 + c1 * v + c2 * v * v + r0 + (rL - r0) * v / (F - 1))
out
// Baseline: least-squares line through the same points, anchored at the last true point.
linPath(array<float> ba, int F, int steps) =>
float sx = 0.0
float sy = 0.0
float sxy = 0.0
float sxx = 0.0
for i = 0 to F - 1
float yv = ago(ba, F - 1 - i)
sx += i
sy += yv
sxy += i * yv
sxx += i * i
float b = (F * sxy - sx * sy) / (F * sxx - sx * sx)
float yL = ago(ba, 0)
out = array.new<float>(steps, na)
for k = 1 to steps
out.set(k - 1, yL + b * k)
out
// Trailing (SMA n, then SMA m) of the price series padded forward with the last close, for bars
// T+1..T+steps. Exact recurrence on the known drop points; no curve is fitted.
padPath(array<float> bc, array<float> b1, float s1Now, float avgNow, int n, int m, int steps) =>
float c = ago(bc, 0)
s1 = array.new<float>(steps + 1, na)
s1.set(0, s1Now)
float run = s1Now
for j = 1 to steps
float dropV = j <= n ? ago(bc, n - j) : c
run += (c - dropV) / n
s1.set(j, run)
out = array.new<float>(steps, na)
float sm = avgNow
for k = 1 to steps
if m > 1
float outV = k - m >= 0 ? s1.get(k - m) : ago(b1, m - k)
sm += (s1.get(k) - outV) / m
else
sm := s1.get(k)
out.set(k - 1, sm)
out
// Peaks and troughs of the closes inside the gap that break a boundary of path P.
// Returns flags, first breaking position, and the bend factor each side would need
// (bend weight measured from position "start"; breaks in the first quarter are accepted).
scanBreaks(array<float> bc, array<float> P, int h, float hd, float tolv, int start) =>
bool anyUp = false
bool anyDn = false
int firstUp = -1
int firstDn = -1
float rUp = na
float rDn = na
float span = math.max(h - start, 1)
if h >= 2
for k = 1 to h - 1
float gk = ago(bc, h - k)
float gp = ago(bc, h - k + 1)
float gn = ago(bc, h - k - 1)
float ctr = P.get(k - 1)
float u = math.max(k - start, 0) / span
float w = u <= 1 ? u * u : 2 * u - 1
if gk > gp and gk >= gn
float vUp = gk - (ctr + hd)
if vUp > tolv
anyUp := true
firstUp := firstUp < 0 ? k : firstUp
if w >= 0.0625
rUp := na(rUp) ? vUp / w : math.max(rUp, vUp / w)
if gk < gp and gk <= gn
float vDn = (ctr - hd) - gk
if vDn > tolv
anyDn := true
firstDn := firstDn < 0 ? k : firstDn
if w >= 0.0625
rDn := na(rDn) ? vDn / w : math.max(rDn, vDn / w)
[anyUp, anyDn, firstUp, firstDn, rUp, rDn]
// Smallest smooth bend from "start": quadratic to the present bar, straight after it.
// Capped at four half-depths.
bendPath(array<float> P, int h, float A, int start, float hd) =>
Q = P.copy()
if not na(A)
float a = math.min(math.abs(A), 4 * hd) * math.sign(A)
float span = math.max(h - start, 1)
for k = 1 to Q.size()
float u = math.max(k - start, 0) / span
float w = u <= 1 ? u * u : 2 * u - 1
Q.set(k - 1, P.get(k - 1) + a * w)
Q
// Principle of symmetry: mirror the path about position k0.
mirrorPath(array<float> E, array<float> ba, int k0) =>
R = E.copy()
int steps = E.size()
if k0 + 1 <= steps
for k = k0 + 1 to steps
int srcK = 2 * k0 - k
float v = srcK >= 1 ? E.get(srcK - 1) : ago(ba, -srcK)
if na(v)
v := ago(ba, ba.size() - 1)
R.set(k - 1, v)
R
// Position (1..h) of the lowest or highest close in the gap.
extremeInGap(array<float> bc, int h, bool wantMax) =>
int best = 1
float bv = ago(bc, h - 1)
if h >= 2
for k = 2 to h
float v = ago(bc, h - k)
if wantMax ? v > bv : v < bv
bv := v
best := k
best
// Chapter 5, 9 and 10 procedure: curve fit, then bend for one-sided breaks, reverse with
// symmetry when a bend would flip direction or both boundaries are broken.
// mode: 0 curve, 1 bend, 2 reversal.
millardPath(array<float> bc, array<float> ba, int h, float hd, int F, int steps, float tolv) =>
E = quadPath(ba, F, steps)
P = E
int mode = 0
if h >= 2
[up, dn, fu, fd, ru, rd] = scanBreaks(bc, E, h, hd, tolv, 0)
if up or dn
float slope0 = E.get(h - 1) - E.get(h - 2)
bool done = false
if up != dn
Q = bendPath(E, h, up ? ru : -rd, 0, hd)
[up2, dn2, fu2, fd2, ru2, rd2] = scanBreaks(bc, Q, h, hd, tolv, 0)
float slope1 = Q.get(h - 1) - Q.get(h - 2)
if (math.sign(slope1) == math.sign(slope0) or not useSym) and not up2 and not dn2
P := Q
mode := 1
done := true
if not done
if useSym
int k0 = up and dn ? math.min(fu, fd) : up ? extremeInGap(bc, h, false) : extremeInGap(bc, h, true)
Mr = mirrorPath(E, ba, k0)
[up3, dn3, fu3, fd3, ru3, rd3] = scanBreaks(bc, Mr, h, hd, tolv, k0)
if up3 != dn3
Mr := bendPath(Mr, h, up3 ? ru3 : -rd3, k0, hd)
P := Mr
mode := 2
else
P := bendPath(E, h, up ? ru : -rd, 0, hd)
mode := 1
[P, mode]
// Chapter 5: an inner channel that meets a boundary of the next outer channel reverses there.
// Applied to the projection beyond the last bar only.
bounceOff(array<float> Pin, array<float> baIn, int hIn, float hdIn, array<float> Pout, int hOut, float hdOut, float tolv) =>
R = Pin
int steps = Pin.size()
if hIn + 1 <= steps
for pass = 1 to 3
int hit = -1
for k = hIn + 1 to steps
int ko = hOut + (k - hIn)
if ko <= Pout.size()
float ci = R.get(k - 1)
float co = Pout.get(ko - 1)
if ci + hdIn > co + hdOut + tolv or ci - hdIn < co - hdOut - tolv
hit := k - 1
break
if hit < hIn
break
R := mirrorPath(R, baIn, hit)
R
// Channel path at the current bar for the selected gap method.
selPath(array<float> bc, array<float> ba, array<float> b1, float s1Now, float avgNow, int n, int m, int h, float hd, int steps) =>
int F = fitCount(h, ba.size())
array<float> P = na
int mode = 0
if gapMethod == "Drop-point (random walk)"
P := padPath(bc, b1, s1Now, avgNow, n, m, steps)
else if gapMethod == "Curve fit only"
P := quadPath(ba, F, steps)
else
[Pm, md] = millardPath(bc, ba, h, hd, F, steps, tolFrac * hd)
P := Pm
mode := md
[P, mode]
// Centred highlighter for positions q = 1..steps after its last true point, prices padded.
hlPadPath(int steps) =>
longP = padPath(bufC, bufC, hlLong, hlLong, hlN, 1, steps)
shortPd = isW ? padPath(bufC, bufW1, hlW1, hlShortW, hlK, hlK, steps) : padPath(bufC, bufC, hlShortP, hlShortP, hlM, 1, steps)
float c = ago(bufC, 0)
out = array.new<float>(steps, na)
for q = 1 to steps
float lv = longP.get(q - 1)
float v = na
if isHL
float sv = q - hlD <= 0 ? ago(bufSh, hlD - q) : shortPd.get(q - hlD - 1)
v := sv - lv
else
float xv = q <= hlH ? ago(bufC, hlH - q) : c
v := xv - lv
out.set(q - 1, v)
out
hlSelPath(int steps) =>
hlCurve ? quadPath(bufHL, fitCount(hlH, bufHL.size()), steps) : hlPadPath(steps)
// ---------------------------------------------------------------- highlighter turning points (chapter 4)
ph = ta.pivothigh(hl, pivLen, pivLen)
pl = ta.pivotlow(hl, pivLen, pivLen)
var array<int> tIdx = array.new<int>()
var array<float> tVal = array.new<float>()
var array<int> tType = array.new<int>()
addTurn(int idx, float val, int typ) =>
int n = tType.size()
if n > 0 and tType.get(n - 1) == typ
float prev = tVal.get(n - 1)
if (typ == 1 and val > prev) or (typ == -1 and val < prev)
tIdx.set(n - 1, idx)
tVal.set(n - 1, val)
else
tIdx.push(idx)
tVal.push(val)
tType.push(typ)
if tType.size() > 60
tIdx.shift()
tVal.shift()
tType.shift()
true
turnBar = bar_index - pivLen - hlH
if not na(ph)
addTurn(turnBar, ph, 1)
else if not na(pl)
addTurn(turnBar, pl, -1)
// Half-waves and swings over the last turnsUsed intervals.
cycleStats() =>
int nt = tIdx.size()
int used = math.min(turnsUsed, nt - 1)
float hwMin = na
float hwMax = na
float hwSum = 0.0
float hwSq = 0.0
float mgMin = na
float mgMax = na
float mgSum = 0.0
float mgSq = 0.0
if used >= 2
for i = nt - used to nt - 1
float hw = tIdx.get(i) - tIdx.get(i - 1)
float mg = math.abs(tVal.get(i) - tVal.get(i - 1))
hwMin := na(hwMin) ? hw : math.min(hwMin, hw)
hwMax := na(hwMax) ? hw : math.max(hwMax, hw)
mgMin := na(mgMin) ? mg : math.min(mgMin, mg)
mgMax := na(mgMax) ? mg : math.max(mgMax, mg)
hwSum += hw
hwSq += hw * hw
mgSum += mg
mgSq += mg * mg
float hwMean = used >= 2 ? hwSum / used : na
float mgMean = used >= 2 ? mgSum / used : na
float hwCv = used >= 2 ? math.sqrt(math.max(hwSq / used - hwMean * hwMean, 0)) / hwMean : na
float mgCv = used >= 2 and mgMean > 0 ? math.sqrt(math.max(mgSq / used - mgMean * mgMean, 0)) / mgMean : na
bool regular = not na(hwCv) and not na(mgCv) and hwCv <= cvWaveMax and mgCv <= cvMagMax
[used, hwMin, hwMax, hwMean, hwCv, mgMin, mgMax, mgCv, regular]
[cyUsed, cyHwMin, cyHwMax, cyHwMean, cyHwCv, cyMgMin, cyMgMax, cyMgCv, cyRegular] = cycleStats()
// ---------------------------------------------------------------- per-bar estimates
inCalc = bar_index >= last_bar_index - calcBars and not na(hdI) and bufAI.size() > 3 * nI
okMid = useMid and not na(hdM) and bufAM.size() > 3 * nM
okOut = useOut and not na(hdO) and bufAO.size() > 3 * nO
inCalcH = bar_index >= last_bar_index - calcBars and not na(hl) and bufHL.size() > 3 * hlN
scoreHL = showTable and scoreTarget == "Highlighter"
float ctrI = na
float slpI = na
float slpM = na
float slpO = na
int modeI = na
if inCalc and hI >= 2
[PI, mdI] = selPath(bufC, bufAI, bufS1I, s1I, avgI, nI, mI, hI, hdI, hI)
ctrI := PI.get(hI - 1)
slpI := PI.get(hI - 1) - PI.get(hI - 2)
modeI := mdI
if okMid and hM >= 2
[PM, mdM] = selPath(bufC, bufAM, bufS1M, s1M, avgM, nM, mM, hM, hdM, hM)
slpM := PM.get(hM - 1) - PM.get(hM - 2)
if okOut and hO >= 2
[PO, mdO] = selPath(bufC, bufAO, bufS1O, s1O, avgO, nO, mO, hO, hdO, hO)
slpO := PO.get(hO - 1) - PO.get(hO - 2)
// highlighter estimate at the current bar (used by the cycle filter and its scorecard)
float hlSlopeNow = na
float hQ = na
float hP = na
float sQ = na
float sP = na
if inCalcH and (cycleFilter != "Off" or scoreHL)
if scoreHL
HQ = quadPath(bufHL, fitCount(hlH, bufHL.size()), hlH)
HP = hlPadPath(hlH)
hQ := HQ.get(hlH - 1)
hP := HP.get(hlH - 1)
sQ := HQ.get(hlH - 1) - HQ.get(hlH - 2)
sP := HP.get(hlH - 1) - HP.get(hlH - 2)
hlSlopeNow := hlCurve ? sQ : sP
else
HS = hlSelPath(hlH)
hlSlopeNow := HS.get(hlH - 1) - HS.get(hlH - 2)
upI = ctrI + hdI
loI = ctrI - hdI
posI = (src - loI) / (2 * hdI)
adjusting = not na(ctrI) and (src - upI > tolFrac * hdI or loI - src > tolFrac * hdI)
// ---------------------------------------------------------------- signals (chapters 6, 8 and 9)
// Buy: inner and middle channels rising, a trough has just formed on or near the lower inner
// boundary (yesterday's close was lower than the day before and today closed higher), and the
// latest close is not outside a boundary. Optional: the highlighter agrees (chapter 9).
// Exit at the first close through the lower boundary, at a down close near the upper boundary,
// or when the middle channel turns down. Shorts mirror the rules.
midUp = not useMid or (not na(slpM) and slpM > 0)
midDn = not useMid or (not na(slpM) and slpM < 0)
outUp = not needOuter or not useOut or (not na(slpO) and slpO > 0)
outDn = not needOuter or not useOut or (not na(slpO) and slpO < 0)
needReg = cycleFilter == "Cycle in trade direction and regular"
cycOkLong = cycleFilter == "Off" or (not na(hlSlopeNow) and hlSlopeNow > 0 and (not needReg or cyRegular))
cycOkShort = cycleFilter == "Off" or (not na(hlSlopeNow) and hlSlopeNow < 0 and (not needReg or cyRegular))
validNow = not na(ctrI) and not na(posI[1])
troughNow = src[1] < src[2] and src > src[1]
peakNow = src[1] > src[2] and src < src[1]
longSetup = validNow and slpI > 0 and midUp and outUp and cycOkLong and troughNow and posI[1] <= nearZone and posI[1] >= -tolFrac / 2 and not adjusting
shortSetup = validNow and slpI < 0 and midDn and outDn and cycOkShort and peakNow and posI[1] >= 1 - nearZone and posI[1] <= 1 + tolFrac / 2 and not adjusting
var bool inLong = false
var bool inShort = false
var int entryBar = na
bool longEntry = false
bool shortEntry = false
bool longExit = false
bool shortExit = false
if validNow
if inLong and bar_index > entryBar
if src < loI - tolFrac * hdI or (posI >= 1 - nearZone and src < src[1]) or (useMid and not na(slpM) and slpM < 0)
longExit := true
inLong := false
if inShort and bar_index > entryBar
if src > upI + tolFrac * hdI or (posI <= nearZone and src > src[1]) or (useMid and not na(slpM) and slpM > 0)
shortExit := true
inShort := false
if not inLong and not inShort
if showLong and longSetup
longEntry := true
inLong := true
entryBar := bar_index
else if showShort and shortSetup
shortEntry := true
inShort := true
entryBar := bar_index
plotshape(longEntry, "Buy setup", shape.triangleup, location.belowbar, colBuy, size = size.small, force_overlay = true)
plotshape(shortEntry, "Short setup", shape.triangledown, location.abovebar, colShort, size = size.small, force_overlay = true)
plotshape(showExit and (longExit or shortExit), "Exit", shape.xcross, location.abovebar, colExit, size = size.small, force_overlay = true)
alertcondition(longEntry, "Millard buy setup", "Millard Channels and Cycles: buy setup on the lower boundary of a rising inner channel")
alertcondition(shortEntry, "Millard short setup", "Millard Channels and Cycles: short setup on the upper boundary of a falling inner channel")
alertcondition(longExit or shortExit, "Millard exit", "Millard Channels and Cycles: exit condition")
// ---------------------------------------------------------------- plots
// price pane: centred channels (exact section)
plot(showHist ? avgI : na, "Inner centre", color.new(colIn, 60), 1, offset = -hI, force_overlay = true)
plot(showHist ? avgI + hdI : na, "Inner upper", colIn, 1, offset = -hI, force_overlay = true)
plot(showHist ? avgI - hdI : na, "Inner lower", colIn, 1, offset = -hI, force_overlay = true)
plot(showHist and useMid ? avgM + hdM : na, "Middle upper", colMid, 1, offset = -hM, force_overlay = true)
plot(showHist and useMid ? avgM - hdM : na, "Middle lower", colMid, 1, offset = -hM, force_overlay = true)
plot(showHist and useOut ? avgO + hdO : na, "Outer upper", colOut, 2, offset = -hO, force_overlay = true)
plot(showHist and useOut ? avgO - hdO : na, "Outer lower", colOut, 2, offset = -hO, force_overlay = true)
// this pane: highlighter and its turning points
plot(hl, "Highlighter (centred)", color.new(#2962FF, 0), 2, offset = -hlH)
plot(ph, "Cycle peak", color.new(#F23645, 20), 4, plot.style_circles, offset = -(pivLen + hlH))
plot(pl, "Cycle trough", color.new(#089981, 20), 4, plot.style_circles, offset = -(pivLen + hlH))
hline(0, "Zero", color.new(color.gray, 50))
// ---------------------------------------------------------------- scorecard (causal)
// Each estimate of a centred value at the current bar is frozen when made and scored h bars
// later, when the true centred value becomes known.
// Channels, 0 Millard, 1 curve fit only, 2 drop-point, 3 linear, 4 last true point; errors in half-depths.
// Highlighter, 0 curve fit, 1 drop-point, 2 last true point; errors in the 95th percentile of |value|.
scCh = scoreTarget == "Inner" or (scoreTarget == "Middle" and useMid) or (scoreTarget == "Outer" and useOut)
scH = scoreTarget == "Middle" ? hM : scoreTarget == "Outer" ? hO : hI
scN = scoreTarget == "Middle" ? nM : scoreTarget == "Outer" ? nO : nI
scM = scoreTarget == "Middle" ? mM : scoreTarget == "Outer" ? mO : mI
scAvg = scoreTarget == "Middle" ? avgM : scoreTarget == "Outer" ? avgO : avgI
scS1 = scoreTarget == "Middle" ? s1M : scoreTarget == "Outer" ? s1O : s1I
scHd = scoreTarget == "Middle" ? hdM : scoreTarget == "Outer" ? hdO : hdI
scBa = scoreTarget == "Middle" ? bufAM : scoreTarget == "Outer" ? bufAO : bufAI
scB1 = scoreTarget == "Middle" ? bufS1M : scoreTarget == "Outer" ? bufS1O : bufS1I
scOn = showTable and scCh
float e0 = na
float e1 = na
float e2 = na
float e3 = na
float g0 = na
float g1 = na
float g2 = na
float g3 = na
if scOn and bar_index >= last_bar_index - calcBars and not na(scHd) and scH >= 2 and scBa.size() > 3 * scN
int F = fitCount(scH, scBa.size())
[P0, md0] = millardPath(bufC, scBa, scH, scHd, F, scH, tolFrac * scHd)
P1 = quadPath(scBa, F, scH)
P2 = padPath(bufC, scB1, scS1, scAvg, scN, scM, scH)
P3 = linPath(scBa, F, scH)
e0 := P0.get(scH - 1)
e1 := P1.get(scH - 1)
e2 := P2.get(scH - 1)
e3 := P3.get(scH - 1)
g0 := P0.get(scH - 1) - P0.get(scH - 2)
g1 := P1.get(scH - 1) - P1.get(scH - 2)
g2 := P2.get(scH - 1) - P2.get(scH - 2)
g3 := P3.get(scH - 1) - P3.get(scH - 2)
var array<float> errSum = array.new<float>(5, 0.0)
var array<float> dirHit = array.new<float>(5, 0.0)
var array<float> slpHit = array.new<float>(5, 0.0)
var int nScored = 0
if scOn and not na(e2[scH]) and not na(e0[scH]) and not na(scAvg) and not na(scAvg[scH]) and scHd[scH] > 0
nScored += 1
float lastThen = scAvg[scH]
float hdThen = scHd[scH]
float trueMove = math.sign(scAvg - lastThen)
float tS = math.sign(scAvg - scAvg[1])
for i = 0 to 4
float est = i == 0 ? e0[scH] : i == 1 ? e1[scH] : i == 2 ? e2[scH] : i == 3 ? e3[scH] : lastThen
float sl = i == 0 ? g0[scH] : i == 1 ? g1[scH] : i == 2 ? g2[scH] : i == 3 ? g3[scH] : na
errSum.set(i, errSum.get(i) + math.abs(est - scAvg) / hdThen)
if i < 4
dirHit.set(i, dirHit.get(i) + (math.sign(est - lastThen) == trueMove ? 1.0 : 0.0))
slpHit.set(i, slpHit.get(i) + (math.sign(sl) == tS ? 1.0 : 0.0))
if scoreHL and not na(hQ[hlH]) and not na(hP[hlH]) and not na(hl) and not na(hl[hlH]) and hlScale[hlH] > 0
nScored += 1
float lastH = hl[hlH]
float scl = hlScale[hlH]
float tSh = math.sign(hl - hl[1])
float tDh = math.sign(hl - lastH)
errSum.set(0, errSum.get(0) + math.abs(hQ[hlH] - hl) / scl)
errSum.set(1, errSum.get(1) + math.abs(hP[hlH] - hl) / scl)
errSum.set(2, errSum.get(2) + math.abs(lastH - hl) / scl)
dirHit.set(0, dirHit.get(0) + (math.sign(hQ[hlH] - lastH) == tDh ? 1.0 : 0.0))
dirHit.set(1, dirHit.get(1) + (math.sign(hP[hlH] - lastH) == tDh ? 1.0 : 0.0))
slpHit.set(0, slpHit.get(0) + (math.sign(sQ[hlH]) == tSh ? 1.0 : 0.0))
slpHit.set(1, slpHit.get(1) + (math.sign(sP[hlH]) == tSh ? 1.0 : 0.0))
// ---------------------------------------------------------------- drawing on the last bar
var array<polyline> drawn = array.new<polyline>()
var box predBox = na
pathPoints(array<float> P, float base, float off, int h) =>
pts = array.new<chart.point>()
pts.push(chart.point.from_index(bar_index - h, base + off))
for k = 1 to P.size()
pts.push(chart.point.from_index(bar_index - h + k, P.get(k - 1) + off))
pts
drawChannel(array<float> P, float base, int h, float hd, color col, int w) =>
drawn.push(polyline.new(pathPoints(P, base, hd, h), line_color = col, line_style = line.style_dashed, line_width = w, force_overlay = true))
drawn.push(polyline.new(pathPoints(P, base, -hd, h), line_color = col, line_style = line.style_dashed, line_width = w, force_overlay = true))
posTable = tablePos == "Top right" ? position.top_right : tablePos == "Bottom right" ? position.bottom_right : tablePos == "Bottom left" ? position.bottom_left : position.top_left
var table tb = table.new(posTable, 5, 12, bgcolor = color.new(color.black, 85), border_width = 1, force_overlay = true)
dirText(float s) =>
na(s) ? "n/a" : s > 0 ? "rising" : s < 0 ? "falling" : "flat"
fmt(float v, string f) =>
na(v) ? "n/a" : str.tostring(v, f)
if barstate.islast
for p in drawn
p.delete()
drawn.clear()
// channels, worked from the outside in (chapter 5)
array<float> PIl = na
array<float> PMl = na
array<float> POl = na
if showGap and not na(hdI) and hI >= 2 and bufAI.size() > 3 * nI
[pa, ma] = selPath(bufC, bufAI, bufS1I, s1I, avgI, nI, mI, hI, hdI, hI + projBars)
PIl := pa
if showGap and okMid and hM >= 2
[pb, mb] = selPath(bufC, bufAM, bufS1M, s1M, avgM, nM, mM, hM, hdM, hM + projBars)
PMl := pb
if showGap and okOut and hO >= 2
[pc, mc] = selPath(bufC, bufAO, bufS1O, s1O, avgO, nO, mO, hO, hdO, hO + projBars)
POl := pc
if not na(PMl) and not na(POl)
PMl := bounceOff(PMl, bufAM, hM, hdM, POl, hO, hdO, tolFrac * hdM)
if not na(PIl)
if not na(PMl)
PIl := bounceOff(PIl, bufAI, hI, hdI, PMl, hM, hdM, tolFrac * hdI)
else if not na(POl)
PIl := bounceOff(PIl, bufAI, hI, hdI, POl, hO, hdO, tolFrac * hdI)
if not na(POl)
drawChannel(POl, avgO, hO, hdO, colOut, 2)
if not na(PMl)
drawChannel(PMl, avgM, hM, hdM, colMid, 1)
if not na(PIl)
drawChannel(PIl, avgI, hI, hdI, colIn, 1)
drawn.push(polyline.new(pathPoints(PIl, avgI, 0.0, hI), line_color = color.new(colIn, 60), line_style = line.style_dotted, line_width = 1, force_overlay = true))
if showPad and not na(hdI) and hI >= 2 and bufAI.size() > 3 * nI
PP = padPath(bufC, bufS1I, s1I, avgI, nI, mI, hI + projBars)
drawn.push(polyline.new(pathPoints(PP, avgI, 0.0, hI), line_color = color.new(color.gray, 0), line_style = line.style_dotted, line_width = 2, force_overlay = true))
// highlighter gap estimate and projection in this pane
float hlSlopeLast = na
if not na(hl) and bufHL.size() > 3 * hlN
HS = hlSelPath(hlH + projBars)
hlSlopeLast := HS.get(hlH - 1) - HS.get(hlH - 2)
drawn.push(polyline.new(pathPoints(HS, hl, 0.0, hlH), line_color = color.new(#2962FF, 0), line_style = line.style_dashed, line_width = 2))
if showPad and hlCurve
HD = hlPadPath(hlH + projBars)
drawn.push(polyline.new(pathPoints(HD, hl, 0.0, hlH), line_color = color.new(color.gray, 0), line_style = line.style_dotted, line_width = 2))
// chapter 4 prediction box
int nt = tIdx.size()
int lastIdx = nt > 0 ? tIdx.get(nt - 1) : na
float lastVal = nt > 0 ? tVal.get(nt - 1) : na
int lastTyp = nt > 0 ? tType.get(nt - 1) : na
if not na(predBox)
predBox.delete()
if showBox and cyUsed >= 2 and not na(lastIdx)
int left = lastIdx + int(cyHwMin)
int right = math.min(lastIdx + int(cyHwMax), bar_index + 490)
float top = lastTyp == 1 ? lastVal - cyMgMin : lastVal + cyMgMax
float bot = lastTyp == 1 ? lastVal - cyMgMax : lastVal + cyMgMin
if right > left
predBox := box.new(left, top, right, bot, border_color = color.new(color.orange, 0), bgcolor = color.new(color.orange, 85), border_style = line.style_dashed)
if showTable
tb.clear(0, 0, 4, 11)
color tc = color.white
color hdr = color.new(color.gray, 70)
// channels now
tb.cell(0, 0, "Channels now", text_color = tc, bgcolor = hdr, text_size = size.small)
tb.cell(1, 0, "Outer " + dirText(slpO), text_color = tc, bgcolor = hdr, text_size = size.small)
tb.cell(2, 0, "Middle " + dirText(slpM), text_color = tc, bgcolor = hdr, text_size = size.small)
tb.cell(3, 0, "Inner " + dirText(slpI), text_color = tc, bgcolor = hdr, text_size = size.small)
tb.cell(4, 0, na(posI) ? "" : "Position " + str.tostring(posI * 100, "#") + "%" + (adjusting ? " (adjusting)" : ""), text_color = tc, bgcolor = hdr, text_size = size.small)
// cycle status
string cyName = (isHL ? "Cycle " + str.tostring(hlN) + "/" + str.tostring(hlM) + (isW ? "w" : "") : "Avg diff " + str.tostring(hlN))
tb.cell(0, 1, cyName + " " + dirText(hlSlopeLast), text_color = tc, text_size = size.small)
tb.cell(1, 1, "Wavelength " + (na(cyHwMean) ? "n/a" : str.tostring(2 * cyHwMean, "#.0") + (math.abs(2 * cyHwMean - hlN) / hlN > 0.3 ? " (off span)" : "")), text_color = tc, text_size = size.small)
tb.cell(2, 1, "Half-waves " + fmt(cyHwMin, "#") + " to " + fmt(cyHwMax, "#") + ", CV " + fmt(cyHwCv, "#.00"), text_color = tc, text_size = size.small)
tb.cell(3, 1, "Swing CV " + fmt(cyMgCv, "#.00"), text_color = tc, text_size = size.small)
tb.cell(4, 1, cyUsed < 2 ? "too few turns" : cyRegular ? "regular" : "irregular", text_color = cyRegular ? color.lime : color.orange, text_size = size.small)
tb.cell(0, 2, "Last turn " + (na(lastIdx) ? "n/a" : (lastTyp == 1 ? "peak, " : "trough, ") + str.tostring(bar_index - lastIdx) + " bars ago"), text_color = tc, text_size = size.small)
tb.cell(1, 2, "Next turn " + (cyUsed < 2 or na(lastIdx) ? "n/a" : str.tostring(lastIdx + cyHwMin - bar_index, "#") + " to " + str.tostring(lastIdx + cyHwMax - bar_index, "#") + " bars from now"), text_color = tc, text_size = size.small)
tb.cell(2, 2, "Cycle filter: " + cycleFilter, text_color = tc, text_size = size.small)
// scorecard
if scOn or scoreHL
int nm = scoreHL ? 3 : 5
tb.cell(0, 3, (scoreHL ? "Highlighter" : scoreTarget) + " gap, n=" + str.tostring(nScored), text_color = tc, bgcolor = hdr, text_size = size.small)
tb.cell(1, 3, scoreHL ? "MAE / 95th pct" : "MAE / half-depth", text_color = tc, bgcolor = hdr, text_size = size.small)
tb.cell(2, 3, "Gap direction hit", text_color = tc, bgcolor = hdr, text_size = size.small)
tb.cell(3, 3, "Slope-now hit", text_color = tc, bgcolor = hdr, text_size = size.small)
tb.cell(4, 3, "vs drop-point MAE", text_color = tc, bgcolor = hdr, text_size = size.small)
names = scoreHL ? array.from("Curve fit", "Drop-point", "Last true point") : array.from("Millard", "Curve fit only", "Drop-point", "Linear", "Last true point")
int padIdx = scoreHL ? 1 : 2
float padMae = nScored > 0 ? errSum.get(padIdx) / nScored : na
for i = 0 to nm - 1
float mae = nScored > 0 ? errSum.get(i) / nScored : na
bool hasDir = i < nm - 1
tb.cell(0, 4 + i, names.get(i), text_color = tc, text_size = size.small)
tb.cell(1, 4 + i, na(mae) ? "" : str.tostring(mae, "#.000"), text_color = tc, text_size = size.small)
tb.cell(2, 4 + i, hasDir and nScored > 0 ? str.tostring(100 * dirHit.get(i) / nScored, "#.0") + "%" : "", text_color = tc, text_size = size.small)
tb.cell(3, 4 + i, hasDir and nScored > 0 ? str.tostring(100 * slpHit.get(i) / nScored, "#.0") + "%" : "", text_color = tc, text_size = size.small)
tb.cell(4, 4 + i, na(mae) or na(padMae) or padMae == 0 ? "" : str.tostring(mae / padMae, "#.00") + "x", text_color = tc, text_size = size.small)
string modeTxt = gapMethod != "Millard: curve fit + bending" or na(modeI) ? "" : modeI == 0 ? ", inner gap: curve" : modeI == 1 ? ", inner gap: bent" : ", inner gap: reversed"
tb.cell(0, 10, "Gap method: " + gapMethod + modeTxt, text_color = tc, text_size = size.tiny)
tb.cell(0, 11, "Scores overlap; bars are not independent", text_color = color.gray, text_size = size.tiny)