本页源码来自 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/
// © ozgurhan
//
// Trend Line Reliability – MTF Selector
// Measures how often trend lines hold on the 4H, 1D and 1W timeframes and draws the current
// support and resistance lines of the most reliable timeframe on any chart.
//
// Method
// Line : drawn through the last two accepted swings of one side; no close between the
// first anchor and the moment of detection may cross it.
// Test : after the line is formed, a wick reaching the line within the touch tolerance
// (consecutive touching bars count once).
// Break : a close beyond the line by more than the break tolerance. The line is retired.
// Reliability : held tests / (held tests + breaks).
// No lookahead: every line is judged only by price action after it was formed.
//
// Credits: the swing acceptance rule (pivot plus a minimum ATR move from the previous opposite swing)
// and the default line parameters are adapted from "Auto Trend Lines, Channels & Patterns [EDGE]".
//@version=6
indicator("Trend Line Reliability – MTF Selector", shorttitle = "TL Reliability", overlay = true,
max_lines_count = 10, max_labels_count = 10)
// ─────────────────────────────────────────────────────────────────────────────
// INPUTS
// ─────────────────────────────────────────────────────────────────────────────
GRP_GENERAL = "General"
GRP_RULES = "Line rules"
GRP_STYLE = "Style"
startTime = input.time(timestamp("01 Jan 2022 00:00 +0000"), "Measure from", group = GRP_GENERAL,
tooltip = "Tests before this date are ignored, so all timeframes are compared over the same period.")
minTests = input.int(20, "Minimum tests to qualify", minval = 1, group = GRP_GENERAL,
tooltip = "A timeframe with fewer tests (held + broken) is marked 'not enough data' and cannot be selected.")
drawLines = input.bool(true, "Draw lines of the most reliable timeframe", group = GRP_GENERAL)
swingLen = input.int(5, "Swing length", minval = 2, maxval = 20, group = GRP_RULES,
tooltip = "Bars on each side of a pivot.")
swingDepth = input.float(1.5, "Swing depth (ATR)", minval = 0.5, maxval = 5.0, step = 0.25, group = GRP_RULES,
tooltip = "A swing is accepted only when the move from the previous opposite swing is at least this many ATR(200).")
minSpan = input.int(4, "Minimum span (swing lengths)", minval = 2, maxval = 12, group = GRP_RULES,
tooltip = "The two anchors of a line must be at least this many swing lengths apart.")
touchTol = input.float(0.3, "Touch tolerance (ATR)", minval = 0.05, maxval = 1.0, step = 0.05, group = GRP_RULES)
breakTol = input.float(0.1, "Break tolerance (ATR)", minval = 0.0, maxval = 1.0, step = 0.05, group = GRP_RULES)
staleMult = input.float(1.0, "Stale after (spans)", minval = 0.5, maxval = 5.0, step = 0.5, group = GRP_RULES,
tooltip = "A line is dropped when price has not touched it for longer than its anchor span times this value.")
resColor = input.color(#ff9800, "Ceiling line", group = GRP_STYLE)
supColor = input.color(#2196f3, "Floor line", group = GRP_STYLE)
lineWidth = input.int(3, "Line width", minval = 1, maxval = 4, group = GRP_STYLE)
showAnchor = input.bool(true, "Mark first anchor", group = GRP_STYLE)
// ─────────────────────────────────────────────────────────────────────────────
// SWING ACCEPTANCE
// Same side: only a more extreme pivot replaces the last swing.
// Opposite side: accepted only after a move of at least minMove from the last swing.
// ─────────────────────────────────────────────────────────────────────────────
acceptSwing(array<int> swBars, array<float> swPrices, array<int> swSides, array<int> swTimes,
int barIdx, float price, int side, float minMove, int barTime) =>
bool accepted = false
int count = swBars.size()
if count == 0
swBars.push(barIdx)
swPrices.push(price)
swSides.push(side)
swTimes.push(barTime)
accepted := true
else if swSides.last() == side
if side == 1 ? price > swPrices.last() : price < swPrices.last()
swBars.set(count - 1, barIdx)
swPrices.set(count - 1, price)
swTimes.set(count - 1, barTime)
accepted := true
else if math.abs(price - swPrices.last()) >= minMove
swBars.push(barIdx)
swPrices.push(price)
swSides.push(side)
swTimes.push(barTime)
accepted := true
if swBars.size() > 60
swBars.shift()
swPrices.shift()
swSides.shift()
swTimes.shift()
accepted
// ─────────────────────────────────────────────────────────────────────────────
// MEASUREMENT ON ONE TIMEFRAME (called through request.security)
// Returns the running test statistics and the current best line of each side.
// ─────────────────────────────────────────────────────────────────────────────
measureTimeframe() =>
float atr200 = ta.atr(200)
float atr50 = ta.atr(50)
float atr14 = ta.atr(14)
float atr = na(atr200) ? (na(atr50) ? atr14 : atr50) : atr200
float pivHi = ta.pivothigh(swingLen, swingLen)
float pivLo = ta.pivotlow(swingLen, swingLen)
var array<int> swBars = array.new<int>()
var array<float> swPrices = array.new<float>()
var array<int> swSides = array.new<int>()
var array<int> swTimes = array.new<int>()
// active lines
var array<int> lnAnchorBar = array.new<int>()
var array<float> lnAnchorPx = array.new<float>()
var array<int> lnAnchorTime = array.new<int>()
var array<float> lnSlope = array.new<float>()
var array<int> lnSide = array.new<int>()
var array<int> lnSpan = array.new<int>()
var array<int> lnLastTouch = array.new<int>()
var array<int> lnTouches = array.new<int>()
var int heldTests = 0
var int breaks = 0
var int lineCount = 0
var int firstTime = na
bool counting = time >= startTime
if counting and na(firstTime)
firstTime := time
// 1) update active lines: break first, then test, then staleness
if lnAnchorBar.size() > 0 and not na(atr)
for i = lnAnchorBar.size() - 1 to 0
int side = lnSide.get(i)
float level = lnAnchorPx.get(i) + lnSlope.get(i) * (bar_index - lnAnchorBar.get(i))
bool retire = false
bool broken = side == 1 ? close > level + breakTol * atr : close < level - breakTol * atr
if broken
if counting
breaks += 1
retire := true
else
bool touched = side == 1 ? high >= level - touchTol * atr : low <= level + touchTol * atr
if touched and bar_index - lnLastTouch.get(i) > swingLen
if counting
heldTests += 1
lnLastTouch.set(i, bar_index)
lnTouches.set(i, lnTouches.get(i) + 1)
else if bar_index - lnLastTouch.get(i) > staleMult * lnSpan.get(i)
retire := true
if retire
lnAnchorBar.remove(i)
lnAnchorPx.remove(i)
lnAnchorTime.remove(i)
lnSlope.remove(i)
lnSide.remove(i)
lnSpan.remove(i)
lnLastTouch.remove(i)
lnTouches.remove(i)
// 2) a new swing creates a line with the previous swing of the same side
for side = 1 to -1 by 2
float pivot = side == 1 ? pivHi : pivLo
if not na(pivot) and not na(atr)
if acceptSwing(swBars, swPrices, swSides, swTimes, bar_index - swingLen, pivot, side, swingDepth * atr, time[swingLen])
int newIdx = swBars.size() - 1
int prevIdx = -1
if newIdx > 0
for k = newIdx - 1 to 0
if swSides.get(k) == side
prevIdx := k
break
if prevIdx >= 0
int bar1 = swBars.get(prevIdx)
int bar2 = swBars.get(newIdx)
float px1 = swPrices.get(prevIdx)
float px2 = swPrices.get(newIdx)
if bar2 - bar1 >= minSpan * swingLen
float slope = (px2 - px1) / (bar2 - bar1)
// no close from the first anchor until now may cross the line
bool valid = true
int lookback = math.min(bar_index - bar1, 1000)
for off = lookback to 0
float lv = px1 + slope * (bar_index - off - bar1)
if side == 1 ? close[off] > lv + breakTol * atr : close[off] < lv - breakTol * atr
valid := false
break
if valid
if counting
lineCount += 1
lnAnchorBar.push(bar1)
lnAnchorPx.push(px1)
lnAnchorTime.push(swTimes.get(prevIdx))
lnSlope.push(slope)
lnSide.push(side)
lnSpan.push(bar2 - bar1)
lnLastTouch.push(bar2)
lnTouches.push(2)
if lnAnchorBar.size() > 20
lnAnchorBar.shift()
lnAnchorPx.shift()
lnAnchorTime.shift()
lnSlope.shift()
lnSide.shift()
lnSpan.shift()
lnLastTouch.shift()
lnTouches.shift()
// 3) best active line per side: most touches, then longest span
int resIdx = -1
int supIdx = -1
if lnAnchorBar.size() > 0
for i = 0 to lnAnchorBar.size() - 1
if lnSide.get(i) == 1
if resIdx == -1 or lnTouches.get(i) > lnTouches.get(resIdx) or (lnTouches.get(i) == lnTouches.get(resIdx) and lnSpan.get(i) > lnSpan.get(resIdx))
resIdx := i
else
if supIdx == -1 or lnTouches.get(i) > lnTouches.get(supIdx) or (lnTouches.get(i) == lnTouches.get(supIdx) and lnSpan.get(i) > lnSpan.get(supIdx))
supIdx := i
int resT1 = resIdx == -1 ? na : lnAnchorTime.get(resIdx)
float resP1 = resIdx == -1 ? na : lnAnchorPx.get(resIdx)
float resNow = resIdx == -1 ? na : lnAnchorPx.get(resIdx) + lnSlope.get(resIdx) * (bar_index - lnAnchorBar.get(resIdx))
int resTch = resIdx == -1 ? 0 : lnTouches.get(resIdx)
int supT1 = supIdx == -1 ? na : lnAnchorTime.get(supIdx)
float supP1 = supIdx == -1 ? na : lnAnchorPx.get(supIdx)
float supNow = supIdx == -1 ? na : lnAnchorPx.get(supIdx) + lnSlope.get(supIdx) * (bar_index - lnAnchorBar.get(supIdx))
int supTch = supIdx == -1 ? 0 : lnTouches.get(supIdx)
[heldTests, breaks, lineCount, firstTime, resT1, resP1, resNow, resTch, supT1, supP1, supNow, supTch, time]
// ─────────────────────────────────────────────────────────────────────────────
// THREE TIMEFRAMES
// ─────────────────────────────────────────────────────────────────────────────
[h4H, b4H, n4H, f4H, rt4H, rp4H, rv4H, rc4H, st4H, sp4H, sv4H, sc4H, t4H] = request.security(syminfo.tickerid, "240", measureTimeframe())
[h1D, b1D, n1D, f1D, rt1D, rp1D, rv1D, rc1D, st1D, sp1D, sv1D, sc1D, t1D] = request.security(syminfo.tickerid, "D", measureTimeframe())
[h1W, b1W, n1W, f1W, rt1W, rp1W, rv1W, rc1W, st1W, sp1W, sv1W, sc1W, t1W] = request.security(syminfo.tickerid, "W", measureTimeframe())
plot(close, "Scale anchor", color = color(na), display = display.none, editable = false)
// ─────────────────────────────────────────────────────────────────────────────
// TABLE AND DRAWING (last bar only)
// ─────────────────────────────────────────────────────────────────────────────
var array<line> drawnLines = array.new<line>()
var array<label> drawnLabels = array.new<label>()
var table panel = table.new(position.top_right, 5, 6, bgcolor = color.new(#131722, 0), border_width = 1,
border_color = color.new(#363a45, 0))
cell(int col, int row, string txt, color txtColor, color bgColor) =>
table.cell(panel, col, row, txt, text_color = txtColor, bgcolor = bgColor, text_size = size.small)
reliability(int held, int broken) => held + broken > 0 ? held * 1.0 / (held + broken) : na
drawLine(int t1, float p1, int tNow, float pNow, color col, string caption) =>
if not na(t1) and not na(pNow) and tNow > t1
// project only a short distance ahead (30% of the line's own length) instead of extending forever,
// so short steep lines do not shoot off the chart
int projMs = int((tNow - t1) * 0.3)
float pEnd = pNow + (pNow - p1) / (tNow - t1) * projMs
drawnLines.push(line.new(t1, p1, tNow + projMs, pEnd, xloc = xloc.bar_time, extend = extend.none,
color = color.new(col, 15), width = lineWidth, style = line.style_solid))
// filled badge on the current bar
drawnLabels.push(label.new(time, pNow, caption, xloc = xloc.bar_time, style = label.style_label_left,
color = color.new(col, 0), textcolor = color.black, size = size.small))
// small dot on the first anchor
if showAnchor
drawnLabels.push(label.new(t1, p1, "", xloc = xloc.bar_time, style = label.style_circle,
color = color.new(col, 0), size = size.tiny))
if barstate.islast
names = array.from("4H", "1D", "1W")
tfCodes = array.from("240", "D", "W")
heldArr = array.from(h4H, h1D, h1W)
brkArr = array.from(b4H, b1D, b1W)
linesArr = array.from(n4H, n1D, n1W)
fromArr = array.from(f4H, f1D, f1W)
// pick the most reliable qualifying timeframe; within 2 points, more tests wins
int best = -1
for i = 0 to 2
int tests = heldArr.get(i) + brkArr.get(i)
float rel = reliability(heldArr.get(i), brkArr.get(i))
if tests >= minTests and not na(rel)
if best == -1
best := i
else
float relBest = reliability(heldArr.get(best), brkArr.get(best))
int testsBest = heldArr.get(best) + brkArr.get(best)
if rel > relBest + 0.02 or (math.abs(rel - relBest) <= 0.02 and tests > testsBest)
best := i
color headBg = color.new(#2a2e39, 0)
color rowBg = color.new(#131722, 0)
color white = color.white
string title = best == -1 ? "NOT ENOUGH DATA" : "MOST RELIABLE: " + names.get(best)
cell(0, 0, title, color.black, best == -1 ? color.new(color.gray, 0) : color.new(#089981, 0))
table.merge_cells(panel, 0, 0, 4, 0)
cell(0, 1, "Timeframe", white, headBg)
cell(1, 1, "Reliability", white, headBg)
cell(2, 1, "Held / Broken", white, headBg)
cell(3, 1, "Lines", white, headBg)
cell(4, 1, "Data from", white, headBg)
for i = 0 to 2
int row = i + 2
bool current = timeframe.period == tfCodes.get(i)
color bg = i == best ? color.new(#089981, 65) : rowBg
int tests = heldArr.get(i) + brkArr.get(i)
float rel = reliability(heldArr.get(i), brkArr.get(i))
bool thin = tests < minTests
color relCol = thin ? color.gray : rel >= 0.6 ? #26a69a : rel >= 0.45 ? color.orange : #ef5350
cell(0, row, names.get(i) + (current ? " ◀ chart" : ""), white, bg)
cell(1, row, na(rel) ? "-" : str.tostring(rel * 100, "0") + "%" + (thin ? " (thin)" : ""), relCol, bg)
cell(2, row, str.tostring(heldArr.get(i)) + " / " + str.tostring(brkArr.get(i)), white, bg)
cell(3, row, str.tostring(linesArr.get(i)), white, bg)
cell(4, row, na(fromArr.get(i)) ? "-" : str.format_time(fromArr.get(i), "yyyy-MM-dd"), color.gray, bg)
cell(0, 5, "Reliability = share of line tests that held", color.gray, rowBg)
table.merge_cells(panel, 0, 5, 4, 5)
// redraw the lines of the selected timeframe
for ln in drawnLines
line.delete(ln)
drawnLines.clear()
for lb in drawnLabels
label.delete(lb)
drawnLabels.clear()
if drawLines and best != -1
string tfName = names.get(best)
int tNow = array.from(t4H, t1D, t1W).get(best)
int resTc = array.from(rc4H, rc1D, rc1W).get(best)
int supTc = array.from(sc4H, sc1D, sc1W).get(best)
drawLine(array.from(rt4H, rt1D, rt1W).get(best), array.from(rp4H, rp1D, rp1W).get(best), tNow,
array.from(rv4H, rv1D, rv1W).get(best), resColor, tfName + " ceiling ◆ " + str.tostring(resTc) + " tests")
drawLine(array.from(st4H, st1D, st1W).get(best), array.from(sp4H, sp1D, sp1W).get(best), tNow,
array.from(sv4H, sv1D, sv1W).get(best), supColor, tfName + " floor ◆ " + str.tostring(supTc) + " tests")