本页源码来自 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
// © Hermetic Trader. All rights reserved.
// Sphinx Stride v1.0 - Leg Projection & Structure
//
// Projects the next swing leg from the protected swing in the chart's own ATR,
// with targets from measured leg sizes (T1 Expansion 4.0, T2 Typical 5.3,
// T3 Extended 7.4 ATR - the 25th / 50th / 75th percentile of proper legs on
// MES 1m and 5m, Aug - Nov 2026). Trend by CHoCH on the chart and on a higher
// timeframe (15m by default): swings, CHoCH level, structure envelope, and SMT
// between ES and NQ at the higher-timeframe swings. Closed bars only; no repaint.
// Companion to Sphinx Regime (the day) and Sphinx Horizon (the week / day).
//@version=6
indicator('Sphinx Stride: Leg Projection & Structure', shorttitle = 'Stride', overlay = true, max_boxes_count = 80, max_lines_count = 200, max_labels_count = 200)
// ============================================================
// === INPUTS ===
// ============================================================
g_sw = '1 · Swings'
i_str = input.int(3, 'Swing strength (bars each side)', minval = 1, maxval = 10, group = g_sw, tooltip = '3 = a 7-candle swing: a high with three lower highs on each side (a low with three higher lows).', display = display.none)
i_lock = input.float(3.0, 'Lock a swing after a move of (x ATR)', minval = 0.5, step = 0.25, group = g_sw, tooltip = 'The latest swing is projected from straight away, dimmed. Until price has moved this far from it, a more extreme swing can still replace it and the projection moves; once it has, the swing is locked and the projection turns full strength. Also the minimum size for a leg to count.', display = display.none)
i_atr = input.int(100, 'ATR length', minval = 10, maxval = 500, group = g_sw, tooltip = 'The ATR of the chart timeframe sets every distance, so the same settings work on 1m, 5m or 15m and the projection grows by itself in busy sessions.', display = display.none)
g_pr = '2 · Projection'
i_l75 = input.float(4.0, 'T1 Expansion (x ATR)', minval = 0, step = 0.1, group = g_pr, tooltip = 'Distances from the protected swing, measured on real legs. T1: three in four legs get at least this far - a leg that stops short lacked displacement (Weak).', display = display.none)
i_l50 = input.float(5.3, 'T2 Typical (x ATR)', minval = 0, step = 0.1, group = g_pr, tooltip = 'Where the median leg ends - the typical draw.', display = display.none)
i_l25 = input.float(7.4, 'T3 Extended (x ATR)', minval = 0, step = 0.1, group = g_pr, tooltip = 'Only one leg in four gets this far. Beyond it the leg is Extended - a trending, overextended move.', display = display.none)
i_l10 = input.float(10.5, 'T4 Extreme (x ATR)', minval = 0, step = 0.5, group = g_pr, tooltip = 'One leg in ten.', display = display.none)
i_show10 = input.bool(false, 'Show T4 Extreme (dotted)', group = g_pr, display = display.none)
i_dir = input.string('With trend + faint pullbacks', 'Project legs', options = ['With trend + faint pullbacks', 'With trend only', 'Both directions'], group = g_pr, tooltip = 'With trend + faint pullbacks: the leg in the trend\'s direction (up from a higher low in a bullish trend, down from a lower high in a bearish one) at full strength; a pullback leg is projected too, dimmed. With trend only: pullbacks are not projected. Both directions: every leg at full strength. The trend follows the CHoCH.', display = display.none)
i_lblPos = input.string('Right', 'Level labels', options = ['Left', 'Right', 'None'], group = g_pr, tooltip = 'Left: at the swing, like the fib tool. Right: at the current bar.', display = display.none)
i_band = input.int(84, 'Exhaustion zone transparency', minval = 40, maxval = 98, group = g_pr, tooltip = 'The zone between T2 and T3, where most legs run out. It brightens once price has passed T1.', display = display.none)
i_grade = input.string('Heat', 'Color scheme', options = ['Heat', 'Single'], group = g_pr, tooltip = 'Heat: T1 cool, T2 warm, T3 hot. Single: one colour throughout.', display = display.none)
c_pr = input.color(#4fc3f7, 'Swing / single color', group = g_pr, display = display.none)
c_g75 = input.color(#26a69a, 'T1', group = g_pr, inline = 'gc', display = display.none)
c_g50 = input.color(#ffca28, 'T2', group = g_pr, inline = 'gc', display = display.none)
c_g25 = input.color(#ff7043, 'T3', group = g_pr, inline = 'gc', display = display.none)
c_g10 = input.color(#ef5350, 'T4', group = g_pr, inline = 'gc', display = display.none)
// colour of a level (0 swing .. 4 = 10%)
_lc(int i) =>
i_grade == 'Single' or i == 0 ? c_pr : i == 1 ? c_g75 : i == 2 ? c_g50 : i == 3 ? c_g25 : c_g10
g_hs = '3 · History'
i_tagSt = input.string('Structure', 'Swing tags', options = ['Structure', 'Structure + result', 'Result', 'Off'], group = g_hs, tooltip = 'Structure: HH / HL (green) or LH / LL (red) at each finished swing. Result: how far the leg into it ran - Weak (ended before T1, no displacement), Normal (T1 to T3) or Extended (beyond T3) - with its size in ATR.', display = display.none)
i_keep = input.int(20, 'Swing tags kept', minval = 0, maxval = 70, group = g_hs, display = display.none)
g_cx = '4 · Marks'
i_mark = input.bool(true, 'Mark the locked swing', group = g_cx, display = display.none)
g_lb = '5 · Labels'
i_lbl = input.bool(true, 'Label the projection', group = g_lb, display = display.none)
i_lblSz = input.string('Small', 'Label size', options = ['Tiny', 'Small', 'Normal'], group = g_lb, display = display.none)
lblSz = i_lblSz == 'Tiny' ? size.tiny : i_lblSz == 'Normal' ? size.normal : size.small
g_of = '6 · Order flow'
i_tbl = input.bool(true, 'Show panel', group = g_of, tooltip = 'Order flow: Bullish when the latest high is a higher high and the latest low a higher low; Bearish for a lower high and lower low; Mixed otherwise. The trend follows the CHoCH: a close through the swing protecting it flips it, and the swing tags confirm it. The top row adds trending when three of the last five legs ran past T3, choppy when three ended before T1.', display = display.none)
i_choch = input.bool(true, 'Show the CHoCH level', group = g_of, tooltip = 'The swing that protects the current trend: the last low in a bullish trend, the last high in a bearish one. A close through it is a change of character (CHoCH) and flips the trend.', display = display.none)
i_chHist = input.int(8, 'Past CHoCHs kept', minval = 0, maxval = 30, group = g_of, tooltip = 'Each CHoCH is marked by a line from the swing that was broken to the candle that closed through it. 0 = none.', display = display.none)
c_up = input.color(#26a69a, 'Bullish', group = g_of, inline = 'cc', display = display.none)
c_dn = input.color(#ef5350, 'Bearish', group = g_of, inline = 'cc', display = display.none)
i_pos = input.string('Bottom Right', 'Panel position', options = ['Top Right', 'Top Left', 'Bottom Right', 'Bottom Left'], group = g_of, display = display.none)
g_hf = '7 · Higher-timeframe flow'
i_htfOn = input.bool(true, 'Use higher-timeframe order flow', group = g_hf, tooltip = 'Runs the same swing and CHoCH logic on a higher timeframe (closed candles only, no repaint) as the bias for the chart\'s legs. Only active when the chart timeframe is lower.', display = display.none)
i_htf = input.timeframe('15', 'Timeframe', group = g_hf, display = display.none)
i_htfFilt = input.string('Dim counter-trend', 'Counter-trend projections', options = ['Dim counter-trend', 'Hide counter-trend', 'Off'], group = g_hf, tooltip = 'A projected leg that goes against the higher-timeframe trend is drawn dimmed and marked, hidden, or treated like any other (Off).', display = display.none)
i_htfLine = input.bool(true, 'Show the higher-timeframe CHoCH level', group = g_hf, display = display.none)
i_hSw = input.bool(true, 'Show higher-timeframe swings', group = g_hf, inline = 'hs', tooltip = 'The higher timeframe\'s swings, tagged against the last swing on their side (HH / LH / HL / LL). A swing that is extended before it settles moves with it.', display = display.none)
i_hSwN = input.int(12, 'Kept', minval = 2, maxval = 40, group = g_hf, inline = 'hs', display = display.none)
i_hSwLn = input.bool(false, 'Extend swings as lines', group = g_hf, inline = 'hl', tooltip = 'Each higher-timeframe swing runs right from its candle until price trades through it. Taken: the line stops at the candle that took it and fades - or is removed.', display = display.none)
i_hTaken = input.string('Fade', 'Taken', options = ['Fade', 'Hide'], group = g_hf, inline = 'hl', display = display.none)
i_env = input.bool(true, 'Structure envelope', group = g_hf, inline = 'ev', tooltip = 'Rails through the last two higher-timeframe swing highs and the last two swing lows, projected forward and rebuilt as new swings form. A visual guide to where price sits in the higher-timeframe structure - watch the reaction at the rails.', display = display.none)
i_envFill = input.bool(true, 'Fill', group = g_hf, inline = 'ev', display = display.none)
i_envBrk = input.bool(false, 'Mark rail breaks', group = g_hf, inline = 'ev', display = display.none)
c_env = input.color(#b39ddb, 'Rail color', group = g_hf, display = display.none)
g_sm = '8 · SMT'
i_smt = input.bool(true, 'SMT at higher-timeframe swings', group = g_sm, tooltip = 'ES against NQ at the latest higher-timeframe swing high and low, each index against its own level. The moment one trades through its level and the other has not, the SMT is drawn - a line from the swing to this chart\'s extreme since, tagged SMT - and tracked live until the other index takes its level too, which clears it. If a new swing forms while it is live, it stays as history. Measured on the full contracts, so micro and full charts agree.', display = display.none)
i_smtRef = input.string('Structure swings', 'SMT levels', options = ['Every pivot', 'Structure swings'], group = g_sm, tooltip = 'Every pivot: the latest higher-timeframe pivot high and low (2 candles each side, as in Sphinx Regime) - several per session, for scalping. Structure swings: only the major swings used for the trend and CHoCH - rarer.', display = display.none)
i_smtM = input.float(0.0, 'Min take beyond the level (x HTF ATR)', minval = 0, step = 0.05, group = g_sm, tooltip = '0 = any trade through the level counts. Raise it to ignore one-tick takes.', display = display.none)
i_smtN = input.int(6, 'Past SMTs kept', minval = 0, maxval = 30, group = g_sm, display = display.none)
s_es = input.symbol('CME_MINI:ES1!', 'ES symbol', group = g_sm, display = display.none)
s_nq = input.symbol('CME_MINI:NQ1!', 'NQ symbol', group = g_sm, display = display.none)
s_ym = input.symbol('CBOT_MINI:YM1!', 'YM symbol', group = g_sm, display = display.none)
// ============================================================
// === SWING ENGINE (confirmed bars only - no repaint) ===
// ============================================================
A = ta.atr(i_atr)
pvH = ta.pivothigh(high, i_str, i_str)
pvL = ta.pivotlow(low, i_str, i_str)
aK = A[i_str]
tK = time[i_str]
hiK = ta.highest(high, i_str)
loK = ta.lowest(low, i_str)
barMs = timeframe.in_seconds() * 1000
// higher-timeframe order flow: the same swing / CHoCH logic on its candles.
// Returns the trend and CHoCH level of the last closed candle.
_htfFlow(int str, float lk, int alen) =>
float a = ta.atr(alen)
float ph = ta.pivothigh(high, str, str)
float pl = ta.pivotlow(low, str, str)
float aK = a[str]
int tK = time[str]
var int zT = 0
var float zP = na
var int zTm = na
var float lH = na
var float lL = na
var int lHT = na
var int lLT = na
var string tH = ''
var string tL = ''
var int trd = 0
if not na(ph) and not na(aK)
if zT == 1
if ph > zP
zP := ph
zTm := tK
tH := na(lH) ? '' : ph > lH ? 'HH' : 'LH'
else if zT == 0 or ph - zP >= lk * aK
if zT == -1
lL := zP
lLT := zTm
tH := na(lH) ? '' : ph > lH ? 'HH' : 'LH'
zT := 1
zP := ph
zTm := tK
if not na(pl) and not na(aK)
if zT == -1
if pl < zP
zP := pl
zTm := tK
tL := na(lL) ? '' : pl < lL ? 'LL' : 'HL'
else if zT == 0 or zP - pl >= lk * aK
if zT == 1
lH := zP
lHT := zTm
tL := na(lL) ? '' : pl < lL ? 'LL' : 'HL'
zT := -1
zP := pl
zTm := tK
int ofx = tH == 'HH' and tL == 'HL' ? 1 : tH == 'LH' and tL == 'LL' ? -1 : 0
float hR = zT == 1 ? zP : lH
float lR = zT == -1 ? zP : lL
int hRT = zT == 1 ? zTm : lHT
int lRT = zT == -1 ? zTm : lLT
if trd == 0 and ofx != 0
trd := ofx
else if trd == 1 and not na(lR) and close < lR
trd := -1
else if trd == -1 and not na(hR) and close > hR
trd := 1
float lvl = trd == 1 ? lR : trd == -1 ? hR : na
int lvT = trd == 1 ? lRT : trd == -1 ? hRT : na
string tg = zT == 1 ? tH : zT == -1 ? tL : ''
[trd[1], lvl[1], lvT[1], zT[1], zP[1], zTm[1], tg[1]]
htfOk = i_htfOn and timeframe.in_seconds() < timeframe.in_seconds(i_htf)
[hTr, hLvl, hLvT, hZT, hZP, hZTm, hTag] = request.security(syminfo.tickerid, i_htf, _htfFlow(i_str, i_lock, i_atr), lookahead = barmerge.lookahead_on)
int htr = htfOk ? nz(hTr) : 0
string htfName = i_htf == '15' ? '15m' : i_htf == '60' ? '1H' : i_htf == '240' ? '4H' : i_htf == '5' ? '5m' : i_htf == '30' ? '30m' : i_htf
// a leg from a swing of this side goes against the higher-timeframe trend
_ctr(int t) =>
i_htfFilt != 'Off' and htr != 0 and (t == -1 ? 1 : -1) != htr
// ---- higher-timeframe map: swings and FVGs ----
var label[] hsL = array.new_label()
var line[] hsLn = array.new_line()
var bool[] hsHi = array.new_bool()
var bool[] hsTk = array.new_bool()
var int hsLastT = na
var int hsLastZ = 0
_hsCol(string tg) =>
tg == 'HH' or tg == 'HL' ? c_up : tg == 'LH' or tg == 'LL' ? c_dn : color.gray
if htfOk and i_hSw and not na(hZTm) and nz(hZT) != 0 and hZTm != nz(hsLastT)
string tx = htfName + (hTag == '' ? ' swing' : ' ' + hTag)
bool hiS = hZT == 1
if hZT == hsLastZ and hsL.size() > 0
// the swing was extended before it settled: redraw it at its new price
int li = hsL.size() - 1
hsL.get(li).delete()
hsLn.get(li).delete()
hsL.set(li, i_hSwLn ? label.new(time + barMs * 3, hZP, tx, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = _hsCol(hTag), size = size.small) : label.new(hZTm, hZP, tx, xloc = xloc.bar_time, style = hiS ? label.style_label_down : label.style_label_up, color = color.new(color.black, 100), textcolor = _hsCol(hTag), size = size.small))
hsLn.set(li, i_hSwLn ? line.new(hZTm, hZP, time, hZP, xloc = xloc.bar_time, color = color.new(_hsCol(hTag), 35), width = 1) : line(na))
hsTk.set(li, false)
else
hsL.push(i_hSwLn ? label.new(time + barMs * 3, hZP, tx, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = _hsCol(hTag), size = size.small) : label.new(hZTm, hZP, tx, xloc = xloc.bar_time, style = hiS ? label.style_label_down : label.style_label_up, color = color.new(color.black, 100), textcolor = _hsCol(hTag), size = size.small))
hsLn.push(i_hSwLn ? line.new(hZTm, hZP, time, hZP, xloc = xloc.bar_time, color = color.new(_hsCol(hTag), 35), width = 1) : line(na))
hsHi.push(hiS)
hsTk.push(false)
while hsL.size() > i_hSwN
hsL.shift().delete()
hsLn.shift().delete()
hsHi.shift()
hsTk.shift()
hsLastT := hZTm
hsLastZ := hZT
// ---- structure envelope: last two swing highs and last two swing lows ----
var float[] eHP = array.new_float()
var int[] eHT = array.new_int()
var float[] eLP = array.new_float()
var int[] eLT = array.new_int()
var int eLastT = na
var int eLastZ = 0
if htfOk and not na(hZTm) and nz(hZT) != 0 and hZTm != nz(eLastT)
bool hiE = hZT == 1
float[] ap = hiE ? eHP : eLP
int[] at = hiE ? eHT : eLT
if hZT == eLastZ and ap.size() > 0
ap.set(ap.size() - 1, hZP)
at.set(at.size() - 1, hZTm)
else
ap.push(hZP)
at.push(hZTm)
if ap.size() > 2
ap.shift()
at.shift()
eLastT := hZTm
eLastZ := hZT
// ---- SMT at the higher-timeframe swings (ES / NQ, full contracts) ----
string fam = str.contains(syminfo.root, 'NQ') ? 'NQ' : str.contains(syminfo.root, 'YM') ? 'YM' : 'ES'
string nmA = fam == 'ES' ? 'NQ' : 'ES'
string symC = ticker.inherit(syminfo.tickerid, fam == 'NQ' ? s_nq : fam == 'YM' ? s_ym : s_es)
string symA = ticker.inherit(syminfo.tickerid, fam == 'ES' ? s_nq : s_es)
_hb() =>
[time[1], high[1], low[1], ta.atr(14)[1]]
[cBT, cBH, cBL, cBA] = request.security(symC, i_htf, _hb(), lookahead = barmerge.lookahead_on)
[aBT, aBH, aBL, aBA] = request.security(symA, i_htf, _hb(), lookahead = barmerge.lookahead_on)
[xHi, xLo] = request.security(symC, timeframe.period, [high, low])
// latest higher-timeframe pivots on this chart (closed candles)
_pvt() =>
float ph = ta.pivothigh(high, 2, 2)
float pl = ta.pivotlow(low, 2, 2)
var float lh = na
var int lht = na
var float ll = na
var int llt = na
if not na(ph)
lh := ph
lht := time[2]
if not na(pl)
ll := pl
llt := time[2]
[lh[1], lht[1], ll[1], llt[1]]
[pH15, pH15T, pL15, pL15T] = request.security(syminfo.tickerid, i_htf, _pvt(), lookahead = barmerge.lookahead_on)
[aHi, aLo] = request.security(symA, timeframe.period, [high, low])
var int[] cTs = array.new_int()
var float[] cHs = array.new_float()
var float[] cLs = array.new_float()
var int[] aTs = array.new_int()
var float[] aHs = array.new_float()
var float[] aLs = array.new_float()
smtOk = htfOk and i_smt
if smtOk and not na(cBT) and cBT != nz(cBT[1])
cTs.push(cBT)
cHs.push(cBH)
cLs.push(cBL)
if cTs.size() > 400
cTs.shift()
cHs.shift()
cLs.shift()
if smtOk and not na(aBT) and aBT != nz(aBT[1])
aTs.push(aBT)
aHs.push(aBH)
aLs.push(aBL)
if aTs.size() > 400
aTs.shift()
aHs.shift()
aLs.shift()
htfMs = timeframe.in_seconds(i_htf) * 1000
// an index's extreme around a time: its higher-timeframe candles within one candle of it
_xAt(int[] ts, float[] vs, int t, bool hi) =>
float r = na
if ts.size() > 0
for i = ts.size() - 1 to 0
int ti = ts.get(i)
if ti < t - htfMs
break
if ti <= t + htfMs
float v = vs.get(i)
r := na(r) ? v : hi ? math.max(r, v) : math.min(r, v)
r
var label[] smL = array.new_label()
var line[] smLn = array.new_line()
var label smLvH = na
var line smLnH = na
var label smLvL = na
var line smLnL = na
var string smTxH = ''
var string smTxL = ''
bool evSmtH = false
bool evSmtL = false
_keep(label lb, line ln) =>
if not na(lb)
smL.push(lb)
smLn.push(ln)
while smL.size() > i_smtN
smL.shift().delete()
smLn.shift().delete()
bool envOk = htfOk and i_env and eHP.size() == 2 and eLP.size() == 2 and eHT.get(1) != eHT.get(0) and eLT.get(1) != eLT.get(0)
_rail(float[] ap, int[] at, int t) =>
float sl = (ap.get(1) - ap.get(0)) / (at.get(1) - at.get(0))
ap.get(1) + sl * (t - at.get(1))
float railU = envOk ? _rail(eHP, eHT, time) : na
float railL = envOk ? _rail(eLP, eLT, time) : na
string envShape = not envOk ? '' : eHP.get(1) > eHP.get(0) and eLP.get(1) > eLP.get(0) ? 'Rising' : eHP.get(1) < eHP.get(0) and eLP.get(1) < eLP.get(0) ? 'Falling' : eHP.get(1) > eHP.get(0) ? 'Expanding' : 'Contracting'
// SMT, live: each side tracks the latest settled swing (the previous one while a
// new swing on that side is still extending)
var int rHT = na
var float rHP = na
var float rHC = na
var float rHA = na
var bool tkHC = false
var bool tkHA = false
var float mxH = na
var int mxHT = na
var int rLT = na
var float rLP = na
var float rLC = na
var float rLA = na
var bool tkLC = false
var bool tkLA = false
var float mnL = na
var int mnLT = na
_tipS(bool hi, bool cTook) =>
string tk = cTook ? fam : nmA
string ft = cTook ? nmA : fam
htfName + ' swing ' + (hi ? 'high' : 'low') + ' SMT\n' + tk + ' traded through its ' + (hi ? 'high' : 'low') + '\n' + ft + ' has not'
int rTH = na
float rPH = na
if i_smtRef == 'Every pivot'
rTH := pH15T
rPH := pH15
else if eHP.size() == 2
rTH := hZT == 1 ? eHT.get(0) : eHT.get(1)
rPH := hZT == 1 ? eHP.get(0) : eHP.get(1)
if smtOk and not na(rTH)
int rT = rTH
float rP = rPH
if rT != nz(rHT)
if tkHC != tkHA
_keep(smLvH, smLnH)
else
label.delete(smLvH)
line.delete(smLnH)
smLvH := label(na)
smLnH := line(na)
rHT := rT
rHP := rP
rHC := _xAt(cTs, cHs, rT, true)
rHA := _xAt(aTs, aHs, rT, true)
tkHC := false
tkHA := false
mxH := na
mxHT := na
if smtOk and not na(rHT) and time > rHT
if na(mxH) or high > mxH
mxH := high
mxHT := time
if not tkHC and not na(rHC) and xHi > rHC + i_smtM * nz(cBA)
tkHC := true
if not tkHA and not na(rHA) and aHi > rHA + i_smtM * nz(aBA)
tkHA := true
bool liveH = tkHC != tkHA
if liveH
if na(smLvH)
smLvH := label.new(mxHT, mxH, 'SMT', xloc = xloc.bar_time, style = label.style_label_down, color = color.new(c_dn, 70), textcolor = color.white, size = size.tiny)
smLnH := line.new(rHT, rHP, mxHT, mxH, xloc = xloc.bar_time, color = color.new(c_dn, 25), width = 1)
evSmtH := true
smLvH.set_xy(mxHT, mxH)
smLvH.set_tooltip(_tipS(true, tkHC))
smLnH.set_xy2(mxHT, mxH)
smTxH := htfName + ' high · ' + (tkHC ? nmA : fam) + ' failed'
else
label.delete(smLvH)
line.delete(smLnH)
smLvH := label(na)
smLnH := line(na)
smTxH := ''
int rTL = na
float rPL = na
if i_smtRef == 'Every pivot'
rTL := pL15T
rPL := pL15
else if eLP.size() == 2
rTL := hZT == -1 ? eLT.get(0) : eLT.get(1)
rPL := hZT == -1 ? eLP.get(0) : eLP.get(1)
if smtOk and not na(rTL)
int rT = rTL
float rP = rPL
if rT != nz(rLT)
if tkLC != tkLA
_keep(smLvL, smLnL)
else
label.delete(smLvL)
line.delete(smLnL)
smLvL := label(na)
smLnL := line(na)
rLT := rT
rLP := rP
rLC := _xAt(cTs, cLs, rT, false)
rLA := _xAt(aTs, aLs, rT, false)
tkLC := false
tkLA := false
mnL := na
mnLT := na
if smtOk and not na(rLT) and time > rLT
if na(mnL) or low < mnL
mnL := low
mnLT := time
if not tkLC and not na(rLC) and xLo < rLC - i_smtM * nz(cBA)
tkLC := true
if not tkLA and not na(rLA) and aLo < rLA - i_smtM * nz(aBA)
tkLA := true
bool liveL = tkLC != tkLA
if liveL
if na(smLvL)
smLvL := label.new(mnLT, mnL, 'SMT', xloc = xloc.bar_time, style = label.style_label_up, color = color.new(c_up, 70), textcolor = color.white, size = size.tiny)
smLnL := line.new(rLT, rLP, mnLT, mnL, xloc = xloc.bar_time, color = color.new(c_up, 25), width = 1)
evSmtL := true
smLvL.set_xy(mnLT, mnL)
smLvL.set_tooltip(_tipS(false, tkLC))
smLnL.set_xy2(mnLT, mnL)
smTxL := htfName + ' low · ' + (tkLC ? nmA : fam) + ' failed'
else
label.delete(smLvL)
line.delete(smLnL)
smLvL := label(na)
smLnL := line(na)
smTxL := ''
// rail breaks: a close through a rail
var label[] eBk = array.new_label()
if envOk and i_envBrk and barstate.isconfirmed
bool bDn = close < railL and close[1] >= railL[1]
bool bUp = close > railU and close[1] <= railU[1]
if bDn or bUp
eBk.push(label.new(time, bDn ? high : low, '', xloc = xloc.bar_time, style = bDn ? label.style_triangledown : label.style_triangleup, color = color.new(bDn ? c_dn : c_up, 20), size = size.tiny, tooltip = htfName + ' rail break ' + (bDn ? 'down' : 'up')))
while eBk.size() > 8
eBk.shift().delete()
bool evRailDn = envOk and barstate.isconfirmed and close < railL and close[1] >= railL[1]
bool evRailUp = envOk and barstate.isconfirmed and close > railU and close[1] <= railU[1]
// draw the rails on the last bar
var line eU = na
var line eL = na
var linefill eF = na
if barstate.islast
line.delete(eU)
line.delete(eL)
linefill.delete(eF)
if envOk
int ex2 = time + barMs * 20
eU := line.new(eHT.get(0), eHP.get(0), ex2, _rail(eHP, eHT, ex2), xloc = xloc.bar_time, color = color.new(c_env, 15), width = 1, style = line.style_dashed)
eL := line.new(eLT.get(0), eLP.get(0), ex2, _rail(eLP, eLT, ex2), xloc = xloc.bar_time, color = color.new(c_env, 15), width = 1, style = line.style_dashed)
if i_envFill
eF := linefill.new(eU, eL, color.new(c_env, 94))
// swing lines run with price until taken
if hsLn.size() > 0
for i = hsLn.size() - 1 to 0
line ln = hsLn.get(i)
if not na(ln) and not hsTk.get(i)
float y = ln.get_y1()
bool taken = hsHi.get(i) ? high > y : low < y
label lb = hsL.get(i)
if taken and time > ln.get_x1()
hsTk.set(i, true)
if i_hTaken == 'Hide'
ln.delete()
hsLn.set(i, line(na))
lb.delete()
else
ln.set_x2(time)
ln.set_style(line.style_dotted)
ln.set_color(color.new(color.gray, 60))
lb.set_x(time)
lb.set_textcolor(color.new(color.gray, 50))
lb.set_size(size.tiny)
else
ln.set_x2(time)
lb.set_x(time + barMs * 3)
// trend by change of character (updated in the order flow section)
var int tr = 0
// project a leg from a swing of this side?
// a leg from a swing of this side is a pullback against the trend
_pbk(int t) =>
tr != 0 and not ((tr == 1 and t == -1) or (tr == -1 and t == 1))
// a leg from a swing of this side goes with the higher-timeframe trend
_alg(int t) =>
htr != 0 and (t == -1 ? 1 : -1) == htr
_show(int t) =>
bool d = i_dir != 'With trend only' or not _pbk(t) or _alg(t)
d and not (i_htfFilt == 'Hide counter-trend' and _ctr(t))
// drawn dimmed: provisional, counter to the higher timeframe, or a pullback
// that the higher timeframe does not back
_dim(int t, bool lk) =>
not lk or _ctr(t) or (i_dir == 'With trend + faint pullbacks' and _pbk(t) and not _alg(t))
// the current swing the next leg is measured from
var int swT = 0 // 1 high, -1 low
var float swP = na
var int swTm = na
var float swA = na
var float ext = na // furthest price since the swing, in the leg's direction
var bool locked = false
var bool entered = false
// live projection: bands, level lines, level labels
var box[] pB = array.new_box()
var line[] pL = array.new_line()
var label[] pT = array.new_label()
var line pMk = na
// result tags of finished legs
var label[] hT = array.new_label()
var label lastTag = na
// the swing before the current one (start of the last finished leg)
var float prvP = na
var float prvA = na
// last settled swing on each side, and the structure tag of the latest high / low
var float lastH = na
var float lastL = na
var int lastHT = na
var int lastLT = na
var string sH = ''
var string sL = ''
// leg history: sizes (x ATR) by direction, and results
var float[] upS = array.new_float()
var float[] dnS = array.new_float()
var string[] rhy = array.new_string()
var bool lastUp = false
bool evLockU = false
bool evLockD = false
bool evInU = false
bool evInD = false
bool evFin = false
_wipeLive() =>
while pB.size() > 0
pB.shift().delete()
while pL.size() > 0
pL.shift().delete()
while pT.size() > 0
pT.shift().delete()
line.delete(pMk)
// level prices from the swing, in order: swing, 75%, 50%, 25%, 10%
_lvls(int t, float p, float a) =>
float d = t == -1 ? 1.0 : -1.0
array.from(p, p + d * i_l75 * a, p + d * i_l50 * a, p + d * i_l25 * a, p + d * i_l10 * a)
_lvTag(int i) =>
i == 0 ? 'Protected' : i == 1 ? 'T1 Expansion' : i == 2 ? 'T2 Typical' : i == 3 ? 'T3 Extended' : 'T4 Extreme'
// draw the ladder from x1 to x2: zone 75-50-25%, optional dotted 10%, swing anchor
_draw(int t, float p, float a, int x1, int x2, bool dim, bool past1) =>
float[] lv = _lvls(t, p, a)
int dB = dim ? 8 : 0
int dL = dim ? 35 : 0
// the exhaustion zone: T2 to T3, brighter once price has passed T1
pB.push(box.new(x1, math.max(lv.get(2), lv.get(3)), x2, math.min(lv.get(2), lv.get(3)), xloc = xloc.bar_time, bgcolor = color.new(_lc(3), math.min(98, i_band + dB - (past1 ? 10 : 0))), border_color = color.new(c_pr, 100)))
int last = i_show10 ? 4 : 3
for i = 1 to last
int fade = dL + (past1 and i == 1 ? 45 : 0)
pL.push(line.new(x1, lv.get(i), x2, lv.get(i), xloc = xloc.bar_time, color = color.new(_lc(i), math.min(90, (i == 2 ? 0 : 30) + fade)), width = i == 2 ? 2 : 1, style = i == 4 ? line.style_dotted : line.style_solid))
if i_lblPos != 'None'
bool lft = i_lblPos == 'Left'
pT.push(label.new(lft ? x1 : x2, lv.get(i), _lvTag(i) + ' ' + str.tostring(lv.get(i), format.mintick), xloc = xloc.bar_time, style = lft ? label.style_label_right : label.style_label_left, color = color.new(color.black, 100), textcolor = color.new(_lc(i), math.min(90, (i == 2 ? 0 : 15) + fade)), size = lblSz))
// anchor: the swing to the zone, dotted, at the swing candle
pL.push(line.new(x1, p, x1, lv.get(1), xloc = xloc.bar_time, color = color.new(c_pr, 30), style = line.style_dotted))
_res(float sz) =>
sz < i_l75 ? 'W' : sz > i_l25 ? 'E' : 'N'
_resTxt(float sz) =>
sz < i_l75 ? 'Weak' : sz > i_l25 ? 'Extended' : 'Normal'
_resCol(float sz) =>
sz < i_l75 ? color.gray : sz > i_l25 ? c_g25 : c_g50
_tagTxt(string st, float sz) =>
string r = _resTxt(sz) + ' ' + str.tostring(sz, '0.0')
i_tagSt == 'Structure' ? (st == '' ? '·' : st) : i_tagSt == 'Result' ? r : (st != '' ? st + ' · ' : '') + r
_tagCol(string st, float sz) =>
i_tagSt == 'Structure' ? (st == 'HH' or st == 'HL' ? c_up : st == 'LH' or st == 'LL' ? c_dn : color.gray) : _resCol(sz)
_push(float[] a, float v) =>
a.push(v)
if a.size() > 4
a.shift()
bool redraw = false
if barstate.isconfirmed
// furthest price since the swing
if swT == -1
ext := math.max(nz(ext, high), high)
if swT == 1
ext := math.min(nz(ext, low), low)
// pivots: the opposite side first, so a leg can complete before a new swing replaces
int first = swT == 1 ? -1 : 1
for pass = 0 to 1
int t = pass == 0 ? first : -first
float p = t == 1 ? pvH : pvL
if not na(p) and not na(aK)
if swT == 0
swT := t
swP := p
swTm := tK
swA := aK
ext := t == -1 ? hiK : loK
locked := false
entered := false
redraw := true
else if t == swT
// a more extreme swing on the same side replaces it: the projection moves
if (t == 1 and p > swP) or (t == -1 and p < swP)
// the finished leg into this swing grew: its tag follows
if not na(lastTag) and not na(prvP)
float sz2 = math.abs(p - prvP) / prvA
string st2 = t == 1 ? (na(lastH) ? '' : p > lastH ? 'HH' : 'LH') : (na(lastL) ? '' : p < lastL ? 'LL' : 'HL')
if t == 1
sH := st2
else
sL := st2
lastTag.set_xy(tK, p)
lastTag.set_text(_tagTxt(st2, sz2))
lastTag.set_textcolor(color.new(_tagCol(st2, sz2), 20))
float[] arr = lastUp ? upS : dnS
if arr.size() > 0
arr.set(arr.size() - 1, sz2)
if rhy.size() > 0
rhy.set(rhy.size() - 1, _res(sz2))
swP := p
swTm := tK
swA := aK
ext := t == -1 ? hiK : loK
locked := false
entered := false
redraw := true
else if math.abs(p - swP) >= i_lock * swA
// the leg is complete: the current swing is settled, the new one tagged
float sz = math.abs(p - swP) / swA
if swT == 1
lastH := swP
lastHT := swTm
else
lastL := swP
lastLT := swTm
string st = t == 1 ? (na(lastH) ? '' : p > lastH ? 'HH' : 'LH') : (na(lastL) ? '' : p < lastL ? 'LL' : 'HL')
if t == 1
sH := st
else
sL := st
lastUp := swT == -1
_push(lastUp ? upS : dnS, sz)
rhy.push(_res(sz))
if rhy.size() > 5
rhy.shift()
lastTag := label(na)
if i_keep > 0 and i_tagSt != 'Off'
lastTag := label.new(tK, p, _tagTxt(st, sz), xloc = xloc.bar_time, style = t == 1 ? label.style_label_down : label.style_label_up, color = color.new(color.black, 100), textcolor = color.new(_tagCol(st, sz), 20), size = size.tiny)
hT.push(lastTag)
while hT.size() > i_keep
hT.shift().delete()
_wipeLive()
prvP := swP
prvA := swA
evFin := true
swT := t
swP := p
swTm := tK
swA := aK
ext := t == -1 ? hiK : loK
locked := false
entered := false
redraw := true
// lock: price has moved far enough from the swing - full strength
if swT != 0 and not locked and not na(swA) and math.abs(ext - swP) >= i_lock * swA
locked := true
redraw := true
evLockU := swT == -1
evLockD := swT == 1
if redraw and swT != 0 and not na(swA)
_wipeLive()
if _show(swT)
_draw(swT, swP, swA, swTm, time, _dim(swT, locked), entered)
pMk := i_mark ? line.new(swTm, swP, swTm + barMs * 4, swP, xloc = xloc.bar_time, color = c_pr, width = 2) : line(na)
// zone reached (live)
if swT != 0 and not na(swA) and not entered
float z75 = _lvls(swT, swP, swA).get(1)
if swT == -1 ? high >= z75 : low <= z75
entered := true
evInU := swT == -1
evInD := swT == 1
_wipeLive()
if _show(swT)
_draw(swT, swP, swA, swTm, time, _dim(swT, locked), true)
pMk := i_mark ? line.new(swTm, swP, swTm + barMs * 4, swP, xloc = xloc.bar_time, color = c_pr, width = 2) : line(na)
// keep the live projection running to the current bar
if swT != 0
for b in pB
b.set_right(time)
for l in pL
if l.get_y1() == l.get_y2()
l.set_x2(time)
if i_lblPos == 'Right'
for x in pT
if x.get_x() != swTm
x.set_x(time)
// ============================================================
// === ORDER FLOW ===
// ============================================================
int of = sH == 'HH' and sL == 'HL' ? 1 : sH == 'LH' and sL == 'LL' ? -1 : 0
// the swing that would end the current order flow: the latest low in a bullish
// flow, the latest high in a bearish one (the live swing counts)
float hiRef = swT == 1 ? swP : lastH
float loRef = swT == -1 ? swP : lastL
int hiRefT = swT == 1 ? swTm : lastHT
int loRefT = swT == -1 ? swTm : lastLT
// trend by change of character: set by the first clear structure, then flipped
// only by a close through the protecting swing
var label[] chL = array.new_label()
var line[] chLn = array.new_line()
var line chLive = na
var label chLiveL = na
bool evChUp = false
bool evChDn = false
if barstate.isconfirmed
if tr == 0 and of != 0
tr := of
else if tr == 1 and not na(loRef) and close < loRef
tr := -1
evChDn := true
else if tr == -1 and not na(hiRef) and close > hiRef
tr := 1
evChUp := true
if (evChUp or evChDn) and i_chHist > 0
float lv = evChUp ? hiRef : loRef
int lt = evChUp ? hiRefT : loRefT
color cc = evChUp ? c_up : c_dn
if not na(lt)
chLn.push(line.new(lt, lv, time, lv, xloc = xloc.bar_time, color = color.new(cc, 25), width = 1))
chL.push(label.new(lt + (time - lt) / 2, lv, 'CHoCH', xloc = xloc.bar_time, style = evChUp ? label.style_label_down : label.style_label_up, color = color.new(color.black, 100), textcolor = color.new(cc, 10), size = size.tiny))
while chLn.size() > i_chHist
chLn.shift().delete()
chL.shift().delete()
// a CHoCH (here or on the higher timeframe) changes which legs are projected
bool htfFlip = htr != htr[1] and htr != 0
if (evChUp or evChDn or htfFlip) and swT != 0 and not na(swA)
_wipeLive()
if _show(swT)
_draw(swT, swP, swA, swTm, time, _dim(swT, locked), entered)
pMk := i_mark ? line.new(swTm, swP, swTm + barMs * 4, swP, xloc = xloc.bar_time, color = c_pr, width = 2) : line(na)
// higher-timeframe CHoCH level
var line hLn = na
var label hLb = na
if barstate.islast
line.delete(hLn)
label.delete(hLb)
if htfOk and i_htfLine and htr != 0 and not na(hLvl) and not na(hLvT)
color hc = htr == 1 ? c_dn : c_up
int hx2 = time + barMs * 6
hLn := line.new(hLvT, hLvl, hx2, hLvl, xloc = xloc.bar_time, color = color.new(hc, 10), width = 2, style = line.style_dashed)
hLb := label.new(hx2, hLvl, htfName + ' CHoCH ' + str.tostring(hLvl, format.mintick), xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = hc, size = size.small)
// live CHoCH level: the swing that would flip the trend
float chLvl = tr == 1 ? loRef : tr == -1 ? hiRef : na
int chT = tr == 1 ? loRefT : tr == -1 ? hiRefT : na
if barstate.islast
line.delete(chLive)
label.delete(chLiveL)
if i_choch and not na(chLvl) and not na(chT)
color cl = tr == 1 ? c_dn : c_up
int x2 = time + barMs * 6
chLive := line.new(chT, chLvl, x2, chLvl, xloc = xloc.bar_time, color = color.new(cl, 20), width = 1, style = line.style_dashed)
chLiveL := label.new(x2, chLvl, 'CHoCH ' + str.tostring(chLvl, format.mintick), xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = color.new(cl, 0), size = size.tiny)
_pos(string p) =>
p == 'Top Left' ? position.top_left : p == 'Bottom Right' ? position.bottom_right : p == 'Bottom Left' ? position.bottom_left : position.top_right
var table tb = table.new(_pos(i_pos), 2, 6, bgcolor = color.new(#131722, 10), border_width = 1, border_color = color.new(#363a45, 0))
if barstate.islast and i_tbl
color cg = color.new(#b2b5be, 0)
string tags = (sH == '' ? '-' : sH) + ' / ' + (sL == '' ? '-' : sL)
string ofT = tr == 0 ? 'Mixed ' + tags : (tr == 1 ? 'Bullish ' : 'Bearish ') + (of == tr ? tags : 'CHoCH, structure not yet confirmed')
color ofC = tr == 1 ? c_up : tr == -1 ? c_dn : #787b86
string chTx = na(chLvl) ? '-' : str.tostring(chLvl, format.mintick) + (na(A) or A == 0 ? '' : ' (' + str.tostring(math.abs(close - chLvl) / A, '0.0') + ' ATR away)')
int nP = 0
int nS = 0
for r in rhy
nP += r == 'E' ? 1 : 0
nS += r == 'W' ? 1 : 0
string rRead = rhy.size() < 3 ? '' : nP >= 3 ? ' · trending' : nS >= 3 ? ' · choppy' : ''
table.cell(tb, 0, 0, 'Stride', text_color = c_pr, text_size = size.small, text_halign = text.align_left)
string stg = '-'
if swT != 0 and not na(swA)
float run = na(ext) ? 0.0 : math.abs(ext - swP) / swA
stg := run < i_l75 ? 'building (before T1)' : run < i_l50 ? 'expanding (past T1)' : run < i_l25 ? 'in exhaustion zone' : 'extended (past T3)'
bool pb = swT != 0 and _pbk(swT)
string topT = swT == 0 ? '-' : (pb ? 'Pullback ' + (swT == -1 ? 'up ' : 'down ') + (_show(swT) ? stg : '· waiting for ' + (tr == 1 ? 'a higher low' : 'a lower high')) : (swT == -1 ? 'Leg up ' : 'Leg down ') + stg) + (locked ? '' : ' · provisional') + (_ctr(swT) ? ' · counter ' + htfName : pb and _alg(swT) ? ' · with ' + htfName : '') + rRead
table.cell(tb, 1, 0, topT, text_color = cg, text_size = size.small, text_halign = text.align_left)
table.cell(tb, 0, 1, 'Order flow', text_color = cg, text_size = size.small, text_halign = text.align_left)
table.cell(tb, 1, 1, ofT, text_color = ofC, text_size = size.small, text_halign = text.align_left)
if htfOk
bool legUp = swT == -1
string al = htr == 0 or swT == 0 ? '' : (legUp ? 1 : -1) == htr ? ' · aligned' : ' · counter'
string hTx = htr == 0 ? 'setting...' : (htr == 1 ? 'Bullish' : 'Bearish') + (na(hLvl) ? '' : ' · CHoCH ' + str.tostring(hLvl, format.mintick)) + al
if envOk
float w = railU - railL
float pos = w > 0 ? (close - railL) / w : na
string where = na(pos) ? '' : pos > 1 ? ' · above upper rail' : pos < 0 ? ' · below lower rail' : pos >= 0.8 ? ' · near upper rail' : pos <= 0.2 ? ' · near lower rail' : ' · mid-channel'
string eTx = envShape + (na(pos) ? '' : ' · price ' + str.tostring(math.round(pos * 100)) + '%') + where
table.cell(tb, 0, 4, htfName + ' channel', text_color = cg, text_size = size.small, text_halign = text.align_left)
table.cell(tb, 1, 4, eTx, text_color = c_env, text_size = size.small, text_halign = text.align_left)
table.cell(tb, 0, 3, htfName + ' flow', text_color = cg, text_size = size.small, text_halign = text.align_left)
table.cell(tb, 1, 3, hTx, text_color = htr == 1 ? c_up : htr == -1 ? c_dn : cg, text_size = size.small, text_halign = text.align_left)
if smtOk
string sTx = smTxH != '' and smTxL != '' ? smTxH + ' ' + smTxL : smTxH != '' ? smTxH : smTxL != '' ? smTxL : 'none'
table.cell(tb, 0, 5, 'SMT', text_color = cg, text_size = size.small, text_halign = text.align_left)
table.cell(tb, 1, 5, sTx, text_color = smTxH != '' and smTxL != '' ? #ffb74d : smTxH != '' ? c_dn : smTxL != '' ? c_up : #787b86, text_size = size.small, text_halign = text.align_left)
table.cell(tb, 0, 2, 'CHoCH at', text_color = cg, text_size = size.small, text_halign = text.align_left)
table.cell(tb, 1, 2, chTx, text_color = tr == 1 ? c_dn : tr == -1 ? c_up : cg, text_size = size.small, text_halign = text.align_left)
// target labels: note where a target meets a higher-timeframe rail or sits on a
// CHoCH level (that CHoCH label then folds into the target's)
if barstate.islast and not na(A)
float tol = A * 0.5
bool foldCh = false
bool foldH = false
for x in pT
string t0 = x.get_text()
if str.startswith(t0, 'T')
int k = str.pos(t0, ' ·')
string base = k >= 0 ? str.substring(t0, 0, k) : t0
float y = x.get_y()
string nt = ''
if envOk
nt := math.abs(y - railU) <= tol or math.abs(y - railL) <= tol ? ' · at ' + htfName + ' rail' : y > railU or y < railL ? ' · beyond ' + htfName + ' rail' : ''
if i_choch and not na(chLvl) and math.abs(y - chLvl) <= tol
nt := nt + ' · CHoCH'
foldCh := true
if htfOk and i_htfLine and not na(hLvl) and math.abs(y - hLvl) <= tol
nt := nt + ' · ' + htfName + ' CHoCH'
foldH := true
x.set_text(base + nt)
if foldCh
label.set_text(chLiveL, '')
if foldH
label.set_text(hLb, '')
// a hidden plot on the close keeps the script on the candles' price scale
plot(close, 'Price anchor', color = color.new(color.white, 100), display = display.pane, editable = false)
// ============================================================
// === ALERTS ===
// ============================================================
alertcondition(evLockU, 'Projection - leg up', 'Stride: swing low locked - up leg projected')
alertcondition(evLockD, 'Projection - leg down', 'Stride: swing high locked - down leg projected')
alertcondition(evInU, 'Zone reached - up', 'Stride: price reached the up-leg projection zone')
alertcondition(evInD, 'Zone reached - down', 'Stride: price reached the down-leg projection zone')
alertcondition(evChUp, 'CHoCH - up', 'Stride: change of character up - a close broke the swing high protecting the bearish trend')
alertcondition(evSmtH, 'SMT at a higher-timeframe high', 'Stride: SMT at the higher-timeframe swing high (ES / NQ)')
alertcondition(evSmtL, 'SMT at a higher-timeframe low', 'Stride: SMT at the higher-timeframe swing low (ES / NQ)')
alertcondition(evRailUp, 'HTF rail break - up', 'Stride: a close above the higher-timeframe upper rail')
alertcondition(evRailDn, 'HTF rail break - down', 'Stride: a close below the higher-timeframe lower rail')
alertcondition(htfOk and htfFlip and htr == 1, 'HTF CHoCH - up', 'Stride: higher-timeframe order flow turned bullish')
alertcondition(htfOk and htfFlip and htr == -1, 'HTF CHoCH - down', 'Stride: higher-timeframe order flow turned bearish')
alertcondition(evChDn, 'CHoCH - down', 'Stride: change of character down - a close broke the swing low protecting the bullish trend')
alertcondition(evFin, 'Leg finished', 'Stride: a projected leg completed - the next swing is set')