本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// © ITA Trading Tools - itamardrori_
//@version=6
// =============================================================================
// Flags & Pennants [ITA]
//
// A flag is a pause after a sharp move: the pole is the move, the flag is a
// short, tight drift against it. A pennant is the same pause squeezing into a
// small triangle. Traders mark them by hand and project the pole's height
// from the breakout as the target.
//
// This finds the pole, draws the flag around the pause as it forms, marks the
// close that breaks out of it, and draws that target. When price reaches the
// target the label says so. When price instead falls back through the far
// side of the flag, the break is marked as failed and the target cancelled.
//
// Decisions worth stating:
//
// the pole at least 4 ATRs, made in 10 bars or fewer. A slow climb is
// a trend, not a pole.
//
// the pause may give back at most half of the pole and may last at most
// 20 bars. Past either, it is no longer a flag and turns grey.
//
// the lines are fitted to the highs and the lows of the pause, then
// pushed out until every bar is inside. A flag drifts against
// the pole or sideways. A pause drifting with the pole is not
// a flag and is skipped.
//
// the break is judged against lines fitted on the bars before it, so the
// breakout bar cannot move its own line.
// =============================================================================
// Drawn in front of the candles, so no later candle can cover a label.
indicator("Flags & Pennants [ITA]", overlay = true, max_bars_back = 500, max_lines_count = 300, max_labels_count = 300, behind_chart = false)
// ─── INPUTS ──────────────────────────────────────────────────────────────────
grpCalc = "Detection"
poleAtr = input.float(4.0, "Smallest Pole In ATRs", minval = 1, maxval = 20, step = 0.5, group = grpCalc,
tooltip = "How big the move before the pause has to be.")
poleMax = input.int(10, "Longest Pole In Bars", minval = 2, maxval = 50, group = grpCalc,
tooltip = "How fast the move has to be. Fewer bars means a sharper pole.")
flagMin = input.int(4, "Shortest Pause In Bars", minval = 2, maxval = 30, group = grpCalc)
flagMax = input.int(20, "Longest Pause In Bars", minval = 5, maxval = 60, group = grpCalc)
retrPct = input.float(50, "Deepest Pullback, Percent Of Pole", minval = 20, maxval = 80, step = 5, group = grpCalc)
sides = input.string("Both", "Direction", options = ["Both", "Bull only", "Bear only"], group = grpCalc)
grpShow = "Display"
keepPast = input.int(8, "Finished Patterns To Keep", minval = 0, maxval = 40, group = grpShow)
showFill = input.bool(true, "Shade The Flag", group = grpShow)
showTgt = input.bool(true, "Draw The Target", group = grpShow)
showPanel = input.bool(true, "Show The Panel", group = grpShow)
lineW = input.int(2, "Line Thickness", minval = 1, maxval = 4, group = grpShow)
labelSizeStr = input.string("Normal", "Label Size",
options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = grpShow)
statPos = input.string("Top Right", "Panel Position",
options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = grpShow)
statSizeStr = input.string("Normal", "Panel Text Size",
options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = grpShow)
grpCol = "Colors"
liveCol = input.color(#e5c56b, "Pattern Still Forming", group = grpCol)
upCol = input.color(#089981, "Broke Up", group = grpCol)
dnCol = input.color(#f23645, "Broke Down", group = grpCol)
deadCol = input.color(#787b86, "Ran Out Without A Break", group = grpCol)
failCol = input.color(#ff9800, "Failed Break", group = grpCol)
labelBg = input.color(color.new(#1e222d, 0), "Label Background", group = grpCol)
sizeOf(string s) =>
r = size.normal
if s == "Tiny"
r := size.tiny
else if s == "Small"
r := size.small
else if s == "Large"
r := size.large
else if s == "Huge"
r := size.huge
r
posOf(string s) =>
r = position.top_right
if s == "Top Left"
r := position.top_left
else if s == "Bottom Right"
r := position.bottom_right
else if s == "Bottom Left"
r := position.bottom_left
r
statSize = sizeOf(statSizeStr)
labelSize = sizeOf(labelSizeStr)
// Least squares through the points, then shifted so every point is on the
// inside: above for the upper line, below for the lower one.
fitEdge(array<int> xs, array<float> ys, bool upper) =>
n = array.size(xs)
sx = 0.0
sy = 0.0
sxy = 0.0
sxx = 0.0
for k = 0 to n - 1
x = float(array.get(xs, k))
y = array.get(ys, k)
sx += x
sy += y
sxy += x * y
sxx += x * x
den = n * sxx - sx * sx
slope = den != 0 ? (n * sxy - sx * sy) / den : 0.0
icpt = (sy - slope * sx) / n
off = upper ? -1e10 : 1e10
for k = 0 to n - 1
res = array.get(ys, k) - (slope * array.get(xs, k) + icpt)
off := upper ? math.max(off, res) : math.min(off, res)
[slope, icpt + off]
// ─── STATE ───────────────────────────────────────────────────────────────────
atr = ta.atr(14)
var bool act = false
var int dir = 0
var int tBar = 0
var int bBar = 0
var float tPx = na
var float bPx = na
var float pole = na
var string kind = ""
var float su = 0.0
var float iu = 0.0
var float sl = 0.0
var float il = 0.0
var line aPole = na
var line aU = na
var line aL = na
var linefill aF = na
var label aLab = na
var array<line> pastLines = array.new<line>()
var array<linefill> pastFills = array.new<linefill>()
var array<label> pastLabels = array.new<label>()
var float tgt = na
var int tgtDir = 0
var bool tgtHit = false
var bool tgtFail = false
var float failLvl = na
var line tgtLine = na
var label tgtLab = na
var string lastName = ""
var int lastBar = na
var int lastEnd = -1
nameOf(int d, string k) =>
(d == 1 ? "Bull " : "Bear ") + k
brokeUp = false
brokeDn = false
// ─── FOLLOWING THE ACTIVE PATTERN ────────────────────────────────────────────
if barstate.isconfirmed and act
xs = array.new<int>()
hs = array.new<float>()
ls = array.new<float>()
for k = 1 to bar_index - tBar
array.push(xs, bar_index - k)
array.push(hs, high[k])
array.push(ls, low[k])
[a1, b1] = fitEdge(xs, hs, true)
[a2, b2] = fitEdge(xs, ls, false)
su := a1
iu := b1
sl := a2
il := b2
upNow = su * bar_index + iu
loNow = sl * bar_index + il
ended = false
isBreak = dir == 1 ? close > upNow : close < loNow
if isBreak
brokeUp := dir == 1
brokeDn := dir == -1
c = dir == 1 ? upCol : dnCol
line.set_xy2(aU, bar_index, upNow)
line.set_xy2(aL, bar_index, loNow)
line.set_color(aU, c)
line.set_color(aL, c)
line.set_color(aPole, c)
if not na(aF)
linefill.set_color(aF, color.new(c, 90))
label.set_textcolor(aLab, c)
yMark = dir == 1 ? high + atr * 0.6 : low - atr * 0.6
array.push(pastLabels, label.new(bar_index, yMark, dir == 1 ? "▲ Break up" : "▼ Break down", style = dir == 1 ? label.style_label_down : label.style_label_up, color = labelBg, textcolor = c, size = labelSize))
// The measured move: the height of the pole, from the line that broke.
tgt := dir == 1 ? upNow + pole : loNow - pole
tgtDir := dir
tgtHit := false
tgtFail := false
// Failed once price closes back beyond the far side of the flag.
failLvl := dir == 1 ? loNow : upNow
tgtLine := na
tgtLab := na
if showTgt
tgtLine := line.new(bar_index, tgt, bar_index + 15, tgt, color = color.new(c, 20), width = 1, style = line.style_dashed)
// Ends at the line's right end and reads leftward, over the open space
// above the chart, so it is not cut off at the right edge.
tgtLab := label.new(bar_index + 15, tgt, "Target " + str.tostring(tgt, format.mintick), style = label.style_label_right, color = labelBg, textcolor = c, size = labelSize)
array.push(pastLines, tgtLine)
array.push(pastLabels, tgtLab)
lastName := nameOf(dir, kind)
lastBar := bar_index
ended := true
else
deepest = 0.0
for k = 0 to bar_index - tBar
deepest := math.max(deepest, dir == 1 ? tPx - low[k] : high[k] - tPx)
if deepest > pole * retrPct / 100.0 or bar_index - tBar > flagMax
// Too deep or too long to still be a flag. Kept on the chart,
// greyed, so the ones that went nowhere stay visible too.
line.set_color(aU, deadCol)
line.set_color(aL, deadCol)
line.set_color(aPole, deadCol)
if not na(aF)
linefill.set_color(aF, color.new(deadCol, 90))
label.set_textcolor(aLab, deadCol)
lastName := nameOf(dir, kind)
lastBar := bar_index
ended := true
else
line.set_xy1(aU, tBar, su * tBar + iu)
line.set_xy2(aU, bar_index, upNow)
line.set_xy1(aL, tBar, sl * tBar + il)
line.set_xy2(aL, bar_index, loNow)
w0 = (su - sl) * tBar + (iu - il)
wN = (su - sl) * bar_index + (iu - il)
kind := wN < w0 * 0.6 ? "Pennant" : "Flag"
label.set_text(aLab, nameOf(dir, kind))
if ended
array.push(pastLines, aPole)
array.push(pastLines, aU)
array.push(pastLines, aL)
if not na(aF)
array.push(pastFills, aF)
array.push(pastLabels, aLab)
act := false
lastEnd := bar_index
aPole := na
aU := na
aL := na
aF := na
aLab := na
// ─── DETECTION ───────────────────────────────────────────────────────────────
// Looked for on every closed bar while nothing is being followed. The pole's
// end is the extreme of the last flagMax bars, its start the opposite extreme
// up to poleMax bars before that. A new pole has to end after the last
// pattern did, so a finished pattern is never found a second time.
if barstate.isconfirmed and not act and bar_index > flagMax + poleMax + 2
for pass = 0 to 1
d = pass == 0 ? 1 : -1
wanted = sides == "Both" or (d == 1 and sides == "Bull only") or (d == -1 and sides == "Bear only")
if wanted and not act
// The end of the pole.
tk = flagMax + 1
for k = flagMax + 1 to 1
if d == 1 ? high[k] > high[tk] : low[k] < low[tk]
tk := k
t = bar_index - tk
ok = tk >= flagMin and t > lastEnd
// The start of the pole.
bk = tk
if ok
for k = tk + poleMax to tk
if d == 1 ? low[k] < low[bk] : high[k] > high[bk]
bk := k
b = bar_index - bk
topPx = d == 1 ? high[tk] : low[tk]
botPx = d == 1 ? low[bk] : high[bk]
pl = math.abs(topPx - botPx)
ok := ok and t - b >= 2 and pl >= poleAtr * atr[tk]
// The pause may give back only so much of the pole.
if ok
deepest = 0.0
for k = 0 to tk
deepest := math.max(deepest, d == 1 ? topPx - low[k] : high[k] - topPx)
ok := deepest <= pl * retrPct / 100.0
if ok
xs = array.new<int>()
hs = array.new<float>()
ls = array.new<float>()
for k = 1 to tk
array.push(xs, bar_index - k)
array.push(hs, high[k])
array.push(ls, low[k])
[a1, b1] = fitEdge(xs, hs, true)
[a2, b2] = fitEdge(xs, ls, false)
len = float(tk)
tol = pl * 0.15
// A flag drifts against the pole or sideways, never with it.
okDir = d == 1 ? a1 * len <= tol and a2 * len <= tol : a1 * len >= -tol and a2 * len >= -tol
w0 = (a1 - a2) * t + (b1 - b2)
wN = (a1 - a2) * bar_index + (b1 - b2)
upNow = a1 * bar_index + b1
loNow = a2 * bar_index + b2
stillIn = close <= upNow and close >= loNow
ok := okDir and w0 <= pl * 0.6 and wN > 0 and stillIn
if ok
act := true
dir := d
tBar := t
bBar := b
tPx := topPx
bPx := botPx
pole := pl
su := a1
iu := b1
sl := a2
il := b2
kind := wN < w0 * 0.6 ? "Pennant" : "Flag"
aPole := line.new(bBar, bPx, tBar, tPx, color = liveCol, width = lineW + 1)
aU := line.new(tBar, su * tBar + iu, bar_index, upNow, color = liveCol, width = lineW)
aL := line.new(tBar, sl * tBar + il, bar_index, loNow, color = liveCol, width = lineW)
aF := showFill ? linefill.new(aU, aL, color.new(liveCol, 90)) : na
// At the far end of the pole, where there is open space.
yLab = d == 1 ? tPx + atr * 0.6 : tPx - atr * 0.6
aLab := label.new(tBar, yLab, nameOf(d, kind), style = d == 1 ? label.style_label_down : label.style_label_up, color = labelBg, textcolor = liveCol, size = labelSize)
// Old patterns are removed oldest first. One owns about four lines, one fill
// and three labels.
while array.size(pastLines) > keepPast * 4 + 4
line.delete(array.shift(pastLines))
while array.size(pastFills) > keepPast + 1
linefill.delete(array.shift(pastFills))
while array.size(pastLabels) > keepPast * 4 + 4
label.delete(array.shift(pastLabels))
// ─── THE TARGET ──────────────────────────────────────────────────────────────
if barstate.isconfirmed and not na(tgt) and not tgtHit and not tgtFail
if (tgtDir == 1 and close < failLvl) or (tgtDir == -1 and close > failLvl)
tgtFail := true
failMark = tgtDir == 1 ? low - atr * 1.2 : high + atr * 1.2
array.push(pastLabels, label.new(bar_index, failMark, "✗ Break failed", style = tgtDir == 1 ? label.style_label_up : label.style_label_down, color = labelBg, textcolor = failCol, size = labelSize))
if not na(tgtLab)
label.set_text(tgtLab, "Target " + str.tostring(tgt, format.mintick) + " cancelled")
label.set_textcolor(tgtLab, failCol)
if not na(tgtLine)
line.set_color(tgtLine, color.new(failCol, 40))
else if (tgtDir == 1 and high >= tgt) or (tgtDir == -1 and low <= tgt)
tgtHit := true
if not na(tgtLab)
label.set_text(tgtLab, "✓ Target " + str.tostring(tgt, format.mintick) + " reached")
label.set_x(tgtLab, bar_index)
if not na(tgtLine)
line.set_x2(tgtLine, bar_index)
line.set_style(tgtLine, line.style_solid)
// ─── THE PANEL ───────────────────────────────────────────────────────────────
distText(float lvl) =>
str.tostring((lvl - close) / close * 100.0, "+#.#;-#.#") + "%"
var table panel = na
if showPanel and barstate.islast
if na(panel)
panel := table.new(posOf(statPos), 3, 4, border_width = 1)
txtCol = color.new(color.white, 25)
table.clear(panel, 0, 0, 2, 3)
table.cell(panel, 0, 0, "FLAGS & PENNANTS", text_color = liveCol, text_size = statSize, text_halign = text.align_left)
if act
upNow = su * bar_index + iu
loNow = sl * bar_index + il
brk = dir == 1 ? upNow : loNow
far = dir == 1 ? loNow : upNow
tg = dir == 1 ? upNow + pole : loNow - pole
c = dir == 1 ? upCol : dnCol
table.cell(panel, 1, 0, nameOf(dir, kind) + ", forming", text_color = liveCol, text_size = statSize)
table.cell(panel, 0, 1, "Breaks on a close " + (dir == 1 ? "above" : "below"), text_color = txtCol, text_size = statSize, text_halign = text.align_left)
table.cell(panel, 1, 1, str.tostring(brk, format.mintick), text_color = c, text_size = statSize)
table.cell(panel, 2, 1, distText(brk), text_color = c, text_size = statSize)
table.cell(panel, 0, 2, "Other side of the flag", text_color = txtCol, text_size = statSize, text_halign = text.align_left)
table.cell(panel, 1, 2, str.tostring(far, format.mintick), text_color = txtCol, text_size = statSize)
table.cell(panel, 2, 2, distText(far), text_color = txtCol, text_size = statSize)
table.cell(panel, 0, 3, "Target if it breaks now", text_color = txtCol, text_size = statSize, text_halign = text.align_left)
table.cell(panel, 1, 3, str.tostring(tg, format.mintick), text_color = c, text_size = statSize)
table.cell(panel, 2, 3, distText(tg), text_color = c, text_size = statSize)
else
table.cell(panel, 1, 0, "None forming", text_color = txtCol, text_size = statSize)
if lastName != ""
table.cell(panel, 0, 1, "Last pattern", text_color = txtCol, text_size = statSize, text_halign = text.align_left)
table.cell(panel, 1, 1, lastName + ", " + str.tostring(bar_index - lastBar) + " bars ago", text_color = txtCol, text_size = statSize)
if not na(tgt)
tc = tgtFail ? failCol : tgtDir == 1 ? upCol : dnCol
table.cell(panel, 0, 2, "Last target", text_color = txtCol, text_size = statSize, text_halign = text.align_left)
table.cell(panel, 1, 2, str.tostring(tgt, format.mintick), text_color = tc, text_size = statSize)
table.cell(panel, 2, 2, tgtHit ? "reached" : tgtFail ? "break failed" : distText(tgt), text_color = tc, text_size = statSize)
// ─── ALERTS ──────────────────────────────────────────────────────────────────
alertcondition(brokeUp, "Bull flag broke up", "Close above a bull flag or pennant.")
alertcondition(brokeDn, "Bear flag broke down", "Close below a bear flag or pennant.")