本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// © Florian Sänger
// Redistribution, decompilation or reuse of any part of this code is not permitted.
//@version=6
// ============================================================================
// PbD Indicator — v0.5.4
//
// Pure notification indicator: no strategy(), no connection to the
// engine or bot, no automated trading. Decisions and trades are made
// manually.
//
// Development stages:
// Stage 1: Impulse, range, volume profile (POC/VAH/VAL), P/b/D classification,
// range display
// Stage 2: Volume module (RVOL, volume type, verdict), status table
// Stage 3a: Setups S1 and S2 incl. D variant, labels
// Stage 3b: S3, S4, reclassify to D after trend stops
// Stage 4: Alerts (text/JSON)
//
// Setting up an alert (one per symbol; check the TradingView plan's
// alert quota first):
// Condition : "PbD" -> "Any alert() function call"
// Interval : Once Per Bar Close
// Message : leave empty, the text comes from alert() in the script
// Push : enable "App" notification (Text format)
// Do not change inputs after creating an alert: creating an alert
// freezes the input values. Create a new alert for new values.
//
// Flow per confirmed bar (Briefing section 2):
// Impulse -> Range (candidate -> active -> frozen -> invalidated)
// -> Volume profile -> P/b/D
//
// Decisions beyond the briefing (added there in 2.1/2.2):
// - A new impulse needs a window that only starts after the previous
// one ends. Otherwise the old window would immediately trigger again
// after a single counter bar, and a range would never form.
// - If price closes beyond the impulse extreme while the range is still
// a candidate, the impulse continues (small pullback, no range).
// - If a candidate is higher than rangeMaxAtr x ATR after minRangeBars,
// it restarts at the current bar, without an impulse reference (making it D).
// - A frozen range survives a new impulse, so retests remain
// possible. It is invalidated as soon as the next range becomes active.
// - Without volume data (sum 0), every bar counts with weight 1 (time profile).
//
// Timeframes: starting values for H1. For index intraday (M5/M15) as a start:
// minRangeBars 8, maxRetestBars 6.
// ============================================================================
IND_ID = "pbd-indicator"
IND_VERSION = "v0.5.4"
indicator(
title = "PbD — Impulse, Volume Profile & Setup Alerts (P/b/D)",
shorttitle = "PbD",
overlay = true,
// The volume profile reads back up to maxRangeBars bars.
max_bars_back = 500,
max_boxes_count = 500,
max_lines_count = 500,
max_labels_count = 500)
SRC_BODY = "Body"
SRC_HL = "High-Low"
VOL_AUTO = "Auto"
VOL_REQ = "Required"
VOL_HINT = "Hint"
VOL_OFF = "Off"
S1_RETEST = "Retest"
S1_NOW = "Immediate"
S2_POC = "POC"
S2_EDGE = "VAL (short: VAH)"
S4_POC = "POC"
S4_EDGE = "VAH (long: VAL)"
FMT_TEXT = "Text"
FMT_JSON = "JSON"
POS_TR = "Top right"
POS_TL = "Top left"
POS_BR = "Bottom right"
POS_BL = "Bottom left"
COL_P = #26a69a
COL_B = #ef5350
COL_D = #9598a1
// ─────────────────────────────────────────────────────────── Parameters
// Starting values from PBD-BRIEFING.md section 7. All thresholds are
// decisions, not requirements from the source — free to change when calibrating.
grpImp = "Impulse"
atrLen = input.int(14, "ATR period", minval=2, group=grpImp, tooltip="Number of bars for the ATR calculation (volatility measure), basis for all ATR thresholds in this indicator.")
impulseLen = input.int(5, "Impulse window (bars)", minval=2, maxval=50, group=grpImp, tooltip="Number of bars over which the body movement for impulse detection is measured.")
impulseAtr = input.float(2.0, "Minimum body movement = ATR x", minval=0.1, step=0.1, group=grpImp, tooltip="Minimum body movement over the impulse window, as a multiple of ATR. Higher = only strong impulses count.")
impulseEr = input.float(0.6, "Minimum efficiency ratio", minval=0.0, maxval=1.0, step=0.05, group=grpImp, tooltip="Minimum efficiency ratio (net movement divided by path traveled) over the impulse window. Higher = fewer pullbacks allowed, purer trend.")
grpRange = "Range & Profile"
minRangeBars = input.int(6, "Range active from (bars)", minval=2, group=grpRange, tooltip="Minimum number of bars before a range candidate counts as an active range (balance instead of trend).")
maxRangeBars = input.int(200, "Range grows at most (bars)", minval=10, maxval=400, group=grpRange, tooltip="After this many bars, a range candidate restarts if it has not yet become active.")
rangeMaxAtr = input.float(4.0, "Range height at most = ATR x", minval=0.5, step=0.25, group=grpRange, tooltip="Maximum height of the range candidate as a multiple of ATR. If exceeded, the range restarts, without an impulse reference.")
rangeMaxEr = input.float(0.5, "Range active up to efficiency ratio", minval=0.0, maxval=1.0, step=0.05, group=grpRange, tooltip="Maximum efficiency ratio of closing prices up to which a range still counts as balance instead of trend.")
rangeTolAtr = input.float(0.25, "Growth tolerance = ATR x", minval=0.0, step=0.05, group=grpRange, tooltip="Tolerance for the range growing beyond its previous boundaries, as a multiple of ATR.")
maxRangeAge = input.int(150, "Invalidation after (bars without event)", minval=10, group=grpRange, tooltip="After this many bars without a new event, a frozen range is invalidated.")
dMinBars = input.int(40, "D from range duration (bars)", minval=5, group=grpRange, tooltip="From this range duration in bars, the range automatically counts as D (balance), regardless of POC position.")
bins = input.int(24, "Profile levels", minval=5, maxval=60, group=grpRange, tooltip="Number of price levels for the volume profile (POC/VAH/VAL calculation). More levels = finer resolution.")
vaPercent = input.float(70, "Value Area (%)", minval=50, maxval=95, group=grpRange, tooltip="Share of volume that defines the value area (between VAH and VAL) around the POC.")
profileSource = input.string(SRC_BODY, "Profile source", options=[SRC_BODY, SRC_HL], group=grpRange, tooltip="Basis of the volume profile: only candle bodies or the full high-low range per bar.")
pocUpper = input.float(0.55, "P from POC position (0-1)", minval=0.5, maxval=1.0, step=0.05, group=grpRange, tooltip="From this normalized POC position (0 = range bottom, 1 = impulse start), the range counts as type P (bullish).")
pocLower = input.float(0.45, "b up to POC position (0-1)", minval=0.0, maxval=0.5, step=0.05, group=grpRange, tooltip="Up to this normalized POC position, the range counts as type b (bearish).")
// Counts across ranges: only one entry per direction is allowed per
// range, two consecutive stops could never occur within a single range.
dAfterFails = input.int(2, "D after consecutive trend stops (0 = off)", minval=0, group=grpRange, tooltip="After this many consecutive trend setup stops, every further range is reclassified to D. 0 = feature off.")
grpSetup = "Setups"
useS1 = input.bool(true, "S1 Break-in", group=grpSetup, tooltip="Enable S1 Break-in: entry after returning into the value area, following a brief excursion.")
useS2 = input.bool(true, "S2 Breakout + Retest", group=grpSetup, tooltip="Enable S2 Breakout + Retest: entry in breakout direction after confirmation.")
useS3 = input.bool(true, "S3 Failed Breakout (Counter-trend)", group=grpSetup, tooltip="Enable S3 Failed Breakout: entry against a failed breakout (counter-trend).")
useS4 = input.bool(true, "S4 Reversal (Counter-trend)", group=grpSetup, tooltip="Enable S4 Reversal: entry on reversal after a confirmed breakout (counter-trend).")
useD = input.bool(true, "Setups in D ranges", group=grpSetup, tooltip="Also allow setups in balance ranges (type D), there as counter-trend at both edges.")
maxBarsOutside = input.int(3, "Excursion at most (bars)", minval=1, group=grpSetup, tooltip="At most this many consecutive closes outside the value area, for an excursion to still count as a return setup (S1/S3).")
maxRetestBars = input.int(10, "Retest deadline (bars)", minval=1, group=grpSetup, tooltip="Deadline in bars within which a waiting setup (S1/S2) must reach its retest, otherwise it expires.")
retestTolAtr = input.float(0.2, "Retest tolerance = ATR x", minval=0.0, step=0.05, group=grpSetup, tooltip="Tolerance at the retest level, as a multiple of ATR.")
breakoutHoldBars = input.int(2, "S2 without volume: closes outside", minval=1, group=grpSetup, tooltip="Without usable volume, this many consecutive closes outside the value area count as breakout confirmation for S2/S4.")
strongBodyAtr = input.float(1.0, "S3/S4 large body = ATR x", minval=0.1, step=0.1, group=grpSetup, tooltip="Minimum candle body size for S3/S4 triggers, as a multiple of ATR.")
stopBufAtr = input.float(0.2, "Stop buffer = ATR x", minval=0.0, step=0.05, group=grpSetup, tooltip="Additional buffer to the stop-loss level, as a multiple of ATR.")
targetR = input.float(2.0, "S2 target = R x", minval=0.5, step=0.25, group=grpSetup, tooltip="Price target (T1) for S2 as a multiple of risk (R), when no other target is given.")
minRR = input.float(1.0, "Min. R:R to T1", minval=0.0, step=0.1, group=grpSetup, tooltip="Minimum reward-risk ratio to T1. If it falls short, the setup counts as blocked (no entry alert).")
s1EntryMode = input.string(S1_RETEST, "S1 entry", options=[S1_RETEST, S1_NOW], group=grpSetup, tooltip="Wait for retest before S1 entry, or enter immediately at the trigger.")
s2StopMode = input.string(S2_POC, "S2 stop behind", options=[S2_POC, S2_EDGE], group=grpSetup, tooltip="Place the stop-loss for S2 behind the POC or behind the range edge (VAL/VAH).")
s4StopMode = input.string(S4_POC, "S4 stop behind", options=[S4_POC, S4_EDGE], group=grpSetup, tooltip="Place the stop-loss for S4 behind the POC or behind the range edge (VAH/VAL).")
s2RetestQuiet = input.bool(false, "S2 retest quieter than breakout", group=grpSetup, tooltip="Only count the S2 retest if it was quieter (lower RVOL) than the original breakout.")
grpVol = "Volume"
// Auto: mode follows syminfo.volumetype (Briefing 4.3). The other values
// override this for every symbol the indicator is applied to.
volMode = input.string(VOL_AUTO, "Volume mode", options=[VOL_AUTO, VOL_REQ, VOL_HINT, VOL_OFF], group=grpVol, tooltip="Auto detects the mode automatically from the symbol's volume type; the other values force a classification for all symbols.")
volLen = input.int(20, "RVOL average (bars)", minval=2, group=grpVol, tooltip="Number of bars for the moving average that current volume is compared against for RVOL.")
volBreakout = input.float(1.5, "Breakout confirmed from RVOL", minval=0.1, step=0.1, group=grpVol, tooltip="From this RVOL, a breakout counts as volume-confirmed.")
volReturn = input.float(1.2, "Return confirmed from RVOL", minval=0.1, step=0.1, group=grpVol, tooltip="From this RVOL, a return into the value area counts as volume-confirmed.")
volDryMax = input.float(1.0, "Dry-up: average RVOL below", minval=0.1, step=0.1, group=grpVol, tooltip="Average RVOL during an excursion, below which volume counts as dried up.")
volExpBars = input.int(3, "Expansion over (bars)", minval=2, maxval=10, group=grpVol, tooltip="Number of bars over which volume must rise for it to count as expansion.")
grpAlert = "Alerts"
// Setup alert: setup detected, entry still pending (retest). Setups with
// immediate entry (S3, S4, S1 "Immediate") only report the entry.
alertSetup = input.bool(false, "Alert on setup active", group=grpAlert, tooltip="Trigger an alert as soon as a setup is detected and waiting for entry (retest).")
alertEntry = input.bool(true, "Alert on entry", group=grpAlert, tooltip="Trigger an alert as soon as a setup is actually entered.")
alertFormat = input.string(FMT_TEXT, "Alert format", options=[FMT_TEXT, FMT_JSON], group=grpAlert, tooltip="Format of the alert message: readable text for push notifications or compact JSON for further processing.")
grpDraw = "Display"
keepProfiles = input.int(5, "Visible ranges", minval=2, maxval=10, group=grpDraw, tooltip="Number of most recently active ranges shown simultaneously on the chart.")
showHistogram = input.bool(false, "Profile histogram", group=grpDraw, tooltip="Show the volume profile as histogram bars on the left side of the range box.")
showTable = input.bool(true, "Status table", group=grpDraw, tooltip="Show a status table with current profile type, range status, RVOL, volume mode, and last setup.")
tablePosition = input.string(POS_TR, "Table position", options=[POS_TR, POS_TL, POS_BR, POS_BL], group=grpDraw, tooltip="Position of the status table on the chart.")
showPoc = input.bool(true, "POC line", inline="poc", group=grpDraw, tooltip="Show/hide the POC line (point of control, most traded price level of the range).")
pocColor = input.color(color.red, "", inline="poc", group=grpDraw, tooltip="Color of the POC line and its text label.")
showVah = input.bool(true, "VAH line", inline="vah", group=grpDraw, tooltip="Show/hide the VAH line (upper edge of the value area).")
vahColor = input.color(color.orange, "", inline="vah", group=grpDraw, tooltip="Color of the VAH line and its text label.")
showVal = input.bool(true, "VAL line", inline="val", group=grpDraw, tooltip="Show/hide the VAL line (lower edge of the value area).")
valColor = input.color(color.orange, "", inline="val", group=grpDraw, tooltip="Color of the VAL line and its text label.")
showImpulse = input.bool(true, "Mark impulse candles", inline="imp", group=grpDraw, tooltip="Highlight the candles that formed the respective impulse and thereby triggered the range.")
impulseColor = input.color(color.gray, "", inline="imp", group=grpDraw, tooltip="Color of the impulse candle highlight.")
showEntryMarks = input.bool(true, "Mark entry (triangle)", group=grpDraw, tooltip="In addition to the setup label, show a triangle marker exactly at the entry price (green = long, red = short).")
// ─────────────────────────────────────────────────────────── Base quantities
atr = ta.atr(atrLen)
bodyTop = math.max(open, close)
bodyBot = math.min(open, close)
// Impulse (Briefing 2.1): body movement over impulseLen bars plus efficiency
// ratio as a measure of "no large pullbacks".
impMove = close - open[impulseLen - 1]
impPath = math.sum(math.abs(close - close[1]), impulseLen)
impEr = impPath > 0 ? math.abs(close - close[impulseLen]) / impPath : 0.0
impNow = math.abs(impMove) >= impulseAtr * atr and impEr >= impulseEr
impNowDir = impMove > 0 ? 1 : -1
// Without volume data (sum so far 0), every bar is weighted equally.
noVolume = ta.cum(nz(volume)) == 0
// ─────────────────────────────────────────────────────────── Volume
// Briefing section 4. The verdict depends on the volume type (4.3):
// real volume is required, tick volume is only a hint, no volume is off.
volSma = ta.sma(nz(volume), volLen)
rvol = volSma > 0 ? nz(volume) / volSma : na
volType = na(syminfo.volumetype) ? "n/a" : syminfo.volumetype
effMode = volMode != VOL_AUTO ? volMode :
noVolume or volType == "n/a" ? VOL_OFF :
volType == "tick" ? VOL_HINT : VOL_REQ
// Without usable volume, S2 only relies on the path over breakoutHoldBars.
volUsable = effMode != VOL_OFF
// Expansion (4.1): volume rises over volExpBars bars. Equal values are
// allowed ("3 to 4, 4, 5"), but it must end higher than it started.
// Whether these bars are all breakout bars is checked in stage 3.
volExpanding() =>
bool ok = nz(volume) > nz(volume[volExpBars - 1])
for i = 0 to volExpBars - 2
if nz(volume[i]) < nz(volume[i + 1])
ok := false
ok
volExpand = volExpanding()
// Dry-up (4.1): RVOL of the excursion bars falls from bar to bar, or lies
// on average below volDryMax. Stage 3 collects the values per excursion.
dryUp(array<float> rv) =>
int n = rv.size()
bool falling = n >= 2
if n >= 2
for i = 1 to n - 1
if rv.get(i) >= rv.get(i - 1)
falling := false
n > 0 and (falling or rv.avg() < volDryMax)
// Verdict for a volume condition: "confirmed" | "weak" | "tick" | "na".
// These codes go into the JSON alert as-is, volText() turns them into display text.
volVerdict(bool confirmed) =>
effMode == VOL_OFF ? "na" :
volType == "tick" and effMode != VOL_REQ ? "tick" :
confirmed ? "confirmed" : "weak"
volText(string verdict) =>
verdict == "confirmed" ? "✅ confirmed" :
verdict == "weak" ? "⚠️ weak" :
verdict == "tick" ? "⚠️ Tick" : "– n/a"
// Only in Required mode does unconfirmed volume block the entry alert.
volBlocks(bool confirmed) =>
effMode == VOL_REQ and not confirmed
// ─────────────────────────────────────────────────────────── Setup types
// Excursion: consecutive closes outside the value area, one per side.
type Excursion
int side // +1 above VAH, -1 below VAL
int startBar
int bars = 1
float extreme // highest high or lowest low
float firstRvol // RVOL of the first bar outside
bool expanded = false // expansion during the excursion
bool s2Checked = false // S2 triggered for this excursion
array<float> rv // RVOL of all excursion bars
// Lifecycle: "watch" (waiting for entry) -> "open" -> "done".
type Setup
string id // "S1" .. "S4"
int dir // +1 long, -1 short
bool counter // counter-trend
int eventBar
int deadline // last bar for the entry
float sl
float evRvol // RVOL of the triggering candle
string verdict // volume verdict, see volVerdict()
string kind = "D" // profile type of the range when triggered
bool volOk
string stage = "watch"
string outcome = "" // "target" | "stop" | "expired" | "cancel" | "blocked"
string note = ""
int entryBar = na
float entry = na
float t1 = na
float t2 = na
float rr = na
label lb = na
float ly = na // label anchor, outside the range box
// Last setup for the status table. An array because functions may not
// reassign global variables, but may change their contents.
var array<Setup> recentSetups = array.new<Setup>()
// Consecutive trend setups stopped out, across ranges. Reset to 0 when
// a trend setup reaches T1. Same array trick as above.
var array<int> failStreak = array.from(0)
// Briefing 2.4: after dAfterFails consecutive trend stops, a larger
// balance phase is expected.
forceD() =>
dAfterFails > 0 and failStreak.get(0) >= dAfterFails
// Boundaries of this larger balance area [low, high]: envelope of all
// reclassified ranges. The reclassification ends when an impulse leaves it
// ("applies until a strong impulse leaves the area"). Resetting only via T1 of
// a trend setup was not enough: in D, trend setups only exist as a
// volume-confirmed breakout, so never without usable volume.
var array<float> dArea = array.new_float(2, na)
// Entry price per direction for the chart marker (plotshape). Same array
// trick: enter() may change the contents, not reassign the variable.
// Reset on every bar, see the impulse block.
var array<float> entryMarkLong = array.new_float(1, na)
var array<float> entryMarkShort = array.new_float(1, na)
newExcursion(int side) =>
Excursion.new(side = side, startBar = bar_index, extreme = side > 0 ? high : low,
firstRvol = rvol, rv = array.from(nz(rvol)))
method extend(Excursion e) =>
e.bars := e.bars + 1
e.extreme := e.side > 0 ? math.max(e.extreme, high) : math.min(e.extreme, low)
e.rv.push(nz(rvol))
if e.bars >= volExpBars and volExpand
e.expanded := true
e
dirText(int dir) =>
dir > 0 ? "LONG" : "SHORT"
fmtPrice(float p) =>
str.tostring(p, format.mintick)
method headline(Setup s) =>
s.id + " " + dirText(s.dir) + " (" + (s.counter ? "Counter-trend" : "Trend") + ")"
method levels(Setup s) =>
"Entry " + fmtPrice(s.entry) + " · SL " + fmtPrice(s.sl) +
"\nT1 " + fmtPrice(s.t1) + (na(s.rr) ? "" : " (" + str.tostring(s.rr, "0.0") + "R)") +
(na(s.t2) ? "" : " · T2 " + fmtPrice(s.t2))
method volLine(Setup s) =>
"Vol: RVOL " + (na(s.evRvol) ? "–" : str.tostring(s.evRvol, "0.0")) + " " + volText(s.verdict)
method summary(Setup s) =>
string st = s.stage == "watch" ? "waiting for retest" :
s.stage == "open" ? "open" :
s.outcome == "target" ? "T1 reached" :
s.outcome == "stop" ? "stop" :
s.outcome == "blocked" ? "no alert" :
s.outcome == "cancel" ? "discarded" : "expired"
s.id + " " + dirText(s.dir) + " · " + st
// One label per setup, created at the trigger and updated with every
// step. Detailed only for actual entries (open, target, stop). Everything
// else is a shorthand, the details are in the tooltip. Finished setups
// without a target are faded.
method render(Setup s) =>
color c = s.dir > 0 ? COL_P : COL_B
string body = s.stage == "watch" or na(s.entry) ? "waiting for retest" : s.levels()
string tail = s.stage != "done" ? "" :
s.outcome == "target" ? "\n→ T1 reached" :
s.outcome == "stop" ? "\n→ Stop" :
s.outcome == "blocked" ? "\n→ no alert: " + s.note :
s.outcome == "cancel" ? "\n→ discarded" : "\n→ expired"
string full = s.headline() + "\n" + body + "\n" + s.volLine() + tail
bool entr = s.stage == "open" or s.outcome == "target" or s.outcome == "stop"
string mark = s.stage == "watch" ? " …" :
s.outcome == "blocked" ? " ✗" : " –"
string txt = entr ? full : s.id + (s.dir > 0 ? " ▲" : " ▼") + mark
color bg = s.stage == "done" and s.outcome != "target" ? color.new(c, 55) : c
if na(s.lb)
s.lb := label.new(bar_index, nz(s.ly, s.dir > 0 ? low : high), txt, color = bg, textcolor = color.white,
style = s.dir > 0 ? label.style_label_up : label.style_label_down, size = entr ? size.small : size.tiny, tooltip = full)
else
s.lb.set_text(txt)
s.lb.set_color(bg)
s.lb.set_tooltip(full)
s.lb.set_size(entr ? size.small : size.tiny)
s
method finish(Setup s, string outcome) =>
s.stage := "done"
s.outcome := outcome
s.render()
// ─────────────────────────────────────────────────────────── Alerts
// Briefing section 5.
tfText() =>
timeframe.isseconds ? "S" + str.tostring(timeframe.multiplier) :
timeframe.isminutes and timeframe.multiplier % 60 == 0 ? "H" + str.tostring(timeframe.multiplier / 60) :
timeframe.isminutes ? "M" + str.tostring(timeframe.multiplier) :
timeframe.isdaily ? "D" : timeframe.isweekly ? "W" : "MN"
setupName(string id) =>
id == "S1" ? "Break-in" : id == "S2" ? "Breakout" : id == "S3" ? "Failed breakout" : "Reversal"
// JSON number: na becomes null. Prices rounded to tick, without thousands separators.
jsonPrice(float v) =>
na(v) ? "null" : str.tostring(math.round_to_mintick(v))
jsonNum(float v) =>
na(v) ? "null" : str.tostring(v, "0.00")
method alertHead(Setup s) =>
"PbD · " + syminfo.ticker + " " + tfText() + " · " + s.kind + " · " + s.id + " " +
setupName(s.id) + " " + dirText(s.dir) + " (" + (s.counter ? "Counter-trend" : "Trend") + ")"
// Text for push notifications. Format as in the briefing:
// PbD · EURUSD H1 · P · S2 Breakout LONG (Trend)
// Entry 1.0850 · SL 1.0820 · T1 1.0910 (2.0R)
// Vol: RVOL 1.8 ⚠️ Tick
method alertText(Setup s, string stage) =>
string mid = stage == "entry" ?
"Entry " + fmtPrice(s.entry) + " · SL " + fmtPrice(s.sl) + " · T1 " + fmtPrice(s.t1) +
" (" + str.tostring(s.rr, "0.0") + "R)" + (na(s.t2) ? "" : " · T2 " + fmtPrice(s.t2)) :
"Setup active, waiting for retest (" + str.tostring(maxRetestBars) + " bars) · SL " + fmtPrice(s.sl)
s.alertHead() + "\n" + mid + "\n" + s.volLine()
// Compact, because TradingView limits alert messages to 300 characters.
method alertJson(Setup s, string stage) =>
'{"src":"pbd","sym":"' + syminfo.ticker + '","tf":"' + timeframe.period + '","prof":"' + s.kind +
'","setup":"' + s.id + '","dir":"' + dirText(s.dir) + '","kind":"' + (s.counter ? "counter" : "trend") +
'","stage":"' + stage + '","entry":' + jsonPrice(s.entry) + ',"sl":' + jsonPrice(s.sl) +
',"t1":' + jsonPrice(s.t1) + ',"t2":' + jsonPrice(s.t2) + ',"rr":' + jsonNum(s.rr) +
',"rvol":' + jsonNum(s.evRvol) + ',"vol":"' + s.verdict + '"}'
// Central place for setup events:
// "setup" - detected (status table)
// "watch" - waiting for entry -> setup alert
// "entry" - entry -> entry alert
// All calls run inside barstate.isconfirmed, so alerts only fire
// on confirmed bars.
method notify(Setup s, string stage) =>
if stage == "setup"
recentSetups.push(s)
if recentSetups.size() > 1
recentSetups.shift()
else if (stage == "watch" and alertSetup) or (stage == "entry" and alertEntry)
string st = stage == "entry" ? "entry" : "setup"
alert(alertFormat == FMT_JSON ? s.alertJson(st) : s.alertText(st), alert.freq_once_per_bar_close)
s
// ─────────────────────────────────────────────────────────── Range
type Range
int startBar
int endBar // last bar in the profile
int lastEvent // for maxRangeAge
float bodyHi = na // range boundaries = body extremes
float bodyLo = na
float wickHi = na // profile boundaries incl. wicks
float wickLo = na
int impulseDir = 0 // +1 / -1, 0 = range without impulse
float impulseStart = na // body extreme at impulse start (S4 target)
float impulseExt = na // body extreme at impulse end
int impStartBar = na // trigger candles: first/last bar of the impulse
int impEndBar = na
float impHi = na // high/low over the impulse bars
float impLo = na
box impBx = na // highlight of the impulse candles
bool active = false
bool frozen = false
int frozenBar = na
bool dead = false
float poc = na
float vah = na
float val = na
string kind = "D" // "P" | "b" | "D"
float pocPos = na // 0 = impulse start or range bottom, 1 = top
string why = "" // reason for D
array<float> vols = na
box bx = na
line lnPoc = na
line lnVah = na
line lnVal = na
label lbKind = na // type, POC position, reason for D
label lbPoc = na // text label at the line end
label lbVah = na
label lbVal = na
array<box> hist = na
Excursion exUp = na
Excursion exDn = na
Setup longSu = na // at most one open setup per direction
Setup shortSu = na
bool longUsed = false // entry alert per direction already used
bool shortUsed = false
bool resolved = false // a setup has reached target or stop
int outBars = 0 // consecutive closes outside the range
bool brokeUp = false // breakout above VAH with volume (for S4)
bool brokeDn = false
bool forcedD = false // reclassified to D after trend stops
kindColor(string kind) =>
kind == "P" ? COL_P : kind == "b" ? COL_B : COL_D
setLine(line l, int x1, float y, int x2, color c) =>
l.set_xy1(x1, y)
l.set_xy2(x2, y)
l.set_color(c)
newRange(int dir, float start, float ext) =>
Range.new(startBar = bar_index, endBar = bar_index, lastEvent = bar_index,
impulseDir = dir, impulseStart = start, impulseExt = ext)
// High/low over the impulse bars [fromBar, toBar], for highlighting the
// trigger candles. Both boundaries lie in the past, hence indexed via
// bar_index - i, as in calcProfile/closeEr.
impulseRange(int fromBar, int toBar) =>
float hi = na
float lo = na
for i = fromBar to toBar
int k = bar_index - i
hi := na(hi) ? high[k] : math.max(hi, high[k])
lo := na(lo) ? low[k] : math.min(lo, low[k])
[hi, lo]
method grow(Range r) =>
r.endBar := bar_index
r.bodyHi := na(r.bodyHi) ? bodyTop : math.max(r.bodyHi, bodyTop)
r.bodyLo := na(r.bodyLo) ? bodyBot : math.min(r.bodyLo, bodyBot)
r.wickHi := na(r.wickHi) ? high : math.max(r.wickHi, high)
r.wickLo := na(r.wickLo) ? low : math.min(r.wickLo, low)
r
// Candidate too high: restart at the current bar, without an impulse reference.
method restart(Range r) =>
r.startBar := bar_index
r.lastEvent := bar_index
r.bodyHi := na
r.bodyLo := na
r.wickHi := na
r.wickLo := na
r.impulseDir := 0
r.impulseStart := na
r.impulseExt := na
r.impStartBar := na
r.impEndBar := na
r.impHi := na
r.impLo := na
r.grow()
// Volume profile (Briefing 2.3): volume per bar distributed evenly across the
// levels of its body (or high-low range). A doji falls into one level.
// Value area: starting from the POC, add whichever neighboring level has more volume.
method calcProfile(Range r) =>
float span = r.wickHi - r.wickLo
if span > 0
float step = span / bins
array<float> vols = array.new_float(bins, 0.0)
for i = r.startBar to r.endBar
int k = bar_index - i
float a = profileSource == SRC_BODY ? math.min(open[k], close[k]) : low[k]
float b = profileSource == SRC_BODY ? math.max(open[k], close[k]) : high[k]
float w = noVolume ? 1.0 : nz(volume[k])
int i0 = math.max(0, math.min(bins - 1, math.floor((a - r.wickLo) / step)))
int i1 = math.max(0, math.min(bins - 1, math.floor((b - r.wickLo) / step)))
float share = w / (i1 - i0 + 1)
for j = i0 to i1
vols.set(j, vols.get(j) + share)
float total = vols.sum()
if total > 0
int pocIdx = vols.indexof(vols.max())
float target = total * vaPercent / 100
float acc = vols.get(pocIdx)
int up = pocIdx + 1
int dn = pocIdx - 1
while acc < target and (up < bins or dn >= 0)
float vUp = up < bins ? vols.get(up) : -1.0
float vDn = dn >= 0 ? vols.get(dn) : -1.0
if vUp >= vDn
acc += vUp
up += 1
else
acc += vDn
dn -= 1
r.poc := r.wickLo + (pocIdx + 0.5) * step
r.vah := r.wickLo + up * step
r.val := r.wickLo + (dn + 1) * step
r.vols := vols
r
// Reclassification after trend stops; reclassified ranges extend the balance area.
method applyForceD(Range r) =>
if r.kind != "D" and forceD()
r.kind := "D"
r.forcedD := true
if r.forcedD
dArea.set(0, na(dArea.get(0)) ? r.bodyLo : math.min(dArea.get(0), r.bodyLo))
dArea.set(1, na(dArea.get(1)) ? r.bodyHi : math.max(dArea.get(1), r.bodyHi))
r
// Efficiency ratio of closing prices since the range started: net movement
// divided by path traveled. A balance oscillates (small), a trend runs
// through (close to 1). Needs at least two bars.
method closeEr(Range r) =>
float path = 0.0
for i = r.startBar + 1 to r.endBar
int k = bar_index - i
path += math.abs(close[k] - close[k + 1])
path > 0 ? math.abs(close - close[bar_index - r.startBar]) / path : 0.0
// Classification (Briefing 2.4), including reclassification after trend
// stops (forceD). P and b describe the shape of impulse and range together:
// thin stem (impulse), thick body (range). The POC position is therefore
// measured across the span from the impulse start to the opposite range
// edge, not within the range alone. There, the POC of a range sitting on top
// of the impulse would often land near the middle.
method classify(Range r) =>
float lo = r.impulseDir > 0 ? math.min(nz(r.impulseStart, r.bodyLo), r.bodyLo) : r.bodyLo
float hi = r.impulseDir < 0 ? math.max(nz(r.impulseStart, r.bodyHi), r.bodyHi) : r.bodyHi
int len = r.endBar - r.startBar + 1
r.pocPos := hi > lo ? (r.poc - lo) / (hi - lo) : 0.5
r.kind := len >= dMinBars ? "D" :
r.impulseDir > 0 and r.pocPos >= pocUpper ? "P" :
r.impulseDir < 0 and r.pocPos <= pocLower ? "b" : "D"
r.why := r.kind != "D" ? "" :
len >= dMinBars ? str.tostring(len) + " bars" :
r.impulseDir == 0 ? "no impulse" : "POC doesn't fit"
r.applyForceD()
// Short info in the box: type, POC position, reason if D.
method boxText(Range r) =>
r.kind + " · POC " + str.tostring(r.pocPos, "0.00") +
(r.forcedD ? " · after trend stops" : r.why != "" ? " · " + r.why : "")
// Draw box and lines up to the current bar. Dashed = still growing,
// solid = frozen.
method draw(Range r) =>
color c = kindColor(r.kind)
if na(r.bx)
r.bx := box.new(r.startBar, r.bodyHi, bar_index, r.bodyLo, border_color = c, bgcolor = color.new(c, 90))
r.lnPoc := line.new(r.startBar, r.poc, bar_index, r.poc, width = 2)
r.lnVah := line.new(r.startBar, r.vah, bar_index, r.vah, width = 1, style = line.style_dotted)
r.lnVal := line.new(r.startBar, r.val, bar_index, r.val, width = 1, style = line.style_dotted)
r.lbPoc := label.new(bar_index, r.poc, "POC", style = label.style_label_right,
color = color.new(color.white, 100), size = size.tiny)
r.lbVah := label.new(bar_index, r.vah, "VAH", style = label.style_label_right,
color = color.new(color.white, 100), size = size.tiny)
r.lbVal := label.new(bar_index, r.val, "VAL", style = label.style_label_right,
color = color.new(color.white, 100), size = size.tiny)
if not na(r.impStartBar)
r.impBx := box.new(r.impStartBar, r.impHi, r.impEndBar, r.impLo,
border_color = na, bgcolor = color.new(impulseColor, 85))
if not na(r.impBx)
r.impBx.set_bgcolor(showImpulse ? color.new(impulseColor, 85) : color.new(impulseColor, 100))
r.bx.set_lefttop(r.startBar, r.bodyHi)
r.bx.set_rightbottom(bar_index, r.bodyLo)
r.bx.set_border_color(c)
r.bx.set_bgcolor(color.new(c, 90))
r.bx.set_border_style(r.frozen ? line.style_solid : line.style_dashed)
setLine(r.lnPoc, r.startBar, r.poc, bar_index, showPoc ? pocColor : color.new(pocColor, 100))
setLine(r.lnVah, r.startBar, r.vah, bar_index, showVah ? vahColor : color.new(vahColor, 100))
setLine(r.lnVal, r.startBar, r.val, bar_index, showVal ? valColor : color.new(valColor, 100))
r.lbPoc.set_xy(bar_index, r.poc)
r.lbPoc.set_textcolor(showPoc ? pocColor : color.new(pocColor, 100))
r.lbVah.set_xy(bar_index, r.vah)
r.lbVah.set_textcolor(showVah ? vahColor : color.new(vahColor, 100))
r.lbVal.set_xy(bar_index, r.val)
r.lbVal.set_textcolor(showVal ? valColor : color.new(valColor, 100))
if na(r.lbKind)
r.lbKind := label.new(r.startBar, r.bodyHi, "", style = label.style_label_lower_left,
color = color.new(color.white, 100), size = size.small)
r.lbKind.set_xy(r.startBar, r.bodyHi)
r.lbKind.set_text(r.boxText())
r.lbKind.set_textcolor(c)
r
// Histogram from the left edge of the range, at most 40% of its length
// wide. On the right of the range it would be in the way while it is still extending.
method drawHist(Range r) =>
if na(r.hist)
r.hist := array.new<box>()
for b in r.hist
b.delete()
r.hist.clear()
if showHistogram and not na(r.vols)
float vMax = r.vols.max()
float step = (r.wickHi - r.wickLo) / bins
int width = math.max(3, math.round((r.endBar - r.startBar + 1) * 0.4))
color c = kindColor(r.kind)
if vMax > 0
for j = 0 to bins - 1
float v = r.vols.get(j)
if v > 0
float y0 = r.wickLo + j * step
bool inVa = y0 >= r.val - step * 0.5 and y0 < r.vah - step * 0.5
int w = math.max(1, math.round(width * v / vMax))
r.hist.push(box.new(r.startBar, y0 + step, r.startBar + w, y0,
border_color = na, bgcolor = color.new(c, inVa ? 60 : 80)))
r
method kill(Range r) =>
r.dead := true
if not na(r.longSu) and r.longSu.stage == "watch"
r.longSu.finish("expired")
if not na(r.shortSu) and r.shortSu.stage == "watch"
r.shortSu.finish("expired")
r.draw()
method remove(Range r) =>
r.bx.delete()
r.lnPoc.delete()
r.lnVah.delete()
r.lnVal.delete()
r.lbKind.delete()
r.lbPoc.delete()
r.lbVah.delete()
r.lbVal.delete()
if not na(r.impBx)
r.impBx.delete()
if not na(r.hist)
for b in r.hist
b.delete()
r
// ─────────────────────────────────────────────────────────── Setups
// Briefing section 3. Described for P (long), b is mirrored, D
// gets S1 at both edges (counter-trend) and breakouts only with volume.
method hasOpen(Range r) =>
(not na(r.longSu) and r.longSu.stage != "done") or (not na(r.shortSu) and r.shortSu.stage != "done")
// At most one open setup per range and direction. A finished one
// (expired, discarded, blocked) may be replaced, a running one never.
method canStart(Range r, int dir) =>
Setup s = dir > 0 ? r.longSu : r.shortSu
bool used = dir > 0 ? r.longUsed : r.shortUsed
not used and (na(s) or s.stage == "done")
// Trend setups exist only long in P, only short in b, and both
// directions in D (can be disabled via useD).
method allows(Range r, int dir) =>
r.kind == "D" ? useD : dir > 0 ? r.kind == "P" : r.kind == "b"
// Label anchor: long below the candle, short above. If the candle covers
// the range, the label goes below/above the entire range, otherwise it would
// sit inside the box. Calculated including wicks, because VAH/VAL can reach that far.
method labelY(Range r, int dir) =>
dir > 0 ? (low > r.bodyHi ? low : math.min(low, r.wickLo)) :
(high < r.bodyLo ? high : math.max(high, r.wickHi))
method start(Range r, Setup s) =>
s.kind := r.kind
s.ly := r.labelY(s.dir)
if s.dir > 0
r.longSu := s
else
r.shortSu := s
r.lastEvent := bar_index
s.render()
s.notify("setup")
// Entry at the close price. Without t1, targetR x risk applies. Below minRR or
// with missing required volume, the setup is only marked: no
// entry alert, and the direction stays free for a later setup.
method enter(Range r, Setup s, float t1, float t2) =>
float risk = s.dir * (close - s.sl)
s.entryBar := bar_index
s.entry := close
s.t1 := na(t1) and risk > 0 ? close + s.dir * targetR * risk : t1
s.t2 := t2
s.rr := risk > 0 and not na(s.t1) ? s.dir * (s.t1 - close) / risk : na
r.lastEvent := bar_index
s.ly := r.labelY(s.dir)
s.lb.set_xy(bar_index, s.ly)
if na(s.rr) or s.rr < minRR
s.stage := "done"
s.outcome := "blocked"
s.note := na(s.rr) ? "no risk" : "R:R " + str.tostring(s.rr, "0.0") + " < " + str.tostring(minRR, "0.0")
else if volBlocks(s.volOk)
s.stage := "done"
s.outcome := "blocked"
s.note := "Volume weak (required)"
else
s.stage := "open"
if s.dir > 0
r.longUsed := true
entryMarkLong.set(0, close)
else
r.shortUsed := true
entryMarkShort.set(0, close)
s.notify("entry")
s.render()
// S1 gets T1 = opposite value area edge, T2 = range edge.
method enterS1(Range r, Setup s) =>
r.enter(s, s.dir > 0 ? r.vah : r.val, s.dir > 0 ? r.bodyHi : r.bodyLo)
// Waiting setups: wait for the retest, discard on a close on the wrong
// side, let it expire after maxRetestBars. Open setups: stop or
// T1. Both in the same bar counts as a stop.
method advance(Range r, Setup s) =>
if not na(s) and s.stage == "watch" and bar_index > s.eventBar
// S1 long tests the VAL, S2 long the VAH, short mirrored respectively.
float lvl = (s.id == "S1") == (s.dir > 0) ? r.val : r.vah
float tol = retestTolAtr * atr
bool back = s.dir > 0 ? close < lvl : close > lvl
bool retest = s.dir > 0 ? low <= lvl + tol and close > lvl : high >= lvl - tol and close < lvl
bool quiet = s.id != "S2" or not s2RetestQuiet or nz(rvol) < nz(s.evRvol)
if back
s.finish("cancel")
else if retest and quiet
if s.id == "S1"
r.enterS1(s)
else
r.enter(s, na, na)
else if bar_index >= s.deadline
s.finish("expired")
else if not na(s) and s.stage == "open" and bar_index > s.entryBar
bool stopHit = s.dir > 0 ? low <= s.sl : high >= s.sl
bool targetHit = s.dir > 0 ? high >= s.t1 : low <= s.t1
if stopHit or targetHit
s.finish(stopHit ? "stop" : "target")
r.resolved := true
r.lastEvent := bar_index
if not s.counter
failStreak.set(0, stopHit ? failStreak.get(0) + 1 : 0)
if not stopHit
dArea.fill(na)
r.applyForceD()
r
// Large candle in direction dir (S3 return, S4 break).
strongBody(int dir) =>
math.abs(close - open) >= strongBodyAtr * atr and (dir > 0 ? close > open : close < open)
// Return into the value area after an excursion of at most
// maxBarsOutside bars. Two readings of the same event:
// S3 Failed Breakout (counter-trend): return with a large body,
// immediate entry, target the opposite value area edge. Short in P,
// long in b, both in D. Volume confirmed when the breakout candle
// has RVOL < 1.0 and the return candle has RVOL >= volReturn.
// S1 Break-in: entry after retest (or immediately). Long in P, short in b,
// both as counter-trend in D. Volume confirmed when the excursion
// dries up and the return candle has RVOL >= volReturn.
// In D both can fit the same direction. S3 wins then, because the large
// return candle is the more precise pattern.
method onReturn(Range r, Excursion e) =>
int dir = -e.side
bool s3Ok = useS3 and (r.kind == "D" ? useD : dir > 0 ? r.kind == "b" : r.kind == "P")
bool s1Ok = useS1 and r.allows(dir)
if e.bars <= maxBarsOutside and r.canStart(dir)
float sl = e.extreme - dir * stopBufAtr * atr
if s3Ok and strongBody(dir)
bool ok = nz(e.firstRvol) < 1.0 and nz(rvol) >= volReturn
Setup s = Setup.new(id = "S3", dir = dir, counter = true, eventBar = bar_index,
deadline = bar_index, sl = sl, evRvol = rvol, verdict = volVerdict(ok), volOk = ok)
r.start(s)
r.enter(s, dir > 0 ? r.vah : r.val, na)
else if s1Ok
bool ok = dryUp(e.rv) and nz(rvol) >= volReturn
Setup s = Setup.new(id = "S1", dir = dir, counter = r.kind == "D", eventBar = bar_index,
deadline = bar_index + maxRetestBars, sl = sl,
evRvol = rvol, verdict = volVerdict(ok), volOk = ok)
r.start(s)
if s1EntryMode == S1_NOW
r.enterS1(s)
else
s.notify("watch")
r
// S4 Reversal (counter-trend): in P, after a breakout above VAH with volume,
// a close below VAL with a large body -> short, target the start of the P
// impulse. Mirrored in b. Volume confirmed at RVOL >= volBreakout. Checked
// on the first bar of a new excursion.
method onReversal(Range r, int dir) =>
bool fits = dir < 0 ? r.kind == "P" and r.brokeUp : r.kind == "b" and r.brokeDn
if useS4 and fits and strongBody(dir) and not na(r.impulseStart) and r.canStart(dir)
bool ok = nz(rvol) >= volBreakout
float edge = s4StopMode == S4_POC ? r.poc : dir < 0 ? r.vah : r.val
Setup s = Setup.new(id = "S4", dir = dir, counter = true, eventBar = bar_index,
deadline = bar_index, sl = edge - dir * stopBufAtr * atr,
evRvol = rvol, verdict = volVerdict(ok), volOk = ok)
r.start(s)
r.enter(s, r.impulseStart, na)
r
// Breakout with volume: breakout candle RVOL >= volBreakout or expansion.
method volBreak(Excursion e) =>
volUsable and (nz(e.firstRvol) >= volBreakout or e.expanded)
// S2 Breakout: close beyond the value area and volume confirmed
// (breakout candle RVOL >= volBreakout or expansion) or breakoutHoldBars
// closes outside. From D only with volume.
method onBreakout(Range r, Excursion e) =>
int dir = e.side
if useS2 and not e.s2Checked and r.allows(dir) and r.canStart(dir)
bool volConf = e.volBreak()
bool hold = r.kind != "D" and e.bars >= breakoutHoldBars
if volConf or hold
e.s2Checked := true
float edge = s2StopMode == S2_POC ? r.poc : dir > 0 ? r.val : r.vah
Setup s = Setup.new(id = "S2", dir = dir, counter = false, eventBar = bar_index,
deadline = bar_index + maxRetestBars, sl = edge - dir * stopBufAtr * atr,
evRvol = e.firstRvol, verdict = volVerdict(volConf), volOk = volConf)
r.start(s)
s.notify("watch")
r
// Per bar on the frozen range: first advance running setups, then
// update excursions and check for new events.
method processSetups(Range r) =>
r.advance(r.longSu)
r.advance(r.shortSu)
bool above = close > r.vah
bool below = close < r.val
if not below and not na(r.exDn)
r.onReturn(r.exDn)
r.exDn := na
if not above and not na(r.exUp)
r.onReturn(r.exUp)
r.exUp := na
if above
bool fresh = na(r.exUp)
r.exUp := fresh ? newExcursion(1) : r.exUp.extend()
if fresh
r.onReversal(1)
r.onBreakout(r.exUp)
// For S4: breakout with volume, or without usable volume over
// breakoutHoldBars (as with S2).
if r.exUp.volBreak() or (not volUsable and r.exUp.bars >= breakoutHoldBars)
r.brokeUp := true
if below
bool fresh = na(r.exDn)
r.exDn := fresh ? newExcursion(-1) : r.exDn.extend()
if fresh
r.onReversal(-1)
r.onBreakout(r.exDn)
if r.exDn.volBreak() or (not volUsable and r.exDn.bars >= breakoutHoldBars)
r.brokeDn := true
r
// ─────────────────────────────────────────────────────────── State
var Range cur = na // candidate or active, growing range
var Range fz = na // frozen range (setup phase)
var array<Range> shown = array.new<Range>()
var int impDir = 0 // current impulse: +1 / -1, 0 = none
var float impStart = na
var float impExt = na
var int impStartBar = na // first bar of the current impulse
var int lastImpEnd = -1
if barstate.isconfirmed and not na(atr) and not na(impPath)
entryMarkLong.set(0, na)
entryMarkShort.set(0, na)
// ── Impulse
if impDir != 0
if impDir > 0 ? close < close[1] : close > close[1]
// First close against the direction: the impulse ends at the bar
// before, the range starts with this bar.
// If the impulse has left the balance area after trend stops,
// the reclassification to D ends (Briefing 2.4).
if forceD() and (na(dArea.get(0)) or impExt > dArea.get(1) or impExt < dArea.get(0))
failStreak.set(0, 0)
dArea.fill(na)
cur := newRange(impDir, impStart, impExt)
cur.impStartBar := impStartBar
cur.impEndBar := bar_index - 1
[impHi, impLo] = impulseRange(impStartBar, bar_index - 1)
cur.impHi := impHi
cur.impLo := impLo
lastImpEnd := bar_index - 1
impDir := 0
else
impExt := impDir > 0 ? math.max(impExt, bodyTop) : math.min(impExt, bodyBot)
else if not na(cur) and not cur.active and cur.impulseDir != 0 and (cur.impulseDir > 0 ? close > cur.impulseExt : close < cur.impulseExt)
// Small pullback: impulse continues, candidate discarded.
impDir := cur.impulseDir
impStart := cur.impulseStart
impExt := impDir > 0 ? bodyTop : bodyBot
cur := na
else if impNow and bar_index - (impulseLen - 1) > lastImpEnd and (impNowDir > 0 ? close > close[1] : close < close[1])
impDir := impNowDir
impStart := impNowDir > 0 ? math.min(open[impulseLen - 1], close[impulseLen - 1]) : math.max(open[impulseLen - 1], close[impulseLen - 1])
impExt := impNowDir > 0 ? bodyTop : bodyBot
impStartBar := bar_index - (impulseLen - 1)
// A new impulse invalidates the growing range (Briefing 2.2 a). A
// frozen range (fz) remains, see the header comment. If the impulse
// candle closes outside the value area, that is also the
// breakout: freeze the range instead of invalidating it, otherwise
// exactly the strongest breakouts would never get a retest (S2).
if not na(cur) and cur.active
if close > cur.vah or close < cur.val
if not na(fz)
fz.kill()
cur.frozen := true
cur.frozenBar := bar_index
cur.lastEvent := bar_index
fz := cur
else
cur.kill()
cur := na
// ── Range
if impDir == 0
if na(cur) and na(fz)
cur := newRange(0, na, na)
if not na(cur)
int len = bar_index - cur.startBar + 1
if not cur.active
cur.grow()
if len >= minRangeBars
// Too high: restart. If price is still running through instead
// of oscillating: stay a candidate until it oscillates or
// becomes too high.
if cur.bodyHi - cur.bodyLo > rangeMaxAtr * atr or len > maxRangeBars
cur.restart()
else if cur.closeEr() <= rangeMaxEr
cur.active := true
cur.calcProfile()
cur.classify()
cur.drawHist()
// Next range active: invalidate the frozen predecessor.
if not na(fz)
fz.kill()
fz := na
shown.push(cur)
if shown.size() > keepProfiles
shown.shift().remove()
else if close > cur.vah or close < cur.val or len > maxRangeBars
// Close outside the value area: freeze (setup phase).
// POC/VAH/VAL no longer change from here on.
cur.frozen := true
cur.frozenBar := bar_index
cur.lastEvent := bar_index
fz := cur
cur := na
else if bodyTop <= cur.bodyHi + rangeTolAtr * atr and bodyBot >= cur.bodyLo - rangeTolAtr * atr
cur.grow()
cur.lastEvent := bar_index
cur.calcProfile()
cur.classify()
cur.drawHist()
// ── Setups on the frozen range
if not na(fz) and not na(fz.vah)
fz.processSetups()
// Invalidation (b): a setup has reached target or stop, none is
// running anymore, and price closes outside the range.
bool outside = close > fz.bodyHi or close < fz.bodyLo
fz.outBars := outside ? fz.outBars + 1 : 0
// Invalidation (d): price moves away from the range without a setup, for
// longer than the retest deadline. Without this rule the range would keep
// living until an impulse was detected or maxRangeAge ran out, and no new
// range would form in the meantime (sluggish moves don't meet the impulse criterion).
if (fz.resolved and outside or fz.outBars > maxRetestBars) and not fz.hasOpen()
fz.kill()
fz := na
// ── Invalidation (c): too long without an event
if not na(fz) and bar_index - fz.lastEvent >= maxRangeAge
fz.kill()
fz := na
// ── Display
if not na(cur) and cur.active
cur.draw()
if not na(fz)
fz.draw()
// ─────────────────────────────────────────────────────────── Status table
var table tbl = na
tableRow(table t, int row, string key, string value, color valueColor) =>
t.cell(0, row, key, text_color = color.gray, text_halign = text.align_left, text_size = size.small)
t.cell(1, row, value, text_color = valueColor, text_halign = text.align_left, text_size = size.small)
if showTable and barstate.islast
if na(tbl)
string tblPos = tablePosition == POS_TR ? position.top_right :
tablePosition == POS_TL ? position.top_left :
tablePosition == POS_BR ? position.bottom_right : position.bottom_left
tbl := table.new(tblPos, 2, 7, bgcolor = color.new(#131722, 15),
border_color = color.new(color.gray, 70), border_width = 1)
// The range shown is the one setups are attached to: the frozen one,
// otherwise the active one.
Range r = not na(fz) ? fz : not na(cur) and cur.active ? cur : na
color rc = na(r) ? color.gray : kindColor(r.kind)
string kind = na(r) ? "–" : r.boxText()
string auct = na(r) ? "–" : r.kind == "P" ? "bullish" : r.kind == "b" ? "bearish" : "Balance"
string status = not na(fz) ? "frozen for " + str.tostring(bar_index - fz.frozenBar) + " bars" :
not na(cur) and cur.active ? "active, growing (" + str.tostring(bar_index - cur.startBar + 1) + " bars)" :
not na(cur) ? "candidate (" + str.tostring(bar_index - cur.startBar + 1) + " bars)" : "none"
if impDir != 0
status := "Impulse " + (impDir > 0 ? "up" : "down") + " · " + status
string vType = volType == "tick" ? "Tick" : volType == "n/a" or noVolume ? "none" : "real (" + volType + ")"
string vMode = effMode + (volMode == VOL_AUTO ? " (auto)" : " (manual)")
tableRow(tbl, 0, "Profile", kind, rc)
tableRow(tbl, 1, "Auction", auct, rc)
tableRow(tbl, 2, "Range", status, color.white)
tableRow(tbl, 3, "RVOL", na(rvol) ? "–" : str.tostring(rvol, "0.00"), na(rvol) ? color.gray : rvol >= volBreakout ? COL_P : color.white)
tableRow(tbl, 4, "Volume", vType + " · " + vMode, effMode == VOL_REQ ? color.white : color.orange)
tableRow(tbl, 5, "Last setup", recentSetups.size() > 0 ? recentSetups.last().summary() : "–", color.white)
// Version visible: shows immediately whether the chart runs the current state.
tableRow(tbl, 6, "Version", IND_VERSION, color.gray)
// ─────────────────────────────────────────────────────────── Entry marker
// plotshape() absolutely must be at the top level (not inside methods
// or if blocks), hence here at the end of the script, fed from the two
// array variables that enter() sets per bar.
plotshape(showEntryMarks ? entryMarkLong.get(0) : na, title = "Long entry",
style = shape.triangleup, location = location.absolute, color = COL_P, size = size.small)
plotshape(showEntryMarks ? entryMarkShort.get(0) : na, title = "Short entry",
style = shape.triangledown, location = location.absolute, color = COL_B, size = size.small)