本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("M-Formation / W-Formation (Double Top / Bottom)", "M/W", overlay = true, max_lines_count = 500, max_labels_count = 500, max_bars_back = 1100)
// ================================================================================
// Enums & UDTs
// ================================================================================
enum PatternMode
Classic = "Classic"
FiveSwing = "FiveSwing (future)"
enum MState
Pending
Broken
Expired
Invalidated
TargetHit
Stopped
Timeout
enum PeakSrc
Wick = "Wick"
WickOrBody = "Wick or body"
type Pivot
bool isHigh = false
float price
int idx
float body
// For W (double bottom) the fields keep their M names but hold the mirrored points:
// h1 = L1 (first pivot low), lo = mid peak H (highest inner pivot high), h2 = L2, peak = trough = min(L1, L2).
type MPattern
bool isW = false
bool cand = false
Pivot p0
Pivot h1
Pivot lo
Pivot h2
float neck
float peak
float target
float tolAbs
float breakLvl
int innerSwings
bool bodyPass = false
bool rough = false
int breakIdx
int endIdx
int lastProcIdx
MState state
float mfe = 0.0
float mae = 0.0
bool mfeDone = false
array<line> lnOutline
line lnNeck
line lnTarget
line lnPred
line lnExt
array<label> labels
type Stats
int cntDetected = 0
int cntBroken = 0
int cntExpired = 0
int cntInvalid = 0
int cntTarget = 0
int cntStopped = 0
int cntTimeout = 0
int cntRough = 0
int sumBars = 0
int mfeN = 0
int mfe50 = 0
int mfe100 = 0
int mfe160 = 0
int mfe200 = 0
float sumMfe = 0.0
float sumMae = 0.0
int emN = 0
int emConf = 0
int emDone = 0
int em50 = 0
int em100 = 0
int em160 = 0
int em200 = 0
int emFail = 0
float emSumMfe = 0.0
float emSumMae = 0.0
// EM / EW history statistics: running extreme since the last confirmed pivot (one per side)
type EmScan
int baseIdx = -1
int exIdx = -1
float exPx
int emitIdx = -1
// One open early signal being measured
type EmTrk
bool isW = false
int h2Idx
float h2Px
float leg
float entryPx
float mfe = 0.0
float mae = 0.0
// Per-bar event flags (a new instance is created every bar)
type Evt
bool formed = false
bool brk = false
bool hit = false
bool inval = false
bool expd = false
bool formedW = false
bool brkW = false
bool hitW = false
bool invalW = false
bool expdW = false
string msg = ""
// ================================================================================
// Inputs
// ================================================================================
string grpDet = "Detection"
string grpRough = "Detection — Roughness"
string grpLife = "Lifecycle"
string grpVis = "Visuals"
string grpTbl = "Table & Alerts"
bool enableM = input.bool(true, "Detect M (double top)", group = grpDet)
bool enableW = input.bool(true, "Detect W (double bottom)", group = grpDet)
patternMode = input.enum(PatternMode.Classic, "Pattern mode", group = grpDet, tooltip = "FiveSwing is not implemented yet. The indicator shows an info label and runs Classic.")
int pivotLen = input.int(5, "Pivot length (bars each side)", minval = 2, maxval = 50, group = grpDet, tooltip = "Swing confirmation. A pivot is confirmed only after this many bars on its right, so signals lag by this length.")
float tolPct = input.float(0.0, "Equal-highs tolerance % (0 = off)", minval = 0.0, maxval = 10, step = 0.1, group = grpDet, tooltip = "Optional percent floor. The tolerance used is the larger of this and the ATR tolerance.")
float tolAtr = input.float(2.5, "Equal-highs tolerance (x ATR)", minval = 0, maxval = 5, step = 0.05, group = grpDet, tooltip = "Max |H2 - H1| in ATR units (ATR at H2). Adapts to every symbol and timeframe.")
float minDepthPct = input.float(0.0, "Min valley depth % (0 = off)", minval = 0, maxval = 50, step = 0.1, group = grpDet, tooltip = "Valley must sit at least this percent below the lower peak. 0 disables.")
float minDepthAtr = input.float(3.0, "Min valley depth (x ATR)", minval = 0, maxval = 20, step = 0.1, group = grpDet, tooltip = "Valley must sit at least this many ATRs below the lower peak. The larger of the % and ATR depth is used.")
int atrLen = input.int(14, "ATR length", minval = 1, maxval = 200, group = grpDet)
int minSpan = input.int(5, "Min bars H1 to H2", minval = 2, group = grpDet)
int maxSpan = input.int(150, "Max bars H1 to H2", minval = 10, maxval = 1000, group = grpDet)
bool requirePriorRise = input.bool(false, "Require prior rise", group = grpDet, tooltip = "Requires a pivot low before H1 that rose into H1 by at least the multiplier times the pattern height.")
float priorRiseMult = input.float(0.5, "Prior rise multiplier", minval = 0, step = 0.1, group = grpDet)
bool roughEnabled = input.bool(true, "Enable rough detection", group = grpRough, tooltip = "Master switch. Off = strict classic rules; all other roughness inputs are ignored.")
PeakSrc peakSource = input.enum(PeakSrc.WickOrBody, "Peak comparison", group = grpRough, tooltip = "WickOrBody also passes equal-highs when the candle body tops of the two peaks are within tolerance (handles one spiky wick).")
int maxInnerSwings = input.int(2, "Max inner swings in valley", minval = 0, maxval = 5, group = grpRough, tooltip = "Minor high/low pairs allowed between H1 and H2. 0 = strict consecutive H1-L-H2.")
float innerHighMaxPct = input.float(50.0, "Max inner retrace %", minval = 0, maxval = 100, step = 5, group = grpRough, tooltip = "An inner high may retrace at most this % of the way from the valley back to the lower peak. Above that it is a third peak, not an M.")
float maxLegRatio = input.float(3.0, "Max leg ratio (time symmetry)", minval = 0, maxval = 10, step = 0.1, group = grpRough, tooltip = "bars(valley to H2) / bars(H1 to valley) must be within [1/r, r]. 0 disables.")
float breakBufPct = input.float(0.0, "Break buffer %", minval = 0, maxval = 5, step = 0.05, group = grpRough, tooltip = "Break needs close < neck x (1 - buffer). Filters 1-tick neckline pokes. 0 = plain close below neck.")
float breakBufAtr = input.float(0.0, "Break buffer (x ATR)", minval = 0, maxval = 3, step = 0.05, group = grpRough, tooltip = "Same as above in ATR units. The larger of the two buffers is used.")
int expiryBars = input.int(50, "Expiry bars (after H2)", minval = 5, group = grpLife, tooltip = "A pending M with no neckline break within this many bars is marked Expired.")
bool invalidateAbovePeak = input.bool(true, "Invalidate on close above peak", group = grpLife, tooltip = "A close above peak + tolerance before the break invalidates the pattern.")
int targetBars = input.int(60, "Target tracking bars (after break)", minval = 5, group = grpLife, tooltip = "Bars after the break to track the target. Also the length of the target line.")
float targetPct = input.float(100.0, "Target % of pattern height", minval = 10, maxval = 300, step = 5, group = grpLife, tooltip = "Target = neckline -/+ this % of (peak - neckline). 100 = classic measured move.")
int maxPatterns = input.int(20, "Max patterns kept", minval = 1, maxval = 80, group = grpLife, tooltip = "Oldest finished patterns are removed from the chart. Table counters keep full history.")
// Effective expiry, clamped so expiry can never fire before detection (detection happens at h2.idx + pivotLen)
int expEff = math.max(expiryBars, pivotLen + 1)
// Effective roughness values: forced to strict values when the master switch is off
PeakSrc effPeak = roughEnabled ? peakSource : PeakSrc.Wick
int effInner = roughEnabled ? maxInnerSwings : 0
float effLeg = roughEnabled ? maxLegRatio : 0.0
float effBufPct = roughEnabled ? breakBufPct : 0.0
float effBufAtr = roughEnabled ? breakBufAtr : 0.0
// Pivot history needed for the inner-swing search (plan §2: 2 x maxInnerSwings + 8; 8 when strict)
int pivCap = 2 * effInner + 8
bool showOutline = input.bool(true, "Show outline", group = grpVis)
bool showNeckline = input.bool(true, "Show neckline", group = grpVis)
bool showTarget = input.bool(true, "Show target line", group = grpVis)
bool showLabels = input.bool(true, "Show labels", group = grpVis)
bool showExpired = input.bool(false, "Keep drawings of expired/invalidated", group = grpVis, tooltip = "If off, drawings of Expired and Invalidated patterns are deleted.")
color colOutline = input.color(color.orange, "Outline color", group = grpVis)
color colOutlineW = input.color(color.teal, "W outline color", group = grpVis)
color colNeck = input.color(color.gray, "Neckline color", group = grpVis)
color colBreak = input.color(color.red, "Break color", group = grpVis)
color colTarget = input.color(color.fuchsia, "Target color", group = grpVis)
int lineWidth = input.int(2, "Line width", minval = 1, maxval = 4, group = grpVis)
bool showPred = input.bool(true, "Show early prediction (H2/L2 to neckline)", group = grpVis, tooltip = "Dashed line from the second top (M) / second bottom (W) to the neckline, drawn before the move. Also shows an early provisional M? / W? before the pivot is confirmed. Deleted if price makes a new extreme instead.")
int predTurnBars = input.int(1, "Prediction: bars after top/bottom", minval = 1, maxval = 10, group = grpVis, tooltip = "Closed bars without a new high (M) / new low (W) needed before the early M? / W? appears. 1 = earliest. Provisional: it is removed if price makes a new extreme.")
bool showTable = input.bool(false, "Show history table", group = grpTbl)
string tablePosIn = input.string("Top right", "Table position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = grpTbl)
bool useDynamicAlerts = input.bool(true, "Use alert() dynamic alerts", group = grpTbl, tooltip = "Choose 'Any alert() function call' in the alert dialog to receive these messages with full numbers.")
bool emHistStats = input.bool(true, "EM history stats", group = grpTbl, tooltip = "Counts every early EM / EW signal over the whole chart history as if it had been shown live (nothing is drawn) and adds the results to the history table.")
tblPos = tablePosIn == "Top right" ? position.top_right : tablePosIn == "Bottom right" ? position.bottom_right : tablePosIn == "Top left" ? position.top_left : position.bottom_left
// ================================================================================
// Persistent state
// ================================================================================
var array<Pivot> pivots = array.new<Pivot>()
var array<MPattern> patterns = array.new<MPattern>()
// Early candidates (not yet pivot-confirmed): slot 0 = M, slot 1 = W. Rebuilt every confirmed bar.
var array<MPattern> cands = array.new<MPattern>(2)
// EM / EW history statistics state (no drawings)
var array<MPattern> emBuf = array.new<MPattern>()
var EmScan emScM = EmScan.new()
var EmScan emScW = EmScan.new()
var array<EmTrk> emOpen = array.new<EmTrk>()
var Stats st = Stats.new()
var Stats stW = Stats.new()
var table tbl = na
var label fsLabel = na
// ================================================================================
// Helpers
// ================================================================================
stateName(MState s) =>
s == MState.Pending ? "Pending" : s == MState.Broken ? "Broken" : s == MState.Expired ? "Expired" : s == MState.Invalidated ? "Invalidated" : s == MState.TargetHit ? "Target hit" : s == MState.Stopped ? "Stopped" : "Timeout"
pctStr(int part, int whole) =>
whole > 0 ? "(" + str.tostring(float(part) / whole * 100, "#") + "%)" : "(—)"
patternDesc(MPattern p) =>
(p.isW ? "W L1 " : "M H1 ") + str.tostring(p.h1.price, format.mintick) + (p.isW ? " | L2 " : " | H2 ") + str.tostring(p.h2.price, format.mintick) + " | diff " + str.tostring(math.abs(p.h2.price - p.h1.price) / math.max(p.h1.price, p.h2.price) * 100, "#.##") + "% | neck " + str.tostring(p.neck, format.mintick) + " | target " + str.tostring(p.target, format.mintick) + " | span " + str.tostring(p.h2.idx - p.h1.idx) + " bars | tol " + str.tostring(p.tolAbs, format.mintick) + " | inner " + str.tostring(p.innerSwings) + (p.bodyPass ? " | R1 body" : " | R1 wick")
// Alternation-enforcing pivot insert. Returns true when a pivot (of this type) was appended or replaced the last one.
pushPivot(bool isHigh, float px, int idx, float bd) =>
bool changed = false
int n = pivots.size()
if n == 0
pivots.push(Pivot.new(isHigh, px, idx, bd))
changed := true
else
Pivot last = pivots.get(n - 1)
if last.isHigh == isHigh
bool better = isHigh ? px > last.price : px < last.price
if better
pivots.set(n - 1, Pivot.new(isHigh, px, idx, bd))
changed := true
else
pivots.push(Pivot.new(isHigh, px, idx, bd))
changed := true
if pivots.size() > pivCap
pivots.shift()
changed
// Geometry rules R2, R3, R4, R7 for one candidate (isW = mirrored for double bottom). R1 (equal extremes) is tested by the caller, R5/R6 in the detection function.
validG(bool isW, Pivot h1, Pivot lo, Pivot h2, float atrV) =>
float loPk = isW ? math.max(h1.price, h2.price) : math.min(h1.price, h2.price)
float depthAbs = isW ? lo.price - loPk : loPk - lo.price
float needDepth = math.max(loPk * minDepthPct / 100, minDepthAtr * atrV)
int span = h2.idx - h1.idx
bool lowestOk = true
if span <= 1000
if isW
float maxHigh = lo.price
for k = bar_index - h2.idx to bar_index - h1.idx
maxHigh := math.max(maxHigh, high[k])
lowestOk := maxHigh <= lo.price
else
float minLow = lo.price
for k = bar_index - h2.idx to bar_index - h1.idx
minLow := math.min(minLow, low[k])
lowestOk := minLow >= lo.price
// Strict order: a bar that is both pivot high and pivot low yields lo.idx == h2.idx (degenerate pattern)
bool orderOk = h1.idx < lo.idx and lo.idx < h2.idx
// R7 leg symmetry (rough only; effLeg = 0 disables)
float legR = float(h2.idx - lo.idx) / math.max(1, lo.idx - h1.idx)
bool legOk = effLeg <= 0 or (legR >= 1.0 / effLeg and legR <= effLeg)
span >= minSpan and span <= maxSpan and depthAbs >= needDepth and lowestOk and orderOk and legOk
// Index of the oldest finished (not Pending / Broken) pattern, or -1
oldestFinished(array<MPattern> arr) =>
int found = -1
int n = arr.size()
if n > 0
for i = 0 to n - 1
MPattern q = arr.get(i)
if found < 0 and q.state != MState.Pending and q.state != MState.Broken
found := i
found
tRow(int r, string a, string b, string c) =>
table.cell(tbl, 0, r, a, text_color = color.silver, text_size = size.small, bgcolor = color.new(color.black, 20))
table.cell(tbl, 1, r, b, text_color = color.white, text_size = size.small, bgcolor = color.new(color.black, 20))
table.cell(tbl, 2, r, c, text_color = color.white, text_size = size.small, bgcolor = color.new(color.black, 20))
true
// ================================================================================
// Methods
// ================================================================================
// Bars from the neck point to the target, same slope as the H2 -> neck leg
extDx(MPattern p, int xNeck) =>
float leg = math.max(math.abs(p.h2.price - p.neck), syminfo.mintick)
math.max(1, int(math.round((xNeck - p.h2.idx) * math.abs(p.neck - p.target) / leg)))
method drawFormation(MPattern this) =>
color oc = this.isW ? colOutlineW : colOutline
if showOutline
if not na(this.p0)
this.lnOutline.push(line.new(this.p0.idx, this.p0.price, this.h1.idx, this.h1.price, xloc = xloc.bar_index, color = oc, width = lineWidth))
this.lnOutline.push(line.new(this.h1.idx, this.h1.price, this.lo.idx, this.lo.price, xloc = xloc.bar_index, color = oc, width = lineWidth))
this.lnOutline.push(line.new(this.lo.idx, this.lo.price, this.h2.idx, this.h2.price, xloc = xloc.bar_index, color = oc, width = lineWidth))
if showNeckline
this.lnNeck := line.new(this.lo.idx, this.neck, bar_index, this.neck, xloc = xloc.bar_index, extend = extend.none, color = colNeck, style = line.style_dashed, width = lineWidth)
if showPred
int pEnd = math.min(math.max(this.h2.idx + math.max(this.h2.idx - this.lo.idx, 1), bar_index + 1), bar_index + 500)
this.lnPred := line.new(this.h2.idx, this.h2.price, pEnd, this.neck, xloc = xloc.bar_index, color = oc, style = line.style_dashed, width = lineWidth)
if not na(this.target)
int eEnd = math.min(pEnd + extDx(this, pEnd), bar_index + 500)
this.lnExt := line.new(pEnd, this.neck, eEnd, this.target, xloc = xloc.bar_index, color = oc, style = line.style_dotted, width = lineWidth)
if showLabels
if this.isW
bool h1Lower = this.h1.price <= this.h2.price
string wTxt = this.rough ? "W~" : "W"
this.labels.push(label.new(this.h1.idx, this.h1.price, "L1", xloc = xloc.bar_index, style = label.style_label_up, color = oc, textcolor = color.white, size = size.tiny))
this.labels.push(label.new(this.h2.idx, this.h2.price, this.cand ? "EW" : "L2", xloc = xloc.bar_index, style = label.style_label_up, color = oc, textcolor = color.white, size = this.cand ? size.normal : size.tiny))
this.labels.push(label.new(this.lo.idx, this.lo.price, "H", xloc = xloc.bar_index, style = label.style_label_down, color = colNeck, textcolor = color.white, size = size.tiny))
if not this.cand
this.labels.push(label.new(h1Lower ? this.h1.idx : this.h2.idx, this.peak, wTxt, xloc = xloc.bar_index, style = label.style_label_up, color = oc, textcolor = color.white, size = size.normal, tooltip = patternDesc(this)))
else
bool h1Higher = this.h1.price >= this.h2.price
string mTxt = this.rough ? "M~" : "M"
this.labels.push(label.new(this.h1.idx, this.h1.price, "H1", xloc = xloc.bar_index, style = label.style_label_down, color = oc, textcolor = color.white, size = size.tiny))
this.labels.push(label.new(this.h2.idx, this.h2.price, this.cand ? "EM" : "H2", xloc = xloc.bar_index, style = label.style_label_down, color = oc, textcolor = color.white, size = this.cand ? size.normal : size.tiny))
this.labels.push(label.new(this.lo.idx, this.lo.price, "L", xloc = xloc.bar_index, style = label.style_label_up, color = colNeck, textcolor = color.white, size = size.tiny))
if not this.cand
this.labels.push(label.new(h1Higher ? this.h1.idx : this.h2.idx, this.peak, mTxt, xloc = xloc.bar_index, style = label.style_label_down, color = oc, textcolor = color.white, size = size.normal, tooltip = patternDesc(this)))
true
method setEnd(MPattern this, int idx) =>
if not na(this.lnNeck)
line.set_x2(this.lnNeck, idx)
if not na(this.lnTarget)
line.set_x2(this.lnTarget, idx)
true
method delPred(MPattern this) =>
if not na(this.lnPred)
line.delete(this.lnPred)
this.lnPred := na
if not na(this.lnExt)
line.delete(this.lnExt)
this.lnExt := na
true
method deleteDrawings(MPattern this) =>
for ln in this.lnOutline
line.delete(ln)
this.lnOutline.clear()
if not na(this.lnNeck)
line.delete(this.lnNeck)
this.lnNeck := na
if not na(this.lnTarget)
line.delete(this.lnTarget)
this.lnTarget := na
if not na(this.lnPred)
line.delete(this.lnPred)
this.lnPred := na
if not na(this.lnExt)
line.delete(this.lnExt)
this.lnExt := na
for lb in this.labels
label.delete(lb)
this.labels.clear()
true
// ================================================================================
// Lifecycle: process ONE bar (k bars back from current) for a pattern.
// Used both for the live per-bar update (k = 0) and for catch-up (k = pivotLen-1 ... 0).
// ================================================================================
advance(MPattern p, int k, Stats s, Evt e) =>
int bi = bar_index - k
float c = close[k]
float lw = low[k]
float hw = high[k]
bool w = p.isW
color oc = w ? colOutlineW : colOutline
if p.state == MState.Pending
bool invalCond = w ? c < p.peak - p.tolAbs : c > p.peak + p.tolAbs
bool brkCond = w ? c > p.breakLvl : c < p.breakLvl
if invalidateAbovePeak and invalCond
p.state := MState.Invalidated
p.endIdx := bi
p.setEnd(bi)
p.delPred()
s.cntInvalid := s.cntInvalid + 1
if w
e.invalW := true
else
e.inval := true
e.msg := e.msg + (w ? "W invalidated (close below bottom) | " : "M invalidated (close above peak) | ") + patternDesc(p) + " || "
else if brkCond
p.state := MState.Broken
p.breakIdx := bi
s.cntBroken := s.cntBroken + 1
s.sumBars := s.sumBars + (bi - p.h2.idx)
if w
e.brkW := true
else
e.brk := true
string lateTxt = bi < bar_index ? " (late: broke " + str.tostring(bar_index - bi) + " bars ago)" : ""
e.msg := e.msg + (w ? "W neckline broken, close " : "M neckline broken, close ") + str.tostring(c, format.mintick) + lateTxt + " | " + patternDesc(p) + " || "
p.delPred()
if showOutline
p.lnOutline.push(line.new(p.h2.idx, p.h2.price, bi, p.neck, xloc = xloc.bar_index, color = oc, width = lineWidth))
if showPred and not na(p.target)
int eEnd = math.min(bi + extDx(p, bi), bar_index + 500)
p.lnExt := line.new(bi, p.neck, eEnd, p.target, xloc = xloc.bar_index, color = oc, style = line.style_dotted, width = lineWidth)
if not na(p.lnNeck)
line.set_x2(p.lnNeck, bi)
line.set_color(p.lnNeck, colBreak)
line.set_style(p.lnNeck, line.style_solid)
if showTarget
int tEnd = bi + targetBars > bar_index + 500 ? bar_index + 500 : bi + targetBars
p.lnTarget := line.new(bi, p.target, tEnd, p.target, xloc = xloc.bar_index, extend = extend.none, color = colTarget, style = line.style_dashed, width = lineWidth)
if showLabels
p.labels.push(label.new(bi, p.neck, "Break", xloc = xloc.bar_index, yloc = yloc.price, style = w ? label.style_label_down : label.style_label_up, color = colBreak, textcolor = color.white, size = size.tiny))
else if bi - p.h2.idx > expEff
p.state := MState.Expired
p.endIdx := bi
p.setEnd(bi)
p.delPred()
s.cntExpired := s.cntExpired + 1
if w
e.expdW := true
else
e.expd := true
e.msg := e.msg + (w ? "W expired without neckline break | " : "M expired without neckline break | ") + patternDesc(p) + " || "
else
if not na(p.lnNeck)
line.set_x2(p.lnNeck, bi)
// Prediction line: cancel on a new extreme beyond H2/L2, otherwise keep it projecting ahead of price
if not na(p.lnPred)
bool beyond = w ? lw < p.h2.price : hw > p.h2.price
if beyond
p.delPred()
else if line.get_x2(p.lnPred) <= bi
line.set_x2(p.lnPred, bi + 1)
if not na(p.lnExt)
int eDx = extDx(p, bi + 1)
line.set_x1(p.lnExt, bi + 1)
line.set_x2(p.lnExt, math.min(bi + 1 + eDx, bar_index + 500))
// Outcome tracking runs on the break bar too (gap through neck and target on the same bar)
if p.state == MState.Broken
bool hitCond = w ? hw >= p.target : lw <= p.target
bool stopCond = w ? c < p.peak : c > p.peak
if hitCond
p.state := MState.TargetHit
p.endIdx := bi
if not na(p.lnTarget)
line.set_x2(p.lnTarget, bi)
s.cntTarget := s.cntTarget + 1
if w
e.hitW := true
else
e.hit := true
e.msg := e.msg + (w ? "W target hit, close " : "M target hit, close ") + str.tostring(c, format.mintick) + " | " + patternDesc(p) + " || "
if showLabels
p.labels.push(label.new(bi, p.target, "Target ✓", xloc = xloc.bar_index, yloc = yloc.price, style = w ? label.style_label_down : label.style_label_up, color = colTarget, textcolor = color.white, size = size.tiny))
else if stopCond
p.state := MState.Stopped
p.endIdx := bi
if not na(p.lnTarget)
line.set_x2(p.lnTarget, bi)
s.cntStopped := s.cntStopped + 1
if showLabels
p.labels.push(label.new(bi, c, "Stop ✗", xloc = xloc.bar_index, yloc = yloc.price, style = w ? label.style_label_up : label.style_label_down, color = colBreak, textcolor = color.white, size = size.tiny))
else if bi - p.breakIdx >= targetBars
p.state := MState.Timeout
p.endIdx := bi
if not na(p.lnTarget)
line.set_x2(p.lnTarget, bi)
s.cntTimeout := s.cntTimeout + 1
if not showExpired and (p.state == MState.Expired or p.state == MState.Invalidated)
p.deleteDrawings()
true
// ================================================================================
// From-H2 measurement: max favorable excursion from the H2 / L2 price as % of the H2 -> neck leg (100% = neckline).
// Tracked from the bar after H2 until Stopped / Timeout / Invalidated / Expired, a close beyond peak +/- tol,
// or expEff + targetBars bars after H2. Counted once per pattern. No effect on states, drawings or alerts.
// ================================================================================
finMfe(MPattern p, Stats s) =>
if not p.mfeDone
p.mfeDone := true
float leg = math.max(math.abs(p.h2.price - p.neck), syminfo.mintick)
float pc = p.mfe / leg * 100
s.mfeN := s.mfeN + 1
s.sumMfe := s.sumMfe + pc
if pc >= 50
s.mfe50 := s.mfe50 + 1
if pc >= 100
s.mfe100 := s.mfe100 + 1
s.sumMae := s.sumMae + p.mae / leg * 100
if pc >= 160
s.mfe160 := s.mfe160 + 1
if pc >= 200
s.mfe200 := s.mfe200 + 1
true
trackMfe(MPattern p, int k, Stats s) =>
if not p.mfeDone
int bi = bar_index - k
bool w = p.isW
float c = close[k]
float fav = w ? high[k] - p.h2.price : p.h2.price - low[k]
float adv = w ? p.h2.price - low[k] : high[k] - p.h2.price
// Heat is only measured until the neckline is reached (bar that reaches it included)
if p.mfe < math.abs(p.h2.price - p.neck)
p.mae := math.max(p.mae, adv)
p.mfe := math.max(p.mfe, fav)
bool cancel = w ? c < p.peak - p.tolAbs : c > p.peak + p.tolAbs
bool ended = p.state == MState.Stopped or p.state == MState.Timeout or p.state == MState.Invalidated or p.state == MState.Expired
if cancel or ended or bi - p.h2.idx >= expEff + targetBars
finMfe(p, s)
true
// ================================================================================
// Detection (rough candidate search, plan §4.1). isW = false: M (double top), true: W (double bottom).
// Called right after a new pivot of the matching type (high for M, low for W) was pushed.
// ================================================================================
detect(bool isW, float atrX, Stats s, Evt e, bool cand, bool dry) =>
if pivots.size() >= 3
int n = pivots.size()
Pivot h2 = pivots.get(n - 1)
bool accepted = false
Pivot cH1 = na
Pivot cLo = na
Pivot cP0 = na
int cInner = 0
float cTol = 0.0
bool cBodyOnly = false
// Smallest inner-swing count jj that passes every rule wins
for jj = 0 to effInner
int iH1 = n - 3 - 2 * jj
if iH1 < 0
break
Pivot h1c = pivots.get(iH1)
if h1c.isHigh == isW
continue
// Neckline anchor = M: lowest inner low / W: highest inner high (earliest on ties)
Pivot loc = na
for kk = iH1 + 1 to n - 2
Pivot qv = pivots.get(kk)
if qv.isHigh == isW
if na(loc)
loc := qv
else if isW ? qv.price > loc.price : qv.price < loc.price
loc := qv
if na(loc)
continue
// Inner opposite-side swings may not pass the allowed retrace level (otherwise it is a third peak / bottom)
float retraceLvl = isW ? loc.price - (loc.price - math.max(h1c.price, h2.price)) * innerHighMaxPct / 100 : loc.price + (math.min(h1c.price, h2.price) - loc.price) * innerHighMaxPct / 100
bool innerOk = true
for kk = iH1 + 1 to n - 2
Pivot qh = pivots.get(kk)
if qh.isHigh != isW
if isW ? qh.price < retraceLvl : qh.price > retraceLvl
innerOk := false
if not innerOk
continue
// R1 equal extremes: wick, or body when peakSource = WickOrBody
float tolC = math.max(math.max(h1c.price, h2.price) * tolPct / 100, tolAtr * atrX)
bool r1Wick = math.abs(h2.price - h1c.price) <= tolC
bool r1Body = effPeak == PeakSrc.WickOrBody and math.abs(h2.body - h1c.body) <= tolC
if not (r1Wick or r1Body)
continue
// R2, R3, R4, R7 geometry
if not validG(isW, h1c, loc, h2, atrX)
continue
// R5 prior move (optional)
int iP0 = n - 4 - 2 * jj
Pivot p0c = na
if iP0 >= 0
p0c := pivots.get(iP0)
if requirePriorRise
bool priorOk = false
if not na(p0c)
if isW
priorOk := p0c.price - h1c.price >= (loc.price - math.min(h1c.price, h2.price)) * priorRiseMult
else
priorOk := h1c.price - p0c.price >= (math.max(h1c.price, h2.price) - loc.price) * priorRiseMult
if not priorOk
continue
cH1 := h1c
cLo := loc
cP0 := p0c
cInner := jj
cTol := tolC
cBodyOnly := not r1Wick
accepted := true
break
if accepted
bool isRough = cInner > 0 or cBodyOnly
// R6 duplicates / replacement of a pending pattern sharing h1 & lo (same side only)
bool ok = true
int replIdx = -1
int nP = patterns.size()
if nP > 0
for i = 0 to nP - 1
MPattern q = patterns.get(i)
if q.isW == isW
if q.h2.idx == h2.idx
ok := false
else if q.h1.idx == cH1.idx and q.lo.idx == cLo.idx
if q.state == MState.Pending
replIdx := i
else
ok := false
if ok
if not cand
if replIdx >= 0
// Replacement of a pending pattern: already counted, so no new detection count
MPattern oldP = patterns.get(replIdx)
oldP.deleteDrawings()
patterns.remove(replIdx)
else
s.cntDetected := s.cntDetected + 1
if isRough
s.cntRough := s.cntRough + 1
MPattern np = MPattern.new()
np.isW := isW
np.cand := cand
np.p0 := cP0
np.h1 := cH1
np.lo := cLo
np.h2 := h2
np.neck := cLo.price
np.peak := isW ? math.min(cH1.price, h2.price) : math.max(cH1.price, h2.price)
np.target := isW ? np.neck + (np.neck - np.peak) * targetPct / 100.0 : np.neck - (np.peak - np.neck) * targetPct / 100.0
np.tolAbs := cTol
np.breakLvl := isW ? np.neck + math.max(np.neck * effBufPct / 100, effBufAtr * atrX) : np.neck - math.max(np.neck * effBufPct / 100, effBufAtr * atrX)
np.innerSwings := cInner
np.bodyPass := cBodyOnly
np.rough := isRough
np.state := MState.Pending
np.lnOutline := array.new<line>()
np.labels := array.new<label>()
if not dry
np.drawFormation()
if cand
// Early candidate: kept outside `patterns` (no stats, events, catch-up or eviction)
if dry
// History statistics only: hand the geometry back, nothing drawn or stored
emBuf.push(np)
else
cands.set(isW ? 1 : 0, np)
else
patterns.push(np)
// EM / EW history statistics: this confirmed pattern was signalled early
if (isW ? emScW.emitIdx : emScM.emitIdx) == np.h2.idx
s.emConf := s.emConf + 1
if isW
e.formedW := true
else
e.formed := true
e.msg := e.msg + (isW ? "W-Formation detected | " : "M-Formation detected | ") + patternDesc(np) + " || "
// Catch-up: replay the bars between the second extreme and this confirmation bar (oldest first)
for j = 0 to pivotLen - 1
advance(np, pivotLen - 1 - j, s, e)
trackMfe(np, pivotLen - 1 - j, s)
np.lastProcIdx := bar_index
true
// Pivots, ATR are computed on every bar at global scope (never inside an if)
float ph = ta.pivothigh(high, pivotLen, pivotLen)
float pl = ta.pivotlow(low, pivotLen, pivotLen)
float atr = ta.atr(atrLen)
float atrPiv = nz(atr[pivotLen])
// ================================================================================
// Early prediction: provisional H2 / L2 = extreme since the last confirmed pivot, at least predTurnBars bars old.
// Runs detect() in candidate mode on a temporary pivot. Rebuilt every confirmed bar (cancels itself when wrong).
// ================================================================================
updateCand(bool isW, Stats s, Evt e) =>
int ci = isW ? 1 : 0
MPattern oldC = cands.get(ci)
if not na(oldC)
oldC.deleteDrawings()
MPattern none = na
cands.set(ci, none)
int n = pivots.size()
if n >= 2
Pivot lastP = pivots.get(n - 1)
int span = bar_index - lastP.idx
if span >= predTurnBars + 1 and span <= maxSpan
int off = 0
float px = isW ? low : high
for k = 1 to span - 1
float v = isW ? low[k] : high[k]
if isW ? v < px : v > px
px := v
off := k
if off >= predTurnBars
Pivot cp = Pivot.new(not isW, px, bar_index - off, isW ? math.min(open[off], close[off]) : math.max(open[off], close[off]))
if lastP.isHigh == isW
// Last confirmed pivot is the valley (M) / mid peak (W): candidate is a new pivot
pivots.push(cp)
detect(isW, nz(atr[off]), s, e, true, false)
pivots.pop()
else if isW ? px < lastP.price : px > lastP.price
// Last confirmed pivot is the same type and was exceeded: candidate replaces it
pivots.set(n - 1, cp)
detect(isW, nz(atr[off]), s, e, true, false)
pivots.set(n - 1, lastP)
true
// ================================================================================
// EM / EW history statistics (no drawings, no effect on patterns / alerts).
// One event per candidate top / bottom bar. Measured from the bar after the signal appeared:
// move from the H2 / L2 price as % of the H2 -> neck leg; heat = adverse move from the signal bar close.
// Ends when price exceeds H2 / L2 (replaced) or expEff + targetBars bars after H2.
// ================================================================================
emFin(EmTrk t, Stats s, bool replaced) =>
float pc = t.mfe / t.leg * 100
s.emDone := s.emDone + 1
s.emSumMfe := s.emSumMfe + pc
if pc >= 50
s.em50 := s.em50 + 1
if pc >= 100
s.em100 := s.em100 + 1
s.emSumMae := s.emSumMae + t.mae / t.leg * 100
if pc >= 160
s.em160 := s.em160 + 1
if pc >= 200
s.em200 := s.em200 + 1
if replaced and pc < 100
s.emFail := s.emFail + 1
true
emTrack(Stats sM, Stats sW) =>
int i = emOpen.size() - 1
while i >= 0
EmTrk t = emOpen.get(i)
bool repl = t.isW ? low < t.h2Px : high > t.h2Px
bool fin = repl
if not repl
if t.mfe < t.leg
t.mae := math.max(t.mae, t.isW ? t.entryPx - low : high - t.entryPx)
t.mfe := math.max(t.mfe, t.isW ? high - t.h2Px : t.h2Px - low)
fin := bar_index - t.h2Idx >= expEff + targetBars
if fin
emFin(t, t.isW ? sW : sM, repl)
emOpen.remove(i)
i := i - 1
true
emHist(bool isW, EmScan sc, Stats s, Evt e) =>
int n = pivots.size()
if n >= 2
Pivot lastP = pivots.get(n - 1)
int span = bar_index - lastP.idx
float cur = isW ? low : high
bool rebased = sc.baseIdx != lastP.idx
if rebased
// Last confirmed pivot changed: rescan the bars after it (most recent bar wins ties)
sc.baseIdx := lastP.idx
sc.exIdx := bar_index
sc.exPx := cur
if span >= 2 and span <= maxSpan
for k = 1 to span - 1
float v = isW ? low[k] : high[k]
if isW ? v < sc.exPx : v > sc.exPx
sc.exPx := v
sc.exIdx := bar_index - k
else if isW ? cur <= sc.exPx : cur >= sc.exPx
sc.exPx := cur
sc.exIdx := bar_index
int off = bar_index - sc.exIdx
// Evaluate only when the extreme just became predTurnBars old, or the pivots changed, and once per extreme
if span >= predTurnBars + 1 and span <= maxSpan and off >= predTurnBars and sc.emitIdx != sc.exIdx and (off == predTurnBars or rebased)
float px = sc.exPx
Pivot cp = Pivot.new(not isW, px, sc.exIdx, isW ? math.min(open[off], close[off]) : math.max(open[off], close[off]))
emBuf.clear()
if lastP.isHigh == isW
pivots.push(cp)
detect(isW, nz(atr[off]), s, e, true, true)
pivots.pop()
else if isW ? px < lastP.price : px > lastP.price
pivots.set(n - 1, cp)
detect(isW, nz(atr[off]), s, e, true, true)
pivots.set(n - 1, lastP)
if emBuf.size() > 0
MPattern m = emBuf.get(0)
sc.emitIdx := sc.exIdx
s.emN := s.emN + 1
emOpen.push(EmTrk.new(isW, m.h2.idx, m.h2.price, math.max(math.abs(m.h2.price - m.neck), syminfo.mintick), close))
emBuf.clear()
true
// ================================================================================
// Per-bar logic (all state changes gated on confirmed bars -> non-repainting)
// ================================================================================
Evt ev = Evt.new()
if barstate.isconfirmed
// 1) Advance existing (Pending / Broken) patterns by the current bar
for p in patterns
if (p.state == MState.Pending or p.state == MState.Broken) and p.lastProcIdx != bar_index
advance(p, 0, p.isW ? stW : st, ev)
p.lastProcIdx := bar_index
// From-H2 measurement keeps running after Target hit (ends inside trackMfe)
if not p.mfeDone
trackMfe(p, 0, p.isW ? stW : st)
// 2) Swing detection. Low first, then high, so alternation is preserved on outside bars.
// W detection runs right after the low push (new low is the last pivot); M after the high push.
bool newLow = false
bool newHigh = false
if not na(pl)
newLow := pushPivot(false, pl, bar_index - pivotLen, math.min(open[pivotLen], close[pivotLen]))
if newLow and enableW
detect(true, atrPiv, stW, ev, false, false)
if not na(ph)
newHigh := pushPivot(true, ph, bar_index - pivotLen, math.max(open[pivotLen], close[pivotLen]))
if newHigh and enableM
detect(false, atrPiv, st, ev, false, false)
// 3) Early prediction candidates (provisional, last bar only; replaced by the real pattern once the pivot confirms)
if showPred and barstate.islast
if enableM
updateCand(false, st, ev)
if enableW
updateCand(true, stW, ev)
// 4) EM / EW history statistics (no drawings). Open signals first, so the bar a signal appears on is not measured.
if emHistStats
emTrack(st, stW)
if enableM
emHist(false, emScM, st, ev)
if enableW
emHist(true, emScW, stW, ev)
// 5) Eviction: keep at most maxPatterns (M + W combined), removing oldest finished first
while patterns.size() > maxPatterns and oldestFinished(patterns) >= 0
int oi = oldestFinished(patterns)
MPattern evictP = patterns.get(oi)
finMfe(evictP, evictP.isW ? stW : st)
evictP.deleteDrawings()
patterns.remove(oi)
// Event flags at global scope (used by alertconditions and data-window plots)
bool evFormed = ev.formed
bool evBreak = ev.brk
bool evTarget = ev.hit
bool evInvalid = ev.inval
bool evExpired = ev.expd
bool evFormedW = ev.formedW
bool evBreakW = ev.brkW
bool evTargetW = ev.hitW
bool evInvalidW = ev.invalW
bool evExpiredW = ev.expdW
// ================================================================================
// Alerts
// ================================================================================
alertcondition(evFormed, "M formed", "M-formation detected on {{ticker}} {{interval}}")
alertcondition(evBreak, "M neckline break", "M neckline broken on {{ticker}} {{interval}}, close {{close}}")
alertcondition(evTarget, "M target hit", "M target hit on {{ticker}} {{interval}}")
alertcondition(evInvalid, "M invalidated", "M invalidated on {{ticker}} {{interval}}")
alertcondition(evExpired, "M expired", "M expired on {{ticker}} {{interval}}")
alertcondition(evFormedW, "W formed", "W-formation detected on {{ticker}} {{interval}}")
alertcondition(evBreakW, "W neckline break", "W neckline broken on {{ticker}} {{interval}}, close {{close}} above neckline")
alertcondition(evTargetW, "W target hit", "W target hit on {{ticker}} {{interval}}")
alertcondition(evInvalidW, "W invalidated", "W invalidated on {{ticker}} {{interval}}")
alertcondition(evExpiredW, "W expired", "W expired on {{ticker}} {{interval}}")
if useDynamicAlerts and barstate.isconfirmed and ev.msg != ""
alert(ev.msg + syminfo.tickerid + " " + timeframe.period, alert.freq_once_per_bar_close)
plot(evBreak ? 1 : 0, "BreakEvent", display = display.data_window)
plot(evFormed ? 1 : 0, "FormedEvent", display = display.data_window)
plot(evBreakW ? 1 : 0, "BreakEventW", display = display.data_window)
plot(evFormedW ? 1 : 0, "FormedEventW", display = display.data_window)
// ================================================================================
// FiveSwing stub: info label, runs Classic
// ================================================================================
if patternMode == PatternMode.FiveSwing and barstate.islast and na(fsLabel)
fsLabel := label.new(bar_index, high, "FiveSwing not implemented — using Classic", xloc = xloc.bar_index, style = label.style_label_left, color = color.gray, textcolor = color.white)
// ================================================================================
// History table (rebuilt on the last bar only): col 0 label | col 1 M | col 2 W
// ================================================================================
if barstate.islast
if showTable
if na(tbl)
tbl := table.new(tblPos, 3, 27, color.new(color.black, 0), border_width = 1, border_color = color.new(color.gray, 40))
int activeM = 0
int activeW = 0
string lastDescM = "—"
string lastDescW = "—"
for p in patterns
string d = stateName(p.state) + " | neck " + str.tostring(p.neck, format.mintick) + " | tgt " + str.tostring(p.target, format.mintick)
bool act = p.state == MState.Pending or p.state == MState.Broken
if p.isW
if act
activeW := activeW + 1
lastDescW := d
else
if act
activeM := activeM + 1
lastDescM := d
string roughDesc = roughEnabled ? "rough (inner<=" + str.tostring(effInner) + ")" : "strict"
string dash = "—"
tRow(0, "M / W Formation", "pivot=" + str.tostring(pivotLen) + " tol=" + str.tostring(tolAtr, "#.##") + "xATR depth=" + str.tostring(minDepthAtr, "#.#") + "xATR " + roughDesc, "")
tRow(1, "Detected", enableM ? str.tostring(st.cntDetected) : dash, enableW ? str.tostring(stW.cntDetected) : dash)
tRow(2, "Broken", enableM ? str.tostring(st.cntBroken) + " " + pctStr(st.cntBroken, st.cntDetected) : dash, enableW ? str.tostring(stW.cntBroken) + " " + pctStr(stW.cntBroken, stW.cntDetected) : dash)
tRow(3, "Expired", enableM ? str.tostring(st.cntExpired) : dash, enableW ? str.tostring(stW.cntExpired) : dash)
tRow(4, "Invalidated", enableM ? str.tostring(st.cntInvalid) : dash, enableW ? str.tostring(stW.cntInvalid) : dash)
tRow(5, "Target hit", enableM ? str.tostring(st.cntTarget) + " " + pctStr(st.cntTarget, st.cntBroken) : dash, enableW ? str.tostring(stW.cntTarget) + " " + pctStr(stW.cntTarget, stW.cntBroken) : dash)
tRow(6, "Stopped", enableM ? str.tostring(st.cntStopped) : dash, enableW ? str.tostring(stW.cntStopped) : dash)
tRow(7, "Timeout", enableM ? str.tostring(st.cntTimeout) : dash, enableW ? str.tostring(stW.cntTimeout) : dash)
tRow(8, "Avg bars H2→break", enableM and st.cntBroken > 0 ? str.tostring(float(st.sumBars) / st.cntBroken, "#.#") : dash, enableW and stW.cntBroken > 0 ? str.tostring(float(stW.sumBars) / stW.cntBroken, "#.#") : dash)
tRow(9, "Active now", enableM ? str.tostring(activeM) : dash, enableW ? str.tostring(activeW) : dash)
tRow(10, "Last pattern", enableM ? lastDescM : dash, enableW ? lastDescW : dash)
tRow(11, "Rough matches", enableM ? str.tostring(st.cntRough) : dash, enableW ? str.tostring(stW.cntRough) : dash)
tRow(12, "From H2/L2: tracked", enableM ? str.tostring(st.mfeN) : dash, enableW ? str.tostring(stW.mfeN) : dash)
tRow(13, "Reached ≥50% to neck", enableM ? str.tostring(st.mfe50) + " " + pctStr(st.mfe50, st.mfeN) : dash, enableW ? str.tostring(stW.mfe50) + " " + pctStr(stW.mfe50, stW.mfeN) : dash)
tRow(14, "Reached ≥100% (neck)", enableM ? str.tostring(st.mfe100) + " " + pctStr(st.mfe100, st.mfeN) : dash, enableW ? str.tostring(stW.mfe100) + " " + pctStr(stW.mfe100, stW.mfeN) : dash)
tRow(15, "Reached ≥160%", enableM ? str.tostring(st.mfe160) + " " + pctStr(st.mfe160, st.mfeN) : dash, enableW ? str.tostring(stW.mfe160) + " " + pctStr(stW.mfe160, stW.mfeN) : dash)
tRow(16, "Reached ≥200%", enableM ? str.tostring(st.mfe200) + " " + pctStr(st.mfe200, st.mfeN) : dash, enableW ? str.tostring(stW.mfe200) + " " + pctStr(stW.mfe200, stW.mfeN) : dash)
tRow(17, "Avg max move (% of H2→neck)", enableM and st.mfeN > 0 ? str.tostring(st.sumMfe / st.mfeN, "#") + "%" : dash, enableW and stW.mfeN > 0 ? str.tostring(stW.sumMfe / stW.mfeN, "#") + "%" : dash)
tRow(18, "Avg heat before neck (%)", enableM and st.mfe100 > 0 ? str.tostring(st.sumMae / st.mfe100, "#") + "%" : dash, enableW and stW.mfe100 > 0 ? str.tostring(stW.sumMae / stW.mfe100, "#") + "%" : dash)
bool emM = enableM and emHistStats
bool emW = enableW and emHistStats
tRow(19, "EM / EW early signals", emM ? str.tostring(st.emN) : dash, emW ? str.tostring(stW.emN) : dash)
tRow(20, "Early → confirmed M / W", emM ? str.tostring(st.emConf) + " " + pctStr(st.emConf, st.emN) : dash, emW ? str.tostring(stW.emConf) + " " + pctStr(stW.emConf, stW.emN) : dash)
tRow(21, "Early: reached ≥50% to neck", emM ? str.tostring(st.em50) + " " + pctStr(st.em50, st.emDone) : dash, emW ? str.tostring(stW.em50) + " " + pctStr(stW.em50, stW.emDone) : dash)
tRow(22, "Early: reached ≥100% (neck)", emM ? str.tostring(st.em100) + " " + pctStr(st.em100, st.emDone) : dash, emW ? str.tostring(stW.em100) + " " + pctStr(stW.em100, stW.emDone) : dash)
tRow(23, "Early: reached ≥160%", emM ? str.tostring(st.em160) + " " + pctStr(st.em160, st.emDone) : dash, emW ? str.tostring(stW.em160) + " " + pctStr(stW.em160, stW.emDone) : dash)
tRow(24, "Early: reached ≥200%", emM ? str.tostring(st.em200) + " " + pctStr(st.em200, st.emDone) : dash, emW ? str.tostring(stW.em200) + " " + pctStr(stW.em200, stW.emDone) : dash)
tRow(25, "Early: failed before neck", emM ? str.tostring(st.emFail) + " " + pctStr(st.emFail, st.emDone) : dash, emW ? str.tostring(stW.emFail) + " " + pctStr(stW.emFail, stW.emDone) : dash)
tRow(26, "Early: avg move | heat before neck", emM and st.emDone > 0 ? str.tostring(st.emSumMfe / st.emDone, "#") + "% | " + (st.em100 > 0 ? str.tostring(st.emSumMae / st.em100, "#") + "%" : dash) : dash, emW and stW.emDone > 0 ? str.tostring(stW.emSumMfe / stW.emDone, "#") + "% | " + (stW.em100 > 0 ? str.tostring(stW.emSumMae / stW.em100, "#") + "%" : dash) : dash)
else
if not na(tbl)
table.delete(tbl)
tbl := na