STRYK: CHANGE OF CHARACTER

Es-Sniper · study · 1078 行 · 点赞 32 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// STRYK: CHANGE OF CHARACTER v1.5.1 (short title STRYK:CHCH)
// ---------------------------------------------------------------------------------------------------------
// One job: tell a TRUE change of character from a wobble, and give a buy / sell signal only on the true one.
//
// The idea (settled over three design rounds with an independent review):
//   A low is only a STRUCTURAL (protected) low if the rally from it closed above the previous swing high — it
//   is the low that BUILT the last higher high. Every other dip is internal and never a reference. A bearish
//   change of character is a candle CLOSE below the protected low by a real margin (displacement). Mirror for
//   bulls. A break of a protected level in the direction of the trend is a BOS (continuation) and simply moves
//   the protected level forward.
//
// How the structure engine runs (no repainting):
//   • Candidate swings are confirmed fractals (N candles each side) — a swing exists only after its right-side
//     candles have closed.
//   • Structure can be computed on the chart timeframe or on a higher timeframe (default 240 = 4-hour) while
//     you watch a lower chart. In higher-timeframe mode the whole engine runs inside the higher-timeframe
//     context on the PREVIOUS completed candle (open[1] … close[1]) with lookahead_on — the TradingView
//     documented non-repainting form — so an event becomes known on the first chart candle after the
//     4-hour candle closes, never before, and never changes afterwards.
//   • The pullback low that produced a break is the lowest low between the broken swing high and the break
//     candle, read from candles that have already closed (running minimum) — no look-ahead, no retroactive
//     promotion.
//
// Trade plan (one at a time, drawn only for the active one):
//   entry = next executable chart price (open of the first chart candle after the signal), hard stop just past
//   the swing that produced the move (+ buffer), target 1R by default (1.5R / 2R selectable). Same-candle stop
//   and target = loss. A new opposite CHoCH supersedes an open plan. Dollar risk from the symbol's point value;
//   plans above the risk cap are marked OVER CAP and counted separately (the tradability record).
//
// Filters (each a master switch, defaults from the source test): New York candle-close window, skip into a
//   3-day run (three completed CME trading days), confirmation candle (off), acceptance (off, measured).
//
// Scorecard: every CHoCH is measured — win % at 1R, net R after costs, 1.5R / 2R counterfactuals, follow-through
//   (a BOS in the signal direction within 12 structure candles), FAILED rate (close back across the level within
//   2 candles), MFE / MAE — for ALL signals and for the TAKEN ones (passed filters, under cap). Nothing here is a
//   claim; it is what happened on this chart under these settings.
//
// v1.5.1 (Nov 1 2026): retest target options (1R / 1.5R / 2R default / 3R of the retest stop, or the original plan target) and
//   retest average MFE in the table — first live cards showed 0 / 25 with the far structural target and ~7-point stops.
// v1.5 (Nov 1 2026): RETEST PLAN (group 5) — second, separately scored entry for small accounts: after a CHoCH wait up to K chart
//   candles for the pullback to the broken level, enter on the first chart close back in the signal direction, stop past the
//   retest extreme, target = the original plan's 1R. Own rows in the table, own marks (RT ▲/▼), 3 alerts. Plots 24 / 64.
// v1.4.1 (Nov 1 2026): compile fixes — tuple variable renamed (collided with the Target colour input), short title cut to 10 characters.
// v1.4 (Nov 1 2026): STOP PLACEMENT — default moved to the LAST SWING before the break (the source rule), not the leg origin;
//   group 4 dropdown keeps the structural stop as an option. Protected levels unchanged. Live cards showed leg-origin stops of
//   65–100 points on MES, which is why nothing was TAKEN.
// v1.3.1 (Nov 1 2026): scorecard row "avg stop pts / $ · min – max" (ALL and TAKEN) so the tradability problem is visible in numbers.
// v1.3 (Nov 1 2026): protected and plan lines default DOTTED and extend 500 candles past the current one; extension selectable
//   (to current / 50 / 100 / 250 / 500 / right edge) per line kind in group 3; styles stay selectable. Plan label rides the line end.
// v1.2 (Nov 1 2026): alerts on every signal — BOS up / down, CHoCH failed, plan superseded / cancelled, and ANY SIGNAL (10 alertconditions)
//   plus alert() messages with live prices for all of them. Plots 21 / 64.
// v1.1.1 (Nov 1 2026): candle colours on EVERY bar (no structure yet = Standby) and a Paint mode: DRAW CANDLES (plotcandle, shows even
//   when the chart's own candles are hidden — default) or RECOLOUR chart candles (barcolor). Distinct default colours. Plots 16 / 64.
// v1.1 (Nov 1 2026): candle colour engine — green bias UP, red bias DOWN, blue STANDBY (no structure / failed CHoCH not yet
//   replaced) + an estimated HTF-delta option; inputs appended as group 2. Budgets: plots 24 / 64 (13 alertconditions + bgcolor + barcolor + plotcandle), lines ≤ 5 live (max 50), labels ≤ 500 pooled,
//   one request.security for the structure timeframe + one for the daily closes. All inputs have tooltips.
// Pine v6 rules honoured: ta.* / request.* called every bar; no unconfirmed pivots; loops guarded (no descending
//   ranges); array reads clamped; inputs only appended in later versions (saved layouts map by position).
// ---------------------------------------------------------------------------------------------------------
//@version=6
indicator("STRYK: CHANGE OF CHARACTER", "STRYK:CHCH", overlay = true, max_lines_count = 50, max_labels_count = 500, max_bars_back = 500)
 
// ============================================================================================================
// INPUTS
// ============================================================================================================
string GM = "MASTER SWITCHES"
mOn    = input.bool(true, "Indicator on", group = GM,
     tooltip = "Master switch. Off hides everything and stops the alerts.")
tfMode = input.string("Higher timeframe (below)", "STRUCTURE FROM", options = ["Higher timeframe (below)", "Chart timeframe"], group = GM, inline = "tf", display = display.none)
tfIn   = input.timeframe("240", "", group = GM, inline = "tf",
     tooltip = "Where the swings and the change of character are measured. HIGHER TIMEFRAME: the structure runs on the timeframe in the box (240 = 4-hour, the tested default) while you watch a lower chart, e.g. the 5-minute — signals appear on the first chart candle after that higher candle closes and never repaint. CHART TIMEFRAME: structure from the candles you are looking at. If the chart timeframe is above the structure timeframe the script falls back to Chart mode and says so in the table.", display = display.none)
pivOpt = input.string("2 candles", "Swing strength", options = ["1 candle", "2 candles", "3 candles"], group = GM, inline = "sw", display = display.none)
dspOpt = input.string("0.10 ATR", "displacement", options = ["None", "2 ticks", "0.10 ATR", "0.20 ATR"], group = GM, inline = "sw",
     tooltip = "SWING STRENGTH: how many candles each side a high or low needs before it counts as a candidate swing (2 = tested default; 1 = more sensitive, 3 = fewer, later swings). DISPLACEMENT: how far the candle must CLOSE beyond the protected level for the break to count as a change of character — a hairline close through is not a change of character. ATR is the 14-candle ATR of the structure timeframe.", display = display.none)
accOpt = input.string("Off (measure only)", "Acceptance", options = ["Off (measure only)", "1 candle", "2 candles"], group = GM, inline = "ac", display = display.none)
cnfOpt = input.string("Off", "confirmation candle", options = ["Off", "On"], group = GM, inline = "ac",
     tooltip = "ACCEPTANCE: OFF = the signal fires at the breaking close and the script only MEASURES whether price closed back across the level within 2 candles (shown as FAILED on the mark and counted in the table). 1 / 2 CANDLES = the entry waits until that many structure candles have closed without a close back across the level; a close back cancels the trade. CONFIRMATION CANDLE: ON = the next structure candle must also close in the signal direction before entry (the source test found this helps on NQ, not on ES). Both add delay — that is the trade-off.", display = display.none)
sesOpt = input.string("New York closes (07:00–15:00)", "New York filter", options = ["Off", "New York closes (07:00–15:00)", "Cash close (11:00–17:30)"], group = GM, inline = "f1", display = display.none)
runOpt = input.string("On", "skip 3-day run", options = ["On", "Off"], group = GM, inline = "f1",
     tooltip = "NEW YORK FILTER: a signal counts only if the structure candle CLOSES inside the window (Chicago time). On the 4-hour, CME candles close at 21:00, 01:00, 05:00, 09:00, 13:00 and 17:00 — so NEW YORK CLOSES keeps only the 09:00 and 13:00 closes, CASH CLOSE keeps 13:00 and 17:00. On a 5-minute chart in Chart mode the window is simply the New York session. SKIP 3-DAY RUN: no long after three up days in a row, no short after three down days (completed CME trading days, settlement to settlement) — the source test found entries into a 3-day run lose. Filtered signals are still marked (dim) and measured in the ALL column.", display = display.none)
rrOpt  = input.string("1R (tested)", "Target", options = ["1R (tested)", "1.5R", "2R"], group = GM, inline = "pl", display = display.none)
capOpt = input.string("$100", "risk cap", options = ["Off", "$50", "$100", "$150", "$200", "$300"], group = GM, inline = "pl",
     tooltip = "TARGET: profit target as a multiple of the stop distance (the source test used 1R; 1.5R and 2R are always measured in the table whatever you pick here). RISK CAP: a plan whose stop distance costs more than this for one contract (from the symbol's point value — MES $5 a point) is marked OVER CAP: it is still drawn and measured in ALL, but not counted as TAKEN. Set to Off to take every signal.", display = display.none)
bufOpt = input.string("2 ticks", "Stop buffer", options = ["0", "1 tick", "2 ticks", "4 ticks"], group = GM, inline = "pl2", display = display.none)
cstOpt = input.string("$4 (research)", "round-trip cost", options = ["$0", "$2", "$4 (research)", "$6"], group = GM, inline = "pl2",
     tooltip = "STOP BUFFER: ticks added beyond the swing extreme for the hard stop. ROUND-TRIP COST: commissions, fees and spread per contract charged against every closed trade in the net-R figures ($4 is a conservative research budget for MES).", display = display.none)
bosOn  = input.string("On", "BOS marks", options = ["On", "Off"], group = GM, inline = "sh", display = display.none)
intOn  = input.string("On", "internal breaks", options = ["On", "Off"], group = GM, inline = "sh", display = display.none)
refOn  = input.string("On", "protected levels", options = ["On", "Off"], group = GM, inline = "sh",
     tooltip = "BOS MARKS: small marks where price broke a swing in the direction of the trend (continuation — not a signal). INTERNAL BREAKS: tiny dim marks where price closed below a minor low (or above a minor high) that was NOT the protected level — the wobbles the indicator refused to call a change of character. PROTECTED LEVELS: the active protected low / high drawn as a line from the swing that made it.", display = display.none)
planOn = input.string("On", "Plan lines", options = ["On", "Off"], group = GM, inline = "sh2", display = display.none)
bgOpt  = input.string("Off", "bias tint", options = ["Off", "Light", "Medium"], group = GM, inline = "sh2",
     tooltip = "PLAN LINES: entry, stop and target of the ACTIVE plan only (finished plans leave their result on the signal mark). BIAS TINT: a faint background colour for the current structure bias (up / down).", display = display.none)
tbOn   = input.string("On", "Table", options = ["On", "Off"], group = GM, inline = "tb", display = display.none)
tbPos  = input.string("Bottom left", "position", options = ["Bottom left", "Bottom right", "Top left", "Top right", "Middle left", "Middle right"], group = GM, inline = "tb", display = display.none)
tbSize = input.string("Small", "size", options = ["Tiny", "Small", "Normal"], group = GM, inline = "tb",
     tooltip = "The scorecard: bias, protected levels, the active plan, and how every change of character on this chart has resolved — ALL signals and TAKEN signals (passed the filters and under the risk cap) side by side. Small is the phone default.", display = display.none)
alOn   = input.string("On", "Alerts", options = ["On", "Off"], group = GM,
     tooltip = "Ten alert conditions: Bull CHoCH, Bear CHoCH, Entry filled, Target hit, Stop hit, BOS up, BOS down, CHoCH failed, Plan superseded / cancelled, and ANY SIGNAL (fires on every one of them — pick this one if you want a single alert for everything). Create them from the alert dialog with condition = this indicator; or choose 'Any alert() function call' to get the messages with the live prices in them.", display = display.none)
 
string G1 = "1 · Looks"
cBull  = input.color(#4ADE80, "Bull", group = G1, inline = "c1", display = display.none)
cBear  = input.color(#F87171, "Bear", group = G1, inline = "c1", display = display.none)
cNeu   = input.color(#9CA3AF, "Neutral", group = G1, inline = "c1",
     tooltip = "BULL: bullish change of character marks, the protected low line, long plan. BEAR: bearish marks, protected high line, short plan. NEUTRAL: internal-break marks, filtered or superseded results, the table's dim text.", display = display.none)
cStop  = input.color(#FBBF24, "Stop", group = G1, inline = "c2", display = display.none)
cTgt   = input.color(#60A5FA, "Target", group = G1, inline = "c2", display = display.none)
cFail  = input.color(#F472B6, "Failed", group = G1, inline = "c2",
     tooltip = "STOP / TARGET: the plan lines and their labels. FAILED: a change of character that closed back across its level inside the acceptance window.", display = display.none)
mkStyle = input.string("Pointer label", "CHoCH mark", options = ["Pointer label", "Text only", "Triangle"], group = G1, inline = "m", display = display.none)
mkSize = input.string("Small", "size", options = ["Tiny", "Small", "Normal", "Large"], group = G1, inline = "m", display = display.none)
mkText = input.color(#111111, "text", group = G1, inline = "m",
     tooltip = "The change-of-character mark: a pointer box with text, text only, or a triangle. Size and text colour. The mark updates with the result (✓ 1R, ✗, FAILED, SUP = superseded, OVER CAP, FILTERED).", display = display.none)
bosSize = input.string("Tiny", "BOS / internal size", options = ["Tiny", "Small", "Normal"], group = G1, inline = "b", display = display.none)
bosTr  = input.string("Dim", "opacity", options = ["Dim", "Normal", "Strong"], group = G1, inline = "b",
     tooltip = "Size and opacity of the BOS marks and the internal-break marks.", display = display.none)
refW   = input.int(1, "Protected line width", minval = 1, maxval = 4, group = G1, inline = "r", display = display.none)
refSty = input.string("Dotted", "style", options = ["Solid", "Dashed", "Dotted"], group = G1, inline = "r", display = display.none)
refLbl = input.string("On", "tag", options = ["On", "Off"], group = G1, inline = "r",
     tooltip = "The protected low / high lines: width, style, and whether each carries a small price tag at its right end.", display = display.none)
plW    = input.int(1, "Plan line width", minval = 1, maxval = 4, group = G1, inline = "p", display = display.none)
plSty  = input.string("Dotted", "style", options = ["Solid", "Dashed", "Dotted"], group = G1, inline = "p", display = display.none)
plSize = input.string("Small", "label", options = ["Tiny", "Small", "Normal"], group = G1, inline = "p",
     tooltip = "Entry / stop / target lines of the active plan: width, style, and the size of the plan label (direction, stop, target, risk in points and dollars).", display = display.none)
tbBg   = input.color(#131722, "Table background", group = G1, inline = "t", display = display.none)
tbTxt  = input.color(#D1D4DC, "body", group = G1, inline = "t", display = display.none)
tbHead = input.color(#787B86, "headers", group = G1, inline = "t",
     tooltip = "Table colours: background, body text, dim headers.", display = display.none)
 
string GC = "2 · Candle colours (v1.1)"
ccOpt  = input.string("CHoCH bias", "CANDLE COLOURS", options = ["Off", "CHoCH bias", "HTF delta (estimated)"], group = GC,
     tooltip = "OFF: chart candles untouched. CHoCH BIAS: candles painted from the structure engine — green while the bias is UP (last change of character or BOS was bullish), red while DOWN, blue on STANDBY: no structure yet, or the latest change of character FAILED (closed back across its level) and no BOS or new change of character has confirmed a direction since. HTF DELTA (estimated): candles painted by the previous completed structure-timeframe candle's estimated delta — where it closed inside its range times its volume — green buyers, red sellers, blue when it is near flat (within 20% of the candle's volume). Estimated from price and volume only; it is not footprint data.", display = display.none)
ccUp   = input.color(#00E676, "Up", group = GC, inline = "cc", display = display.none)
ccDn   = input.color(#FF1744, "Down", group = GC, inline = "cc", display = display.none)
ccSb   = input.color(#2979FF, "Standby", group = GC, inline = "cc",
     tooltip = "Candle colours for up, down and standby / sideways.", display = display.none)
ccTr   = input.string("Solid", "Candle opacity", options = ["Solid", "Soft"], group = GC,
     tooltip = "SOLID paints the candles fully; SOFT leaves them slightly see-through so the original up / down body colour still shows underneath.", display = display.none)
ccMode = input.string("Draw candles (always visible)", "Paint mode", options = ["Draw candles (always visible)", "Recolour chart candles"], group = GC,
     tooltip = "DRAW CANDLES: the script draws its own full candles (body, wick and border) in the engine colours on every bar — they show even when the chart's own candles are hidden or transparent, which is the usual setup when several candle engines are on one chart. RECOLOUR: the chart's native candles are recoloured instead (needs the chart candles visible). Every bar gets a colour in both modes; before the first structure exists the colour is Standby.", display = display.none)
 
string GL = "3 · Line extension (v1.3)"
refExt = input.string("500 candles", "Protected lines extend", options = ["To current candle", "50 candles", "100 candles", "250 candles", "500 candles", "To the right edge"], group = GL,
     tooltip = "How far the protected low / high lines run past the current candle, in chart candles (the price tag sits at the end). TO THE RIGHT EDGE runs the line to the edge of the chart.", display = display.none)
plExt  = input.string("500 candles", "Plan lines extend", options = ["To current candle", "50 candles", "100 candles", "250 candles", "500 candles", "To the right edge"], group = GL,
     tooltip = "How far the entry / stop / target lines of the active plan run past the current candle, in chart candles.", display = display.none)
 
string GS = "4 · Stop placement (v1.4)"
stopOpt = input.string("Last swing (tested rule)", "Stop at", options = ["Last swing (tested rule)", "Leg origin (structural)"], group = GS,
     tooltip = "LAST SWING: the hard stop goes just past the most recent confirmed swing before the break — the lower high before a bearish change of character, the higher low before a bullish one. This is the source rule ('just past the last swing high or low') and gives a much smaller stop. LEG ORIGIN: the stop goes past the swing that produced the whole leg — the same price as the new protected level — which is wider and rarely hit. The protected level itself is unchanged either way; this only moves the stop.", display = display.none)
 
string GR = "5 · Retest entry (v1.5)"
rtOn   = input.string("On", "RETEST PLAN", options = ["On", "Off"], group = GR, inline = "rt", display = display.none)
rtWait = input.string("24 candles", "wait up to", options = ["12 candles", "24 candles", "48 candles", "96 candles"], group = GR, inline = "rt",
     tooltip = "A second, separately scored plan for small accounts. After a change of character, wait up to this many CHART candles for price to come back to the broken level (the retest). Entry = the first chart candle that closes back in the signal direction after the touch, filled at the next open. Stop = just past the retest extreme (the highest high of the pullback for a short, the lowest low for a long) + buffer. Target = the ORIGINAL plan's 1R target, so the reward stays the structure's, only the stop shrinks. Cancelled if price reaches the original target before the retest, if the pullback runs past the original stop, or if the wait runs out. Scored in its own rows of the table; never mixed with the original plan.", display = display.none)
rtTol  = input.string("0 ticks", "touch tolerance", options = ["0 ticks", "2 ticks", "4 ticks"], group = GR, inline = "rt2", display = display.none)
rtLines = input.string("On", "lines", options = ["On", "Off"], group = GR, inline = "rt2",
     tooltip = "TOUCH TOLERANCE: how close price must come to the broken level to count as a retest (0 = must touch or cross). LINES: draw the retest plan's entry / stop / target while it is active.", display = display.none)
rtTgt  = input.string("2R of the retest stop", "Retest target", options = ["1R of the retest stop", "1.5R of the retest stop", "2R of the retest stop", "3R of the retest stop", "Original plan target"], group = GR,
     tooltip = "What the retest plan aims for. R OF THE RETEST STOP: a multiple of the retest's own (small) stop distance — the realistic choice on a 5-minute entry. ORIGINAL PLAN TARGET: the structure plan's 1R level, far away relative to a 5-minute stop (on the first live cards this went 0 for 25). The table shows the retest's average favourable excursion in R so you can see how far these trades actually travel before choosing.", display = display.none)
 
// ============================================================================================================
// CONSTANTS
// ============================================================================================================
string TZ    = "America/Chicago"
float  TICK  = syminfo.mintick
float  PTVAL = syminfo.pointvalue
int    N     = pivOpt == "1 candle" ? 1 : pivOpt == "3 candles" ? 3 : 2
int    ACCM  = accOpt == "1 candle" ? 1 : accOpt == "2 candles" ? 2 : 0
bool   CNF   = cnfOpt == "On"
float  RR    = rrOpt == "1.5R" ? 1.5 : rrOpt == "2R" ? 2.0 : 1.0
float  CAP   = capOpt == "Off" ? 1e12 : capOpt == "$50" ? 50 : capOpt == "$150" ? 150 : capOpt == "$200" ? 200 : capOpt == "$300" ? 300 : 100
float  BUF   = (bufOpt == "0" ? 0 : bufOpt == "1 tick" ? 1 : bufOpt == "4 ticks" ? 4 : 2) * TICK
float  COST  = cstOpt == "$0" ? 0 : cstOpt == "$2" ? 2 : cstOpt == "$6" ? 6 : 4
int    FTH   = 12                      // follow-through horizon in structure candles
int    MEASM = 2                       // FAILED measurement window when acceptance is Off
int    MAXMK = 110                     // pooled marks per kind (4 pools ≤ 440 + fixed labels ≤ 500)
int    RTK   = rtWait == "12 candles" ? 12 : rtWait == "48 candles" ? 48 : rtWait == "96 candles" ? 96 : 24
float  RTOL  = (rtTol == "2 ticks" ? 2 : rtTol == "4 ticks" ? 4 : 0) * TICK
bool   RTON  = rtOn == "On"
bool   htfOK = timeframe.in_seconds() < timeframe.in_seconds(tfIn)
bool   useHTF = tfMode == "Higher timeframe (below)" and htfOK
bool   vis   = mOn
f_ext(string s) => s == "To current candle" ? 0 : s == "50 candles" ? 50 : s == "100 candles" ? 100 : s == "250 candles" ? 250 : 500
int    REFX  = f_ext(refExt)
int    PLX   = f_ext(plExt)
bool   REFINF = refExt == "To the right edge"
bool   PLINF  = plExt == "To the right edge"
int    BARMS  = timeframe.in_seconds() * 1000          // chart candle length in ms (time-based lines extend by candles × this)
 
// ============================================================================================================
// STRUCTURE ENGINE — pure function, runs on the chart or inside the higher-timeframe context
// Inputs are the candle series (lagged by one in the higher-timeframe context so only closed candles count).
// Returns: bias, protected low (+time), protected high (+time), event, event id, broken level, swing extreme
// for the stop, the close, candle time, candle close time.
// Events: 2 bull CHoCH · -2 bear CHoCH · 1 BOS up · -1 BOS down · 3 internal break up · -3 internal break down
// ============================================================================================================
f_eng(float o, float h, float l, float c, int tm, int tc, float atrV) =>
    var int   bias    = 0
    var float refLo   = na
    var int   refLoT  = na
    var float refHi   = na
    var int   refHiT  = na
    var float lastPH  = na
    var bool  phBrk   = true
    var float lastPL  = na
    var bool  plBrk   = true
    // tracker A: since the last candidate swing high — running low (the pullback) and the high made since it
    var float aLo = na
    var int   aLoT = na
    var float aHi = na
    var int   aHiT = na
    // tracker B: since the last candidate swing low — running high and the low made since it
    var float bHi = na
    var int   bHiT = na
    var float bLo = na
    var int   bLoT = na
    // tracker C: since the protected high — running low (origin of the next rally) and the high since it
    var float cLo = na
    var int   cLoT = na
    var float cHi = na
    var int   cHiT = na
    // tracker D: since the protected low — running high (origin of the next drop) and the low since it
    var float dHi = na
    var int   dHiT = na
    var float dLo = na
    var int   dLoT = na
    var int   evId = 0
    int   evt   = 0
    float evLvl = na
    float evExt = na
    float evTight = na        // last candidate swing before the break (the "last swing" stop of the source rules)
    // candidate swings (confirmed N candles later) — ta.* called every bar
    float ph    = ta.pivothigh(h, N, N)
    float pl    = ta.pivotlow(l, N, N)
    float lowN  = ta.lowest(l, N)
    int   lowNb = ta.lowestbars(l, N)
    float highN = ta.highest(h, N)
    int   highNb = ta.highestbars(h, N)
    if not na(ph)
        lastPH := ph
        phBrk  := false
        aLo    := lowN
        aLoT   := tm[math.max(0, -nz(lowNb))]
        aHi    := h
        aHiT   := tm
    if not na(pl)
        lastPL := pl
        plBrk  := false
        bHi    := highN
        bHiT   := tm[math.max(0, -nz(highNb))]
        bLo    := l
        bLoT   := tm
    // running trackers (a new extreme restarts its companion)
    if not na(aLo)
        if l < aLo
            aLo := l
            aLoT := tm
            aHi := h
            aHiT := tm
        else if h > aHi
            aHi := h
            aHiT := tm
    if not na(bHi)
        if h > bHi
            bHi := h
            bHiT := tm
            bLo := l
            bLoT := tm
        else if l < bLo
            bLo := l
            bLoT := tm
    if not na(cLo)
        if l < cLo
            cLo := l
            cLoT := tm
            cHi := h
            cHiT := tm
        else if h > cHi
            cHi := h
            cHiT := tm
    if not na(dHi)
        if h > dHi
            dHi := h
            dHiT := tm
            dLo := l
            dLoT := tm
        else if l < dLo
            dLo := l
            dLoT := tm
    // displacement
    float dsp = dspOpt == "2 ticks" ? 2 * TICK : dspOpt == "0.10 ATR" ? 0.10 * atrV : dspOpt == "0.20 ATR" ? 0.20 * atrV : 0.0
    bool bearCh = bias != -1 and not na(refLo) and c < refLo - dsp
    bool bullCh = bias != 1 and not na(refHi) and c > refHi + dsp
    if bearCh
        // the high that produced this drop becomes the protected high; the rally origin tracker starts here
        evt   := -2
        evId  += 1
        evLvl := refLo
        evExt := dHi
        evTight := not na(lastPH) and lastPH > c and lastPH <= dHi ? lastPH : dHi
        refHi := dHi
        refHiT := dHiT
        cLo   := dLo
        cLoT  := dLoT
        cHi   := h
        cHiT  := tm
        refLo := na
        refLoT := na
        dHi   := na
        bias  := -1
        if not na(lastPL) and c < lastPL
            plBrk := true
    else if bullCh
        evt   := 2
        evId  += 1
        evLvl := refHi
        evExt := cLo
        evTight := not na(lastPL) and lastPL < c and lastPL >= cLo ? lastPL : cLo
        refLo := cLo
        refLoT := cLoT
        dHi   := cHi
        dHiT  := cHiT
        dLo   := l
        dLoT  := tm
        refHi := na
        refHiT := na
        cLo   := na
        bias  := 1
        if not na(lastPH) and c > lastPH
            phBrk := true
    else
        // breaks of candidate swings: continuation (BOS) with the trend, internal against it, first structure when neutral
        if not na(lastPH) and not phBrk and c > lastPH
            phBrk := true
            if bias >= 0
                evt    := bias == 0 ? 0 : 1
                evLvl  := lastPH
                refLo  := aLo
                refLoT := aLoT
                dHi    := aHi
                dHiT   := aHiT
                dLo    := l
                dLoT   := tm
                bias   := 1
            else
                evt   := 3
                evLvl := lastPH
        if not na(lastPL) and not plBrk and c < lastPL
            plBrk := true
            if bias <= 0 and evt != 1
                evt    := bias == 0 ? 0 : -1
                evLvl  := lastPL
                refHi  := bHi
                refHiT := bHiT
                cLo    := bLo
                cLoT   := bLoT
                cHi    := h
                cHiT   := tm
                bias   := -1
            else if evt == 0
                evt   := -3
                evLvl := lastPL
    [bias, refLo, refLoT, refHi, refHiT, evt, evId, evLvl, evExt, evTight, c, tm, tc]
 
// ---- two call sites, both executed every bar (request.* and ta.* must never be conditional) ------------------
[hB, hRL, hRLT, hRH, hRHT, hEv, hId, hLvl, hExt, hTi, hC, hTm, hTc] = request.security(syminfo.tickerid, tfIn,
     f_eng(open[1], high[1], low[1], close[1], time[1], time_close[1], ta.atr(14)[1]), lookahead = barmerge.lookahead_on)
[cB, cRL, cRLT, cRH, cRHT, cEv, cId, cLvl, cExt, cTi, cC, cTm, cTc] = f_eng(open, high, low, close, time, time_close, ta.atr(14))
[d1, d2, d3, d4] = request.security(syminfo.tickerid, "D", [close[1], close[2], close[3], close[4]], lookahead = barmerge.lookahead_on)
// estimated delta of the previous completed structure candle: close position inside its range × volume (not footprint data)
[hdD, hdV] = request.security(syminfo.tickerid, useHTF ? tfIn : timeframe.period, [(high[1] - low[1] > 0 ? (2 * close[1] - high[1] - low[1]) / (high[1] - low[1]) : 0.0) * volume[1], volume[1]], lookahead = barmerge.lookahead_on)
 
int   bias  = useHTF ? hB   : cB
float refLo = useHTF ? hRL  : cRL
int   refLoT = useHTF ? hRLT : cRLT
float refHi = useHTF ? hRH  : cRH
int   refHiT = useHTF ? hRHT : cRHT
int   evt   = useHTF ? hEv  : cEv
int   evId  = useHTF ? hId  : cId
float evLvl = useHTF ? hLvl : cLvl
float evExt = useHTF ? hExt : cExt
float evTight = useHTF ? hTi : cTi
float sC    = useHTF ? hC   : cC
int   sTm   = useHTF ? hTm  : cTm
int   sTc   = useHTF ? hTc  : cTc
// a new structure candle = the engine's candle time moved (in Chart mode every bar; in HTF mode once per HTF candle)
bool  newSC = ta.change(sTm) != 0
// an event is "new" when its id advances (HTF values repeat on every chart candle of the same HTF candle)
var int seenId = 0
bool  newEv  = evt != 0 and (math.abs(evt) != 2 or evId != seenId) and newSC and (useHTF or barstate.isconfirmed)
if newEv and math.abs(evt) == 2
    seenId := evId
var bool standby = false                 // v1.1: the latest change of character failed and nothing has confirmed a direction since
if newEv and (math.abs(evt) == 1 or math.abs(evt) == 2)
    standby := false
 
// ============================================================================================================
// FILTERS (evaluated on the structure candle's CLOSE time, Chicago)
// ============================================================================================================
int  cHr  = hour(sTc, TZ)
int  cMn  = minute(sTc, TZ)
int  cHM  = cHr * 100 + cMn
bool sesOK = sesOpt == "Off" ? true : sesOpt == "New York closes (07:00–15:00)" ? (cHM >= 700 and cHM <= 1500) : (cHM >= 1100 and cHM <= 1730)
bool run3Up = d1 > d2 and d2 > d3 and d3 > d4
bool run3Dn = d1 < d2 and d2 < d3 and d3 < d4
 
// ============================================================================================================
// PLAN + SCORECARD STATE
// ============================================================================================================
type Plan
    int   dir    = 0        // 1 long, -1 short, 0 none
    int   stage  = 0        // 0 none · 1 waiting (confirmation / acceptance) · 2 armed (fill next open) · 3 open · 4 observing after 1R (for 1.5R / 2R / MFE) · 5 done
    float lvl    = na
    float entry  = na
    float stop   = na
    float tgt    = na
    float risk   = na
    int   id     = 0
    bool  taken  = false
    bool  over   = false
    bool  sesF   = false
    bool  runF   = false
    int   wait   = 0        // structure candles waited (confirmation / acceptance)
    int   age    = 0        // structure candles since the signal
    bool  failed = false
    bool  ft     = false
    bool  win1   = false
    bool  win15  = false
    bool  win2   = false
    bool  loss   = false
    float mfe    = 0.0
    float mae    = 0.0
    label mark   = na
var Plan P = Plan.new()
var Plan R = Plan.new()                 // v1.5 retest plan (same fields; stage 1 = waiting for the retest, 2 = fill next open, 3 = open, 5 = done)
var float rExt = na                     // retest extreme so far (highest high for a short, lowest low for a long)
var bool  rTouched = false
var int   rBars = 0                     // chart candles waited
var array<label> rtPool = array.new<label>()
var array<int>   rSig  = array.new<int>(2, 0)
var array<int>   rWin  = array.new<int>(2, 0)
var array<int>   rLoss = array.new<int>(2, 0)
var array<float> rSumR = array.new<float>(2, 0.0)
var array<float> rSumStop = array.new<float>(2, 0.0)
var array<float> rSumMFE = array.new<float>(2, 0.0)
float RTR = rtTgt == "1R of the retest stop" ? 1.0 : rtTgt == "1.5R of the retest stop" ? 1.5 : rtTgt == "3R of the retest stop" ? 3.0 : 2.0
var int rCancel = 0
// totals: index 0 = ALL, 1 = TAKEN
var array<int>   nSig  = array.new<int>(2, 0)
var array<int>   nWin  = array.new<int>(2, 0)
var array<int>   nLoss = array.new<int>(2, 0)
var array<int>   nW15  = array.new<int>(2, 0)
var array<int>   nW2   = array.new<int>(2, 0)
var array<int>   nSup  = array.new<int>(2, 0)
var array<int>   nFail = array.new<int>(2, 0)
var array<int>   nFT   = array.new<int>(2, 0)
var array<float> sumR  = array.new<float>(2, 0.0)
var array<float> sumMFE = array.new<float>(2, 0.0)
var array<float> sumMAE = array.new<float>(2, 0.0)
var int nFilt = 0
var array<float> sumStop = array.new<float>(2, 0.0)     // stop distance in points, summed per filled plan (tradability)
var array<int>   nStop   = array.new<int>(2, 0)
var float minStop = na
var float maxStop = na
var int nOver = 0
var int nCancel = 0
 
f_sz(string s) => s == "Tiny" ? size.tiny : s == "Small" ? size.small : s == "Large" ? size.large : size.normal
f_lsty(string s) => s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid
f_px(float p) => str.tostring(p, format.mintick)
f_k(float v) => str.tostring(v, "#.##")
int bosAl = bosTr == "Dim" ? 55 : bosTr == "Strong" ? 0 : 30
 
// pooled marks
var array<label> mkPool  = array.new<label>()
var array<label> bosPool = array.new<label>()
var array<label> intPool = array.new<label>()
f_pool(array<label> pool, label lb) =>
    pool.push(lb)
    if pool.size() > MAXMK
        label.delete(pool.shift())
 
// result bookkeeping for a finished plan
f_tally(int k, bool win1, bool loss, bool w15, bool w2, bool sup, bool failed, bool ft, float r, float mfe, float mae) =>
    if sup
        nSup.set(k, nSup.get(k) + 1)
    else
        if win1
            nWin.set(k, nWin.get(k) + 1)
        if loss
            nLoss.set(k, nLoss.get(k) + 1)
        if w15
            nW15.set(k, nW15.get(k) + 1)
        if w2
            nW2.set(k, nW2.get(k) + 1)
        sumR.set(k, sumR.get(k) + r)
        sumMFE.set(k, sumMFE.get(k) + mfe)
        sumMAE.set(k, sumMAE.get(k) + mae)
    if failed
        nFail.set(k, nFail.get(k) + 1)
    if ft
        nFT.set(k, nFT.get(k) + 1)
 
f_markText(string base, string res) => res == "" ? base : base + " " + res
 
f_close(string res, color col) =>
    // tally into ALL and, when taken, TAKEN; write the result on the mark
    bool sup = res == "SUP"
    float costR = P.risk > 0 ? COST / (P.risk * PTVAL) : 0.0
    float r = P.loss ? -1.0 - costR : P.win1 ? RR - costR : 0.0
    f_tally(0, P.win1, P.loss, P.win15, P.win2, sup, P.failed, P.ft, r, P.mfe, P.mae)
    if P.taken
        f_tally(1, P.win1, P.loss, P.win15, P.win2, sup, P.failed, P.ft, r, P.mfe, P.mae)
    if not na(P.mark)
        string base = P.dir > 0 ? "CHoCH ▲" : "CHoCH ▼"
        string tag  = P.over ? "OVER CAP · " : (P.sesF or P.runF) ? "FILTERED · " : ""
        P.mark.set_text(mkStyle == "Triangle" ? res : f_markText(base, tag + res))
        P.mark.set_color(color.new(col, mkStyle == "Text only" ? 100 : 0))
        if mkStyle == "Text only"
            P.mark.set_textcolor(col)
    P.stage := 5
    P.dir := 0
 
f_rClose(string res, color col) =>
    // tally the retest plan (ALL and, when taken, TAKEN) and write the result on its mark
    if R.stage == 3
        float costR = R.risk > 0 ? COST / (R.risk * PTVAL) : 0.0
        float r = R.loss ? -1.0 - costR : R.win1 ? (math.abs(R.tgt - R.entry) / R.risk) - costR : 0.0
        for k = 0 to 1
            if k == 0 or R.taken
                if R.win1
                    rWin.set(k, rWin.get(k) + 1)
                if R.loss
                    rLoss.set(k, rLoss.get(k) + 1)
                rSumR.set(k, rSumR.get(k) + r)
                rSumMFE.set(k, rSumMFE.get(k) + R.mfe)
    if not na(R.mark)
        R.mark.set_text("RT " + (R.dir > 0 ? "▲ " : "▼ ") + res)
        R.mark.set_textcolor(col)
    R.stage := 5
    R.dir := 0
 
// ============================================================================================================
// EVENT HANDLING
// ============================================================================================================
int stageSeries = P.stage               // series copy (object fields have no history operator)
int rStageSeries = R.stage
bool isCh = newEv and math.abs(evt) == 2
bool supEvt = false
if vis and isCh
    int dir = evt > 0 ? 1 : -1
    // supersede an unresolved plan
    if P.stage >= 1 and P.stage <= 4 and P.dir != 0
        if P.stage < 4
            supEvt := true
        if P.stage == 4
            f_close(P.win1 ? "✓ " + f_k(RR) + "R" : "✗", P.win1 ? (dir > 0 ? cBear : cBull) : cNeu)   // already decided at 1R; keep its result
        else
            f_close("SUP", cNeu)
    // new plan
    P.dir   := dir
    P.id    := evId
    P.lvl   := evLvl
    float stopSrc = stopOpt == "Last swing (tested rule)" and not na(evTight) ? evTight : evExt
    P.stop  := dir > 0 ? stopSrc - BUF : stopSrc + BUF
    P.entry := na
    P.tgt   := na
    P.risk  := na
    P.wait  := 0
    P.age   := 0
    P.failed := false
    P.ft    := false
    P.win1  := false
    P.win15 := false
    P.win2  := false
    P.loss  := false
    P.mfe   := 0.0
    P.mae   := 0.0
    P.sesF  := not sesOK
    P.runF  := runOpt == "On" and ((dir > 0 and run3Up) or (dir < 0 and run3Dn))
    // provisional risk from the structure close (the fill refines it)
    float provRisk = math.abs(sC - P.stop)
    P.over  := provRisk * PTVAL > CAP
    P.taken := not P.sesF and not P.runF and not P.over
    P.stage := (CNF or ACCM > 0) ? 1 : 2
    nSig.set(0, nSig.get(0) + 1)
    if P.taken
        nSig.set(1, nSig.get(1) + 1)
    if P.sesF or P.runF
        nFilt += 1
    if P.over
        nOver += 1
    // the mark
    color mc = dir > 0 ? cBull : cBear
    string base = dir > 0 ? "CHoCH ▲" : "CHoCH ▼"
    string tag  = P.over ? "OVER CAP" : (P.sesF or P.runF) ? "FILTERED" : ""
    string txt  = mkStyle == "Triangle" ? "" : f_markText(base, tag)
    label lb = label.new(bar_index, dir > 0 ? low : high, txt,
         style = mkStyle == "Triangle" ? (dir > 0 ? label.style_triangleup : label.style_triangledown) : mkStyle == "Text only" ? (dir > 0 ? label.style_label_up : label.style_label_down) : (dir > 0 ? label.style_label_up : label.style_label_down),
         color = color.new(mc, mkStyle == "Text only" ? 100 : P.taken ? 0 : 40), textcolor = mkStyle == "Text only" ? mc : mkText, size = f_sz(mkSize),
         tooltip = (dir > 0 ? "Bullish change of character\nclose above protected high " : "Bearish change of character\nclose below protected low ") + f_px(evLvl) + "\nstop past " + f_px(stopOpt == "Last swing (tested rule)" and not na(evTight) ? evTight : evExt) + " · new protected level " + f_px(evExt) + (tag != "" ? "\n" + tag : ""))
    P.mark := lb
    f_pool(mkPool, lb)
    // v1.5: arm the retest plan (cancel any unresolved one first)
    if R.stage >= 1 and R.stage <= 3 and R.dir != 0
        if R.stage < 3
            rCancel += 1
        f_rClose("SUP", cNeu)
    if RTON
        R.dir   := dir
        R.id    := evId
        R.lvl   := evLvl
        R.stage := 1
        R.entry := na
        R.stop  := na
        R.tgt   := na
        R.risk  := na
        R.win1  := false
        R.loss  := false
        R.mfe   := 0.0
        R.mae   := 0.0
        R.sesF  := P.sesF
        R.runF  := P.runF
        R.over  := false
        R.taken := false
        R.mark  := na
        rExt    := dir > 0 ? low : high
        rTouched := false
        rBars   := 0
 
// BOS and internal marks
if vis and newEv and math.abs(evt) == 1 and bosOn == "On"
    bool up = evt > 0
    label b = label.new(bar_index, up ? high : low, "BOS", style = up ? label.style_label_down : label.style_label_up,
         color = color.new(up ? cBull : cBear, 100), textcolor = color.new(up ? cBull : cBear, bosAl), size = f_sz(bosSize),
         tooltip = (up ? "Break of structure up — continuation; protected low moved to " : "Break of structure down — continuation; protected high moved to ") + f_px(up ? refLo : refHi))
    f_pool(bosPool, b)
if vis and newEv and math.abs(evt) == 3 and intOn == "On"
    bool up = evt > 0
    label i = label.new(bar_index, up ? high : low, "·", style = up ? label.style_label_down : label.style_label_up,
         color = color.new(cNeu, 100), textcolor = color.new(cNeu, bosAl), size = f_sz(bosSize),
         tooltip = up ? "Internal break: close above a minor high that is NOT the protected high — not a change of character" : "Internal break: close below a minor low that is NOT the protected low — not a change of character")
    f_pool(intPool, i)
 
// ============================================================================================================
// PLAN LIFE CYCLE (chart candles; structure candles counted via newSC)
// ============================================================================================================
int stNowPrev = stageSeries             // the stage at the start of this chart candle = how it stood at the previous close
bool fillEvt = false
bool failEvt = false
bool cancEvt = false
if vis and P.dir != 0 and P.stage >= 1 and P.stage <= 4
    bool scClosed = newSC and not isCh          // a structure candle closed since the signal
    if scClosed
        P.age += 1
    // FAILED measurement (close back across the level) — within ACCM when acceptance is on, else MEASM
    int failWin = ACCM > 0 ? ACCM : MEASM
    if scClosed and P.age <= failWin and not P.failed
        bool backAcross = P.dir > 0 ? sC < P.lvl : sC > P.lvl
        if backAcross
            P.failed := true
            standby  := true
            failEvt  := true
            if ACCM > 0 and P.stage <= 2
                nCancel += 1
                f_close("FAILED", cFail)
    // follow-through: a BOS in the signal direction within the horizon, before price trades back through the stop
    if P.dir != 0 and newEv and ((P.dir < 0 and evt == -1) or (P.dir > 0 and evt == 1)) and P.age <= FTH
        P.ft := true
    // stage 1: waiting for confirmation candle / acceptance
    if P.dir != 0 and P.stage == 1 and scClosed
        P.wait += 1
        bool confOK = not CNF or (P.dir > 0 ? sC > P.lvl : sC < P.lvl)
        if CNF and P.wait == 1 and not confOK
            nCancel += 1
            cancEvt := true
            f_close("NO CONF", cNeu)
        else if P.wait >= math.max(CNF ? 1 : 0, ACCM) and not P.failed
            P.stage := 2
    // stage 2: fill at the next executable price (this candle's open — in HTF mode this is the first chart candle after the HTF close)
    if P.dir != 0 and P.stage == 2 and (useHTF or (stNowPrev == 2 and not isCh))
        P.entry := open
        P.risk  := math.abs(P.entry - P.stop)
        if P.risk <= 0
            nCancel += 1
            f_close("NO RISK", cNeu)
        else
            P.tgt   := P.dir > 0 ? P.entry + RR * P.risk : P.entry - RR * P.risk
            sumStop.set(0, sumStop.get(0) + P.risk)
            nStop.set(0, nStop.get(0) + 1)
            minStop := na(minStop) ? P.risk : math.min(minStop, P.risk)
            maxStop := na(maxStop) ? P.risk : math.max(maxStop, P.risk)
            bool wasOver = P.over
            P.over  := P.risk * PTVAL > CAP
            nOver   += (P.over ? 1 : 0) - (wasOver ? 1 : 0)
            bool wasTaken = P.taken
            P.taken := not P.sesF and not P.runF and not P.over
            if wasTaken and not P.taken
                nSig.set(1, nSig.get(1) - 1)
            else if not wasTaken and P.taken
                nSig.set(1, nSig.get(1) + 1)
            if P.taken
                sumStop.set(1, sumStop.get(1) + P.risk)
                nStop.set(1, nStop.get(1) + 1)
            P.stage := 3
            fillEvt := true
            if alOn == "On"
                alert("STRYK:CHoCH entry " + (P.dir > 0 ? "LONG" : "SHORT") + " " + f_px(P.entry) + " stop " + f_px(P.stop) + " target " + f_px(P.tgt) + " risk " + f_k(P.risk) + " pts $" + f_k(P.risk * PTVAL), alert.freq_once_per_bar_close)
    // stage 3 / 4: outcome on chart candles — stop checked first (same-candle = loss)
    if P.dir != 0 and (P.stage == 3 or P.stage == 4)
        float fav = P.dir > 0 ? (high - P.entry) / P.risk : (P.entry - low) / P.risk
        float adv = P.dir > 0 ? (P.entry - low) / P.risk : (high - P.entry) / P.risk
        P.mfe := math.max(P.mfe, fav)
        if P.stage == 3
            P.mae := math.max(P.mae, adv)
        bool stopHit = P.dir > 0 ? low <= P.stop : high >= P.stop
        bool tgtHit  = P.dir > 0 ? high >= P.tgt : low <= P.tgt
        if P.stage == 3
            if stopHit
                P.loss := true
                if alOn == "On"
                    alert("STRYK:CHoCH stop hit " + (P.dir > 0 ? "LONG" : "SHORT") + " at " + f_px(P.stop), alert.freq_once_per_bar_close)
                f_close("✗", cNeu)
            else if tgtHit
                P.win1 := true
                if fav >= 1.5
                    P.win15 := true
                if fav >= 2.0
                    P.win2 := true
                if alOn == "On"
                    alert("STRYK:CHoCH target hit " + (P.dir > 0 ? "LONG" : "SHORT") + " at " + f_px(P.tgt), alert.freq_once_per_bar_close)
                if P.win2 or P.age >= FTH
                    f_close("✓ " + f_k(RR) + "R", P.dir > 0 ? cBull : cBear)
                else
                    P.stage := 4            // keep observing for 1.5R / 2R and follow-through
        else
            if fav >= 1.5
                P.win15 := true
            if fav >= 2.0
                P.win2 := true
            if stopHit or P.win2 or P.age >= FTH
                f_close("✓ " + f_k(RR) + "R", P.dir > 0 ? cBull : cBear)
 
// ============================================================================================================
// RETEST PLAN LIFE CYCLE (chart candles) — v1.5
// ============================================================================================================
bool rFillEvt = false
bool rTgtEvt  = false
bool rStopEvt = false
int  rStagePrev = rStageSeries
if vis and R.dir != 0 and R.stage >= 1 and R.stage <= 3 and not isCh
    bool bearR = R.dir < 0
    // the original plan's target is the retest target (available once the original has filled)
    float baseTgt = P.id == R.id and not na(P.tgt) ? P.tgt : na          // P.id / P.tgt / P.stop persist after the original plan closes
    float baseStop = P.id == R.id and not na(P.stop) ? P.stop : na
    if R.stage == 1
        rBars += 1
        rExt := bearR ? math.max(rExt, high) : math.min(rExt, low)
        bool tgtFirst = not na(baseTgt) and (bearR ? low <= baseTgt : high >= baseTgt)
        bool through  = not na(baseStop) and (bearR ? high >= baseStop : low <= baseStop)
        if tgtFirst
            rCancel += 1
            f_rClose("NO RETEST (target first)", cNeu)
        else if through
            rCancel += 1
            f_rClose("CANCELLED (through the swing)", cNeu)
        else if rBars > RTK
            rCancel += 1
            f_rClose("NO RETEST (timed out)", cNeu)
        else
            if bearR ? high >= R.lvl - RTOL : low <= R.lvl + RTOL
                rTouched := true
            if rTouched and (bearR ? close < R.lvl : close > R.lvl) and (useHTF or barstate.isconfirmed)
                R.stage := 2
    else if R.stage == 2 and rStagePrev == 2
        R.entry := open
        R.stop  := bearR ? rExt + BUF : rExt - BUF
        R.risk  := math.abs(R.entry - R.stop)
        float origTgt = not na(baseTgt) ? baseTgt : (not na(baseStop) ? (bearR ? sC - math.abs(sC - baseStop) : sC + math.abs(baseStop - sC)) : na)
        R.tgt   := rtTgt == "Original plan target" ? origTgt : (bearR ? R.entry - RTR * R.risk : R.entry + RTR * R.risk)
        bool geomOK = R.risk > 0 and not na(R.tgt) and (bearR ? R.tgt < R.entry : R.tgt > R.entry)
        if not geomOK
            rCancel += 1
            f_rClose("CANCELLED (geometry)", cNeu)
        else
            R.over  := R.risk * PTVAL > CAP
            R.taken := not R.sesF and not R.runF and not R.over
            R.stage := 3
            rFillEvt := true
            rSig.set(0, rSig.get(0) + 1)
            rSumStop.set(0, rSumStop.get(0) + R.risk)
            if R.taken
                rSig.set(1, rSig.get(1) + 1)
                rSumStop.set(1, rSumStop.get(1) + R.risk)
            color rc = bearR ? cBear : cBull
            label rl = label.new(bar_index, bearR ? high : low, "RT " + (bearR ? "▼" : "▲") + (R.over ? " OVER CAP" : (R.sesF or R.runF) ? " FILTERED" : ""), style = bearR ? label.style_label_down : label.style_label_up,
                 color = color.new(rc, 100), textcolor = rc, size = f_sz(bosSize),
                 tooltip = "Retest entry " + f_px(R.entry) + "\nstop " + f_px(R.stop) + " · target " + f_px(R.tgt) + "\nrisk " + f_k(R.risk) + " pts  $" + f_k(R.risk * PTVAL))
            R.mark := rl
            f_pool(rtPool, rl)
            if alOn == "On"
                alert("STRYK:CHCH RETEST entry " + (bearR ? "SHORT " : "LONG ") + f_px(R.entry) + " stop " + f_px(R.stop) + " target " + f_px(R.tgt) + " risk " + f_k(R.risk) + " pts $" + f_k(R.risk * PTVAL), alert.freq_once_per_bar_close)
    if R.dir != 0 and R.stage == 3
        float fav = bearR ? (R.entry - low) / R.risk : (high - R.entry) / R.risk
        float adv = bearR ? (high - R.entry) / R.risk : (R.entry - low) / R.risk
        R.mfe := math.max(R.mfe, fav)
        R.mae := math.max(R.mae, adv)
        bool stopHit = bearR ? high >= R.stop : low <= R.stop
        bool tgtHit  = bearR ? low <= R.tgt : high >= R.tgt
        if stopHit
            R.loss := true
            rStopEvt := true
            f_rClose("✗", cNeu)
        else if tgtHit
            R.win1 := true
            rTgtEvt := true
            f_rClose("✓ " + f_k(math.abs(R.tgt - R.entry) / R.risk) + "R", bearR ? cBear : cBull)
 
// ============================================================================================================
// DRAWINGS: protected levels, active plan, bias tint
// ============================================================================================================
var line  lnLo = na
var line  lnHi = na
var label lbLo = na
var label lbHi = na
var line  lnE  = na
var line  lnS  = na
var line  lnT  = na
var label lbP  = na
var int   pStartBar = na
 
f_lvl(line ln, label lb, float y, int t0, color col, string txt, bool show) =>
    line  l2 = ln
    label b2 = lb
    if show and not na(y) and not na(t0)
        if na(l2)
            l2 := line.new(t0, y, time + REFX * BARMS, y, xloc = xloc.bar_time, color = col, width = refW, style = f_lsty(refSty), extend = REFINF ? extend.right : extend.none)
        else
            l2.set_xy1(t0, y)
            l2.set_xy2(time + REFX * BARMS, y)
            l2.set_color(col)
            l2.set_width(refW)
            l2.set_style(f_lsty(refSty))
            l2.set_extend(REFINF ? extend.right : extend.none)
        if refLbl == "On"
            if na(b2)
                b2 := label.new(time + REFX * BARMS, y, txt, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(col, 100), textcolor = col, size = size.tiny)
            else
                b2.set_xy(time + REFX * BARMS, y)
                b2.set_text(txt)
                b2.set_textcolor(col)
        else if not na(b2)
            b2.set_text("")
    else
        if not na(l2)
            line.delete(l2)
            l2 := na
        if not na(b2)
            label.delete(b2)
            b2 := na
    [l2, b2]
 
if barstate.islast
    bool showRef = vis and refOn == "On"
    [a1, a2] = f_lvl(lnLo, lbLo, refLo, refLoT, cBull, " protected low " + (na(refLo) ? "" : f_px(refLo)), showRef)
    lnLo := a1
    lbLo := a2
    [a3, a4] = f_lvl(lnHi, lbHi, refHi, refHiT, cBear, " protected high " + (na(refHi) ? "" : f_px(refHi)), showRef)
    lnHi := a3
    lbHi := a4
 
// plan lines: drawn from the fill candle while the plan is open / observing
if vis and planOn == "On" and P.dir != 0 and (P.stage == 3 or P.stage == 4) and not na(P.entry)
    if na(lnE)
        pStartBar := bar_index
    int x0 = math.max(pStartBar, bar_index - 400)
    color pc = P.dir > 0 ? cBull : cBear
    if na(lnE)
        lnE := line.new(x0, P.entry, bar_index + PLX, P.entry, color = pc, width = plW, style = f_lsty(plSty), extend = PLINF ? extend.right : extend.none)
        lnS := line.new(x0, P.stop, bar_index + PLX, P.stop, color = cStop, width = plW, style = f_lsty(plSty), extend = PLINF ? extend.right : extend.none)
        lnT := line.new(x0, P.tgt, bar_index + PLX, P.tgt, color = cTgt, width = plW, style = f_lsty(plSty), extend = PLINF ? extend.right : extend.none)
        lbP := label.new(bar_index, P.stop, "", style = P.dir > 0 ? label.style_label_lower_left : label.style_label_upper_left, color = color.new(pc, 100), textcolor = pc, size = f_sz(plSize))
    lnE.set_xy1(x0, P.entry)
    lnE.set_xy2(bar_index + PLX, P.entry)
    lnE.set_color(pc)
    lnS.set_xy1(x0, P.stop)
    lnS.set_xy2(bar_index + PLX, P.stop)
    lnT.set_xy1(x0, P.tgt)
    lnT.set_xy2(bar_index + PLX, P.tgt)
    lbP.set_xy(bar_index + math.min(PLX, 500), P.stop)
    lbP.set_text((P.dir > 0 ? "LONG " : "SHORT ") + f_px(P.entry) + "\nstop " + f_px(P.stop) + " · T " + f_px(P.tgt) + "\nrisk " + f_k(P.risk) + " pts  $" + f_k(P.risk * PTVAL) + (P.over ? "  OVER CAP" : "") + (P.stage == 4 ? "\n1R reached — observing" : ""))
    lbP.set_textcolor(pc)
else
    if not na(lnE)
        line.delete(lnE)
        line.delete(lnS)
        line.delete(lnT)
        label.delete(lbP)
        lnE := na
        lnS := na
        lnT := na
        lbP := na
    pStartBar := na
 
// retest plan lines (active retest only)
var line  rlE = na
var line  rlS = na
var line  rlT = na
var int   rStartBar = na
if vis and rtLines == "On" and R.dir != 0 and R.stage == 3 and not na(R.entry)
    if na(rlE)
        rStartBar := bar_index
    int rx0 = math.max(rStartBar, bar_index - 400)
    color rpc = R.dir > 0 ? cBull : cBear
    if na(rlE)
        rlE := line.new(rx0, R.entry, bar_index + PLX, R.entry, color = rpc, width = plW, style = line.style_dotted, extend = PLINF ? extend.right : extend.none)
        rlS := line.new(rx0, R.stop, bar_index + PLX, R.stop, color = cStop, width = plW, style = line.style_dotted, extend = PLINF ? extend.right : extend.none)
        rlT := line.new(rx0, R.tgt, bar_index + PLX, R.tgt, color = cTgt, width = plW, style = line.style_dotted, extend = PLINF ? extend.right : extend.none)
    rlE.set_xy1(rx0, R.entry)
    rlE.set_xy2(bar_index + PLX, R.entry)
    rlS.set_xy1(rx0, R.stop)
    rlS.set_xy2(bar_index + PLX, R.stop)
    rlT.set_xy1(rx0, R.tgt)
    rlT.set_xy2(bar_index + PLX, R.tgt)
else
    if not na(rlE)
        line.delete(rlE)
        line.delete(rlS)
        line.delete(rlT)
        rlE := na
        rlS := na
        rlT := na
    rStartBar := na
 
color bgCol = vis and bgOpt != "Off" and bias != 0 ? color.new(bias > 0 ? cBull : cBear, bgOpt == "Light" ? 94 : 88) : na
bgcolor(bgCol)
 
// v1.1 candle colour engine — one barcolor (1 plot slot); colour chosen per candle, call unconditional
bool  dFlat   = na(hdV) or hdV <= 0 or na(hdD) or math.abs(hdD) < 0.2 * hdV
color ccBias  = standby or na(bias) or bias == 0 ? ccSb : bias > 0 ? ccUp : ccDn      // every bar gets a colour; no structure yet = Standby
color ccDelta = dFlat ? ccSb : hdD > 0 ? ccUp : ccDn
color ccPick  = ccOpt == "CHoCH bias" ? ccBias : ccDelta
bool  ccShow  = vis and ccOpt != "Off"
color ccCol   = ccShow ? color.new(ccPick, ccTr == "Soft" ? 35 : 0) : na
bool  ccDraw  = ccMode == "Draw candles (always visible)"
// two outputs, both called every bar (plot calls cannot be conditional): one is live, the other paints na
barcolor(ccDraw ? na : ccCol, title = "Candle recolour")
plotcandle(open, high, low, close, title = "Engine candles", color = ccDraw ? ccCol : na, wickcolor = ccDraw ? ccCol : na, bordercolor = ccDraw ? ccCol : na, display = display.pane)
 
// ============================================================================================================
// TABLE
// ============================================================================================================
f_tpos(string s) => s == "Bottom right" ? position.bottom_right : s == "Top left" ? position.top_left : s == "Top right" ? position.top_right : s == "Middle left" ? position.middle_left : s == "Middle right" ? position.middle_right : position.bottom_left
f_pct(int a, int b) => b > 0 ? str.tostring(100.0 * a / b, "#") + "%" : "–"
f_avg(float s, int n) => n > 0 ? str.tostring(s / n, "#.##") : "–"
var table tb = na
if vis and tbOn == "On"
    if na(tb)
        tb := table.new(f_tpos(tbPos), 3, 19, bgcolor = color.new(tbBg, 10), border_width = 1, border_color = color.new(tbHead, 80))
    if barstate.islast
        string ts = tbSize == "Tiny" ? size.tiny : tbSize == "Normal" ? size.normal : size.small
        string biasTxt = bias > 0 ? "UP" : bias < 0 ? "DOWN" : "NEUTRAL"
        color  biasCol = bias > 0 ? cBull : bias < 0 ? cBear : cNeu
        string modeTxt = useHTF ? "structure " + tfIn + " on " + timeframe.period : (tfMode == "Higher timeframe (below)" and not htfOK ? "chart TF above " + tfIn + " → chart mode" : "structure = chart " + timeframe.period)
        tb.cell(0, 0, "STRYK:CHoCH", text_color = tbTxt, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 0, biasTxt, text_color = biasCol, text_size = ts)
        tb.cell(2, 0, modeTxt, text_color = tbHead, text_size = ts, text_halign = text.align_right)
        tb.cell(0, 1, "protected low", text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 1, na(refLo) ? "–" : f_px(refLo), text_color = cBull, text_size = ts)
        tb.cell(2, 1, na(refLo) ? "" : "bear CHoCH below", text_color = tbHead, text_size = ts, text_halign = text.align_right)
        tb.cell(0, 2, "protected high", text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 2, na(refHi) ? "–" : f_px(refHi), text_color = cBear, text_size = ts)
        tb.cell(2, 2, na(refHi) ? "" : "bull CHoCH above", text_color = tbHead, text_size = ts, text_halign = text.align_right)
        string planTxt = P.dir == 0 ? "no plan" : P.stage == 1 ? (P.dir > 0 ? "LONG waiting" : "SHORT waiting") : P.stage == 2 ? (P.dir > 0 ? "LONG fills next open" : "SHORT fills next open") : (P.dir > 0 ? "LONG " : "SHORT ") + f_px(P.entry) + " · stop " + f_px(P.stop) + " · T " + f_px(P.tgt)
        tb.cell(0, 3, "plan", text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 3, planTxt, text_color = P.dir > 0 ? cBull : P.dir < 0 ? cBear : tbHead, text_size = ts)
        tb.cell(2, 3, P.dir != 0 and not na(P.risk) ? "$" + f_k(P.risk * PTVAL) + (P.over ? " OVER CAP" : "") : (P.dir != 0 ? (P.over ? "over cap" : "") : ""), text_color = P.over ? cStop : tbHead, text_size = ts, text_halign = text.align_right)
        tb.cell(0, 4, "", text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 4, "ALL", text_color = tbHead, text_size = ts)
        tb.cell(2, 4, "TAKEN", text_color = tbHead, text_size = ts, text_halign = text.align_right)
        int closedA = nWin.get(0) + nLoss.get(0)
        int closedT = nWin.get(1) + nLoss.get(1)
        tb.cell(0, 5, "signals", text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 5, str.tostring(nSig.get(0)), text_color = tbTxt, text_size = ts)
        tb.cell(2, 5, str.tostring(nSig.get(1)), text_color = tbTxt, text_size = ts, text_halign = text.align_right)
        tb.cell(0, 6, "won / lost at " + f_k(RR) + "R", text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 6, str.tostring(nWin.get(0)) + " / " + str.tostring(nLoss.get(0)) + "  " + f_pct(nWin.get(0), closedA), text_color = tbTxt, text_size = ts)
        tb.cell(2, 6, str.tostring(nWin.get(1)) + " / " + str.tostring(nLoss.get(1)) + "  " + f_pct(nWin.get(1), closedT), text_color = tbTxt, text_size = ts, text_halign = text.align_right)
        tb.cell(0, 7, "net R after costs", text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 7, closedA > 0 ? f_k(sumR.get(0)) + "  (" + f_avg(sumR.get(0), closedA) + "/trade)" : "–", text_color = sumR.get(0) >= 0 ? cBull : cBear, text_size = ts)
        tb.cell(2, 7, closedT > 0 ? f_k(sumR.get(1)) + "  (" + f_avg(sumR.get(1), closedT) + "/trade)" : "–", text_color = sumR.get(1) >= 0 ? cBull : cBear, text_size = ts, text_halign = text.align_right)
        tb.cell(0, 8, "reached 1.5R / 2R", text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 8, f_pct(nW15.get(0), closedA) + " / " + f_pct(nW2.get(0), closedA), text_color = tbTxt, text_size = ts)
        tb.cell(2, 8, f_pct(nW15.get(1), closedT) + " / " + f_pct(nW2.get(1), closedT), text_color = tbTxt, text_size = ts, text_halign = text.align_right)
        tb.cell(0, 9, "follow-through (BOS ≤ " + str.tostring(FTH) + ")", text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 9, f_pct(nFT.get(0), nSig.get(0)), text_color = tbTxt, text_size = ts)
        tb.cell(2, 9, f_pct(nFT.get(1), nSig.get(1)), text_color = tbTxt, text_size = ts, text_halign = text.align_right)
        tb.cell(0, 10, "failed (back across ≤ " + str.tostring(ACCM > 0 ? ACCM : MEASM) + ")", text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 10, f_pct(nFail.get(0), nSig.get(0)), text_color = cFail, text_size = ts)
        tb.cell(2, 10, f_pct(nFail.get(1), nSig.get(1)), text_color = cFail, text_size = ts, text_halign = text.align_right)
        tb.cell(0, 11, "avg MFE / MAE (R)", text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 11, f_avg(sumMFE.get(0), closedA) + " / " + f_avg(sumMAE.get(0), closedA), text_color = tbTxt, text_size = ts)
        tb.cell(2, 11, f_avg(sumMFE.get(1), closedT) + " / " + f_avg(sumMAE.get(1), closedT), text_color = tbTxt, text_size = ts, text_halign = text.align_right)
        float avgStopA = nStop.get(0) > 0 ? sumStop.get(0) / nStop.get(0) : na
        float avgStopT = nStop.get(1) > 0 ? sumStop.get(1) / nStop.get(1) : na
        tb.cell(0, 12, "avg stop  pts / $ · min – max", text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 12, na(avgStopA) ? "–" : f_k(avgStopA) + " / $" + str.tostring(avgStopA * PTVAL, "#") + " · " + f_k(minStop) + "–" + f_k(maxStop), text_color = na(avgStopA) ? tbTxt : avgStopA * PTVAL > CAP ? cStop : tbTxt, text_size = ts)
        tb.cell(2, 12, na(avgStopT) ? "–" : f_k(avgStopT) + " / $" + str.tostring(avgStopT * PTVAL, "#"), text_color = tbTxt, text_size = ts, text_halign = text.align_right)
        tb.cell(0, 13, "superseded · filtered · over cap", text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 13, str.tostring(nSup.get(0)) + " · " + str.tostring(nFilt) + " · " + str.tostring(nOver), text_color = tbTxt, text_size = ts)
        tb.cell(2, 13, "cancelled " + str.tostring(nCancel), text_color = tbHead, text_size = ts, text_halign = text.align_right)
        // retest plan rows
        int rClosedA = rWin.get(0) + rLoss.get(0)
        int rClosedT = rWin.get(1) + rLoss.get(1)
        string rState = not RTON ? "off" : R.dir == 0 ? "–" : R.stage == 1 ? (R.dir > 0 ? "waiting for retest ▲ " : "waiting for retest ▼ ") + str.tostring(rBars) + "/" + str.tostring(RTK) : R.stage == 2 ? "fills next open" : (R.dir > 0 ? "LONG " : "SHORT ") + f_px(R.entry) + " · stop " + f_px(R.stop)
        tb.cell(0, 14, "RETEST plan (5-min entry)", text_color = tbTxt, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 14, rState, text_color = R.dir > 0 ? cBull : R.dir < 0 ? cBear : tbHead, text_size = ts)
        tb.cell(2, 14, R.stage == 3 and not na(R.risk) ? "$" + f_k(R.risk * PTVAL) + (R.over ? " OVER CAP" : "") : "", text_color = R.over ? cStop : tbHead, text_size = ts, text_halign = text.align_right)
        tb.cell(0, 15, "retest filled · won / lost at " + (rtTgt == "Original plan target" ? "orig. target" : f_k(RTR) + "R"), text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 15, str.tostring(rSig.get(0)) + " · " + str.tostring(rWin.get(0)) + " / " + str.tostring(rLoss.get(0)) + "  " + f_pct(rWin.get(0), rClosedA), text_color = tbTxt, text_size = ts)
        tb.cell(2, 15, str.tostring(rSig.get(1)) + " · " + str.tostring(rWin.get(1)) + " / " + str.tostring(rLoss.get(1)) + "  " + f_pct(rWin.get(1), rClosedT), text_color = tbTxt, text_size = ts, text_halign = text.align_right)
        tb.cell(0, 16, "retest net R · avg stop · avg MFE", text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 16, (rClosedA > 0 ? f_k(rSumR.get(0)) + " (" + f_avg(rSumR.get(0), rClosedA) + "/trade)" : "–") + (rSig.get(0) > 0 ? " · " + f_avg(rSumStop.get(0), rSig.get(0)) + " pts $" + str.tostring(rSumStop.get(0) / rSig.get(0) * PTVAL, "#") : "") + (rClosedA > 0 ? " · " + f_avg(rSumMFE.get(0), rClosedA) + "R" : ""), text_color = rSumR.get(0) >= 0 ? cBull : cBear, text_size = ts)
        tb.cell(2, 16, (rClosedT > 0 ? f_k(rSumR.get(1)) + " (" + f_avg(rSumR.get(1), rClosedT) + "/trade)" : "–") + (rSig.get(1) > 0 ? " · " + f_avg(rSumStop.get(1), rSig.get(1)) + " pts" : "") + (rClosedT > 0 ? " · " + f_avg(rSumMFE.get(1), rClosedT) + "R" : ""), text_color = rSumR.get(1) >= 0 ? cBull : cBear, text_size = ts, text_halign = text.align_right)
        tb.cell(0, 17, "retest cancelled (no retest · through · timed out · superseded)", text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 17, str.tostring(rCancel), text_color = tbTxt, text_size = ts)
        tb.cell(2, 17, "", text_color = tbHead, text_size = ts)
        string note = closedA < 30 ? "sample small — read as preliminary" : closedA < 200 ? "preliminary (< 200 closed)" : "sample ≥ 200 closed"
        tb.cell(0, 18, note, text_color = tbHead, text_size = ts, text_halign = text.align_left)
        tb.cell(1, 18, "", text_color = tbHead, text_size = ts)
        tb.cell(2, 18, "measured on this chart only", text_color = tbHead, text_size = ts, text_halign = text.align_right)
else if not na(tb)
    table.delete(tb)
    tb := na
 
// ============================================================================================================
// ALERTS (confirmed events only)
// ============================================================================================================
bool aBull = vis and alOn == "On" and isCh and evt == 2
bool aBear = vis and alOn == "On" and isCh and evt == -2
bool w1Now = P.win1
bool lsNow = P.loss
bool aFill = vis and alOn == "On" and fillEvt
bool aTgt  = vis and alOn == "On" and w1Now and not w1Now[1]
bool aStop = vis and alOn == "On" and lsNow and not lsNow[1]
bool aBosU = vis and alOn == "On" and newEv and evt == 1
bool aBosD = vis and alOn == "On" and newEv and evt == -1
bool aFail = vis and alOn == "On" and failEvt
bool aSup  = vis and alOn == "On" and (supEvt or cancEvt)
bool aRFill = vis and alOn == "On" and rFillEvt
bool aRTgt  = vis and alOn == "On" and rTgtEvt
bool aRStop = vis and alOn == "On" and rStopEvt
bool aAny  = aBull or aBear or aFill or aTgt or aStop or aBosU or aBosD or aFail or aSup or aRFill or aRTgt or aRStop
alertcondition(aRFill, "Retest entry filled", "STRYK:CHCH retest plan entered on the 5-minute pullback")
alertcondition(aRTgt,  "Retest target hit",   "STRYK:CHCH retest plan target reached")
alertcondition(aRStop, "Retest stop hit",     "STRYK:CHCH retest plan stop hit")
alertcondition(aBull, "Bull CHoCH", "STRYK:CHoCH bullish change of character — close above the protected high")
alertcondition(aBear, "Bear CHoCH", "STRYK:CHoCH bearish change of character — close below the protected low")
alertcondition(aFill, "Entry filled", "STRYK:CHoCH plan entered at the next executable price")
alertcondition(aTgt,  "Target hit",  "STRYK:CHoCH target reached")
alertcondition(aStop, "Stop hit",    "STRYK:CHoCH stop hit")
alertcondition(aBosU, "BOS up",      "STRYK:CHoCH break of structure up — continuation, protected low moved")
alertcondition(aBosD, "BOS down",    "STRYK:CHoCH break of structure down — continuation, protected high moved")
alertcondition(aFail, "CHoCH failed", "STRYK:CHoCH the change of character closed back across its level — standby")
alertcondition(aSup,  "Plan superseded / cancelled", "STRYK:CHoCH the open plan was superseded by an opposite CHoCH or cancelled by the confirmation filter")
alertcondition(aAny,  "ANY signal",  "STRYK:CHCH signal — open the chart (CHoCH, BOS, entry, target, stop, failed, superseded or retest)")
// dynamic messages for the events that did not already send one above
if aBosU or aBosD
    alert("STRYK:CHoCH BOS " + (aBosU ? "up — protected low now " + f_px(refLo) : "down — protected high now " + f_px(refHi)), alert.freq_once_per_bar_close)
if aFail
    alert("STRYK:CHoCH FAILED — the change of character closed back across " + f_px(P.lvl) + " — standby", alert.freq_once_per_bar_close)
if aRTgt or aRStop
    alert("STRYK:CHCH retest " + (aRTgt ? "target hit" : "stop hit"), alert.freq_once_per_bar_close)
if aSup
    alert("STRYK:CHoCH plan " + (cancEvt ? "cancelled (no confirmation candle)" : "superseded by an opposite change of character"), alert.freq_once_per_bar_close)
if aBull or aBear
    alert("STRYK:CHoCH " + (aBull ? "BULL" : "BEAR") + " change of character at " + f_px(evLvl) + " — stop past " + f_px(P.stop) + (P.over ? " — OVER CAP" : "") + ((P.sesF or P.runF) ? " — FILTERED" : ""), alert.freq_once_per_bar_close)

← 返回列表