本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// Mozilla Public License 2.0. Copyright PickMyTrade.
// Source-aligned CRT / Turtle Soup implementation, 27 October 2026.
// Confirmed HTF range + wick raid -> MSS -> FVG/OB retest; alternate HTF close.
// No extra Turtle Body Soup trap. Exact engineering choices: source_aligned/SPEC.txt.
// Reference observations are committed at candle close, never broker fills.
indicator("Candle Range Theory - Quantified [Pickmytrade]", "CRT Quant", overlay = true, behind_chart = false, max_boxes_count = 60, max_lines_count = 12, max_labels_count = 30, max_bars_back = 100)
const string G_CONTEXT = "01 · Fixed confirmed context"
const string G_VIEW = "02 · Restrained chart presentation"
const string G_ALERT = "03 · Observation alerts"
const string G_COVER = "04 · Cover presentation"
const string G_ROUTE = "05 · Receiver automation"
string contextInput = input.timeframe("240", "Higher timeframe", options = ["60", "120", "240"], group = G_CONTEXT, tooltip = "Confirmed native C1/C2 reference. Use a standard 1m, 3m or 5m execution chart for the lower-timeframe MSS/retest route; 3m is the displayed example, not a proven optimum. HTF/chart ratio must be an integer of at least three. Wait for completed C2; MSS events that occurred before its close are not backdated as entries.")
bool rangeInput = input.bool(true, "Current fixed range", group = G_VIEW, tooltip = "During a valid episode this is completed C1, frozen before C3 is observed. Without a completed CRT, show the latest closed HTF candle as a neutral observation range. The display extends by known calendar windows while this reference persists; there is no C3 execution deadline.")
int historyInput = input.int(2, "Muted past windows", minval = 0, maxval = 5, group = G_VIEW, tooltip = "Retain this many prior reference windows in muted grey. They are presentation history; changing retention never changes the state engine.")
bool levelsInput = input.bool(true, "Range / structure / protection levels", group = G_VIEW, tooltip = "Shows frozen C1 midpoint, swept edge, known structure or HTF-C2 trigger, C2-buffered stop and selected midpoint/opposite-edge target. FVG/OB entry zone is selected after MSS formation; its later retest is confirmation. Lines and boxes are reference observations, not working broker orders.")
bool labelsInput = input.bool(true, "One BUY / SELL SETUP label", group = G_VIEW, tooltip = "A closed zone-retest candle creates one setup in MSS mode; native HTF close confirmation creates it in the alternative mode. Reference entry is the next available open. No retrospective zone-edge limit fill is invented; no second setup from the same reference.")
bool exitsInput = input.bool(false, "Optional reference-exit text", group = G_VIEW, tooltip = "Off by default. If enabled, show sparse REFERENCE STOP / TARGET text or UNKNOWN. The known open or model boundary is recorded only when the observation candle closes; this is not an actual open-time fill acknowledgement.")
int textInput = input.int(12, "Plain text size · pixels", minval = 8, maxval = 24, group = G_VIEW)
bool panelInput = input.bool(true, "Current workflow panel", group = G_VIEW)
bool alertsInput = input.bool(true, "Dynamic state messages", group = G_ALERT, tooltip = "One JSON events array per confirmed chart close. Includes context, MSS, zone, setup and reference entry/exit/censor states. Prices are close-committed observations. Missing bars after reference entry censor the result; no webhook execution or broker synchronization is provided. Choose either these messages or individual alert conditions if duplicate notifications are unwanted.")
bool coverInput = input.bool(true, "Lower heading and compact key", group = G_COVER, tooltip = "Presentation only. Hide the workflow panel and use viewport-anchored title/key. Turn off to show the detailed workflow panel. Use neutral candles and a navy chart background through chart settings; the indicator does not overwrite them.")
int headingInput = input.int(44, "Heading size · pixels", minval = 24, maxval = 64, step = 2, group = G_COVER)
string modelInput = input.string("CRT + Turtle Soup", "Confirmation model", options = ["CRT + Turtle Soup", "CRT HTF confirmation"], group = G_CONTEXT, tooltip = "CRT + Turtle Soup: completed HTF one-sided wick raid and inside close, then a future confirmed opposing-swing break, its three-candle FVG or last opposing candle, and a strictly later zone retest. No fresh outside-body trap. CRT HTF confirmation instead waits for a subsequent native HTF CLOSE beyond the original C2 other extreme; it does not stack MSS filters. Mechanical source interpretation, not a universal discretionary trading system.")
string deliveryInput = input.string("Off", "alert() delivery", options = ["Off", "Observations", "Receiver JSON"], group = G_ROUTE, tooltip = "Off sends no dynamic alert() calls. Observations sends the research events array. Receiver JSON sends separate raw entry/close payloads at intent time, never the delayed REFERENCE_ENTRY/EXIT records. Individual alertcondition choices remain informational and independent. Never send the observation wrapper to an order webhook.")
bool armInput = input.bool(false, "Arm receiver messages", group = G_ROUTE, tooltip = "Requires Receiver JSON mode, mapped execution symbol, and account-generated BUY, SELL and close-only templates that pass the offline validator and native shape guards. Defaults OFF. Native guards are not a full JSON parser. This arms messages only; it cannot verify broker positions, delivery, brackets or order acceptance. Test in demo first.")
string executionSymbolInput = input.string("", "Mapped execution symbol", group = G_ROUTE, tooltip = "Receiver/broker instrument, explicitly mapped to this chart. OANDA spot Gold and a futures GC contract are different markets. Empty blocks routing. Never assume the chart ticker is your broker instrument.")
float quantityInput = input.float(1, "Fixed receiver quantity", minval = 0.000001, group = G_ROUTE, tooltip = "Substituted as a number into [[QTY]]. Units/contracts/lots depend on your account-generated receiver schema. No automatic risk sizing or contract conversion.")
string buyPayloadInput = input.string("", "Generated BUY JSON template", group = G_ROUTE, tooltip = "Paste your receiver-generated account JSON privately. Use data buy, numeric unquoted [[QTY]], [[SL]] and [[TP]], and [[SYMBOL]] inside quotes. Optional [[PRICE]], [[EPISODE_ID]], [[TIME]] UTC request time and [[BAR_TIME]] close time. Keep account-generated routing/security fields. Broker-native absolute-price brackets are required. No credentials are included in this source.")
string sellPayloadInput = input.string("", "Generated SELL JSON template", group = G_ROUTE, tooltip = "Same template contract as BUY, with data sell. Entries are setup-close requests; order type and actual fills depend on receiver configuration. A supplied price field may change order semantics even with MKT in some schemas. Verify the generated account configuration in demo. Configure no-stacking, deduplication and strategy-specific ownership.")
string closePayloadInput = input.string("", "Generated CLOSE-ONLY JSON template", group = G_ROUTE, tooltip = "Require data close and reverse_order_close false. Use supported strategy/episode ownership. A broad close may affect other positions. This version requests close-only reconciliation for an owned unknown/invalid reference path. There is NO automatic C3 time exit. Broker brackets must protect the entry. Offline validation and demo receiver checks remain necessary.")
bool ribbonInput = input.bool(true, "Level highlight bands", group = G_VIEW, tooltip = "Display only: thin layered rectangles around the exact reference high/low, with current structure, stop and midpoint highlights. Orange marks the upper range edge; blue the lower edge. Band thickness is decorative, not a tolerance, entry zone, probability or confidence reading. Actual CRT comparisons, signals and protective references remain exact. No EMA, ATR price guide, volume profile or added filter.")
int pivotInput = input.int(1, "Confirmed swing strength", minval = 1, maxval = 5, group = G_CONTEXT, tooltip = "1 is a strict three-candle swing: center above/below both neighbors. Strength N requires N completed bars on each side, with no ties. Freeze the latest unbroken opposite swing formed inside C2 and known by its close. This explicit numeric choice is not an official ICT optimum.")
string targetInput = input.string("Opposite range edge", "Single execution target", options = ["Opposite range edge", "50% midpoint"], group = G_CONTEXT, tooltip = "The linked tutorials discuss midpoint and opposing liquidity objectives. Select one broker/reference target; no partial exits or favorable target switching. An objective reached before confirmation consumes this attempt. Midpoint remains a visual reference when the opposite edge is selected.")
int bufferInput = input.int(1, "Stop buffer · ticks", minval = 1, maxval = 100, group = G_CONTEXT, tooltip = "Fixed beyond the completed C2 sweep extreme. One tick is a transparent mechanical default, not a universal adequate buffer. Units and spread vary by feed. Changing this input changes the model and invalidates comparisons with the frozen default study.")
bool mssModel = modelInput == "CRT + Turtle Soup"
const color BLUE = #246BFF
const color ORANGE = #FF8A18
const color INK = #D8E1EF
const color QUIET = #91A0B7
float chartSeconds = timeframe.isminutes ? timeframe.in_seconds() : na
float contextSeconds = timeframe.in_seconds(contextInput)
float ratio = contextSeconds / chartSeconds
bool supported = chart.is_standard and timeframe.isminutes and not na(ratio) and ratio >= 3 and math.abs(ratio - math.round(ratio)) < 0.00000001
if barstate.isfirst and not supported
runtime.error("Use standard minute-based candles with an integer HTF/chart ratio >= 3. Start with a 4h reference on a standard 1m, 3m or 5m execution chart; no interval is a proven optimum. Synthetic charts are unsupported.")
int chartMs = int(chartSeconds * 1000)
int contextMs = int(contextSeconds * 1000)
float tick = syminfo.mintick
float eps = tick * 0.0000001
float markAtr = ta.atr(14)
// Every requested price is offset: C2 [1], C1 [2]. lookahead_on distributes
// already confirmed values from the beginning of C3 without future-price use.
[c2Open, c2High, c2Low, c2Close, c2Time, c2End, c1Open, c1High, c1Low, c1Close, c1Time, c1End] = request.security(syminfo.tickerid, contextInput, [open[1], high[1], low[1], close[1], time[1], time_close[1], open[2], high[2], low[2], close[2], time[2], time_close[2]], lookahead = barmerge.lookahead_on)
int c3Start = time(contextInput)
int c3End = time_close(contextInput)
bool pricesValid = not na(open) and not na(high) and not na(low) and not na(close) and high >= math.max(open, close) and low <= math.min(open, close) and high >= low
bool chartFull = not na(time_close) and time_close - time == chartMs
bool contextPrices = not na(c1Open) and not na(c1Close) and not na(c1High) and not na(c1Low) and not na(c2Open) and not na(c2Close) and not na(c2High) and not na(c2Low) and c1High > c1Low and c2High > c2Low and c1High >= math.max(c1Open, c1Close) and c1Low <= math.min(c1Open, c1Close) and c2High >= math.max(c2Open, c2Close) and c2Low <= math.min(c2Open, c2Close)
bool contextFull = not na(c1Time) and not na(c1End) and not na(c2Time) and not na(c2End) and not na(c3Start) and not na(c3End) and c1End - c1Time == contextMs and c2End - c2Time == contextMs and c3End - c3Start == contextMs and c2Time == c1End and c3Start == c2End
bool sweptLow = contextPrices and c2Low <= c1Low - tick + eps
bool sweptHigh = contextPrices and c2High >= c1High + tick - eps
bool reclaim = contextPrices and c2Close > c1Low and c2Close < c1High
int contextSide = sweptLow and not sweptHigh and reclaim ? 1 : sweptHigh and not sweptLow and reclaim ? -1 : 0
// Current native HTF values are used ONLY at their own confirmed close boundary.
// No developing native close is used as an earlier confirmation.
[nativeClose, nativeEnd] = request.security(syminfo.tickerid, contextInput, [close, time_close], gaps = barmerge.gaps_on, lookahead = barmerge.lookahead_off)
f_down(float value) =>
math.floor(value / syminfo.mintick + 0.00000001) * syminfo.mintick
f_up(float value) =>
math.ceil(value / syminfo.mintick - 0.00000001) * syminfo.mintick
f_price(float value) =>
na(value) ? "—" : str.tostring(value, format.mintick)
f_number(float value) =>
na(value) ? "null" : str.tostring(value, format.mintick)
f_level(line previous, int leftTime, int rightTime, float price, color ink, string stroke) =>
line result = previous
bool show = levelsInput and not na(leftTime) and not na(rightTime) and not na(price) and rightTime > leftTime
if show
if na(result)
result := line.new(leftTime, price, rightTime, price, xloc = xloc.bar_time, color = ink, width = 1, style = stroke)
else
line.set_xy1(result, leftTime, price)
line.set_xy2(result, rightTime, price)
line.set_color(result, ink)
line.set_style(result, stroke)
else if not na(result)
line.delete(result)
result := na
result
f_caption(label previous, int rightTime, float price, string caption, color ink) =>
label result = previous
bool show = levelsInput and not na(rightTime) and not na(price)
if show
if na(result)
result := label.new(rightTime, price, caption, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(#0B101B, 100), textcolor = ink, size = textInput)
else
label.set_xy(result, rightTime, price)
label.set_text(result, caption)
label.set_textcolor(result, ink)
else if not na(result)
label.delete(result)
result := na
result
f_event(string kind, string id, int side, float stop, float target, float entry, string reason) =>
"{\"event\":\"" + kind + "\",\"episode_id\":\"" + id + "\",\"ticker\":\"" + syminfo.tickerid + "\",\"chart_tf\":\"" + timeframe.period + "\",\"context_tf\":\"" + contextInput + "\",\"side\":" + str.tostring(side) + ",\"stop_reference\":" + f_number(stop) + ",\"target_reference\":" + f_number(target) + ",\"entry_reference\":" + f_number(entry) + ",\"reason\":\"" + reason + "\",\"observed_bar_close\":" + str.tostring(time_close) + ",\"scope\":\"reference observation; broker state unobserved\"}"
f_compact(string value) =>
string result = ""
bool quoted = false
bool escaped = false
if str.length(value) > 0 and str.length(value) <= 12000
for i = 0 to str.length(value) - 1
string ch = str.substring(value, i, i + 1)
if quoted
result += ch
if escaped
escaped := false
else if ch == "\\"
escaped := true
else if ch == "\""
quoted := false
else if ch == "\""
result += ch
quoted := true
else if ch != " " and ch != "\n" and ch != "\t" and str.match(ch, "\\x0D") == ""
result += ch
result
f_top_key(string value, string keyName) =>
string needle = "\"" + keyName + "\":"
int at = str.pos(value, needle)
bool unique = str.split(value, needle).size() == 2
int depth = 0
bool quoted = false
bool escaped = false
if unique and at > 0
for i = 0 to at - 1
string ch = str.substring(value, i, i + 1)
if quoted
if escaped
escaped := false
else if ch == "\\"
escaped := true
else if ch == "\""
quoted := false
else if ch == "\""
quoted := true
else if ch == "{"
depth += 1
else if ch == "}"
depth -= 1
unique and at > 0 and depth == 1 and not quoted
f_keys_literal(string value) =>
bool valid = true
bool quoted = false
bool escaped = false
bool tokenEscaped = false
if str.length(value) > 0
for i = 0 to str.length(value) - 1
string ch = str.substring(value, i, i + 1)
if quoted
if escaped
escaped := false
else if ch == "\\"
escaped := true
tokenEscaped := true
else if ch == "\""
quoted := false
if i + 1 < str.length(value) and str.substring(value, i + 1, i + 2) == ":" and tokenEscaped
valid := false
else if ch == "\""
quoted := true
tokenEscaped := false
valid
f_value(string value, string keyName, string expected) =>
string needle = "\"" + keyName + "\":" + expected
int at = str.pos(value, needle)
int ending = at + str.length(needle)
bool found = at >= 0 and ending < str.length(value)
bool delimited = found and (str.substring(value, ending, ending + 1) == "," or str.substring(value, ending, ending + 1) == "}")
f_top_key(value, keyName) and delimited
f_template(string value, string action) =>
string compact = f_compact(value)
bool framed = str.length(value) <= 12000 and str.startswith(compact, "{") and str.endswith(compact, "}") and f_keys_literal(compact)
bool actionMatches = f_value(compact, "data", "\"" + action + "\"")
bool reverseSafe = not str.contains(compact, "\"reverse_order_close\":") or f_value(compact, "reverse_order_close", "false")
bool contract = action == "close" ? f_value(compact, "reverse_order_close", "false") : f_value(compact, "sl", "[[SL]]") and f_value(compact, "tp", "[[TP]]") and f_value(compact, "quantity", "[[QTY]]") and reverseSafe
framed and actionMatches and contract and f_value(compact, "symbol", "\"[[SYMBOL]]\"")
f_symbol(string value) =>
str.length(value) > 0 and value == str.trim(value) and not str.contains(value, "[[") and not str.contains(value, "{{") and str.match(value, "[\\x00-\\x1F]") == ""
f_escape(string value) =>
string result = str.replace_all(str.replace_all(str.replace_all(str.replace_all(value, "\\", "\\\\"), "\"", "\\\""), "\n", "\\n"), "\t", "\\t")
// Pine supports \n and \t escapes, but not a literal \r escape. Match
// actual carriage returns through regex; never replace the letter r.
string carriage = str.match(value, "\\x0D")
if carriage != ""
result := str.replace_all(result, carriage, "\\r")
result
f_payload(string source, string id, float stop, float target) =>
string result = str.replace_all(source, "[[SYMBOL]]", f_escape(executionSymbolInput))
result := str.replace_all(result, "[[QTY]]", str.tostring(quantityInput, "0.########"))
result := str.replace_all(result, "[[SL]]", f_number(stop))
result := str.replace_all(result, "[[TP]]", f_number(target))
result := str.replace_all(result, "[[PRICE]]", f_number(close))
result := str.replace_all(result, "[[EPISODE_ID]]", f_escape(id))
result := str.replace_all(result, "[[TIME]]", str.format_time(timenow, "yyyy-MM-dd'T'HH:mm:ss'Z'", "UTC"))
result := str.replace_all(result, "[[BAR_TIME]]", str.format_time(time_close, "yyyy-MM-dd'T'HH:mm:ss'Z'", "UTC"))
// alert() does not process TradingView placeholders; substitute these here.
result := str.replace_all(result, "{{ticker}}", f_escape(executionSymbolInput))
result := str.replace_all(result, "{{close}}", f_number(close))
result := str.replace_all(result, "{{timenow}}", str.format_time(timenow, "yyyy-MM-dd'T'HH:mm:ss'Z'", "UTC"))
result
f_resolved(string value) =>
not str.contains(value, "[[") and not str.contains(value, "{{")
// Input changes rebuild the script, so expensive shape checks run only once.
// These guards are deliberately not a full JSON parser or broker schema check.
var bool routeTemplates = f_template(buyPayloadInput, "buy") and f_template(sellPayloadInput, "sell") and f_template(closePayloadInput, "close") and f_symbol(executionSymbolInput) and f_resolved(f_payload(buyPayloadInput, "check", 1, 2)) and f_resolved(f_payload(sellPayloadInput, "check", 1, 2)) and f_resolved(f_payload(closePayloadInput, "check", 1, 2))
bool routeReady = deliveryInput == "Receiver JSON" and armInput and routeTemplates
string routeStatus = deliveryInput == "Off" ? "ALERTS OFF" : deliveryInput == "Observations" ? "OBSERVATIONS ONLY" : not armInput ? "RECEIVER DISARMED" : not routeTemplates ? "ROUTING BLOCKED · CHECK TEMPLATES" : "RECEIVER MESSAGES ARMED"
f_phase(int phase) =>
switch phase
1 => mssModel ? "WAIT MSS" : "WAIT HTF CONFIRMATION"
2 => "WAIT ENTRY ZONE"
3 => "WAIT ZONE RETEST"
4 => "ENTRY INTENT"
5 => "REFERENCE ACTIVE"
6 => "REFERENCE CLOSED"
7 => "INVALID / NO SETUP"
8 => "TARGET CONSUMED"
10 => "UNKNOWN / CENSORED"
=> "NEUTRAL RANGE"
f_wait(int phase, int side) =>
switch phase
1 => mssModel ? "Future close through confirmed swing" : "Native HTF close beyond C2 extreme"
2 => "Next close selects MSS FVG / last opposing candle"
3 => "First later entry-zone overlap"
4 => "Next available open reference"
5 => "Fixed stop or selected target; no C3 time exit"
6 => "Reference complete"
7 => "Invalid / missing structure or zone"
8 => "Objective already reached before setup"
10 => "Missing active path; reconcile broker state"
=> "Wait for confirmed HTF sweep / reclaim"
type Swing
float price
int origin
int known
int side
bool broken = false
type Episode
int phase = 0
int side = 0
int start = na
int ending = na
int c2Start = na
float high = na
float low = na
float mid = na
float stop = na
float target = na
float trigger = na
float c2High = na
float c2Low = na
int mssBar = na
float previousHigh = na
float previousLow = na
float obHigh = na
float obLow = na
int obTime = na
float zoneHigh = na
float zoneLow = na
int zoneBar = na
int zoneTime = na
string zoneKind = ""
string id = ""
string reason = "Wait for confirmed CRT"
type ReferencePlan
int phase = 0
int side = 0
float stop = na
float target = na
float entry = na
float risk = na
int signalEnd = na
int lastClose = na
string id = ""
bool liveIntent = false
var Episode episode = Episode.new()
var ReferencePlan plan = ReferencePlan.new()
var array<Swing> swings = array.new<Swing>()
var int trackedWindow = na
var int previousChartClose = na
var float lastBearHigh = na
var float lastBearLow = na
var int lastBearTime = na
var float lastBullHigh = na
var float lastBullLow = na
var int lastBullTime = na
var box currentRange = na
var array<box> history = array.new<box>()
var array<label> setupLabels = array.new<label>()
var array<label> exitLabels = array.new<label>()
var string lastReference = "—"
bool buySetup = false
bool sellSetup = false
bool referenceExit = false
bool referenceUnknown = false
float exportedRisk = na
array<string> messages = array.new<string>()
array<string> executionMessages = array.new<string>()
array<bool> executionEntries = array.new<bool>()
bool newWindow = na(trackedWindow) or c3Start != trackedWindow
bool chartGap = not na(previousChartClose) and time != previousChartClose
if barstate.isconfirmed
// A new completed context is known at this bar's open. It can supersede
// unfilled waiting only; it never overwrites a pending or active plan.
if newWindow
trackedWindow := c3Start
bool eligible = contextPrices and contextFull and time == c3Start and contextSide != 0
bool waiting = episode.phase >= 1 and episode.phase <= 3
bool initialize = plan.phase == 0 and (eligible or not waiting)
if initialize
if episode.phase >= 1 and episode.phase <= 3
messages.push(f_event("CONTEXT_SUPERSEDED", episode.id, episode.side, episode.stop, episode.target, na, "Newer confirmed unfilled context"))
if not na(currentRange)
box.set_bgcolor(currentRange, color.new(#8796AD, 97))
box.set_border_color(currentRange, color.new(#8796AD, 82))
history.push(currentRange)
if history.size() > historyInput
box.delete(history.shift())
currentRange := na
episode := Episode.new()
episode.start := c3Start
episode.ending := c3End
episode.high := eligible ? c1High : c2High
episode.low := eligible ? c1Low : c2Low
episode.mid := (episode.high + episode.low) * 0.5
episode.id := syminfo.tickerid + ":" + contextInput + ":" + str.tostring(c1Time) + ":" + str.tostring(c2Time) + (mssModel ? ":MSS" : ":HTF")
episode.reason := not contextFull ? "Partial / gapped HTF context" : not eligible ? "Wait for one-sided HTF sweep and inside close" : "Confirmed CRT context"
if eligible
episode.phase := 1
episode.side := contextSide
episode.c2Start := c2Time
episode.c2High := c2High
episode.c2Low := c2Low
episode.stop := contextSide == 1 ? f_down(c2Low - bufferInput * tick) : f_up(c2High + bufferInput * tick)
float targetPrice = targetInput == "50% midpoint" ? episode.mid : contextSide == 1 ? c1High : c1Low
episode.target := contextSide == 1 ? f_down(targetPrice) : f_up(targetPrice)
if mssModel
if swings.size() > 0
for i = swings.size() - 1 to 0
Swing p = swings.get(i)
if p.side == contextSide and not p.broken and p.origin >= c2Time and p.origin < c3Start and p.known <= c3Start and contextSide * (p.price - c2Close) > 0
episode.trigger := p.price + contextSide * tick
break
if na(episode.trigger)
episode.phase := 7
episode.reason := "No confirmed unbroken opposing swing inside C2"
else
episode.trigger := contextSide == 1 ? c2High + tick : c2Low - tick
messages.push(f_event("CRT_CONTEXT", episode.id, episode.side, episode.stop, episode.target, na, episode.reason))
if rangeInput and not na(episode.high) and episode.high > episode.low
currentRange := box.new(episode.start, episode.high, episode.ending, episode.low, xloc = xloc.bar_time, border_color = color.new(#AAB6C9, 60), bgcolor = color.new(#8796AD, 95))
else if eligible and plan.phase != 0
messages.push(f_event("CONTEXT_SKIPPED", episode.id, episode.side, episode.stop, episode.target, plan.entry, "Prior reference plan pending or active"))
int finish = 0
float exitReference = na
string finishReason = ""
if plan.phase != 0
if not pricesValid or not chartFull or (plan.phase == 2 and time != plan.lastClose)
finish := plan.phase == 1 ? 5 : 4
finishReason := plan.phase == 1 ? "ENTRY INVALID · PARTIAL / INVALID OBSERVATION" : "UNKNOWN · ACTIVE GAP / INVALID OBSERVATION"
else
if plan.phase == 1
plan.entry := open
plan.phase := 2
plan.lastClose := time
episode.phase := 5
episode.reason := "Reference active; fixed protection, no C3 time exit"
messages.push(f_event("REFERENCE_ENTRY", plan.id, plan.side, plan.stop, plan.target, plan.entry, time > plan.signalEnd ? "Next available open after gap" : "Next open reference; close-committed"))
bool stopOpen = plan.side == 1 ? open <= plan.stop : open >= plan.stop
bool targetOpen = plan.side == 1 ? open >= plan.target : open <= plan.target
bool stopTouch = plan.side == 1 ? low <= plan.stop : high >= plan.stop
bool targetTouch = plan.side == 1 ? high >= plan.target : low <= plan.target
if stopOpen
finish := 1
exitReference := open
finishReason := "STOP · KNOWN OPEN"
else if targetOpen
finish := 2
exitReference := open
finishReason := "TARGET · KNOWN OPEN"
else if stopTouch
finish := 1
exitReference := plan.stop
finishReason := targetTouch ? "STOP · AMBIGUOUS DOUBLE TOUCH" : "STOP · OBSERVED TOUCH"
else if targetTouch
finish := 2
exitReference := plan.target
finishReason := "TARGET · OBSERVED TOUCH"
plan.lastClose := time_close
if finish != 0
referenceExit := finish <= 2
referenceUnknown := finish == 4
lastReference := finishReason
episode.phase := finish == 4 ? 10 : finish == 5 ? 7 : 6
episode.reason := finishReason
messages.push(f_event(finish == 4 ? "REFERENCE_UNKNOWN" : finish == 5 ? "ENTRY_INVALID" : "REFERENCE_EXIT", plan.id, plan.side, plan.stop, plan.target, plan.entry, finishReason))
if routeReady and plan.liveIntent and barstate.isrealtime and finish >= 4
executionMessages.push(f_payload(closePayloadInput, plan.id, plan.stop, plan.target))
executionEntries.push(false)
if exitsInput and finish != 5
exitLabels.push(label.new(bar_index, na(exitReference) ? close : exitReference, finish == 4 ? "UNKNOWN" : finish == 1 ? "REFERENCE STOP" : "REFERENCE TARGET", style = label.style_none, textcolor = finish == 4 ? QUIET : plan.side == 1 ? BLUE : ORANGE, size = textInput, tooltip = finishReason + " · reference observation, not broker acknowledgement"))
if exitLabels.size() > 10
label.delete(exitLabels.shift())
plan.phase := 0
plan.liveIntent := false
bool triggerSetup = false
if episode.phase >= 1 and episode.phase <= 3 and plan.phase == 0
bool stopHit = episode.side == 1 ? low <= episode.stop : high >= episode.stop
bool targetHit = episode.side == 1 ? high >= episode.target : low <= episode.target
bool failedReclaim = episode.side == 1 ? close <= episode.low : close >= episode.high
if not pricesValid or not chartFull or chartGap
episode.phase := 7
episode.reason := "INVALID · MISSING / PARTIAL CHART OBSERVATION"
else if stopHit
episode.phase := 7
episode.reason := "INVALID · STOP TOUCHED BEFORE ENTRY"
else if targetHit
episode.phase := 8
episode.reason := "CONSUMED · SELECTED OBJECTIVE ALREADY REACHED"
else if failedReclaim
episode.phase := 7
episode.reason := "INVALID · RANGE RECLAIM FAILED"
else if episode.phase == 1
bool broke = episode.side * (close - episode.trigger) >= -eps
if not mssModel
if time_close == c3End and time_close == nativeEnd and time_close > episode.start and (time_close - episode.start) % contextMs == 0 and not na(nativeClose) and math.abs(close - nativeClose) <= eps and broke
triggerSetup := true
else if broke and episode.side * (close - open) > 0
episode.mssBar := bar_index
episode.previousHigh := high[1]
episode.previousLow := low[1]
episode.obHigh := episode.side == 1 ? lastBearHigh : lastBullHigh
episode.obLow := episode.side == 1 ? lastBearLow : lastBullLow
episode.obTime := episode.side == 1 ? lastBearTime : lastBullTime
if na(episode.obTime) or episode.obTime < episode.c2Start
episode.obHigh := na
episode.obLow := na
episode.phase := 2
episode.reason := "MSS close observed; wait for next-bar zone formation"
messages.push(f_event("MSS_CONFIRMED", episode.id, episode.side, episode.stop, episode.target, na, "Future directional close through pre-known swing"))
else if episode.phase == 2
bool fvg = episode.side == 1 ? low >= episode.previousHigh + tick - eps : high <= episode.previousLow - tick + eps
if fvg
episode.zoneLow := episode.side == 1 ? episode.previousHigh : high
episode.zoneHigh := episode.side == 1 ? low : episode.previousLow
episode.zoneKind := "FVG"
else if not na(episode.obHigh)
episode.zoneLow := episode.obLow
episode.zoneHigh := episode.obHigh
episode.zoneKind := "OB"
else
episode.phase := 7
episode.reason := "No MSS-leg FVG or last opposing candle"
if episode.phase == 2
episode.zoneBar := bar_index
episode.zoneTime := time_close
episode.phase := 3
episode.reason := "Wait for first strictly later entry-zone retest"
messages.push(f_event("ENTRY_ZONE_FROZEN", episode.id, episode.side, episode.stop, episode.target, na, episode.zoneKind + " selected at closed-bar formation"))
else if episode.phase == 3
if bar_index > episode.zoneBar and low <= episode.zoneHigh and high >= episode.zoneLow
triggerSetup := true
if triggerSetup
float risk = episode.side * (close - episode.stop)
if risk < tick - eps or episode.side * (episode.target - close) <= 0
episode.phase := 7
episode.reason := "INVALID · SIGNAL GEOMETRY"
else
episode.phase := 4
episode.reason := mssModel ? "Confirmed later zone retest; next-open reference" : "Confirmed native HTF C2-extreme break; next-open reference"
plan := ReferencePlan.new(phase = 1, side = episode.side, stop = episode.stop, target = episode.target, risk = risk, signalEnd = time_close, lastClose = time_close, id = episode.id)
buySetup := episode.side == 1
sellSetup := episode.side == -1
exportedRisk := risk
messages.push(f_event(buySetup ? "BUY_SETUP" : "SELL_SETUP", episode.id, episode.side, episode.stop, episode.target, na, episode.reason))
if routeReady and barstate.isrealtime
executionMessages.push(f_payload(buySetup ? buyPayloadInput : sellPayloadInput, episode.id, episode.stop, episode.target))
executionEntries.push(true)
if labelsInput
float offset = math.max(tick * 4, nz(markAtr, high - low) * 0.25)
setupLabels.push(label.new(bar_index, buySetup ? low - offset : high + offset, buySetup ? "BUY SETUP" : "SELL SETUP", style = label.style_none, textcolor = buySetup ? BLUE : ORANGE, size = textInput, tooltip = modelInput + "\n" + episode.reason + "\nSL " + f_price(episode.stop) + " · target " + f_price(episode.target) + "\nSetup-close intent; next-open reference, not broker fill acknowledgement."))
if setupLabels.size() > 5
label.delete(setupLabels.shift())
// Structure becomes available only AFTER processing this completed bar.
// The strict pivot is never plotted/triggered back on its original candle.
if not pricesValid or not chartFull or chartGap
swings.clear()
lastBearTime := na
lastBullTime := na
if pricesValid and chartFull
for p in swings
if p.side == 1 ? close > p.price : close < p.price
p.broken := true
bool strictHigh = bar_index >= pivotInput * 2
bool strictLow = strictHigh
bool contiguous = strictHigh
if strictHigh
for j = 0 to pivotInput * 2
contiguous := contiguous and time_close[j] - time[j] == chartMs
if j < pivotInput * 2
contiguous := contiguous and time[j] == time_close[j + 1]
if j != pivotInput
strictHigh := strictHigh and high[pivotInput] > high[j]
strictLow := strictLow and low[pivotInput] < low[j]
if contiguous and strictHigh
swings.push(Swing.new(high[pivotInput], time[pivotInput], time_close, 1))
if contiguous and strictLow
swings.push(Swing.new(low[pivotInput], time[pivotInput], time_close, -1))
while swings.size() > 0 and (swings.first().origin < c2Time or swings.size() > 512)
swings.shift()
if close < open
lastBearHigh := high
lastBearLow := low
lastBearTime := time
else if close > open
lastBullHigh := high
lastBullLow := low
lastBullTime := time
if pricesValid
previousChartClose := time_close
episode.ending := math.max(nz(episode.ending, c3End), c3End)
if not na(currentRange)
box.set_right(currentRange, episode.ending)
color direction = episode.side == 1 ? BLUE : ORANGE
box.set_border_color(currentRange, episode.side != 0 ? color.new(direction, 42) : color.new(#AAB6C9, 65))
box.set_bgcolor(currentRange, episode.side != 0 ? color.new(direction, 93) : color.new(#8796AD, 96))
if barstate.isconfirmed and deliveryInput == "Observations" and alertsInput and messages.size() > 0
alert("{\"events\":[" + array.join(messages, ",") + "]}", alert.freq_once_per_bar_close)
if barstate.isconfirmed and barstate.isrealtime and routeReady and executionMessages.size() > 0
for i = 0 to executionMessages.size() - 1
string payload = executionMessages.get(i)
if f_resolved(payload)
alert(payload, alert.freq_all)
if executionEntries.get(i)
plan.liveIntent := true
bool hasPlan = plan.phase != 0
float shownStop = hasPlan ? plan.stop : episode.stop
float shownTarget = hasPlan ? plan.target : episode.target
// Decorative rectangles around the actual fixed reference levels only.
// Upper edge = orange, lower edge = blue; neither creates a trade condition.
var int bandWindow = na
var array<int> bandStarts = array.new<int>()
var array<box> levelBands = array.new<box>()
if barstate.isconfirmed and (na(bandWindow) or bandWindow != episode.start)
bandWindow := episode.start
bandStarts.push(episode.start)
if bandStarts.size() > historyInput + 1
bandStarts.shift()
int firstBandWindow = bandStarts.first()
while levelBands.size() > 0 and box.get_left(levelBands.first()) < firstBandWindow
box.delete(levelBands.shift())
if ribbonInput and levelsInput and not na(episode.mid) and episode.high > episode.low
float edgeHalfWidth = math.max(tick * 2, (episode.high - episode.low) * 0.025)
for layer = 0 to 1
float width = layer == 0 ? edgeHalfWidth : edgeHalfWidth * 0.5
int opacity = layer == 0 ? 88 : 75
levelBands.push(box.new(episode.start, episode.high + width, episode.ending, episode.high - width, xloc = xloc.bar_time, border_color = color.new(ORANGE, 100), bgcolor = color.new(ORANGE, opacity)))
levelBands.push(box.new(episode.start, episode.low + width, episode.ending, episode.low - width, xloc = xloc.bar_time, border_color = color.new(BLUE, 100), bgcolor = color.new(BLUE, opacity)))
if barstate.isconfirmed and levelBands.size() > 0
for band in levelBands
if box.get_left(band) == episode.start
box.set_right(band, episode.ending)
f_highlight(box previous, float price, color ink, bool enabled) =>
box result = previous
if ribbonInput and levelsInput and enabled and not na(price) and not na(episode.start)
float width = math.max(tick * 2, (episode.high - episode.low) * 0.007)
if na(result)
result := box.new(episode.start, price + width, episode.ending, price - width, xloc = xloc.bar_time, border_color = color.new(ink, 80), bgcolor = color.new(ink, 85))
else
box.set_lefttop(result, episode.start, price + width)
box.set_rightbottom(result, episode.ending, price - width)
box.set_bgcolor(result, color.new(ink, 85))
box.set_border_color(result, color.new(ink, 80))
else if not na(result)
box.delete(result)
result := na
result
var box structureBand = na
var box stopBand = na
var box midpointBand = na
if barstate.islast
bool directional = episode.side != 0
color setupInk = episode.side == 1 ? BLUE : ORANGE
structureBand := f_highlight(structureBand, episode.trigger, setupInk, directional)
stopBand := f_highlight(stopBand, shownStop, QUIET, directional)
midpointBand := f_highlight(midpointBand, episode.mid, QUIET, true)
var box entryZone = na
if barstate.islast
bool showZone = levelsInput and not na(episode.zoneHigh) and episode.phase >= 3 and episode.phase <= 5
if showZone
color zoneInk = episode.side == 1 ? BLUE : ORANGE
if na(entryZone)
entryZone := box.new(episode.zoneTime, episode.zoneHigh, episode.ending, episode.zoneLow, xloc = xloc.bar_time, border_color = color.new(zoneInk, 20), bgcolor = color.new(zoneInk, 90), text = episode.zoneKind + " · entry zone", text_color = zoneInk, text_size = 11)
else
box.set_lefttop(entryZone, episode.zoneTime, episode.zoneHigh)
box.set_rightbottom(entryZone, episode.ending, episode.zoneLow)
box.set_text(entryZone, episode.zoneKind + " · entry zone")
box.set_border_color(entryZone, color.new(zoneInk, 20))
box.set_bgcolor(entryZone, color.new(zoneInk, 90))
box.set_text_color(entryZone, zoneInk)
else if not na(entryZone)
box.delete(entryZone)
entryZone := na
// Current-episode line objects replace historical plot fragments. The Data
// Window retains the analytical series; presentation cannot change signals.
var line midpointLine = na
var line edgeLine = na
var line triggerLine = na
var line stopLine = na
var line targetLine = na
var line entryLine = na
var label edgeCaption = na
var label targetCaption = na
var label triggerCaption = na
var label stopCaption = na
if barstate.islast
color contextInk = episode.side == 1 ? BLUE : episode.side == -1 ? ORANGE : QUIET
float edgePrice = episode.side != 0 ? (episode.side == 1 ? episode.low : episode.high) : na
midpointLine := f_level(midpointLine, episode.start, episode.ending, episode.mid, color.new(QUIET, 30), line.style_dashed)
edgeLine := f_level(edgeLine, episode.start, episode.ending, edgePrice, contextInk, line.style_solid)
triggerLine := f_level(triggerLine, episode.start, episode.ending, episode.trigger, INK, line.style_dotted)
stopLine := f_level(stopLine, episode.start, episode.ending, shownStop, color.new(QUIET, 15), line.style_dashed)
targetLine := f_level(targetLine, episode.start, episode.ending, shownTarget, color.new(contextInk, 15), line.style_solid)
entryLine := f_level(entryLine, episode.start, episode.ending, hasPlan and plan.phase >= 2 ? plan.entry : na, color.new(INK, 30), line.style_dotted)
edgeCaption := f_caption(edgeCaption, episode.ending, edgePrice, "C1 " + (episode.side == 1 ? "LOW" : "HIGH") + " · swept edge", contextInk)
targetCaption := f_caption(targetCaption, episode.ending, shownTarget, targetInput == "50% midpoint" ? "50% MIDPOINT · target" : "OPPOSITE EDGE · target", contextInk)
triggerCaption := f_caption(triggerCaption, episode.ending, episode.trigger, mssModel ? "MSS · structure trigger" : "C2 EXTREME · HTF close", INK)
stopCaption := f_caption(stopCaption, episode.ending, shownStop, "BEYOND C2 · stop", QUIET)
plot(episode.mid, "50% range midpoint reference", display = display.data_window)
plot(episode.side != 0 ? (episode.side == 1 ? episode.low : episode.high) : na, "Swept C1 edge", display = display.data_window)
plot(episode.trigger, "Frozen structure / C2 trigger", display = display.data_window)
plot(shownStop, "Frozen stop reference", display = display.data_window)
plot(shownTarget, "Selected target reference", display = display.data_window)
plot(hasPlan and plan.phase >= 2 ? plan.entry : na, "Observed next-open entry reference", display = display.data_window)
plot(exportedRisk, "Setup planned signal risk", display = display.data_window)
plot(buySetup ? 1 : sellSetup ? -1 : na, "Setup side", display = display.data_window)
var table panel = table.new(position.top_right, 2, 8, bgcolor = #0C1424, frame_color = #2C3A50, frame_width = 1)
var table heading = table.new(position.top_center, 1, 3)
var table key = table.new(position.bottom_center, 2, 3, bgcolor = color.new(#142033, 28), frame_color = #253249, frame_width = 1)
if barstate.isfirst
table.merge_cells(key, 0, 1, 1, 1)
table.merge_cells(key, 0, 2, 1, 2)
if barstate.islast
table.clear(panel, 0, 0, 1, 7)
table.clear(heading, 0, 0, 0, 2)
table.clear(key, 0, 0, 1, 2)
if coverInput
table.cell(heading, 0, 0, "", height = 7)
table.cell(heading, 0, 1, "CANDLE RANGE THEORY", text_color = #EDF2FA, text_size = headingInput, text_formatting = text.format_bold)
table.cell(heading, 0, 2, mssModel ? "Pickmytrade · Quantified CRT · MSS & zone retest" : "Pickmytrade · Quantified CRT · Native HTF confirmation", text_color = #AAB6C9, text_size = 14)
table.cell(key, 0, 0, "BLUE · lower range edge", text_color = BLUE, text_size = 12)
table.cell(key, 1, 0, "ORANGE · upper range edge", text_color = ORANGE, text_size = 12)
table.cell(key, 0, 1, f_phase(episode.phase), text_color = episode.side == 1 ? BLUE : episode.side == -1 ? ORANGE : INK, text_size = 12, tooltip = episode.reason)
table.cell(key, 0, 2, modelInput + " · One attempt · " + routeStatus, text_color = QUIET, text_size = 11, tooltip = "Research interpretation; no demonstrated predictive edge. Delivery mode, symbol mapping and receiver templates are separate from observed reference prices. Recreate TradingView alerts after any source/input changes.")
else if panelInput
table.cell(panel, 0, 0, "CRT · SOURCE WORKFLOW", text_color = INK, text_size = size.small, text_halign = text.align_left)
table.cell(panel, 1, 0, f_phase(episode.phase), text_color = episode.side == 1 ? BLUE : episode.side == -1 ? ORANGE : INK, text_size = size.small, text_halign = text.align_left)
array<string> names = array.from("Context / chart", "Direction", "Fixed range", "Waiting", "Structure / HTF trigger", "Stop / target", "Entry reference")
array<string> values = array.from(contextInput + " / " + timeframe.period, episode.side == 1 ? "LONG CONTEXT" : episode.side == -1 ? "SHORT CONTEXT" : "NEUTRAL RANGE", f_price(episode.low) + " – " + f_price(episode.high), episode.phase == 0 ? episode.reason : f_wait(episode.phase, episode.side), f_price(episode.trigger), f_price(shownStop) + " / " + f_price(shownTarget), hasPlan ? f_price(plan.entry) : "—")
for i = 0 to names.size() - 1
table.cell(panel, 0, i + 1, names.get(i), text_color = QUIET, text_size = size.small, text_halign = text.align_left)
table.cell(panel, 1, i + 1, values.get(i), text_color = INK, text_size = size.small, text_halign = text.align_left, tooltip = i == 3 ? episode.reason : "Closed-candle reference workflow; no broker state. Last reference: " + lastReference)
alertcondition(buySetup, "BUY SETUP · conditional next-open reference", "Confirmed CRT source-model setup | {{ticker}} {{interval}} | MSS-zone retest or native HTF C2-extreme confirmation. Next-open reference; not broker acknowledgement.")
alertcondition(sellSetup, "SELL SETUP · conditional next-open reference", "Confirmed CRT source-model setup | {{ticker}} {{interval}} | MSS-zone retest or native HTF C2-extreme confirmation. Next-open reference; not broker acknowledgement.")
alertcondition(referenceExit, "Reference exit observed", "CRT reference exit observed at chart close | {{ticker}} {{interval}} | Known opening gaps precede intrabar extremes; ambiguous double touches use stop first. Not broker execution.")
alertcondition(referenceUnknown, "Reference outcome UNKNOWN", "CRT reference path is UNKNOWN/censored due to missing or invalid observations | {{ticker}} {{interval}} | No exit or zero result is invented.")
// No strategy orders, fees, PnL, confidence score, AI model or live broker state.
// Source-aligned mechanics are a separate hypothesis; no profitable edge established.
// Native data alignment, runtime, alerts and research parity require verification.