本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// ═══════════════════════════════════════════════════════════════════════════════════════════
// PRICE ACCEPTANCE vs REJECTION ENGINE [PARE]
// Advanced Intraday Market Behaviour Analysis Indicator | Pine Script® v6
// ═══════════════════════════════════════════════════════════════════════════════════════════
//
// AUTHOR ............... Michael_Fx_Trader
// PUBLISHER ............ Michael_Fx_Trader
// RIGHTS HOLDER ........ Michael_Fx_Trader (all rights reserved)
// INDICATOR NAME ....... Price Acceptance vs Rejection Engine [PARE]
// DASHBOARD NAME ....... PRICE BEHAVIOUR TERMINAL
//
// ───────────────────────────────────────────────────────────────────────────────────────────
// AUTHOR VERIFICATION & ORIGINALITY DECLARATION
// ───────────────────────────────────────────────────────────────────────────────────────────
// I, Michael_Fx_Trader, declare and verify that:
//
// 1. This script is my ORIGINAL work. It was designed and implemented from scratch as an
// independent price-behaviour analysis engine built on measurable OHLCV data.
// 2. It is NOT a copy, fork, clone, re-skin or derivative of any other published or private
// TradingView script, open-source or closed-source.
// 3. It is NOT a renamed RSI, MACD, moving-average crossover, SMC, ICT, BOS/CHoCH, FVG,
// order-block or liquidity-sweep indicator. Every score, zone, label and signal is produced
// by the calculations contained in this file.
// 4. I am the sole author, publisher and rights holder. No part of this code may be copied,
// re-published, re-sold or re-distributed without my written permission.
// 5. The indicator displays NO invented win-rates, trade counts or performance statistics.
//
// DISCLAIMER
// This tool is for technical analysis and education only. All scores represent TECHNICAL
// EVIDENCE, not a probability of winning. It is not financial advice. Trading involves risk.
//
// ───────────────────────────────────────────────────────────────────────────────────────────
// ENGINE OVERVIEW (see inline sections for the exact maths)
// ───────────────────────────────────────────────────────────────────────────────────────────
// 1. Acceptance Engine ........ 0-100 score, bullish + bearish, 7 independent measurements
// 2. Rejection Engine ......... 0-100 score, bullish + bearish, 9 independent measurements
// 3. Reference Area Engine .... pivot + close-clustering areas, ATR-merged, 6 lifecycle states
// 4. Failed Acceptance ........ state machine: breakout -> developing acceptance -> failure
// 5. Transition Engine ........ debounced behaviour-mode machine + two sequence detectors
// 6. Price Staying Power ...... ATR-normalised hold-quality score
// 7. Conflict Detector ........ buyer/seller conflict classification, NO CLEAR CONTROL
// 8. Behaviour Momentum ....... efficiency / progress / follow-through / decay (no RSI/MACD)
// 9. Combined Evidence ........ configurable weights, correlation de-duplication, penalty
// 10. Signal Engine ............ EARLY / CONFIRMED / HIGH-CONVICTION, cooldown, no duplicates
// 11. Trade Plan Engine ........ ENTRY / SL / TP1-TP3, frozen after confirmation
// 12. Visual System + Dashboard (PRICE BEHAVIOUR TERMINAL) + Multi-Timeframe context
//
// ───────────────────────────────────────────────────────────────────────────────────────────
// REPAINTING / DELAY NOTES (honest disclosure)
// ───────────────────────────────────────────────────────────────────────────────────────────
// * Signals, labels and trade plans are produced on CONFIRMED bars only (barstate.isconfirmed).
// * Once a signal/plan is created, its Entry / SL / TP levels are never moved or recalculated.
// * Pivot-based areas use ta.pivothigh / ta.pivotlow, which can only be known "Pivot Length"
// bars AFTER the pivot. An area is therefore created with that delay; the zone is drawn
// starting at the pivot bar for readability, but no score or signal uses it before it exists.
// * Higher-timeframe data uses request.security(..., expr[1], lookahead_on): ONLY the last
// fully closed HTF bar is used, so no future information leaks into the chart timeframe.
// * Volume is optional. If the symbol has no volume, the volume factor is neutral (1.0).
// ═══════════════════════════════════════════════════════════════════════════════════════════
indicator(title = "Price Acceptance vs Rejection Engine [PARE]", shorttitle = "PARE", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_polylines_count = 100, max_bars_back = 500)
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 0 — INPUTS
// ═══════════════════════════════════════════════════════════════════════════════════════════
G_GEN = "A. General Settings"
G_ACC = "B. Acceptance Engine"
G_REJ = "C. Rejection Engine"
G_AREA = "D. Reference Areas"
G_FAIL = "E. Failed Acceptance"
G_MOM = "F. Momentum"
G_SIG = "G. Signals and Risk"
G_WGT = "G2. Evidence Weights"
G_HTF = "H. Multi-Timeframe"
G_VIS = "I. Visual Settings"
G_COL = "I2. Colours"
// A. General
sensitivity = input.float(1.0, "Analysis Sensitivity", minval = 0.5, maxval = 2.0, step = 0.1, group = G_GEN, tooltip = "Higher = reacts to smaller distances / faster evidence. 1.0 is tuned for 5-minute charts. Use ~0.8 on 1m, ~1.2 on 15m.")
refMode = input.string("Adaptive Area", "Reference Calculation Mode", options = ["Rolling Midpoint", "Rolling High/Low", "User Price", "Adaptive Area"], group = G_GEN)
lookbackLen = input.int(40, "Default Lookback", minval = 10, maxval = 150, group = G_GEN)
userPrice = input.price(0.0, "User-Defined Price Level (mode: User Price)", group = G_GEN)
minSignalScore = input.int(60, "Minimum Signal Score", minval = 30, maxval = 100, group = G_GEN)
cooldownBars = input.int(8, "Cooldown Bars Between Signals", minval = 1, maxval = 100, group = G_GEN)
trendFilter = input.bool(false, "Optional Trend-Context Filter", group = G_GEN)
trendLen = input.int(100, "Trend Filter Length (EMA)", minval = 20, maxval = 400, group = G_GEN)
// B. Acceptance
accLen = input.int(20, "Acceptance Lookback", minval = 8, maxval = 100, group = G_ACC)
minCloses = input.int(3, "Minimum Consecutive Closes", minval = 2, maxval = 20, group = G_ACC)
minAccPct = input.int(55, "Minimum Acceptance % (closes on one side)", minval = 30, maxval = 100, group = G_ACC)
stayThr = input.int(60, "Staying Power Threshold", minval = 30, maxval = 100, group = G_ACC)
// C. Rejection
wickSens = input.float(0.40, "Wick Sensitivity (min wick / range)", minval = 0.2, maxval = 0.8, step = 0.05, group = G_REJ)
minFailed = input.int(2, "Minimum Failed Attempts", minval = 1, maxval = 10, group = G_REJ)
rejLen = input.int(12, "Rejection Lookback", minval = 5, maxval = 60, group = G_REJ)
retBars = input.int(2, "Return-Speed Threshold (bars)", minval = 1, maxval = 10, group = G_REJ)
trigRejMin = input.int(60, "Rejection Score Needed To Trigger Setup", minval = 40, maxval = 95, group = G_REJ)
// D. Reference areas
areaWidthATR = input.float(0.8, "Area Width (x ATR)", minval = 0.2, maxval = 3.0, step = 0.1, group = G_AREA)
clusterTol = input.float(0.5, "ATR Clustering / Merge Tolerance", minval = 0.0, maxval = 3.0, step = 0.1, group = G_AREA)
minInter = input.int(2, "Minimum Interactions", minval = 1, maxval = 10, group = G_AREA)
maxAreas = input.int(3, "Maximum Active Areas", minval = 1, maxval = 6, group = G_AREA)
pivLen = input.int(3, "Pivot Length (detection delay = this many bars)", minval = 2, maxval = 10, group = G_AREA)
// E. Failed acceptance
failConfirm = input.int(3, "Confirmation Bars", minval = 2, maxval = 8, group = G_FAIL)
failRetThr = input.float(0.15, "Return Threshold (x ATR below/above area)", minval = 0.0, maxval = 1.5, step = 0.05, group = G_FAIL)
failEstablish = input.float(2.5, "Invalidation: Move Considered Established (x ATR)", minval = 1.0, maxval = 6.0, step = 0.25, group = G_FAIL)
failExpire = input.int(40, "Invalidation: Tracking Expires After (bars)", minval = 10, maxval = 200, group = G_FAIL)
// F. Momentum
momLen = input.int(14, "Momentum Lookback", minval = 6, maxval = 60, group = G_MOM)
atrLen = input.int(14, "ATR Period", minval = 5, maxval = 50, group = G_MOM)
effThr = input.float(0.35, "Efficiency Threshold", minval = 0.1, maxval = 0.9, step = 0.05, group = G_MOM)
decaySens = input.float(1.0, "Decay Sensitivity", minval = 0.3, maxval = 3.0, step = 0.1, group = G_MOM)
// G. Signals & risk
minConviction = input.int(78, "Minimum Conviction Score (HIGH-CONVICTION)", minval = 50, maxval = 100, group = G_SIG)
stopPad = input.float(0.25, "Stop Padding (x ATR)", minval = 0.0, maxval = 3.0, step = 0.05, group = G_SIG)
tp1R = input.float(1.0, "TP1 Risk/Reward", minval = 0.25, step = 0.25, group = G_SIG)
tp2R = input.float(2.0, "TP2 Risk/Reward", minval = 0.5, step = 0.25, group = G_SIG)
tp3R = input.float(3.0, "TP3 Risk/Reward", minval = 0.75, step = 0.25, group = G_SIG)
minRiskATR = input.float(0.5, "Minimum Risk Distance (x ATR)", minval = 0.1, step = 0.1, group = G_SIG)
maxRiskATR = input.float(4.0, "Maximum Risk Distance (x ATR)", minval = 0.5, step = 0.5, group = G_SIG)
maxPlans = input.int(3, "Maximum Historical Trade Plans", minval = 1, maxval = 20, group = G_SIG)
planWidth = input.int(14, "Trade Plan Box Width (bars)", minval = 4, maxval = 60, group = G_SIG)
dynAlerts = input.bool(true, "Send Dynamic alert() Messages With Price Levels", group = G_SIG, tooltip = "Create ONE alert on this indicator using 'Any alert() function call' to receive messages with levels. alertcondition() entries remain available separately.")
// G2. Weights
wAcc = input.float(25.0, "Weight: Acceptance", minval = 1.0, maxval = 100.0, group = G_WGT)
wRej = input.float(25.0, "Weight: Rejection", minval = 1.0, maxval = 100.0, group = G_WGT)
wStay = input.float(15.0, "Weight: Staying Power", minval = 1.0, maxval = 100.0, group = G_WGT)
wFail = input.float(15.0, "Weight: Failed-Acceptance Evidence", minval = 1.0, maxval = 100.0, group = G_WGT)
wMom = input.float(20.0, "Weight: Behaviour Momentum", minval = 1.0, maxval = 100.0, group = G_WGT)
wConf = input.float(30.0, "Conflict Penalty Strength (%)", minval = 0.0, maxval = 100.0, group = G_WGT)
// H. Multi-timeframe
useHtf = input.bool(true, "Use Higher-Timeframe Confirmation", group = G_HTF)
htf1 = input.timeframe("15", "Confirmation Timeframe", group = G_HTF)
useHtf2 = input.bool(false, "Use Second Higher Timeframe", group = G_HTF)
htf2 = input.string("60", "Second Timeframe", options = ["30", "60", "240"], group = G_HTF)
htfMode = input.string("Not Opposing", "Confirmation Requirement", options = ["Not Opposing", "Supporting"], group = G_HTF)
showHtfRow = input.bool(false, "Show HTF Row In Dashboard", group = G_HTF)
// I. Visual
showDash = input.bool(true, "Show Dashboard", group = G_VIS)
dashPosIn = input.string("Top Right", "Dashboard Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = G_VIS)
showStrip = input.bool(true, "Show Bottom Status Strip", group = G_VIS)
showZones = input.bool(true, "Show Reference Zones", group = G_VIS)
showGlow = input.bool(true, "Show Zone Glow / Rejection Footprint", group = G_VIS)
showMidline = input.bool(true, "Show Zone Midpoint", group = G_VIS)
showZoneLabels = input.bool(true, "Show Zone Labels", group = G_VIS)
zoneLabelOff = input.int(60, "Zone Label Offset From Last Bar", minval = 10, maxval = 200, group = G_VIS)
showRejMarkers = input.bool(true, "Show Rejection Markers", group = G_VIS)
showRings = input.bool(true, "Show Dashed Highlight Circles", group = G_VIS)
showFailed = input.bool(true, "Show Failed Acceptance", group = G_VIS)
failFormal = input.bool(false, "Use Formal Names (FAILED BULLISH ACCEPTANCE)", group = G_VIS)
showTransitions= input.bool(false, "Show Transition Labels On Chart", group = G_VIS)
showSignals = input.bool(true, "Show BUY / SELL Signals", group = G_VIS)
showEarly = input.bool(true, "Show EARLY Setups", group = G_VIS)
showPlans = input.bool(true, "Show Trade Plans (Entry/SL/TP)", group = G_VIS)
// I2. Colours
cBull = input.color(#00E676, "Bullish", group = G_COL)
cBear = input.color(#FF1744, "Bearish", group = G_COL)
cAcc = input.color(#2979FF, "Acceptance Zone", group = G_COL)
cAmb = input.color(#FFB300, "Conflict / Uncertainty", group = G_COL)
cGrey = input.color(#787B86, "Neutral", group = G_COL)
cCyan = input.color(#00E5FF, "Bullish Rejection", group = G_COL)
cPurple = input.color(#B388FF, "Bearish Rejection Bar", group = G_COL)
cFail = input.color(#D500F9, "Failed Acceptance", group = G_COL)
cNavy = input.color(#0B1530, "Dashboard Background", group = G_COL)
cHeader = input.color(#0D47A1, "Dashboard Header", group = G_COL)
cFrame = input.color(#2979FF, "Dashboard Frame", group = G_COL)
cDim = #1C2A4A
cBlueM = #00B0FF
cWhite = color.white
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 1 — TYPES AND GLOBAL STORAGE
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Area states: 0 UNTESTED | 1 DEVELOPING | 2 ACCEPTED | 3 REJECTED | 4 BALANCED | 5 INVALIDATED
type Area
float top
float bot
float mid
int inter = 0
int turns = 0
float acc = 0.0
float rej = 0.0
float pri = 0.0
int state = 0
int lastBar = 0
int lastType = 0
int born = 0
int origin = 0 // 1 = born from pivot low (support-like), -1 = pivot high (resistance-like), 0 = close cluster
int accDir = 1
int rejDir = 1
bool touched = false
box bx
box glow
line ml
label lb
label tx
type Plan
int dir = 0
int entryBar = 0
float entry
float sl
float tp1
float tp2
float tp3
float inv
int status = 0 // 0 active | 1 stop loss | 2 TP3 complete | 3 invalidated
int hit = 0 // highest TP reached
int endBar = 0
box riskBox
box rewBox
line lnEntry
line ln1
line ln2
line ln3
line lnSl
label lbEntry
label lbSl
label lb1
label lb2
label lb3
var array<Area> areas = array.new<Area>()
var array<Plan> plans = array.new<Plan>()
var array<label> evLabels = array.new<label>()
var array<box> evBoxes = array.new<box>()
var array<polyline> evPolys = array.new<polyline>()
var array<float> bins = array.new_float(20, 0.0)
var Plan curPlan = na
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 2 — GENERIC HELPERS
// ═══════════════════════════════════════════════════════════════════════════════════════════
f_clamp(float x, float lo, float hi) =>
math.max(lo, math.min(hi, x))
f_band(float s, bool rejection) =>
s <= 30.0 ? "WEAK" : s <= 50.0 ? "DEVELOPING" : s <= 70.0 ? "MODERATE" : s <= 85.0 ? "STRONG" : rejection ? "EXTREME" : "VERY STRONG"
f_pos(string s) =>
s == "Top Right" ? position.top_right : s == "Top Left" ? position.top_left : s == "Bottom Right" ? position.bottom_right : position.bottom_left
f_trimLabels(array<label> arr, int maxN) =>
while arr.size() > maxN
label.delete(arr.shift())
f_trimBoxes(array<box> arr, int maxN) =>
while arr.size() > maxN
box.delete(arr.shift())
f_trimPolys(array<polyline> arr, int maxN) =>
while arr.size() > maxN
polyline.delete(arr.shift())
// Dashed ring (circle highlight) built as a closed polyline in bar/price space
f_ring(float cx, float cy, float rx, float ry, color c, int w) =>
array<chart.point> pts = array.new<chart.point>()
for k = 0 to 11
float ang = 2.0 * math.pi * k / 12.0
int px = int(math.round(cx + rx * math.cos(ang)))
pts.push(chart.point.from_index(px, cy + ry * math.sin(ang)))
polyline.new(pts, curved = true, closed = true, xloc = xloc.bar_index, line_color = c, fill_color = na, line_style = line.style_dashed, line_width = w)
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 3 — ACCEPTANCE ENGINE
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Seven independent measurements (dir = +1 bullish acceptance ABOVE the area, -1 bearish BELOW it):
// a closes beyond the area / window (percentage of closes on one side + count)
// b consecutive closes in the same region (persistence)
// c candle-body position vs area midpoint (bodies fully beyond the midpoint)
// d distance travelled away from the area (ATR-normalised)
// e returns into the area (fewer returns = better acceptance)
// f progress after crossing (net move since the first close beyond the area)
// g breakout maintenance (worst low/high of the run stays outside the area)
// A brief breakout is never treated as confirmed acceptance:
// consecutive closes < 2 -> score capped at 30 (weak)
// consecutive closes < Min Closes -> score capped at 50 (developing)
// Returns [score 0-100, % closes beyond area, consecutive closes]
f_accept(int dir, float top, float bot, float mid, float atrV, int len, int minCl, float sens) =>
float score = 0.0
float pct = 0.0
int consec = 0
if bar_index > len + 2
int n = 0
int bodyOk = 0
int returns = 0
bool away = false
for i = len - 1 to 0
bool ab = dir == 1 ? close[i] > top : close[i] < bot
if ab
n += 1
away := true
else if away
returns += 1
away := false
bool bOk = dir == 1 ? math.min(open[i], close[i]) > mid : math.max(open[i], close[i]) < mid
if bOk
bodyOk += 1
float ext = dir == 1 ? 1.0e10 : -1.0e10
for i = 0 to len - 1
bool ab2 = dir == 1 ? close[i] > top : close[i] < bot
if ab2
consec += 1
ext := dir == 1 ? math.min(ext, low[i]) : math.max(ext, high[i])
else
break
pct := 100.0 * n / len
if n > 0
float a = n / (len * 1.0)
float b = f_clamp(consec / (minCl * 2.5), 0.0, 1.0)
float c = bodyOk / (len * 1.0)
float dist = dir == 1 ? (close - top) / atrV : (bot - close) / atrV
float d = f_clamp(dist / (1.5 / sens), 0.0, 1.0)
float e = f_clamp(1.0 - returns / 4.0, 0.0, 1.0)
float prog = 0.0
if consec > 0
float baseC = nz(close[consec], close)
prog := (dir == 1 ? close - baseC : baseC - close) / atrV
float f = f_clamp(prog / (1.2 / sens), 0.0, 1.0)
float g = 0.0
if consec > 0
g := dir == 1 ? (ext > bot ? 1.0 : ext > bot - 0.25 * atrV ? 0.5 : 0.0) : (ext < top ? 1.0 : ext < top + 0.25 * atrV ? 0.5 : 0.0)
score := 100.0 * (0.22 * a + 0.15 * b + 0.12 * c + 0.14 * d + 0.10 * e + 0.15 * f + 0.12 * g)
if consec < 2
score := math.min(score, 30.0)
else if consec < minCl
score := math.min(score, 50.0)
[f_clamp(score, 0.0, 100.0), pct, consec]
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 4 — REJECTION ENGINE
// ═══════════════════════════════════════════════════════════════════════════════════════════
// dir = +1 bullish rejection (price attempts LOWER, buyers recover) | -1 bearish rejection.
// An "attempt" = wick reaches beyond the area midpoint. It is a FAILED attempt only if the candle
// closes back on the original side of the midpoint. Not every long wick scores: the evidence below
// must accumulate (failed attempts, recovery speed, previous tests, movement away from the extreme).
// wick proportion | close position in range | failed attempts | penetration depth |
// speed of return | consecutive rejection candles | previously tested area |
// body shrinkage after repeated attempts | movement away from the rejected extreme
// Score is capped when failed attempts < minimum (55) or the area was never tested before (60),
// and decays with the age of the latest rejection candle.
// Returns [score 0-100, failed attempts, consecutive rejection candles, bars since last rejection candle]
f_reject(int dir, float top, float bot, float mid, float atrV, int len, int retB, float wickS, int inter, int minI, bool shrink, int minFail) =>
float score = 0.0
int fails = 0
int consRej = 0
int ago = 999
if bar_index > len + retB + 3
int broke = 0
int quick = 0
int rc = 0
int visits = 0
float sumWick = 0.0
float sumPos = 0.0
float maxDepth = 0.0
float extreme = dir == 1 ? 1.0e10 : -1.0e10
bool inVisit = false
for i = len - 1 to 0
float rg = math.max(high[i] - low[i], syminfo.mintick)
bool attempt = dir == 1 ? low[i] < mid : high[i] > mid
bool recovered = dir == 1 ? close[i] > mid : close[i] < mid
bool touch = high[i] >= bot and low[i] <= top
if touch and not inVisit
visits += 1
inVisit := touch
extreme := dir == 1 ? math.min(extreme, low[i]) : math.max(extreme, high[i])
if attempt
float depth = dir == 1 ? (mid - low[i]) / atrV : (high[i] - mid) / atrV
maxDepth := math.max(maxDepth, depth)
if recovered
fails += 1
quick += 1
else
broke += 1
for j = 1 to retB
if i - j >= 0
bool rec2 = dir == 1 ? close[i - j] > mid : close[i - j] < mid
if rec2
quick += 1
break
float wk = dir == 1 ? (math.min(open[i], close[i]) - low[i]) / rg : (high[i] - math.max(open[i], close[i])) / rg
float cp = dir == 1 ? (close[i] - low[i]) / rg : (high[i] - close[i]) / rg
if recovered and wk >= wickS and cp >= 0.5
rc += 1
sumWick += wk
sumPos += cp
ago := i
for i = 0 to len - 1
float rg2 = math.max(high[i] - low[i], syminfo.mintick)
bool att2 = dir == 1 ? low[i] < mid : high[i] > mid
bool rec3 = dir == 1 ? close[i] > mid : close[i] < mid
float wk2 = dir == 1 ? (math.min(open[i], close[i]) - low[i]) / rg2 : (high[i] - math.max(open[i], close[i])) / rg2
if att2 and rec3 and wk2 >= wickS * 0.7
consRej += 1
else
break
if rc > 0
float avgW = sumWick / rc
float avgP = sumPos / rc
float wS = f_clamp(avgW / 0.7, 0.0, 1.0)
float pS = f_clamp((avgP - 0.4) / 0.5, 0.0, 1.0)
float aS = f_clamp(fails / (minFail * 1.5), 0.0, 1.0)
float dS = f_clamp(maxDepth / 0.8, 0.0, 1.0)
int tot = fails + broke
float spS = tot > 0 ? quick / (tot * 1.0) : 0.0
float cS = f_clamp(consRej / 2.0, 0.0, 1.0)
int tested = math.max(visits, inter)
float prS = f_clamp(tested / (minI + 2.0), 0.0, 1.0)
float shS = (shrink and fails >= 2) ? 1.0 : 0.0
float moved = dir == 1 ? (close - extreme) / atrV : (extreme - close) / atrV
float mvS = f_clamp(moved / 1.5, 0.0, 1.0)
score := 100.0 * (0.16 * wS + 0.14 * pS + 0.18 * aS + 0.10 * dS + 0.12 * spS + 0.08 * cS + 0.08 * prS + 0.04 * shS + 0.10 * mvS)
if fails < minFail
score := math.min(score, 55.0)
if tested < minI
score := math.min(score, 60.0)
float dec = f_clamp(1.0 - ago / (len * 0.75), 0.0, 1.0)
score := score * (0.45 + 0.55 * dec)
[f_clamp(score, 0.0, 100.0), fails, consRej, ago]
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 5 — PRICE STAYING POWER
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Measures how well price HOLDS the newly reached area beyond the old boundary (ATR-normalised):
// bars maintained | % closes in the new area | max adverse excursion back into the old area |
// distance maintained from the boundary | tests of the boundary that held (failed returns)
f_stay(int dir, float top, float bot, float atrV, int consec, int len, int minCl) =>
float score = 0.0
if consec >= 1 and bar_index > len + 8
float bound = dir == 1 ? top : bot
int c1 = math.min(consec, len)
int w = math.min(len, math.max(consec, 6))
int cnt = 0
int held = 0
float adv = 0.0
float minD = 1.0e10
for i = 0 to w - 1
bool ab = dir == 1 ? close[i] > bound : close[i] < bound
if ab
cnt += 1
if i < c1
float ad = dir == 1 ? bound - low[i] : high[i] - bound
adv := math.max(adv, ad)
float dc = dir == 1 ? close[i] - bound : bound - close[i]
minD := math.min(minD, dc)
bool tc = dir == 1 ? low[i] <= bound : high[i] >= bound
if tc and ab
held += 1
float persist = f_clamp(consec / (minCl * 3.0), 0.0, 1.0)
float pS = cnt / (w * 1.0)
float advS = f_clamp(1.0 - adv / (0.8 * atrV), 0.0, 1.0)
float distS = f_clamp(minD / (0.6 * atrV), 0.0, 1.0)
float heldS = held > 0 ? f_clamp(0.5 + held / 4.0, 0.0, 1.0) : 0.4
score := 100.0 * (0.25 * persist + 0.25 * pS + 0.20 * advS + 0.15 * distS + 0.15 * heldS)
f_clamp(score, 0.0, 100.0)
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 6 — HIGHER-TIMEFRAME CONTEXT FUNCTIONS (evaluated inside request.security)
// ═══════════════════════════════════════════════════════════════════════════════════════════
f_htfAcc() =>
float hi = ta.highest(high, 20)
float lo = ta.lowest(low, 20)
float md = (hi + lo) / 2.0
ta.sma(close > md ? 100.0 : 0.0, 10)
f_htfRej() =>
float r = math.max(high - low, syminfo.mintick)
ta.sma(((math.min(open, close) - low) - (high - math.max(open, close))) / r, 8)
f_htfBias(float acc, float rej) =>
f_clamp(0.6 * (acc - 50.0) * 2.0 + 0.4 * f_clamp(rej * 250.0, -100.0, 100.0), -100.0, 100.0)
f_htfText(float b) =>
na(b) ? "N/A" : b >= 35.0 ? "BULL ACCEPT" : b <= -35.0 ? "BEAR ACCEPT" : b >= 15.0 ? "BULL LEAN" : b <= -15.0 ? "BEAR LEAN" : "NEUTRAL"
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 7 — REFERENCE AREA ENGINE (lifecycle + drawing)
// ═══════════════════════════════════════════════════════════════════════════════════════════
f_killArea(Area a) =>
if not na(a.bx)
box.delete(a.bx)
if not na(a.glow)
box.delete(a.glow)
if not na(a.ml)
line.delete(a.ml)
if not na(a.lb)
label.delete(a.lb)
if not na(a.tx)
label.delete(a.tx)
f_makeArea(float c, float w, int origin, int bornBar) =>
Area a = Area.new(top = c + w / 2.0, bot = c - w / 2.0, mid = c, inter = origin == 0 ? 0 : 1, lastBar = bar_index, born = math.max(0, bornBar), origin = origin)
a.pri := a.inter * 8.0 + 25.0
if showZones
if showGlow
a.glow := box.new(a.born, a.top, bar_index, a.bot, border_color = na, bgcolor = color.new(cAcc, 94), extend = extend.right, xloc = xloc.bar_index)
a.bx := box.new(a.born, a.top, bar_index, a.bot, border_color = color.new(cAcc, 35), border_width = 1, bgcolor = color.new(cAcc, 84), extend = extend.right, xloc = xloc.bar_index)
if showMidline
a.ml := line.new(a.born, a.mid, bar_index + 1, a.mid, xloc = xloc.bar_index, extend = extend.right, color = color.new(cAcc, 25), style = line.style_dotted, width = 1)
if showZoneLabels
a.lb := label.new(bar_index, a.mid, "", xloc = xloc.bar_index, style = label.style_label_down, color = cAcc, textcolor = cWhite, size = size.small)
a.tx := label.new(bar_index, a.mid, "", xloc = xloc.bar_index, style = label.style_none, color = color.new(cAcc, 100), textcolor = cAcc, size = size.small)
a
f_pruneAreas(array<Area> arr, int maxN) =>
while arr.size() > maxN
int worst = 0
float wp = 1.0e10
for i = 0 to arr.size() - 1
Area a = arr.get(i)
if a.pri < wp
wp := a.pri
worst := i
f_killArea(arr.get(worst))
arr.remove(worst)
// Merge a new candidate into an existing area when overlapping / within ATR tolerance, otherwise create one
f_addOrMerge(array<Area> arr, float c, float w, int origin, bool isPivot, int bornBar, float tol, float maxW) =>
float nTop = c + w / 2.0
float nBot = c - w / 2.0
int found = -1
if arr.size() > 0
for i = 0 to arr.size() - 1
Area a = arr.get(i)
float gap = math.max(0.0, math.max(a.bot, nBot) - math.min(a.top, nTop))
if gap <= tol and a.state != 5
found := i
break
if found >= 0
Area m = arr.get(found)
float t = math.max(m.top, nTop)
float b = math.min(m.bot, nBot)
if t - b > maxW
float wt = math.max(m.inter, 1)
float cc = (m.mid * wt + c) / (wt + 1.0)
t := cc + maxW / 2.0
b := cc - maxW / 2.0
m.top := t
m.bot := b
m.mid := (t + b) / 2.0
if isPivot
m.turns += 1
else
arr.push(f_makeArea(c, w, origin, bornBar))
true
// Merge any areas that came to overlap each other
f_mergePass(array<Area> arr, float tol, float maxW) =>
bool again = true
int guard = 0
while again and guard < 8
again := false
guard += 1
int n = arr.size()
if n > 1
for i = 0 to n - 2
for j = i + 1 to n - 1
Area a = arr.get(i)
Area b = arr.get(j)
float gap = math.max(0.0, math.max(a.bot, b.bot) - math.min(a.top, b.top))
if gap <= tol
float t = math.max(a.top, b.top)
float bt = math.min(a.bot, b.bot)
if t - bt > maxW
float wa = math.max(a.inter, 1)
float wb = math.max(b.inter, 1)
float cc = (a.mid * wa + b.mid * wb) / (wa + wb)
t := cc + maxW / 2.0
bt := cc - maxW / 2.0
a.top := t
a.bot := bt
a.mid := (t + bt) / 2.0
a.inter += b.inter
a.turns += b.turns
a.lastBar := math.max(a.lastBar, b.lastBar)
f_killArea(b)
arr.remove(j)
again := true
break
if again
break
// Visual state of one area (colour = state, intensity = score)
f_styleArea(Area a, float atrV) =>
int kind = 0
if a.state == 3
kind := a.rejDir
else if a.state == 2 and a.origin == 1 and a.accDir == 1
kind := 1
color base = (a.state == 5 or a.state == 0) ? cGrey : a.state == 4 ? cAmb : kind == 1 ? cBull : kind == -1 ? cBear : cAcc
float sc = a.state == 3 ? a.rej : a.acc
int tr = int(math.round(f_clamp(90.0 - sc * 0.25, 62.0, 92.0)))
if not na(a.bx)
box.set_top(a.bx, a.top)
box.set_bottom(a.bx, a.bot)
box.set_bgcolor(a.bx, color.new(base, tr))
box.set_border_color(a.bx, color.new(base, a.state == 5 ? 70 : 35))
box.set_border_style(a.bx, a.state == 5 ? line.style_dashed : line.style_solid)
if not na(a.glow)
float gp = 0.18 * atrV
box.set_top(a.glow, a.top + gp)
box.set_bottom(a.glow, a.bot - gp)
box.set_bgcolor(a.glow, color.new(base, a.state == 3 ? 86 : 94))
if not na(a.ml)
line.set_y1(a.ml, a.mid)
line.set_y2(a.ml, a.mid)
line.set_color(a.ml, color.new(base, 25))
if not na(a.lb) and not na(a.tx)
string loS = str.tostring(a.bot, format.mintick)
string hiS = str.tostring(a.top, format.mintick)
int sx = math.max(a.born, bar_index - zoneLabelOff)
if kind == -1 and a.state == 3
label.set_style(a.lb, label.style_none)
label.set_xy(a.lb, bar_index - 14, a.top + 0.35 * atrV)
label.set_text(a.lb, "Rejected Area")
label.set_textcolor(a.lb, cBear)
label.set_color(a.lb, color.new(base, 100))
label.set_xy(a.tx, bar_index - 14, a.top - 0.2 * atrV)
label.set_text(a.tx, "RZ: " + loS + " – " + hiS)
label.set_textcolor(a.tx, cBear)
else if kind == 1
label.set_style(a.lb, label.style_label_up)
label.set_xy(a.lb, sx, a.bot)
label.set_text(a.lb, "Strong Support\n(" + (a.state == 2 ? "Acceptance: " + str.tostring(int(math.round(a.acc))) : "Rejection: " + str.tostring(int(math.round(a.rej)))) + ")")
label.set_textcolor(a.lb, #69F0AE)
label.set_color(a.lb, #0B3D1F)
label.set_xy(a.tx, bar_index - 40, a.bot - 0.45 * atrV)
label.set_text(a.tx, "SZ: " + loS + " – " + hiS)
label.set_textcolor(a.tx, cBull)
else
string nm = a.state == 2 ? "Acceptance Zone\n(Score: " + str.tostring(int(math.round(a.acc))) + ")" : a.state == 4 ? "Balanced Area" : a.state == 5 ? "Invalidated Area" : a.state == 0 ? "Untested Area" : "Developing Area"
label.set_style(a.lb, label.style_label_down)
label.set_xy(a.lb, sx, a.top)
label.set_text(a.lb, nm)
label.set_textcolor(a.lb, a.state == 4 ? cAmb : #40C4FF)
label.set_color(a.lb, #0A2A55)
label.set_xy(a.tx, bar_index - 40, a.bot)
label.set_text(a.tx, "")
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 8 — TRADE PLAN DRAWING
// ═══════════════════════════════════════════════════════════════════════════════════════════
f_makePlan(int dir, float entry, float sl, float t1, float t2, float t3, float inv) =>
int rb = bar_index + planWidth
Plan p = Plan.new(dir = dir, entryBar = bar_index, entry = entry, sl = sl, tp1 = t1, tp2 = t2, tp3 = t3, inv = inv, endBar = bar_index)
if showPlans
float rwTop = math.max(entry, t3)
float rwBot = math.min(entry, t3)
float rkTop = math.max(entry, sl)
float rkBot = math.min(entry, sl)
p.rewBox := box.new(bar_index, rwTop, rb, rwBot, border_color = na, bgcolor = color.new(cBull, 80), xloc = xloc.bar_index)
p.riskBox := box.new(bar_index, rkTop, rb, rkBot, border_color = color.new(cBear, 40), border_width = 1, bgcolor = color.new(cBear, 76), xloc = xloc.bar_index)
p.lnEntry := line.new(bar_index, entry, rb, entry, xloc = xloc.bar_index, color = cBull, style = line.style_dashed, width = 1)
p.ln1 := line.new(bar_index, t1, rb, t1, xloc = xloc.bar_index, color = color.new(cBull, 25), style = line.style_dashed, width = 1)
p.ln2 := line.new(bar_index, t2, rb, t2, xloc = xloc.bar_index, color = color.new(cBull, 25), style = line.style_dashed, width = 1)
p.ln3 := line.new(bar_index, t3, rb, t3, xloc = xloc.bar_index, color = cCyan, style = line.style_solid, width = 2)
p.lnSl := line.new(bar_index, sl, rb, sl, xloc = xloc.bar_index, color = cBear, style = line.style_solid, width = 1)
p.lbEntry := label.new(rb, entry, "ENTRY: " + str.tostring(entry, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = #0B3D1F, textcolor = #69F0AE, size = size.small)
p.lb1 := label.new(rb, t1, "TP1: " + str.tostring(t1, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = #0B3D1F, textcolor = #69F0AE, size = size.small)
p.lb2 := label.new(rb, t2, "TP2: " + str.tostring(t2, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = #0B3D1F, textcolor = #69F0AE, size = size.small)
p.lb3 := label.new(rb, t3, "TP3: " + str.tostring(t3, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = #0B3D1F, textcolor = #84FFFF, size = size.small)
p.lbSl := label.new(rb, sl, "SL: " + str.tostring(sl, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = #5A0F0F, textcolor = #FF8A80, size = size.small)
p
f_planLayout(Plan p, int rb) =>
if showPlans and not na(p.rewBox)
box.set_right(p.rewBox, rb)
box.set_right(p.riskBox, rb)
line.set_x2(p.lnEntry, rb)
line.set_x2(p.ln1, rb)
line.set_x2(p.ln2, rb)
line.set_x2(p.ln3, rb)
line.set_x2(p.lnSl, rb)
label.set_x(p.lbEntry, rb)
label.set_x(p.lb1, rb)
label.set_x(p.lb2, rb)
label.set_x(p.lb3, rb)
label.set_x(p.lbSl, rb)
f_planMarkHit(Plan p, int lvl) =>
if showPlans and not na(p.rewBox)
if lvl == 1
label.set_text(p.lb1, "TP1 ✓ " + str.tostring(p.tp1, format.mintick))
line.set_style(p.ln1, line.style_solid)
else if lvl == 2
label.set_text(p.lb2, "TP2 ✓ " + str.tostring(p.tp2, format.mintick))
line.set_style(p.ln2, line.style_solid)
else if lvl == 3
label.set_text(p.lb3, "TP3 ✓ " + str.tostring(p.tp3, format.mintick))
f_killPlan(Plan p) =>
if not na(p.rewBox)
box.delete(p.rewBox)
if not na(p.riskBox)
box.delete(p.riskBox)
if not na(p.lnEntry)
line.delete(p.lnEntry)
if not na(p.ln1)
line.delete(p.ln1)
if not na(p.ln2)
line.delete(p.ln2)
if not na(p.ln3)
line.delete(p.ln3)
if not na(p.lnSl)
line.delete(p.lnSl)
if not na(p.lbEntry)
label.delete(p.lbEntry)
if not na(p.lb1)
label.delete(p.lb1)
if not na(p.lb2)
label.delete(p.lb2)
if not na(p.lb3)
label.delete(p.lb3)
if not na(p.lbSl)
label.delete(p.lbSl)
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 9 — CORE SERIES (ATR-normalised, top-level so ta.* runs on every bar)
// ═══════════════════════════════════════════════════════════════════════════════════════════
float atrN = math.max(nz(ta.atr(atrLen), ta.tr), syminfo.mintick * 3)
float rng = math.max(high - low, syminfo.mintick)
float body = math.abs(close - open)
bool warm = bar_index > lookbackLen + 12
bool conf = barstate.isconfirmed
float rollHi = nz(ta.highest(high, lookbackLen)[1], high)
float rollLo = nz(ta.lowest(low, lookbackLen)[1], low)
float rollMid = (rollHi + rollLo) / 2.0
float hiClose = ta.highest(close, lookbackLen)
float loClose = ta.lowest(close, lookbackLen)
float ph = ta.pivothigh(high, pivLen, pivLen)
float pl = ta.pivotlow(low, pivLen, pivLen)
bool bodyShrink = ta.sma(body, 3) < nz(ta.sma(body, 6)[3], 1.0e10)
float lowRej = ta.lowest(low, rejLen)
float highRej = ta.highest(high, rejLen)
int lbOff = ta.lowestbars(low, 4)
int hbOff = ta.highestbars(high, 4)
float lowAnch = ta.lowest(low, 4)
float highAnch = ta.highest(high, 4)
float emaT = ta.ema(close, trendLen)
float compress = 100.0 - nz(ta.percentrank(ta.sma(rng, 5), 100), 50.0)
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 10 — REFERENCE AREA ENGINE (creation, merging, per-bar scoring, active selection)
// ═══════════════════════════════════════════════════════════════════════════════════════════
float areaW = areaWidthATR * atrN
float areaTol = clusterTol * atrN
float areaMaxW = areaW * 2.0
if warm
// Turning points (confirmed pivots -> detection delay = pivLen bars)
if not na(ph)
f_addOrMerge(areas, ph - 0.25 * areaW, areaW, -1, true, bar_index - pivLen, areaTol, areaMaxW)
f_mergePass(areas, areaTol, areaMaxW)
f_pruneAreas(areas, maxAreas)
if not na(pl)
f_addOrMerge(areas, pl + 0.25 * areaW, areaW, 1, true, bar_index - pivLen, areaTol, areaMaxW)
f_mergePass(areas, areaTol, areaMaxW)
f_pruneAreas(areas, maxAreas)
// Rolling close distribution (clustering of closing prices), evaluated every 5th bar
if bar_index % 5 == 0 and conf and (hiClose - loClose) > atrN * 0.8
bins.fill(0.0)
float bw = (hiClose - loClose) / 20.0
for i = 0 to lookbackLen - 1
int bi = int(math.max(0, math.min(19, math.floor((close[i] - loClose) / bw))))
bins.set(bi, bins.get(bi) + 1.0)
float best = 0.0
int bestI = -1
for k = 0 to 19
float lft = k > 0 ? bins.get(math.max(k - 1, 0)) : 0.0
float rgt = k < 19 ? bins.get(math.min(k + 1, 19)) : 0.0
float v = bins.get(k) + 0.5 * lft + 0.5 * rgt
if v > best
best := v
bestI := k
if bestI >= 0 and best / lookbackLen >= 0.35
f_addOrMerge(areas, loClose + (bestI + 0.5) * bw, areaW, 0, false, bar_index, areaTol, areaMaxW)
f_mergePass(areas, areaTol, areaMaxW)
f_pruneAreas(areas, maxAreas)
int actIdx = -1
float actTop = na
float actBot = na
float actMid = na
int actInter = 0
int actState = 0
float bestSc = 0.0
if warm and areas.size() > 0
for i = 0 to areas.size() - 1
Area a = areas.get(i)
// interaction counting: one interaction per distinct visit into the area
bool tch = high >= a.bot - 0.05 * atrN and low <= a.top + 0.05 * atrN
if tch and not a.touched
a.inter += 1
a.lastBar := bar_index
a.lastType := close > a.top ? 1 : close < a.bot ? -1 : 0
a.touched := tch
// behavioural scores of this area
[aB, aBp, aBc] = f_accept(1, a.top, a.bot, a.mid, atrN, accLen, minCloses, sensitivity)
[aS, aSp, aSc] = f_accept(-1, a.top, a.bot, a.mid, atrN, accLen, minCloses, sensitivity)
[rB, rBf, rBc, rBa] = f_reject(1, a.top, a.bot, a.mid, atrN, rejLen, retBars, wickSens / sensitivity, a.inter, minInter, bodyShrink, minFailed)
[rS, rSf, rSc, rSa] = f_reject(-1, a.top, a.bot, a.mid, atrN, rejLen, retBars, wickSens / sensitivity, a.inter, minInter, bodyShrink, minFailed)
a.acc := math.max(aB, aS)
a.accDir := aB >= aS ? 1 : -1
a.rej := math.max(rB, rS)
a.rejDir := rB >= rS ? 1 : -1
// lifecycle state
bool inside = close <= a.top and close >= a.bot
bool broken = (a.origin == 1 and aS >= 80.0) or (a.origin == -1 and aB >= 80.0)
bool stale = bar_index - a.lastBar > lookbackLen * 5
int st = 1
if broken or stale
st := 5
else if a.inter == 0
st := 0
else if a.rej >= 55.0 and a.rej > a.acc
st := 3
else if a.acc >= 60.0
st := 2
else if inside or (a.acc < 40.0 and a.rej < 40.0 and a.inter >= minInter)
st := 4
a.state := st
// priority = repeated interaction + behavioural evidence + recency
float rec = math.max(0.0, 1.0 - (bar_index - a.lastBar) / (lookbackLen * 4.0))
a.pri := a.inter * 8.0 + a.turns * 4.0 + math.max(a.acc, a.rej) * 0.4 + rec * 25.0 - (st == 5 ? 1000.0 : 0.0)
float dist = math.abs(close - a.mid) / atrN
if st != 5 and a.inter >= minInter and dist <= 4.0
float sc2 = a.pri / (1.0 + dist)
if sc2 > bestSc
bestSc := sc2
actIdx := i
f_styleArea(a, atrN)
if actIdx >= 0
Area aa = areas.get(actIdx)
actTop := aa.top
actBot := aa.bot
actMid := aa.mid
actInter := aa.inter
actState := aa.state
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 11 — ACTIVE REFERENCE AREA
// ═══════════════════════════════════════════════════════════════════════════════════════════
float rHalf = 0.5 * areaW
float nearHL = math.abs(close - rollHi) < math.abs(close - rollLo) ? rollHi : rollLo
bool useAdapt = refMode == "Adaptive Area" and actIdx >= 0
float refMid = refMode == "Rolling Midpoint" ? rollMid : refMode == "Rolling High/Low" ? nearHL : refMode == "User Price" ? (userPrice > 0.0 ? userPrice : rollMid) : (useAdapt ? actMid : rollMid)
float refTop = useAdapt ? actTop : refMid + rHalf
float refBot = useAdapt ? actBot : refMid - rHalf
int refInter = useAdapt ? actInter : 0
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 12 — ENGINE EVALUATION ON THE ACTIVE REFERENCE
// ═══════════════════════════════════════════════════════════════════════════════════════════
[accBull, accPctBull, consBull] = f_accept(1, refTop, refBot, refMid, atrN, accLen, minCloses, sensitivity)
[accBear, accPctBear, consBear] = f_accept(-1, refTop, refBot, refMid, atrN, accLen, minCloses, sensitivity)
[rejBull, failsBull, consRejBull, agoRejBull] = f_reject(1, refTop, refBot, refMid, atrN, rejLen, retBars, wickSens / sensitivity, refInter, minInter, bodyShrink, minFailed)
[rejBear, failsBear, consRejBear, agoRejBear] = f_reject(-1, refTop, refBot, refMid, atrN, rejLen, retBars, wickSens / sensitivity, refInter, minInter, bodyShrink, minFailed)
float stayBull = f_stay(1, refTop, refBot, atrN, consBull, accLen, minCloses)
float stayBear = f_stay(-1, refTop, refBot, atrN, consBear, accLen, minCloses)
float stayDom = math.max(stayBull, stayBear)
// ───────────────────────────────────────────────────────────────────────────────────────────
// BEHAVIOUR MOMENTUM (efficiency, progress, follow-through, body consistency, expansion, decay)
// ───────────────────────────────────────────────────────────────────────────────────────────
float netD = close - nz(close[momLen], close)
float pathD = math.sum(nz(math.abs(ta.change(close))), momLen)
float effR = pathD > 0 ? math.abs(netD) / pathD : 0.0
float bullCnt = math.sum(close > open ? 1.0 : 0.0, momLen)
float bearCnt = math.sum(close < open ? 1.0 : 0.0, momLen)
float bodyCons = ta.sma(body / rng, momLen)
float ftB = math.sum((close[1] > open[1] and close > close[1]) ? 1.0 : 0.0, momLen) / math.max(1.0, math.sum(close[1] > open[1] ? 1.0 : 0.0, momLen))
float ftS = math.sum((close[1] < open[1] and close < close[1]) ? 1.0 : 0.0, momLen) / math.max(1.0, math.sum(close[1] < open[1] ? 1.0 : 0.0, momLen))
float rangeExp = ta.sma(rng, math.max(3, int(momLen / 2))) / ta.sma(rng, momLen)
float volMa = ta.sma(volume, 20)
bool hasVol = nz(volMa) > 0
float volFs = ta.sma(hasVol ? f_clamp(volume / volMa, 0.5, 1.5) : 1.0, 5)
float expS = f_clamp(((hasVol ? 0.6 * rangeExp + 0.4 * volFs : rangeExp) - 0.7) / 0.6, 0.0, 1.0)
float effS = f_clamp(effR / (effThr * 1.5), 0.0, 1.0)
float progB = netD > 0 ? f_clamp(netD / (atrN * math.sqrt(momLen) * 1.2 / sensitivity), 0.0, 1.0) : 0.0
float progS = netD < 0 ? f_clamp(-netD / (atrN * math.sqrt(momLen) * 1.2 / sensitivity), 0.0, 1.0) : 0.0
float momBull = 100.0 * ((netD > 0 ? 0.28 * effS : 0.0) + 0.20 * progB + 0.15 * bodyCons + 0.17 * ftB + 0.12 * (1.0 - bearCnt / momLen) + 0.08 * expS)
float momBear = 100.0 * ((netD < 0 ? 0.28 * effS : 0.0) + 0.20 * progS + 0.15 * bodyCons + 0.17 * ftS + 0.12 * (1.0 - bullCnt / momLen) + 0.08 * expS)
momBull := f_clamp(netD > 0 ? momBull : momBull * 0.4, 0.0, 100.0)
momBear := f_clamp(netD < 0 ? momBear : momBear * 0.4, 0.0, 100.0)
float momDom = math.max(momBull, momBear)
float momPeak = ta.highest(momDom, momLen)
float momDrop = momPeak > 5.0 ? (momPeak - momDom) / momPeak : 0.0
float momContr = f_clamp(1.0 - rangeExp, 0.0, 1.0)
float momDecay = 100.0 * f_clamp((0.65 * momDrop + 0.70 * momContr) * decaySens, 0.0, 1.0)
// ───────────────────────────────────────────────────────────────────────────────────────────
// FAILED ACCEPTANCE DETECTOR (two state machines)
// 1. Closes beyond the area (>= 2 consecutive) -> start tracking, freeze the area boundary
// 2. Initial acceptance develops (peak score >= 31)
// 3. Price stops progressing; several closes return back to/inside the frozen area
// 4. Close is back inside/below(above) the area by at least the return threshold -> FAILED
// Invalidation: tracking ends after N bars, or when the acceptance became established (>=71)
// ───────────────────────────────────────────────────────────────────────────────────────────
var bool trkB = false
var float fbTopB = 0.0
var float fbBotB = 0.0
var int trkStartB = 0
var float peakHighB = 0.0
var float peakAccB = 0.0
var int lastFailBull = -10000
var float failPeakB = 0.0
var bool trkS = false
var float fbTopS = 0.0
var float fbBotS = 0.0
var int trkStartS = 0
var float peakLowS = 0.0
var float peakAccS = 0.0
var int lastFailBear = -10000
var float failPeakS = 0.0
bool failBullEvt = false
bool failBearEvt = false
int cbB = 0
int cbS = 0
float evtTopB = na
float evtBotB = na
int evtStartB = 0
float evtTopS = na
float evtBotS = na
int evtStartS = 0
if warm
// ---- failed BULLISH acceptance ----
if not trkB
if consBull >= 2 and bar_index - lastFailBull > failConfirm * 2
trkB := true
fbTopB := refTop
fbBotB := refBot
trkStartB := bar_index - consBull + 1
peakHighB := high
peakAccB := accBull
else
peakHighB := math.max(peakHighB, high)
peakAccB := math.max(peakAccB, accBull)
for i = 0 to failConfirm - 1
if close[i] <= fbTopB
cbB += 1
bool retd = cbB >= math.max(2, failConfirm - 1)
bool below = close < fbTopB and (fbTopB - close) / atrN >= failRetThr
if retd and below and peakAccB >= 31.0 and bar_index - trkStartB >= 3 and conf
failBullEvt := true
evtTopB := math.max(peakHighB, fbTopB)
evtBotB := fbBotB
evtStartB := trkStartB
lastFailBull := bar_index
failPeakB := peakAccB
trkB := false
else if bar_index - trkStartB > failExpire or (peakAccB >= 71.0 and accBull >= 71.0 and not retd)
trkB := false
// ---- failed BEARISH acceptance ----
if not trkS
if consBear >= 2 and bar_index - lastFailBear > failConfirm * 2
trkS := true
fbTopS := refTop
fbBotS := refBot
trkStartS := bar_index - consBear + 1
peakLowS := low
peakAccS := accBear
else
peakLowS := math.min(peakLowS, low)
peakAccS := math.max(peakAccS, accBear)
for i = 0 to failConfirm - 1
if close[i] >= fbBotS
cbS += 1
bool retd2 = cbS >= math.max(2, failConfirm - 1)
bool above = close > fbBotS and (close - fbBotS) / atrN >= failRetThr
if retd2 and above and peakAccS >= 31.0 and bar_index - trkStartS >= 3 and conf
failBearEvt := true
evtTopS := fbTopS
evtBotS := math.min(peakLowS, fbBotS)
evtStartS := trkStartS
lastFailBear := bar_index
failPeakS := peakAccS
trkS := false
else if bar_index - trkStartS > failExpire or (peakAccS >= 71.0 and accBear >= 71.0 and not retd2)
trkS := false
// Failed-acceptance evidence (decays for 16 bars; partial credit while an acceptance is weakening)
int agoFB = bar_index - lastFailBull
int agoFS = bar_index - lastFailBear
float failBullScore = agoFB <= 15 ? (60.0 + 0.4 * failPeakB) * (1.0 - agoFB / 16.0) : (trkB ? 25.0 * f_clamp(cbB / (failConfirm * 1.0), 0.0, 1.0) : 0.0)
float failBearScore = agoFS <= 15 ? (60.0 + 0.4 * failPeakS) * (1.0 - agoFS / 16.0) : (trkS ? 25.0 * f_clamp(cbS / (failConfirm * 1.0), 0.0, 1.0) : 0.0)
// ───────────────────────────────────────────────────────────────────────────────────────────
// CONFLICT DETECTOR
// ───────────────────────────────────────────────────────────────────────────────────────────
float cBS = math.min(accBull, rejBear)
float cSB = math.min(accBear, rejBull)
float cBoth = math.min(accBull, accBear)
float cRej = math.min(rejBull, rejBear)
float rejMax = math.max(rejBull, rejBear)
float accMax = math.max(accBull, accBear)
float moveAw = math.abs(close - nz(close[math.max(1, int(rejLen / 2))], close)) / atrN
float cStall = (rejMax >= 60.0 and moveAw < 0.5) ? rejMax * 0.6 : 0.0
float conflictScore = math.max(math.max(cBS, cSB), math.max(cBoth, math.max(cRej, cStall)))
string conflictClass = "NO CLEAR CONTROL"
if cBoth >= 45.0
conflictClass := "BALANCED AUCTION"
else if cBS >= 40.0 or cSB >= 40.0
conflictClass := "BUYER-SELLER CONFLICT"
else if (accBull >= 50.0 and accBull < nz(accBull[3]) - 8.0) or (accBear >= 50.0 and accBear < nz(accBear[3]) - 8.0)
conflictClass := "ACCEPTANCE WEAKENING"
else if (rejBull >= 40.0 and rejBull > nz(rejBull[3]) + 10.0) or (rejBear >= 40.0 and rejBear > nz(rejBear[3]) + 10.0)
conflictClass := "REJECTION INCREASING"
else if (accMax >= 60.0 and (accBull >= accBear ? rejBear : rejBull) < 35.0) or (rejMax >= 70.0 and cRej < 30.0)
conflictClass := "DIRECTIONAL CONTROL"
string conflictLvl = conflictScore < 25.0 ? "LOW" : conflictScore < 50.0 ? "MODERATE" : "HIGH"
// ───────────────────────────────────────────────────────────────────────────────────────────
// COMBINED MARKET BEHAVIOUR SCORE (technical evidence, NOT a probability)
// Correlated pairs are de-duplicated: hold = (Acceptance, Staying Power),
// reversal = (Rejection, Failed-Acceptance). Each pair uses 60% max() + 40% weighted blend,
// so the same closes/wicks are not counted twice. Conflict penalty uses opposing evidence.
// ───────────────────────────────────────────────────────────────────────────────────────────
f_evidence(float acc, float rej, float stay, float fail, float mom, float opp) =>
float A = acc / 100.0
float R = rej / 100.0
float S = stay / 100.0
float F = fail / 100.0
float M = mom / 100.0
float hold = 0.6 * math.max(A, S) + 0.4 * ((wAcc * A + wStay * S) / (wAcc + wStay))
float rev = 0.6 * math.max(R, F) + 0.4 * ((wRej * R + wFail * F) / (wRej + wFail))
float raw = ((wAcc + wStay) * hold + (wRej + wFail) * rev + wMom * M) / (wAcc + wStay + wRej + wFail + wMom)
float pen = wConf / 100.0 * 0.5 * (0.6 * opp + 0.4 * conflictScore)
f_clamp(100.0 * raw - pen, 0.0, 100.0)
float bullEv = f_evidence(accBull, rejBull, stayBull, failBearScore, momBull, math.max(accBear, rejBear))
float bearEv = f_evidence(accBear, rejBear, stayBear, failBullScore, momBear, math.max(accBull, rejBull))
string control = "NEUTRAL"
if bullEv >= 45.0 and bullEv - bearEv >= 12.0
control := "BUYERS"
else if bearEv >= 45.0 and bearEv - bullEv >= 12.0
control := "SELLERS"
else if math.max(bullEv, bearEv) < 35.0
control := "NO CLEAR CONTROL"
// ───────────────────────────────────────────────────────────────────────────────────────────
// TRANSITION ENGINE (debounced behaviour-mode machine + sequence detectors)
// mode: 0 balanced | 1 bullish acceptance | 2 bearish acceptance | 3 bullish rejection | 4 bearish rejection
// A new mode must persist for 3 bars before a transition is reported ("sufficient evidence").
// ───────────────────────────────────────────────────────────────────────────────────────────
float accD = math.max(accBull, accBear)
float accPctD = accBull >= accBear ? accPctBull : accPctBear
float rejD = math.max(rejBull, rejBear)
int rawMode = 0
if accD >= 51.0 and accPctD >= minAccPct and accD >= rejD
rawMode := accBull >= accBear ? 1 : 2
else if rejD >= 51.0
rawMode := rejBull >= rejBear ? 3 : 4
var int stableMode = 0
var int candMode = 0
var int candCnt = 0
var string lastTrans = "None"
var string lastTransShort = "None"
var int lastTransBar = -10000
var int pendFailDir = 0
var int pendFailBar = -10000
var int pendRejDir = 0
var int pendRejBar = -10000
bool transRejToAcc = false
bool transAccToRej = false
string transText = ""
string transShort = ""
int transDir = 0
if warm and conf
if rawMode == stableMode
candCnt := 0
candMode := stableMode
else
if rawMode == candMode
candCnt += 1
else
candMode := rawMode
candCnt := 1
if candCnt >= 3
int prevM = stableMode
stableMode := rawMode
candCnt := 0
if (prevM == 3 or prevM == 4) and (rawMode == 1 or rawMode == 2)
transRejToAcc := true
transDir := rawMode == 1 ? 1 : -1
transText := "REJECTION → " + (rawMode == 1 ? "BULLISH" : "BEARISH") + " ACCEPTANCE"
transShort := "→ Acceptance"
else if (prevM == 1 or prevM == 2) and (rawMode == 3 or rawMode == 4)
transAccToRej := true
transDir := rawMode == 3 ? 1 : -1
transText := "ACCEPTANCE → " + (rawMode == 3 ? "BULLISH" : "BEARISH") + " REJECTION"
transShort := "→ Rejection"
else if prevM == 0 and (rawMode == 1 or rawMode == 2)
transDir := rawMode == 1 ? 1 : -1
transText := "BALANCED → " + (rawMode == 1 ? "BULLISH" : "BEARISH") + " ACCEPTANCE"
transShort := "→ Acceptance"
// Failed acceptance -> opposite directional recovery
if failBullEvt
pendFailDir := 1
pendFailBar := bar_index
if failBearEvt
pendFailDir := -1
pendFailBar := bar_index
if pendFailDir != 0
if bar_index - pendFailBar > 25
pendFailDir := 0
else if pendFailDir == 1 and accBear >= 45.0 and consBear >= 2
transText := "FAILED BULLISH ACCEPTANCE → BEARISH RECOVERY"
transShort := "→ Bear Recovery"
transDir := -1
pendFailDir := 0
else if pendFailDir == -1 and accBull >= 45.0 and consBull >= 2
transText := "FAILED BEARISH ACCEPTANCE → BULLISH RECOVERY"
transShort := "→ Bull Recovery"
transDir := 1
pendFailDir := 0
// Repeated rejection -> strong directional movement
if rejBull >= 51.0 and failsBull >= minFailed
pendRejDir := 1
pendRejBar := bar_index
if rejBear >= 51.0 and failsBear >= minFailed
pendRejDir := -1
pendRejBar := bar_index
if pendRejDir != 0 and bar_index > pendRejBar
if bar_index - pendRejBar > 20
pendRejDir := 0
else if pendRejDir == 1 and momBull >= 60.0 and (close - lowRej) / atrN >= 1.5 and consBull >= 2
transText := "REPEATED REJECTION → BULLISH MOVE"
transShort := "→ Bull Move"
transDir := 1
pendRejDir := 0
else if pendRejDir == -1 and momBear >= 60.0 and (highRej - close) / atrN >= 1.5 and consBear >= 2
transText := "REPEATED REJECTION → BEARISH MOVE"
transShort := "→ Bear Move"
transDir := -1
pendRejDir := 0
if transText != "" and bar_index - lastTransBar >= 6
lastTrans := transText
lastTransShort := transShort
lastTransBar := bar_index
else
transText := ""
// ───────────────────────────────────────────────────────────────────────────────────────────
// MULTI-TIMEFRAME CONTEXT (confirmed HTF bar only: expr[1] + lookahead_on => no repaint/leak)
// ───────────────────────────────────────────────────────────────────────────────────────────
float h1Acc = request.security(syminfo.tickerid, htf1, f_htfAcc()[1], lookahead = barmerge.lookahead_on)
float h1Rej = request.security(syminfo.tickerid, htf1, f_htfRej()[1], lookahead = barmerge.lookahead_on)
float h2Acc = request.security(syminfo.tickerid, htf2, f_htfAcc()[1], lookahead = barmerge.lookahead_on)
float h2Rej = request.security(syminfo.tickerid, htf2, f_htfRej()[1], lookahead = barmerge.lookahead_on)
bool h1Valid = useHtf and timeframe.in_seconds(htf1) > timeframe.in_seconds(timeframe.period)
bool h2Valid = useHtf and useHtf2 and timeframe.in_seconds(htf2) > timeframe.in_seconds(timeframe.period)
float h1Bias = h1Valid ? f_htfBias(h1Acc, h1Rej) : na
float h2Bias = h2Valid ? f_htfBias(h2Acc, h2Rej) : na
float htfNeed = htfMode == "Supporting" ? 15.0 : -25.0
bool htfOkBuy = (na(h1Bias) or h1Bias > htfNeed) and (na(h2Bias) or h2Bias > htfNeed)
bool htfOkSell = (na(h1Bias) or h1Bias < -htfNeed) and (na(h2Bias) or h2Bias < -htfNeed)
bool trendOkBuy = not trendFilter or close > emaT or emaT > nz(emaT[5], emaT)
bool trendOkSell = not trendFilter or close < emaT or emaT < nz(emaT[5], emaT)
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 13 — PRECISION SIGNAL ENGINE
// ═══════════════════════════════════════════════════════════════════════════════════════════
var int lastConfBar = -10000
var int lastEarlyBar = -10000
var int curSigDir = 0
var int curSigStr = 0
var int curSigBar = -10000
var float sigEv = 0.0
var int lastRejBullLbl = -10000
var int lastRejBearLbl = -10000
bool oppBullOk = math.max(rejBear, accBear) < 50.0 and conflictScore < 50.0 and conflictClass != "BALANCED AUCTION"
bool oppBearOk = math.max(rejBull, accBull) < 50.0 and conflictScore < 50.0 and conflictClass != "BALANCED AUCTION"
bool trigBull = (rejBull >= trigRejMin and failsBull >= 1) or failBearScore >= 50.0
bool trigBear = (rejBear >= trigRejMin and failsBear >= 1) or failBullScore >= 50.0
bool trigBullE = rejBull >= 50.0 or failBearScore >= 35.0
bool trigBearE = rejBear >= 50.0 or failBullScore >= 35.0
bool devBull = accBull >= 31.0
bool devBear = accBear >= 31.0
bool holdBullLoose = close > refTop and stayBull >= stayThr * 0.7
bool holdBearLoose = close < refBot and stayBear >= stayThr * 0.7
bool holdBullStrict = close > refTop and stayBull >= stayThr
bool holdBearStrict = close < refBot and stayBear >= stayThr
bool momUpBull = momBull > nz(momBull[2]) and momBull >= 35.0
bool momUpBear = momBear > nz(momBear[2]) and momBear >= 35.0
bool buyHigh = trigBull and devBull and holdBullStrict and momUpBull and oppBullOk and bullEv >= minConviction and trendOkBuy and htfOkBuy
bool buyConf = trigBull and devBull and holdBullLoose and oppBullOk and bullEv >= minSignalScore and trendOkBuy and htfOkBuy
bool buyEarly = trigBullE and close > refMid and oppBullOk and bullEv >= minSignalScore - 15 and trendOkBuy
bool sellHigh = trigBear and devBear and holdBearStrict and momUpBear and oppBearOk and bearEv >= minConviction and trendOkSell and htfOkSell
bool sellConf = trigBear and devBear and holdBearLoose and oppBearOk and bearEv >= minSignalScore and trendOkSell and htfOkSell
bool sellEarly = trigBearE and close < refMid and oppBearOk and bearEv >= minSignalScore - 15 and trendOkSell
// Trade-plan arithmetic (validated before any signal is issued)
float slBuy = lowRej - stopPad * atrN
float slSell = highRej + stopPad * atrN
float riskBuy = close - slBuy
float riskSell = slSell - close
bool rrOk = tp1R > 0 and tp2R > tp1R and tp3R > tp2R
bool planOkBuy = rrOk and not na(riskBuy) and riskBuy >= minRiskATR * atrN and riskBuy <= maxRiskATR * atrN and slBuy < close
bool planOkSell = rrOk and not na(riskSell) and riskSell >= minRiskATR * atrN and riskSell <= maxRiskATR * atrN and slSell > close
bool canSig = warm and conf and na(curPlan) and bar_index - lastConfBar >= cooldownBars
bool sigBuy = canSig and (buyHigh or buyConf) and planOkBuy and not (sellHigh or sellConf)
bool sigSell = canSig and (sellHigh or sellConf) and planOkSell and not (buyHigh or buyConf)
bool earlyOk = warm and conf and na(curPlan) and bar_index - lastEarlyBar >= cooldownBars and bar_index - lastConfBar >= cooldownBars
bool earlyBuy = earlyOk and buyEarly and not (buyHigh or buyConf) and not sigBuy and not sigSell and not sellEarly
bool earlySell = earlyOk and sellEarly and not (sellHigh or sellConf) and not sigBuy and not sigSell and not buyEarly
// Plan lifecycle events
bool tp1Evt = false
bool tp2Evt = false
bool tp3Evt = false
bool slEvt = false
bool invEvt = false
int evtDir = 0
float evtLvl = na
// Open a new plan (levels are frozen at this moment and never recalculated)
if sigBuy or sigSell
int d = sigBuy ? 1 : -1
float ent = close
float rk = d == 1 ? riskBuy : riskSell
float slv = d == 1 ? slBuy : slSell
float t1 = ent + d * tp1R * rk
float t2 = ent + d * tp2R * rk
float t3 = ent + d * tp3R * rk
float inv = d == 1 ? refBot - 0.1 * atrN : refTop + 0.1 * atrN
curPlan := f_makePlan(d, ent, slv, t1, t2, t3, inv)
plans.push(curPlan)
while plans.size() > maxPlans
f_killPlan(plans.shift())
lastConfBar := bar_index
curSigDir := d
curSigStr := (d == 1 ? buyHigh : sellHigh) ? 3 : 2
curSigBar := bar_index
sigEv := d == 1 ? bullEv : bearEv
if showSignals
string txt = (d == 1 ? "BUY" : "SELL") + (curSigStr == 3 ? " ★" : "")
label sl_ = label.new(bar_index, d == 1 ? low : high, txt, xloc = xloc.bar_index, style = d == 1 ? label.style_label_up : label.style_label_down, color = d == 1 ? #00A843 : #D50000, textcolor = cWhite, size = curSigStr == 3 ? size.large : size.normal, tooltip = (curSigStr == 3 ? "HIGH-CONVICTION SETUP" : "CONFIRMED SETUP") + "\nEvidence: " + str.tostring(sigEv, "#") + "/100")
evLabels.push(sl_)
if dynAlerts
alert("PARE " + (curSigStr == 3 ? "HIGH-CONVICTION " : "CONFIRMED ") + (d == 1 ? "BUY" : "SELL") + " | " + syminfo.ticker + " " + timeframe.period + " | Entry " + str.tostring(ent, format.mintick) + " | SL " + str.tostring(slv, format.mintick) + " | TP1 " + str.tostring(t1, format.mintick) + " | TP2 " + str.tostring(t2, format.mintick) + " | TP3 " + str.tostring(t3, format.mintick), alert.freq_once_per_bar_close)
if earlyBuy or earlySell
int d2 = earlyBuy ? 1 : -1
lastEarlyBar := bar_index
if showSignals and showEarly
label el = label.new(bar_index, d2 == 1 ? low : high, d2 == 1 ? "e-BUY" : "e-SELL", xloc = xloc.bar_index, style = d2 == 1 ? label.style_label_up : label.style_label_down, color = color.new(d2 == 1 ? cBull : cBear, 55), textcolor = cWhite, size = size.tiny, tooltip = "EARLY SETUP (no trade plan — wait for confirmation)")
evLabels.push(el)
// Manage the active plan on confirmed bars (conservative: SL is checked before targets within one bar)
if not na(curPlan) and conf and bar_index > curPlan.entryBar
Plan p = curPlan
bool hSL = p.dir == 1 ? low <= p.sl : high >= p.sl
bool h1 = p.dir == 1 ? high >= p.tp1 : low <= p.tp1
bool h2 = p.dir == 1 ? high >= p.tp2 : low <= p.tp2
bool h3 = p.dir == 1 ? high >= p.tp3 : low <= p.tp3
int nh = h3 ? 3 : h2 ? 2 : h1 ? 1 : 0
evtDir := p.dir
if hSL
slEvt := true
evtLvl := p.sl
p.status := 1
else
if nh > p.hit
if p.hit < 1 and nh >= 1
tp1Evt := true
f_planMarkHit(p, 1)
if p.hit < 2 and nh >= 2
tp2Evt := true
f_planMarkHit(p, 2)
if p.hit < 3 and nh >= 3
tp3Evt := true
f_planMarkHit(p, 3)
evtLvl := nh == 3 ? p.tp3 : nh == 2 ? p.tp2 : p.tp1
p.hit := nh
if p.hit >= 3
p.status := 2
else if p.hit == 0 and (p.dir == 1 ? close < p.inv : close > p.inv)
invEvt := true
evtLvl := p.inv
p.status := 3
if p.status != 0
p.endBar := bar_index
if showPlans and not na(p.lbEntry)
if p.status == 1
label.set_text(p.lbSl, "SL ✗ " + str.tostring(p.sl, format.mintick))
else if p.status == 3
label.set_text(p.lbEntry, "ENTRY (INVALIDATED) " + str.tostring(p.entry, format.mintick))
f_planLayout(p, bar_index + 1)
curPlan := na
if dynAlerts and (tp1Evt or tp2Evt or tp3Evt or slEvt or invEvt)
string what = slEvt ? "STOP LOSS HIT" : invEvt ? "SETUP INVALIDATED" : tp3Evt ? "TP3 HIT" : tp2Evt ? "TP2 HIT" : "TP1 HIT"
alert("PARE " + what + " | " + (evtDir == 1 ? "BUY" : "SELL") + " | " + syminfo.ticker + " " + timeframe.period + " | Level " + str.tostring(evtLvl, format.mintick), alert.freq_once_per_bar_close)
if not na(curPlan)
f_planLayout(curPlan, math.max(curPlan.entryBar + planWidth, bar_index + 2))
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 14 — EVENT VISUALS (rejection markers, failed acceptance, transitions)
// ═══════════════════════════════════════════════════════════════════════════════════════════
bool rejBullEvt = warm and conf and rejBull >= 71.0 and nz(rejBull[1]) < 71.0 and bar_index - lastRejBullLbl > 8
bool rejBearEvt = warm and conf and rejBear >= 71.0 and nz(rejBear[1]) < 71.0 and bar_index - lastRejBearLbl > 8
if rejBullEvt
lastRejBullLbl := bar_index
if showRejMarkers
int ax = bar_index + lbOff
label l1 = label.new(ax, lowAnch, "Bullish Rejection\n(Score: " + str.tostring(int(math.round(rejBull))) + ")", xloc = xloc.bar_index, style = label.style_label_up, color = #064E5A, textcolor = #84FFFF, size = size.small, tooltip = "Rejection strength: " + f_band(rejBull, true))
evLabels.push(l1)
if showRings
evPolys.push(f_ring(ax, lowAnch + 0.2 * atrN, 3.0, 0.55 * atrN, color.new(cCyan, 70), 3))
evPolys.push(f_ring(ax, lowAnch + 0.2 * atrN, 3.0, 0.55 * atrN, cCyan, 1))
if rejBearEvt
lastRejBearLbl := bar_index
if showRejMarkers
int bx2 = bar_index + hbOff
label l2 = label.new(bx2, highAnch, "Bearish Rejection\n(Score: " + str.tostring(int(math.round(rejBear))) + ")", xloc = xloc.bar_index, style = label.style_label_down, color = #B71C1C, textcolor = cWhite, size = size.small, tooltip = "Rejection strength: " + f_band(rejBear, true))
evLabels.push(l2)
if showRings
evPolys.push(f_ring(bx2, highAnch - 0.2 * atrN, 3.0, 0.55 * atrN, color.new(cBear, 70), 3))
evPolys.push(f_ring(bx2, highAnch - 0.2 * atrN, 3.0, 0.55 * atrN, cBear, 1))
if failBullEvt and showFailed
box fb = box.new(evtStartB, evtTopB, bar_index, evtBotB, xloc = xloc.bar_index, border_color = color.new(cFail, 30), border_width = 1, border_style = line.style_dashed, bgcolor = color.new(cFail, 88))
evBoxes.push(fb)
label fl = label.new(bar_index - 2, close, failFormal ? "FAILED BULLISH ACCEPTANCE\n(Return Inside)" : "Failed Breakout\n(Return Inside)", xloc = xloc.bar_index, style = label.style_label_right, color = #4A148C, textcolor = #EA80FC, size = size.small, tooltip = "FAILED BULLISH ACCEPTANCE: price closed above the area, acceptance began to develop, then returned inside/below it.")
evLabels.push(fl)
if showRings
evPolys.push(f_ring(bar_index, close, 2.5, 0.5 * atrN, color.new(cFail, 70), 3))
evPolys.push(f_ring(bar_index, close, 2.5, 0.5 * atrN, cFail, 1))
if failBearEvt and showFailed
box fb2 = box.new(evtStartS, evtTopS, bar_index, evtBotS, xloc = xloc.bar_index, border_color = color.new(cFail, 30), border_width = 1, border_style = line.style_dashed, bgcolor = color.new(cFail, 88))
evBoxes.push(fb2)
label fl2 = label.new(bar_index - 2, close, failFormal ? "FAILED BEARISH ACCEPTANCE\n(Return Inside)" : "Failed Breakdown\n(Return Inside)", xloc = xloc.bar_index, style = label.style_label_right, color = #4A148C, textcolor = #EA80FC, size = size.small, tooltip = "FAILED BEARISH ACCEPTANCE: price closed below the area, acceptance began to develop, then returned inside/above it.")
evLabels.push(fl2)
if showRings
evPolys.push(f_ring(bar_index, close, 2.5, 0.5 * atrN, color.new(cFail, 70), 3))
evPolys.push(f_ring(bar_index, close, 2.5, 0.5 * atrN, cFail, 1))
if transText != "" and showTransitions
label tl = label.new(bar_index, transDir >= 0 ? low : high, transText, xloc = xloc.bar_index, style = transDir >= 0 ? label.style_label_up : label.style_label_down, color = color.new(cHeader, 20), textcolor = cWhite, size = size.tiny)
evLabels.push(tl)
f_trimLabels(evLabels, 150)
f_trimBoxes(evBoxes, 40)
f_trimPolys(evPolys, 40)
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 15 — MARKET STATE AND CURRENT SIGNAL
// ═══════════════════════════════════════════════════════════════════════════════════════════
string mState = "BALANCED"
color mStateCol = cGrey
if bar_index - math.max(lastFailBull, lastFailBear) <= 10
mState := "FAILED ACCEPTANCE"
mStateCol := cFail
else if bar_index - lastTransBar <= 8
mState := "TRANSITIONING"
mStateCol := cCyan
else if accD >= 51.0 and accD >= rejD
mState := "ACCEPTING"
mStateCol := cBull
else if rejD >= 51.0
mState := "REJECTING"
mStateCol := cBear
bool planActive = not na(curPlan)
string sigTxt = "WAITING"
color sigCol = cGrey
if planActive or (curSigDir != 0 and bar_index - curSigBar <= 10)
sigTxt := curSigDir == 1 ? "BUY" : "SELL"
sigCol := curSigDir == 1 ? cBull : cBear
else if bar_index - lastEarlyBar <= 3 and (earlyBuy or earlySell or bar_index == lastEarlyBar)
sigTxt := "EARLY"
sigCol := cAmb
else if conflictLvl == "HIGH"
sigTxt := "NO TRADE"
sigCol := cAmb
float setupStrength = planActive ? sigEv : math.max(bullEv, bearEv)
color setupCol = (planActive and curSigDir == -1) or (not planActive and bearEv > bullEv) ? cBear : cBull
color ctrlCol = control == "BUYERS" ? cBull : control == "SELLERS" ? cBear : cAmb
color confCol = conflictLvl == "LOW" ? cBull : conflictLvl == "MODERATE" ? cAmb : cBear
float behavMom = momDom
float stayShow = stayDom
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 16 — DASHBOARD: PRICE BEHAVIOUR TERMINAL
// ═══════════════════════════════════════════════════════════════════════════════════════════
string dashPosStr = f_pos(dashPosIn)
var table dash = table.new(dashPosStr, 12, 15, bgcolor = cNavy, frame_color = cFrame, frame_width = 2, border_width = 0)
var table strip = table.new(position.bottom_left, 5, 1, bgcolor = cNavy, frame_color = cFrame, frame_width = 1, border_color = cFrame, border_width = 1)
if barstate.isfirst and showDash
for r = 0 to 14
for c = 0 to 11
table.cell(dash, c, r, "", width = c == 0 ? 11.0 : c == 1 ? 3.0 : 1.1, text_color = cWhite, text_halign = c == 1 ? text.align_center : text.align_left, text_size = size.small, bgcolor = cNavy)
table.merge_cells(dash, 0, 0, 11, 0)
for rr in array.from(1, 8, 9, 10, 11, 13, 14)
table.merge_cells(dash, 1, rr, 11, rr)
table.merge_cells(dash, 0, 12, 1, 12)
table.cell_set_text_halign(dash, 0, 0, text.align_left)
for rr in array.from(1, 8, 9, 10, 11, 13, 14)
table.cell_set_text_halign(dash, 1, rr, text.align_right)
if barstate.islast and showDash
// header
table.cell_set_text(dash, 0, 0, "📈 PRICE BEHAVIOUR TERMINAL")
table.cell_set_bgcolor(dash, 0, 0, cHeader)
table.cell_set_text_size(dash, 0, 0, size.normal)
table.cell_set_tooltip(dash, 0, 0, "Price Acceptance vs Rejection Engine [PARE]\nAuthor / Publisher: Michael_Fx_Trader\nScores are technical evidence, not a probability of winning.")
// market state
table.cell_set_text(dash, 0, 1, "MARKET STATE")
table.cell_set_text(dash, 1, 1, mState + " ●")
table.cell_set_text_color(dash, 1, 1, mStateCol)
// bar rows
array<string> lbls = array.from("BULLISH ACCEPTANCE", "BEARISH ACCEPTANCE", "BULLISH REJECTION", "BEARISH REJECTION", "STAYING POWER", "MOMENTUM")
array<float> vals = array.from(accBull, accBear, rejBull, rejBear, stayShow, behavMom)
array<color> cols = array.from(cBull, cBear, cCyan, cPurple, cAmb, cBlueM)
for k = 0 to 5
int r = 2 + k
float v = vals.get(k)
color cc = cols.get(k)
int filled = int(math.round(v / 10.0))
table.cell_set_text(dash, 0, r, lbls.get(k))
table.cell_set_text(dash, 1, r, str.tostring(int(math.round(v))))
table.cell_set_text_color(dash, 1, r, cc)
string tip = k == 4 ? "Staying power: " + f_band(v, false) : k == 5 ? "Behaviour momentum (decay score: " + str.tostring(int(math.round(momDecay))) + ")" : lbls.get(k) + ": " + f_band(v, k == 2 or k == 3)
table.cell_set_tooltip(dash, 0, r, tip)
for j = 0 to 9
table.cell_set_bgcolor(dash, 2 + j, r, j < filled ? cc : cDim)
// control / conflict
table.cell_set_text(dash, 0, 8, "MARKET CONTROL")
table.cell_set_text(dash, 1, 8, control)
table.cell_set_text_color(dash, 1, 8, ctrlCol)
table.cell_set_text(dash, 0, 9, "CONFLICT STATUS")
table.cell_set_text(dash, 1, 9, conflictLvl)
table.cell_set_text_color(dash, 1, 9, confCol)
table.cell_set_tooltip(dash, 0, 9, "Classification: " + conflictClass + " | Conflict score: " + str.tostring(int(math.round(conflictScore))))
// signal
table.cell_set_text(dash, 0, 10, "CURRENT SIGNAL")
table.cell_set_text(dash, 1, 10, (sigTxt == "BUY" ? "▲ " : sigTxt == "SELL" ? "▼ " : "") + sigTxt)
table.cell_set_text_color(dash, 1, 10, sigCol)
table.cell_set_text_size(dash, 1, 10, size.large)
table.cell_set_text(dash, 0, 11, "SETUP STRENGTH")
table.cell_set_text(dash, 1, 11, str.tostring(int(math.round(setupStrength))) + "/100")
table.cell_set_text_color(dash, 1, 11, #C6FF00)
int dots = int(math.round(setupStrength / 10.0))
for j = 0 to 9
table.cell_set_text(dash, 2 + j, 12, "●")
table.cell_set_text_color(dash, 2 + j, 12, j < dots ? setupCol : cDim)
table.cell_set_text_halign(dash, 2 + j, 12, text.align_center)
table.cell_set_text(dash, 0, 13, "REFERENCE AREA")
table.cell_set_text(dash, 1, 13, str.tostring(refBot, format.mintick) + " – " + str.tostring(refTop, format.mintick))
table.cell_set_text_color(dash, 1, 13, cWhite)
if showHtfRow
table.cell_set_text(dash, 0, 14, "HTF " + htf1)
table.cell_set_text(dash, 1, 14, f_htfText(h1Bias) + (h2Valid ? " | " + htf2 + ": " + f_htfText(h2Bias) : ""))
table.cell_set_text_color(dash, 1, 14, na(h1Bias) ? cGrey : h1Bias >= 15 ? cBull : h1Bias <= -15 ? cBear : cAmb)
if barstate.isfirst and showStrip
for c = 0 to 4
table.cell(strip, c, 0, "", width = 9.0, text_color = cWhite, text_size = size.small, text_halign = text.align_left, bgcolor = cNavy)
if barstate.islast and showStrip
table.cell_set_text(strip, 0, 0, "〰 Compression\n(" + str.tostring(int(math.round(compress))) + "%)")
table.cell_set_text_color(strip, 0, 0, cPurple)
table.cell_set_text(strip, 1, 0, "🛡 Acceptance\n(" + str.tostring(int(math.round(accMax))) + "%)")
table.cell_set_text_color(strip, 1, 0, cBlueM)
table.cell_set_text(strip, 2, 0, "⛔ Rejection\n(" + str.tostring(int(math.round(rejMax))) + "%)")
table.cell_set_text_color(strip, 2, 0, #FF8A80)
table.cell_set_text(strip, 3, 0, "⚡ Momentum\n(" + str.tostring(int(math.round(momDom))) + "%)")
table.cell_set_text_color(strip, 3, 0, cAmb)
table.cell_set_text(strip, 4, 0, "🎯 Transition\n" + lastTransShort)
table.cell_set_text_color(strip, 4, 0, cCyan)
table.cell_set_tooltip(strip, 4, 0, "Last confirmed transition: " + lastTrans)
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 17 — DATA WINDOW OUTPUT
// ═══════════════════════════════════════════════════════════════════════════════════════════
plot(accBull, "Bullish Acceptance", display = display.data_window)
plot(accBear, "Bearish Acceptance", display = display.data_window)
plot(rejBull, "Bullish Rejection", display = display.data_window)
plot(rejBear, "Bearish Rejection", display = display.data_window)
plot(stayBull, "Staying Power (Bull)", display = display.data_window)
plot(stayBear, "Staying Power (Bear)", display = display.data_window)
plot(momBull, "Behaviour Momentum Bull", display = display.data_window)
plot(momBear, "Behaviour Momentum Bear", display = display.data_window)
plot(momDecay, "Momentum Decay", display = display.data_window)
plot(bullEv, "Bullish Evidence", display = display.data_window)
plot(bearEv, "Bearish Evidence", display = display.data_window)
plot(conflictScore, "Conflict Score", display = display.data_window)
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SECTION 18 — ALERT CONDITIONS
// (message placeholders carry symbol, timeframe and price; dynamic alert() adds Entry/SL/TP levels)
// ═══════════════════════════════════════════════════════════════════════════════════════════
bool evAccBull = warm and conf and accBull >= 51.0 and nz(accBull[1]) < 51.0
bool evAccBear = warm and conf and accBear >= 51.0 and nz(accBear[1]) < 51.0
bool evStayB = warm and conf and stayBull >= stayThr and nz(stayBull[1]) < stayThr
bool evStayS = warm and conf and stayBear >= stayThr and nz(stayBear[1]) < stayThr
bool evStay = evStayB or evStayS
bool evBuyCtl = warm and conf and control == "BUYERS" and control[1] != "BUYERS"
bool evSellCtl = warm and conf and control == "SELLERS" and control[1] != "SELLERS"
alertcondition(evAccBull, "PARE: New Bullish Acceptance", "PARE | New BULLISH ACCEPTANCE | {{ticker}} | {{interval}} | Close {{close}}")
alertcondition(evAccBear, "PARE: New Bearish Acceptance", "PARE | New BEARISH ACCEPTANCE | {{ticker}} | {{interval}} | Close {{close}}")
alertcondition(rejBullEvt, "PARE: Strong Bullish Rejection", "PARE | STRONG BULLISH REJECTION | {{ticker}} | {{interval}} | Close {{close}}")
alertcondition(rejBearEvt, "PARE: Strong Bearish Rejection", "PARE | STRONG BEARISH REJECTION | {{ticker}} | {{interval}} | Close {{close}}")
alertcondition(failBullEvt, "PARE: Failed Bullish Acceptance", "PARE | FAILED BULLISH ACCEPTANCE | {{ticker}} | {{interval}} | Close {{close}}")
alertcondition(failBearEvt, "PARE: Failed Bearish Acceptance", "PARE | FAILED BEARISH ACCEPTANCE | {{ticker}} | {{interval}} | Close {{close}}")
alertcondition(transAccToRej, "PARE: Acceptance to Rejection", "PARE | TRANSITION Acceptance -> Rejection | {{ticker}} | {{interval}} | Close {{close}}")
alertcondition(transRejToAcc, "PARE: Rejection to Acceptance", "PARE | TRANSITION Rejection -> Acceptance | {{ticker}} | {{interval}} | Close {{close}}")
alertcondition(evStay, "PARE: Staying Power Confirmation", "PARE | STAYING POWER CONFIRMED | {{ticker}} | {{interval}} | Close {{close}}")
alertcondition(evBuyCtl, "PARE: Buyer Control", "PARE | BUYER CONTROL | {{ticker}} | {{interval}} | Close {{close}}")
alertcondition(evSellCtl, "PARE: Seller Control", "PARE | SELLER CONTROL | {{ticker}} | {{interval}} | Close {{close}}")
alertcondition(sigBuy, "PARE: Confirmed BUY", "PARE | CONFIRMED BUY | {{ticker}} | {{interval}} | Entry {{close}}")
alertcondition(sigSell, "PARE: Confirmed SELL", "PARE | CONFIRMED SELL | {{ticker}} | {{interval}} | Entry {{close}}")
alertcondition(invEvt, "PARE: Setup Invalidation", "PARE | SETUP INVALIDATED | {{ticker}} | {{interval}} | Close {{close}}")
alertcondition(tp1Evt, "PARE: TP1 Hit", "PARE | TP1 HIT | {{ticker}} | {{interval}} | Close {{close}}")
alertcondition(tp2Evt, "PARE: TP2 Hit", "PARE | TP2 HIT | {{ticker}} | {{interval}} | Close {{close}}")
alertcondition(tp3Evt, "PARE: TP3 Hit", "PARE | TP3 HIT | {{ticker}} | {{interval}} | Close {{close}}")
alertcondition(slEvt, "PARE: Stop Loss Hit", "PARE | STOP LOSS HIT | {{ticker}} | {{interval}} | Close {{close}}")