本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ahmad1darwich
//@version=6
indicator("Nexus Auto Trend Lines", shorttitle = "NX Trend", overlay = true, max_lines_count = 500, max_labels_count = 300)
// ---------- Inputs ----------
string GRP_D = "Detection"
bool autoInput = input.bool(true, "Auto settings (all timeframes)", group = GRP_D, tooltip = "Adapts pivot length, swing distance and line life to the chart timeframe, from 1 minute to 1 year. Turn off to use the manual values below.")
int pivLenInput = input.int(8, "Pivot length", minval = 2, maxval = 50, group = GRP_D, tooltip = "Bars on each side of a swing. A trend line is drawn this many bars after the second swing forms. Bigger = fewer, stronger lines.")
int minGapInput = input.int(10, "Minimum bars between the two swings", minval = 2, group = GRP_D)
int maxGapInput = input.int(150, "Maximum bars between the two swings", minval = 10, group = GRP_D)
float marginInput = input.float(0.2, "Break margin (x ATR)", minval = 0, step = 0.05, group = GRP_D, tooltip = "A line is broken only when a bar CLOSES beyond it by this many ATR.")
bool cleanInput = input.bool(false, "Reject lines price already cut through", group = GRP_D, tooltip = "A line is drawn only if no bar closed beyond it between the two swings and now. Gives fewer but cleaner lines.")
float touchTolInput = input.float(0.25, "Touch tolerance (x ATR)", minval = 0.05, step = 0.05, group = GRP_D, tooltip = "A later swing within this distance of a line counts as one more touch. More touches = stronger line (drawn thicker).")
bool showTagInput = input.bool(true, "Line tags (touch count)", group = GRP_D)
int maxAgeInput = input.int(300, "Remove a line after (bars)", minval = 20, group = GRP_D, tooltip = "Old lines that were never broken are removed so the chart stays clean.")
string GRP_L = "Layers"
bool showResInput = input.bool(true, "Descending lines (resistance)", group = GRP_L)
bool showSupInput = input.bool(true, "Ascending lines (support)", group = GRP_L)
int keepInput = input.int(3, "Keep active lines per side", minval = 1, maxval = 6, group = GRP_L)
bool showBrokenInput = input.bool(true, "Keep broken lines (faded)", group = GRP_L)
bool showBreakInput = input.bool(true, "Break labels", group = GRP_L)
bool showDashInput = input.bool(true, "Show dashboard", group = GRP_L)
string dashPosInput = input.string("Top right", "Dashboard position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = GRP_L)
string GRP_ST = "Style"
string themeInput = input.string("Neon", "Theme", options = ["Neon", "Classic", "Minimal", "Mono"], group = GRP_ST)
bool customColorsInput = input.bool(false, "Custom line colors", group = GRP_ST, tooltip = "Turn on to use the two colors below instead of the theme colors for support and resistance.")
color supColorInput = input.color(#00E676, "Support (ascending)", group = GRP_ST, inline = "cc")
color resColorInput = input.color(#FF1744, "Resistance (descending)", group = GRP_ST, inline = "cc")
// ---------- Theme ----------
pick(color neon, color classic, color minimal, color mono) =>
themeInput == "Neon" ? neon : themeInput == "Classic" ? classic : themeInput == "Minimal" ? minimal : mono
color bullC = customColorsInput ? supColorInput : pick(#00E5A0, #089981, #26A69A, #D1D4DC)
color bearC = customColorsInput ? resColorInput : pick(#FF3D71, #F23645, #EF5350, #787B86)
color accentC = pick(#7C4DFF, #2962FF, #B2B5BE, #E0E3EB)
color textC = pick(#9598A1, #787B86, #9598A1, #B2B5BE)
// ---------- Auto settings per timeframe ----------
int tfSec = timeframe.in_seconds()
bool isDay = tfSec >= 86400 and tfSec < 604800
bool isWeek = tfSec >= 604800 and tfSec < 2000000
bool isMonth = tfSec >= 2000000
int autoPiv = tfSec <= 300 ? 10 : tfSec <= 3600 ? 8 : tfSec < 86400 ? 6 : isDay ? 5 : isWeek ? 4 : 3
int autoMin = tfSec < 86400 ? 10 : isDay ? 6 : isWeek ? 4 : 3
int autoMax = tfSec < 86400 ? 150 : isDay ? 100 : isWeek ? 60 : 40
int autoAge = tfSec < 86400 ? 300 : isDay ? 200 : isWeek ? 120 : 80
int pivLen = autoInput ? autoPiv : pivLenInput
int minGap = autoInput ? autoMin : minGapInput
int maxGap = autoInput ? autoMax : maxGapInput
int maxAge = autoInput ? autoAge : maxAgeInput
// ---------- Types and state ----------
type TLine
line ln
int x1
float y1
int x2
float y2
bool isSupport
int touches
label tag
method priceAt(TLine t, int bar) =>
t.y2 + (t.y2 - t.y1) / (t.x2 - t.x1) * (bar - t.x2)
var array<TLine> resLines = array.new<TLine>()
var array<TLine> supLines = array.new<TLine>()
var array<line> history = array.new<line>()
// Recent confirmed swings (price and bar), used to connect non-adjacent pivots.
var array<float> hiP = array.new<float>()
var array<int> hiB = array.new<int>()
var array<float> loP = array.new<float>()
var array<int> loB = array.new<int>()
var float lastH = na
var int lastHBar = na
var float prevH = na
var int prevHBar = na
var float lastL = na
var int lastLBar = na
var float prevL = na
var int prevLBar = na
var string lastBreak = "-"
var int lastBreakBar = na
var int lastBreakDir = 0
// ---------- Calculations ----------
float atr = ta.atr(14)
float ph = ta.pivothigh(high, pivLen, pivLen)
float pl = ta.pivotlow(low, pivLen, pivLen)
// Creates one trend line through two confirmed swings, extended to the right.
addLine(array<TLine> arr, int x1, float y1, int x2, float y2, bool isSupport, color c, int touchCount) =>
float yNow = y2 + (y2 - y1) / (x2 - x1) * (bar_index - x2)
line ln = line.new(x1, y1, bar_index, yNow, extend = extend.right, color = c, width = 2)
label tg = label.new(bar_index + 2, yNow, "", style = label.style_label_left, color = color.new(c, 25), textcolor = color.white, size = size.tiny)
arr.push(TLine.new(ln = ln, x1 = x1, y1 = y1, x2 = x2, y2 = y2, isSupport = isSupport, touches = touchCount, tag = tg))
if arr.size() > keepInput
TLine old = arr.shift()
old.ln.delete()
old.tag.delete()
// True when no close between the first swing and now pushed through the candidate line.
lineClean(int x1, float y1, int x2, float y2, bool isSupport) =>
float slope = (y2 - y1) / (x2 - x1)
float tol = na(atr) ? 0.0 : atr * touchTolInput * 0.5
bool ok = true
int span = bar_index - x1
for off = 0 to span
int bx = bar_index - off
float lp = y1 + slope * (bx - x1)
float cl = close[off]
if isSupport ? cl < lp - tol : cl > lp + tol
ok := false
ok
// A new confirmed swing near an existing line counts as one more touch.
countTouches(array<TLine> arr, float pivotPrice, int pivotBar) =>
if arr.size() > 0
float tol = na(atr) ? 0.0 : atr * touchTolInput
for t in arr
if pivotBar > t.x2 and math.abs(pivotPrice - t.priceAt(pivotBar)) <= tol
t.touches := t.touches + 1
// Checks every active line: break (close beyond by margin) or too old. Returns true when a line broke.
processLines(array<TLine> arr, bool isSupport) =>
bool broke = false
if arr.size() > 0
for i = arr.size() - 1 to 0
TLine t = arr.get(i)
float p = t.priceAt(bar_index)
float mg = na(atr) ? 0.0 : atr * marginInput
bool brk = isSupport ? close < p - mg : close > p + mg
bool tooOld = bar_index - t.x2 > maxAge
if brk
broke := true
t.tag.delete()
if showBrokenInput
t.ln.set_extend(extend.none)
t.ln.set_xy2(bar_index, p)
t.ln.set_color(color.new(isSupport ? bearC : bullC, 40))
t.ln.set_width(2)
history.push(t.ln)
if history.size() > 8
line oldLn = history.shift()
oldLn.delete()
else
t.ln.delete()
if showBreakInput
label.new(bar_index, isSupport ? high : low, isSupport ? "▼" : "▲", style = isSupport ? label.style_label_down : label.style_label_up, color = color.new(isSupport ? bearC : bullC, 20), textcolor = color.white, size = size.tiny, tooltip = isSupport ? "Support broken" : "Resistance broken")
arr.remove(i)
else if tooOld
t.ln.delete()
t.tag.delete()
arr.remove(i)
else
t.tag.set_xy(bar_index + 2, p)
t.tag.set_text(showTagInput ? (isSupport ? "S x" : "R x") + str.tostring(t.touches) : "")
t.ln.set_width(t.touches >= 3 ? 3 : 2)
broke
// ---------- Detection (confirmed bars only) ----------
bool newRes = false
bool newSup = false
if barstate.isconfirmed and not na(ph)
countTouches(resLines, ph, bar_index - pivLen)
lastH := ph
lastHBar := bar_index - pivLen
if showResInput and hiP.size() > 0
int best = -1
for i = hiP.size() - 1 to 0
int pb = hiB.get(i)
float py = hiP.get(i)
int gap = lastHBar - pb
float yNow = lastH + (lastH - py) / gap * (bar_index - lastHBar)
bool okGap = gap >= minGap and gap <= maxGap
bool okSlope = lastH < py and close < yNow
if okGap and okSlope
bool nearest = i == hiP.size() - 1
bool okClean = (nearest and not cleanInput) or lineClean(pb, py, lastHBar, lastH, false)
if okClean
best := i
if best >= 0
int bb = hiB.get(best)
float bp = hiP.get(best)
float slp = (lastH - bp) / (lastHBar - bb)
float tolT = na(atr) ? 0.0 : atr * touchTolInput
int tc = 2
for j = 0 to hiP.size() - 1
int jb = hiB.get(j)
if jb > bb
if math.abs(hiP.get(j) - (bp + slp * (jb - bb))) <= tolT
tc += 1
addLine(resLines, bb, bp, lastHBar, lastH, false, bearC, tc)
newRes := true
hiP.push(ph)
hiB.push(lastHBar)
if hiP.size() > 10
hiP.shift()
hiB.shift()
if barstate.isconfirmed and not na(pl)
countTouches(supLines, pl, bar_index - pivLen)
lastL := pl
lastLBar := bar_index - pivLen
if showSupInput and loP.size() > 0
int best = -1
for i = loP.size() - 1 to 0
int pb = loB.get(i)
float py = loP.get(i)
int gap = lastLBar - pb
float yNow = lastL + (lastL - py) / gap * (bar_index - lastLBar)
bool okGap = gap >= minGap and gap <= maxGap
bool okSlope = lastL > py and close > yNow
if okGap and okSlope
bool nearest = i == loP.size() - 1
bool okClean = (nearest and not cleanInput) or lineClean(pb, py, lastLBar, lastL, true)
if okClean
best := i
if best >= 0
int bb = loB.get(best)
float bp = loP.get(best)
float slp = (lastL - bp) / (lastLBar - bb)
float tolT = na(atr) ? 0.0 : atr * touchTolInput
int tc = 2
for j = 0 to loP.size() - 1
int jb = loB.get(j)
if jb > bb
if math.abs(loP.get(j) - (bp + slp * (jb - bb))) <= tolT
tc += 1
addLine(supLines, bb, bp, lastLBar, lastL, true, bullC, tc)
newSup := true
loP.push(pl)
loB.push(lastLBar)
if loP.size() > 10
loP.shift()
loB.shift()
bool breakUp = false
bool breakDn = false
if barstate.isconfirmed
breakUp := processLines(resLines, false)
breakDn := processLines(supLines, true)
if breakUp
lastBreak := "▲ Resistance broken"
lastBreakBar := bar_index
lastBreakDir := 1
if breakDn
lastBreak := "▼ Support broken"
lastBreakBar := bar_index
lastBreakDir := -1
// ---------- Dashboard ----------
dashPos = dashPosInput == "Top right" ? position.top_right : dashPosInput == "Bottom right" ? position.bottom_right : dashPosInput == "Top left" ? position.top_left : position.bottom_left
var table dash = table.new(dashPos, 2, 5, border_width = 1, border_color = color.new(#787B86, 85), frame_color = color.new(accentC, 40), frame_width = 1)
if showDashInput and barstate.islast
float resNow = resLines.size() > 0 ? resLines.get(-1).priceAt(bar_index) : na
float supNow = supLines.size() > 0 ? supLines.get(-1).priceAt(bar_index) : na
string resTxt = na(resNow) ? "-" : str.tostring(resNow, format.mintick) + " x" + str.tostring(resLines.get(-1).touches)
string supTxt = na(supNow) ? "-" : str.tostring(supNow, format.mintick) + " x" + str.tostring(supLines.get(-1).touches)
string lastTxt = na(lastBreakBar) ? "-" : str.tostring(bar_index - lastBreakBar) + " bars ago"
string linesTxt = str.tostring(resLines.size()) + " / " + str.tostring(supLines.size())
color lastC = lastBreakDir == 1 ? bullC : lastBreakDir == -1 ? bearC : textC
table.cell(dash, 0, 0, "NEXUS", text_color = color.white, bgcolor = color.new(accentC, 15), text_size = size.small)
table.cell(dash, 1, 0, "Auto Trend Lines", text_color = color.white, bgcolor = color.new(accentC, 15), text_size = size.small)
table.cell(dash, 0, 1, "Resistance now", text_color = textC, bgcolor = color.new(#131722, 10), text_size = size.small, text_halign = text.align_left)
table.cell(dash, 1, 1, resTxt, text_color = bearC, bgcolor = color.new(#131722, 10), text_size = size.small, text_halign = text.align_right, text_font_family = font.family_monospace)
table.cell(dash, 0, 2, "Support now", text_color = textC, bgcolor = color.new(#131722, 10), text_size = size.small, text_halign = text.align_left)
table.cell(dash, 1, 2, supTxt, text_color = bullC, bgcolor = color.new(#131722, 10), text_size = size.small, text_halign = text.align_right, text_font_family = font.family_monospace)
table.cell(dash, 0, 3, "Last break", text_color = textC, bgcolor = color.new(#131722, 10), text_size = size.small, text_halign = text.align_left)
table.cell(dash, 1, 3, lastBreak + " • " + lastTxt, text_color = lastC, bgcolor = color.new(#131722, 10), text_size = size.small, text_halign = text.align_right, text_font_family = font.family_monospace)
table.cell(dash, 0, 4, "Active (R / S)", text_color = textC, bgcolor = color.new(#131722, 10), text_size = size.small, text_halign = text.align_left)
table.cell(dash, 1, 4, linesTxt, text_color = accentC, bgcolor = color.new(#131722, 10), text_size = size.small, text_halign = text.align_right, text_font_family = font.family_monospace)
// ---------- Alerts ----------
alertcondition(newRes, "New descending trend line", "Nexus Trend Lines: new descending line on {{ticker}} {{interval}}")
alertcondition(newSup, "New ascending trend line", "Nexus Trend Lines: new ascending line on {{ticker}} {{interval}}")
alertcondition(breakUp, "Descending line broken up", "Nexus Trend Lines: resistance line broken upward on {{ticker}} {{interval}} at {{close}}")
alertcondition(breakDn, "Ascending line broken down", "Nexus Trend Lines: support line broken downward on {{ticker}} {{interval}} at {{close}}")