本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This work is licensed under Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © IQTrend_Dev
//@version=6
indicator("Candlestick Patterns with Statistics [IQTrend]", shorttitle = "Candlestick Patterns [IQTrend]", overlay = true,
max_labels_count = 500, max_bars_back = 600)
// ---------- settings ----------
grpStats = "Statistics"
grpPats = "Patterns"
grpRules = "Pattern rules"
grpColor = "Colors"
horizon = input.int(6, "Look ahead (bars)", minval = 1, maxval = 500, group = grpStats, display = display.none,
tooltip = "How many bars after the pattern we check the close. 6 bars on 4h = one day.")
feePct = input.float(0.1, "Round-trip costs (%)", minval = 0, step = 0.01, group = grpStats, display = display.none,
tooltip = "Fees + spread + slippage for a full trade. Used in the 'After costs' column.")
minCount = input.int(30, "Min. signals to trust a row", minval = 1, group = grpStats, display = display.none,
tooltip = "Patterns with fewer signals are greyed out, moved to the bottom and never make the top list.")
sortRows = input.bool(true, "Sort rows by edge", group = grpStats, display = display.none)
topOnly = input.bool(true, "Show only the top patterns", group = grpStats, display = display.none,
tooltip = "Keeps only the best N patterns by edge, in the table and on the chart. Ranked on the loaded history.")
topN = input.int(5, "Number of top patterns", minval = 1, maxval = 16, group = grpStats, display = display.none)
tblPos = input.string("Top right", "Table position", options = ["Top right", "Bottom right", "Bottom left", "Top left"], group = grpStats, display = display.none)
tblSize = input.string("Small", "Table text size", options = ["Tiny", "Small", "Normal"], group = grpStats, display = display.none)
showHam = input.bool(true, "Hammer", group = grpPats, display = display.none)
showIH = input.bool(true, "Inverted hammer", group = grpPats, display = display.none)
showSS = input.bool(true, "Shooting star", group = grpPats, display = display.none)
showHM = input.bool(true, "Hanging man", group = grpPats, display = display.none)
showBuE = input.bool(true, "Bullish engulfing", group = grpPats, display = display.none)
showBeE = input.bool(true, "Bearish engulfing", group = grpPats, display = display.none)
showBuH = input.bool(true, "Bullish harami", group = grpPats, display = display.none)
showBeH = input.bool(true, "Bearish harami", group = grpPats, display = display.none)
showPL = input.bool(true, "Piercing line", group = grpPats, display = display.none)
showDC = input.bool(true, "Dark cloud cover", group = grpPats, display = display.none)
showMS = input.bool(true, "Morning star", group = grpPats, display = display.none)
showES = input.bool(true, "Evening star", group = grpPats, display = display.none)
show3W = input.bool(true, "Three white soldiers", group = grpPats, display = display.none)
show3B = input.bool(true, "Three black crows", group = grpPats, display = display.none)
showBuM = input.bool(true, "Bullish marubozu", group = grpPats, display = display.none)
showBeM = input.bool(true, "Bearish marubozu", group = grpPats, display = display.none)
showMarks = input.bool(true, "Mark patterns on the chart", group = grpPats, display = display.none)
useTrend = input.bool(true, "Use trend filter", group = grpRules, display = display.none,
tooltip = "Reversal patterns only count after a move: close below the SMA for bullish ones, above it for bearish ones.")
trendLen = input.int(10, "Trend SMA length", minval = 2, group = grpRules, display = display.none)
bodyLen = input.int(14, "Average body length", minval = 2, group = grpRules, display = display.none,
tooltip = "A body is 'long' or 'small' compared to the average body over this many bars.")
colBull = input.color(#22d3ee, "Bullish", group = grpColor, display = display.none)
colBear = input.color(#9b5cf6, "Bearish", group = grpColor, display = display.none)
colGood = input.color(#2fd59a, "Edge above random", group = grpColor, display = display.none)
colBad = input.color(#ff6b81, "Edge below random", group = grpColor, display = display.none)
colText = input.color(#f5f2ff, "Text", group = grpColor, display = display.none)
colMuted = input.color(#8f88ab, "Muted text", group = grpColor, display = display.none)
colBg = input.color(#07060d, "Table background", group = grpColor, display = display.none)
colHead = input.color(#7c3aed, "Table header", group = grpColor, display = display.none)
// ---------- candle anatomy ----------
body = math.abs(close - open)
rng = high - low
upWick = high - math.max(open, close)
dnWick = math.min(open, close) - low
avgBody = ta.ema(body, bodyLen)
green = close > open
red = close < open
bigBody = body > avgBody
smallBdy = body < avgBody
trendMa = ta.sma(close, trendLen)
fallBefore = not useTrend or close[1] < trendMa[1]
riseBefore = not useTrend or close[1] > trendMa[1]
// ---------- patterns ----------
// hammer and its relatives share one shape, the trend decides the name
hammerLike = rng > 0 and smallBdy and dnWick >= 2 * body and upWick <= 0.3 * rng
starLike = rng > 0 and smallBdy and upWick >= 2 * body and dnWick <= 0.3 * rng
hammer = hammerLike and fallBefore
hangMan = hammerLike and riseBefore
invHammer = starLike and fallBefore
shootStar = starLike and riseBefore
bullEngulf = fallBefore and green and red[1] and close >= open[1] and open <= close[1] and body > body[1]
bearEngulf = riseBefore and red and green[1] and close <= open[1] and open >= close[1] and body > body[1]
bullHarami = fallBefore and red[1] and bigBody[1] and green and math.max(open, close) < open[1] and math.min(open, close) > close[1]
bearHarami = riseBefore and green[1] and bigBody[1] and red and math.max(open, close) < close[1] and math.min(open, close) > open[1]
prevMid = (open[1] + close[1]) / 2
piercing = fallBefore and red[1] and bigBody[1] and green and open < close[1] and close > prevMid and close < open[1]
darkCloud = riseBefore and green[1] and bigBody[1] and red and open > close[1] and close < prevMid and close > open[1]
firstMid = (open[2] + close[2]) / 2
mornStar = (not useTrend or close[2] < trendMa[2]) and red[2] and bigBody[2] and smallBdy[1] and math.max(open[1], close[1]) < close[2] and green and close > firstMid
eveStar = (not useTrend or close[2] > trendMa[2]) and green[2] and bigBody[2] and smallBdy[1] and math.min(open[1], close[1]) > close[2] and red and close < firstMid
soldiers = green and green[1] and green[2] and bigBody and bigBody[1] and bigBody[2] and close > close[1] and close[1] > close[2] and open > open[1] and open < close[1] and open[1] > open[2] and open[1] < close[2] and upWick < 0.25 * body
crows = red and red[1] and red[2] and bigBody and bigBody[1] and bigBody[2] and close < close[1] and close[1] < close[2] and open < open[1] and open > close[1] and open[1] < open[2] and open[1] > close[2] and dnWick < 0.25 * body
bullMaru = green and bigBody and upWick <= 0.05 * rng and dnWick <= 0.05 * rng
bearMaru = red and bigBody and upWick <= 0.05 * rng and dnWick <= 0.05 * rng
// ---------- statistics ----------
N = 16
var names = array.from("Hammer", "Inverted hammer", "Bullish engulfing", "Bullish harami",
"Piercing line", "Morning star", "Three white soldiers", "Bullish marubozu",
"Shooting star", "Hanging man", "Bearish engulfing", "Bearish harami",
"Dark cloud cover", "Evening star", "Three black crows", "Bearish marubozu")
var tags = array.from("H", "IH", "BE", "HR", "PL", "MS", "3W", "M", "SS", "HM", "BE", "HR", "DC", "ES", "3B", "M")
// 1 = bullish, -1 = bearish
var dirs = array.from(1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1)
var enabled = array.from(showHam, showIH, showBuE, showBuH, showPL, showMS, show3W, showBuM,
showSS, showHM, showBeE, showBeH, showDC, showES, show3B, showBeM)
var hits = array.new<int>(N, 0)
var hitsFee = array.new<int>(N, 0)
var counts = array.new<int>(N, 0)
// "random candle" baseline = every closed bar
var int allBars = 0
var int allUp = 0
var int allDown = 0
// all 16 patterns of a bar packed into one number (bit i = pattern i),
// so looking back `horizon` bars is a single history lookup
bit(cond, i) => cond ? int(math.pow(2, i)) : 0
mask = bit(hammer, 0) + bit(invHammer, 1) + bit(bullEngulf, 2) + bit(bullHarami, 3) +
bit(piercing, 4) + bit(mornStar, 5) + bit(soldiers, 6) + bit(bullMaru, 7) +
bit(shootStar, 8) + bit(hangMan, 9) + bit(bearEngulf, 10) + bit(bearHarami, 11) +
bit(darkCloud, 12) + bit(eveStar, 13) + bit(crows, 14) + bit(bearMaru, 15)
has(m, i) => math.floor(m / math.pow(2, i)) % 2 == 1
// a pattern is scored once its look-ahead window has fully closed:
// we take the pattern `horizon` bars back and compare with this close
maskThen = mask[horizon]
closeThen = close[horizon]
if barstate.isconfirmed and closeThen > 0
move = (close - closeThen) / closeThen * 100
allBars += 1
allUp += move > 0 ? 1 : 0
allDown += move < 0 ? 1 : 0
if maskThen > 0
for i = 0 to N - 1
if has(maskThen, i)
m = dirs.get(i) * move
counts.set(i, counts.get(i) + 1)
hits.set(i, hits.get(i) + (m > 0 ? 1 : 0))
hitsFee.set(i, hitsFee.get(i) + (m > feePct ? 1 : 0))
// ---------- marks on the chart ----------
// plotshape can't be switched off for old bars later, so in "top only" mode
// we remember the bars with patterns and draw labels on the last bar instead.
// time + price are stored, so drawing old labels needs no history lookups
// (bar_index labels far in the past break in Replay mode)
markGap = ta.atr(14) * 0.4
var occTime = array.new<int>()
var occMask = array.new<int>()
var occLow = array.new<float>()
var occHigh = array.new<float>()
if topOnly and showMarks and barstate.isconfirmed and mask > 0
occTime.push(time)
occMask.push(mask)
occLow.push(low - nz(markGap))
occHigh.push(high + nz(markGap))
if occTime.size() > 5000
occTime.shift()
occMask.shift()
occLow.shift()
occHigh.shift()
marks = barstate.isconfirmed and showMarks and not topOnly
plotshape(marks and showHam and hammer, "Hammer", shape.triangleup, location.belowbar, colBull, text = "H", textcolor = colBull, size = size.tiny, display = display.pane)
plotshape(marks and showIH and invHammer, "Inverted hammer", shape.triangleup, location.belowbar, colBull, text = "IH", textcolor = colBull, size = size.tiny, display = display.pane)
plotshape(marks and showBuE and bullEngulf, "Bullish engulfing", shape.triangleup, location.belowbar, colBull, text = "BE", textcolor = colBull, size = size.tiny, display = display.pane)
plotshape(marks and showBuH and bullHarami, "Bullish harami", shape.triangleup, location.belowbar, colBull, text = "HR", textcolor = colBull, size = size.tiny, display = display.pane)
plotshape(marks and showPL and piercing, "Piercing line", shape.triangleup, location.belowbar, colBull, text = "PL", textcolor = colBull, size = size.tiny, display = display.pane)
plotshape(marks and showMS and mornStar, "Morning star", shape.triangleup, location.belowbar, colBull, text = "MS", textcolor = colBull, size = size.tiny, display = display.pane)
plotshape(marks and show3W and soldiers, "Three white soldiers", shape.triangleup, location.belowbar, colBull, text = "3W", textcolor = colBull, size = size.tiny, display = display.pane)
plotshape(marks and showBuM and bullMaru, "Bullish marubozu", shape.triangleup, location.belowbar, colBull, text = "M", textcolor = colBull, size = size.tiny, display = display.pane)
plotshape(marks and showSS and shootStar, "Shooting star", shape.triangledown, location.abovebar, colBear, text = "SS", textcolor = colBear, size = size.tiny, display = display.pane)
plotshape(marks and showHM and hangMan, "Hanging man", shape.triangledown, location.abovebar, colBear, text = "HM", textcolor = colBear, size = size.tiny, display = display.pane)
plotshape(marks and showBeE and bearEngulf, "Bearish engulfing", shape.triangledown, location.abovebar, colBear, text = "BE", textcolor = colBear, size = size.tiny, display = display.pane)
plotshape(marks and showBeH and bearHarami, "Bearish harami", shape.triangledown, location.abovebar, colBear, text = "HR", textcolor = colBear, size = size.tiny, display = display.pane)
plotshape(marks and showDC and darkCloud, "Dark cloud cover", shape.triangledown, location.abovebar, colBear, text = "DC", textcolor = colBear, size = size.tiny, display = display.pane)
plotshape(marks and showES and eveStar, "Evening star", shape.triangledown, location.abovebar, colBear, text = "ES", textcolor = colBear, size = size.tiny, display = display.pane)
plotshape(marks and show3B and crows, "Three black crows", shape.triangledown, location.abovebar, colBear, text = "3B", textcolor = colBear, size = size.tiny, display = display.pane)
plotshape(marks and showBeM and bearMaru, "Bearish marubozu", shape.triangledown, location.abovebar, colBear, text = "M", textcolor = colBear, size = size.tiny, display = display.pane)
// ---------- helpers ----------
pct(a, b) => b > 0 ? 100.0 * a / b : na
edgeOf(i) =>
base = dirs.get(i) == 1 ? pct(allUp, allBars) : pct(allDown, allBars)
pct(hits.get(i), counts.get(i)) - base
bestPatterns() =>
ids = array.new<int>()
edges = array.new<float>()
for i = 0 to N - 1
e = edgeOf(i)
if enabled.get(i) and counts.get(i) >= minCount and not na(e)
ids.push(i)
edges.push(e)
best = array.new<int>()
if ids.size() > 0
idx = edges.sort_indices(order.descending)
for k = 0 to math.min(topN, ids.size()) - 1
best.push(ids.get(idx.get(k)))
best
// ---------- table ----------
tablePos = switch tblPos
"Bottom right" => position.bottom_right
"Bottom left" => position.bottom_left
"Top left" => position.top_left
=> position.top_right
txtSize = switch tblSize
"Tiny" => size.tiny
"Normal" => size.normal
=> size.small
var tbl = table.new(tablePos, 6, N + 4, bgcolor = color.new(colBg, 8),
border_color = color.new(colHead, 70), border_width = 1, frame_color = color.new(colHead, 40), frame_width = 1)
cell(col, row, txt, txtColor) =>
tbl.cell(col, row, txt, text_color = txtColor, text_size = txtSize, text_halign = col == 0 ? text.align_left : text.align_right)
if barstate.islast
tbl.merge_cells(0, 0, 5, 0)
tbl.cell(0, 0, "Candlestick patterns: what happened " + str.tostring(horizon) + " bars later", text_color = colText, bgcolor = color.new(colHead, 25), text_size = txtSize)
cell(0, 1, "Pattern", colMuted)
cell(1, 1, "Signals", colMuted)
cell(2, 1, "Right way", colMuted)
cell(3, 1, "Random", colMuted)
cell(4, 1, "Edge", colMuted)
cell(5, 1, "After costs", colMuted)
best = bestPatterns()
rows = array.new<int>()
sortKey = array.new<float>()
for i = 0 to N - 1
if enabled.get(i) and (not topOnly or best.includes(i))
e = edgeOf(i)
rows.push(i)
// thin rows sink to the bottom
sortKey.push(na(e) ? -1e9 : counts.get(i) < minCount ? -1e8 + counts.get(i) : e)
sorted = array.new<int>()
if rows.size() > 0
if sortRows or topOnly
sorted := sortKey.sort_indices(order.descending)
else
for k = 0 to rows.size() - 1
sorted.push(k)
r = 2
for k = 0 to rows.size() - 1
if rows.size() == 0
break
i = rows.get(sorted.get(k))
n = counts.get(i)
bull = dirs.get(i) == 1
wr = pct(hits.get(i), n)
wrFee = pct(hitsFee.get(i), n)
base = bull ? pct(allUp, allBars) : pct(allDown, allBars)
edge = wr - base
thin = n < minCount
nameColor = thin ? colMuted : bull ? colBull : colBear
edgeColor = thin or na(edge) ? colMuted : edge >= 1 ? colGood : edge <= -1 ? colBad : colText
cell(0, r, names.get(i), nameColor)
cell(1, r, str.tostring(n), thin ? colMuted : colText)
cell(2, r, na(wr) ? "-" : str.tostring(wr, "0.0") + "%", thin ? colMuted : colText)
cell(3, r, na(base) ? "-" : str.tostring(base, "0.0") + "%", colMuted)
cell(4, r, na(edge) ? "-" : (edge > 0 ? "+" : "") + str.tostring(edge, "0.0"), edgeColor)
cell(5, r, na(wrFee) ? "-" : str.tostring(wrFee, "0.0") + "%", thin ? colMuted : colText)
r += 1
if topOnly and rows.size() == 0
tbl.merge_cells(0, r, 5, r)
tbl.cell(0, r, "No pattern has " + str.tostring(minCount) + "+ signals yet. Scroll back for more history or lower 'Min. signals'.", text_color = colMuted, text_size = txtSize, text_halign = text.align_left)
r += 1
footer = "Random: all " + str.tostring(allBars) + " closed bars. Edge in % points. Grey: under " + str.tostring(minCount) + " signals."
if topOnly
footer := "Top " + str.tostring(topN) + " by edge. " + footer
tbl.merge_cells(0, r, 5, r)
tbl.cell(0, r, footer, text_color = colMuted, text_size = txtSize, text_halign = text.align_left)
// top-only marks: drawn when the script loads and again on every new bar
var labels = array.new<label>()
var int drawnAt = -1
if barstate.islast and topOnly and showMarks and drawnAt != bar_index
drawnAt := bar_index
for lb in labels
lb.delete()
labels.clear()
best = bestPatterns()
if best.size() > 0 and occTime.size() > 0
for k = occTime.size() - 1 to 0
if labels.size() >= 440
break
t = occTime.get(k)
m = occMask.get(k)
upTxt = ""
dnTxt = ""
for i in best
if has(m, i)
if dirs.get(i) == 1
upTxt += (upTxt == "" ? "" : " ") + tags.get(i)
else
dnTxt += (dnTxt == "" ? "" : " ") + tags.get(i)
if upTxt != ""
labels.push(label.new(t, occLow.get(k), upTxt, xloc = xloc.bar_time, style = label.style_triangleup, color = colBull, textcolor = colBull, size = size.tiny))
if dnTxt != ""
labels.push(label.new(t, occHigh.get(k), dnTxt, xloc = xloc.bar_time, style = label.style_triangledown, color = colBear, textcolor = colBear, size = size.tiny))
// ---------- alerts ----------
anyBull = hammer or invHammer or bullEngulf or bullHarami or piercing or mornStar or soldiers or bullMaru
anyBear = shootStar or hangMan or bearEngulf or bearHarami or darkCloud or eveStar or crows or bearMaru
alertcondition(barstate.isconfirmed and anyBull, "Any bullish pattern", "{{ticker}} {{interval}}: bullish candle pattern, close {{close}}")
alertcondition(barstate.isconfirmed and anyBear, "Any bearish pattern", "{{ticker}} {{interval}}: bearish candle pattern, close {{close}}")