Market Map [GoldenDream]

Golden_Dream · study · 1703 行 · 点赞 148 · TradingView 原页

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

Pine Script

// © GoldenDream
//@version=6
// ════════════════════════════════════════════════════════════════════════════
//  Market Map [GoldenDream]
//
//  A written, conditional market plan drawn on the chart: what the structure
//  says, where the key levels are, and the route price is most likely to take
//  to reach them.
//
//  HOW IT WORKS
//   1. Structure: trend is read from swing highs and lows on three
//      timeframes (context, main and timing), chosen from the chart
//      timeframe. "Short-term" horizon keeps everything close to price.
//   2. Levels: swing highs / lows, previous day and week, Fibonacci of the
//      last swing, unfilled wicks, equal highs / lows and multi-touch
//      support / resistance zones.
//   3. Plan: a sell / buy zone in the direction of the trend (or of the
//      strongest evidence in a sideways market), the confirmation to wait
//      for, targets and the level that cancels the plan.
//   4. Route: a short-term path built from the chart's own recent swings,
//      stepping from level to level, then a dashed projection on to the
//      plan's targets. Targets are kept within a realistic distance (a
//      multiple of the average daily range); anything further is shown
//      separately as a "larger target".
//
//  Extra visuals (each can be turned off): structure breaks (BOS / CHoCH),
//  unfilled fair value gaps, premium / discount bands, previous day high /
//  low and optional trend-coloured candles.
//
//  The chart follows the plan as it unfolds: the zone is marked reached or
//  used, and a finished setup is replaced by the next near-term move.
//
//  Non-repainting: higher-timeframe data uses completed bars only.
//  This is a planning and analysis tool, not a trading signal. Paths show the
//  most likely route based on the current evidence, not a guarantee, and the
//  timing of the path is illustrative.
// ════════════════════════════════════════════════════════════════════════════
indicator("Market Map [GoldenDream]", shorttitle="Market Map", overlay=true, max_lines_count=200, max_labels_count=150, max_boxes_count=100, max_polylines_count=10)
 
//────────────────────────────────────────────
// INPUTS
//────────────────────────────────────────────
grp_a   = "Timeframes"
useAuto = input.bool(true, "Auto-select timeframes from the chart", group=grp_a, display=display.none, tooltip="Picks the context / main / timing timeframes from the chart timeframe and the planning horizon below. Turn off to choose them yourself.")
horizon = input.string("Short-term", "Planning horizon", options=["Short-term", "Swing"], group=grp_a, display=display.none, active=useAuto, tooltip="Short-term (context / main / timing):\n1m: 15m / 5m / 1m\n3m–5m: 1H / 15m / chart\n15m–30m: 4H / 1H / chart\n1H: D / 4H / 1H\n4H: W / D / 4H\n\nSwing:\n1m–3m: 1H / 15m / 5m\n5m: 4H / 1H / 15m\n15m–30m: D / 4H / 1H\n1H: W / D / 4H\n\nShort-term keeps zones and targets close to price. Swing plans bigger moves.")
htfIn   = input.timeframe("240", "Manual: main timeframe", group=grp_a, display=display.none, active=not useAuto, tooltip="The timeframe the plan is built on: structure, Fibonacci, zones, wicks and liquidity.")
hiTfIn  = input.timeframe("D", "Manual: context timeframe (higher)", group=grp_a, display=display.none, active=not useAuto, tooltip="Bigger-picture trend, used for the alignment reading.")
loTfIn  = input.timeframe("60", "Manual: timing timeframe (lower)", group=grp_a, display=display.none, active=not useAuto, tooltip="Shorter-term trend, used to spot corrective moves. Should be lower than the main timeframe.")
pivLen  = input.int(5, "Swing strength (bars each side)", minval=2, maxval=20, group=grp_a, display=display.none, tooltip="How many bars on each side a high or low must beat to count as a swing. Higher = only major swings. Lower = more, smaller swings.")
 
grp_z      = "Support / Resistance Zones"
useZones   = input.bool(true, "Show multi-touch zones", group=grp_z, display=display.none, tooltip="Zones where price has turned several times on the main timeframe. More touches = a level the market respects. Shows the nearest zone above and below price.")
zoneSrc    = input.string("Main timeframe", "Build zones on", options=["Main timeframe", "Timing timeframe"], group=grp_z, display=display.none, active=useZones, tooltip="Main: zones from the plan's timeframe (e.g. 1H on a 5m chart). Fewer, more significant levels.\nTiming: zones from the lower timeframe (e.g. 15m on a 5m chart). Closer, more frequent levels for intraday trading.")
minTouches = input.int(2, "Minimum touches", minval=2, maxval=10, group=grp_z, display=display.none, active=useZones, tooltip="How many swing highs / lows must cluster at a price before it counts as a zone. 2 = nearest tested level. 3+ = fewer, stronger zones that may sit further from price. The label always shows the touch count.")
zoneTol    = input.float(0.35, "Zone width (x ATR)", minval=0.1, maxval=2.0, step=0.05, group=grp_z, display=display.none, active=useZones, tooltip="How close swings must be to count as the same zone, and how thick the zone is drawn. Measured in main-timeframe ATR.")
zoneMemory = input.int(40, "Swings remembered", minval=10, maxval=100, group=grp_z, display=display.none, active=useZones, tooltip="How many recent main-timeframe swings are used to find zones. Higher = older levels can count.")
 
grp_l    = "Location (Premium / Discount)"
usePD    = input.bool(true, "Show location in the range", group=grp_l, display=display.none, tooltip="Where price sits between the main-timeframe range high and low. Top quarter = premium (better for sells), bottom quarter = discount (better for buys).")
pdLen    = input.int(100, "Range length (main-timeframe bars)", minval=20, maxval=500, group=grp_l, display=display.none, active=usePD, tooltip="How many main-timeframe bars define the range.")
showEq   = input.bool(true, "Draw the range equilibrium (50%) line", group=grp_l, display=display.none, active=usePD, tooltip="The middle of the range. Above it is premium, below it is discount.")
 
grp_x    = "Extra data"
useWicks = input.bool(true, "Unfilled wicks", group=grp_x, display=display.none, tooltip="The most recent large upper and lower wicks on the main timeframe that price hasn't traded back through. Price often revisits them.")
wickPct  = input.float(40, "Wick must be at least this % of the candle", minval=10, maxval=90, group=grp_x, display=display.none, active=useWicks, tooltip="Higher = only very large wicks count.") / 100
useLiq   = input.bool(true, "Equal highs / lows (liquidity)", group=grp_x, display=display.none, tooltip="Two swing highs or lows at nearly the same price. Stop losses tend to cluster beyond them.")
eqTol    = input.float(0.15, "Equal if within (x ATR)", minval=0.02, maxval=1.0, step=0.01, group=grp_x, display=display.none, active=useLiq, tooltip="How close two swings must be to count as equal.")
useConf  = input.bool(true, "Confluence check", group=grp_x, display=display.none, tooltip="Flags when the buy / sell zone lines up with other levels. More reasons at one price = a stronger zone.")
confTol  = input.float(0.25, "Confluence distance (x ATR)", minval=0.05, maxval=1.0, step=0.05, group=grp_x, display=display.none, active=useConf, tooltip="How close another level must be to the zone to count as confluence.")
useAdr   = input.bool(true, "ADR (volatility) context", group=grp_x, display=display.none, tooltip="How much of the average daily range has been used today, and how much room is typically left.")
adrLen   = input.int(14, "ADR length (days)", minval=1, maxval=100, group=grp_x, display=display.none, active=useAdr, tooltip="Number of days in the average daily range.")
useRsi   = input.bool(true, "Momentum (RSI 14 on main timeframe)", group=grp_x, display=display.none, tooltip="A quick read on whether momentum supports the bias.")
 
grp_v       = "Liquidity Sweeps & Volume"
useSweep    = input.bool(true, "Detect liquidity sweeps", group=grp_v, display=display.none, tooltip="A sweep is a candle that trades through a level (equal highs / lows, previous day high / low, swing high / low, a zone, an unfilled wick or a recent local swing) and then closes back on the other side. Often a stop hunt before a reversal.")
showSweepMk = input.bool(false, "Mark sweeps on the chart", group=grp_v, display=display.none, active=useSweep, tooltip="Small crosses above / below candles that swept a level.")
sweepLen    = input.int(3, "Local swing strength (chart bars)", minval=2, maxval=10, group=grp_v, display=display.none, active=useSweep, tooltip="Size of the recent chart-timeframe swings that count as local liquidity.")
useVol      = input.bool(true, "Volume confirmation", group=grp_v, display=display.none, tooltip="Compares each candle's volume with its recent average. A rejection on strong volume is more convincing.")
volExt      = input.bool(false, "Read volume from another symbol", group=grp_v, display=display.none, active=useVol, tooltip="Spot gold (XAUUSD) only has broker tick volume. Turn this on to use real exchange volume from gold futures instead.")
volSym      = input.symbol("COMEX:GC1!", "Volume symbol", group=grp_v, display=display.none, active=useVol and volExt, tooltip="COMEX:GC1! = gold futures. Futures trading hours differ slightly from spot.")
volLen      = input.int(20, "Average volume length (bars)", minval=5, maxval=200, group=grp_v, display=display.none, active=useVol, tooltip="Number of chart bars in the average volume.")
volThr      = input.float(1.3, "Strong volume = at least x average", minval=1.0, maxval=5.0, step=0.1, group=grp_v, display=display.none, active=useVol, tooltip="1.3 = at least 30% above average volume.")
 
grp_t    = "Track Record"
useStats = input.bool(true, "Track the plan's past results", group=grp_t, display=display.none, tooltip="Follows every past plan on the loaded chart history, bar by bar, and reports how it played out. Results depend on how much history is loaded.")
statsN   = input.int(30, "Plans per direction to count", minval=5, maxval=200, group=grp_t, display=display.none, active=useStats, tooltip="How many of the most recent bearish and bullish plans are included. Simulated trades keep the last 2x this number.")
zoneChoice = input.string("0.5 – 0.618", "Buy / sell zone", options=["0.5 – 0.618", "0.618 – 0.786", "0.382 – 0.618"], group=grp_t, display=display.none, tooltip="Which Fibonacci retracement band is the zone. Compare the track record for each to see which suits the market and timeframe.")
rejBody  = input.float(50, "Rejection candle: body at least % of its range", minval=0, maxval=100, step=5, group=grp_t, display=display.none, tooltip="Filters out weak, indecisive candles. 0 = any candle closing back out of the zone counts.") / 100
rejBars  = input.int(24, "Rejection must come within N bars of entering the zone", minval=1, maxval=500, group=grp_t, display=display.none, tooltip="Chart bars. A close back out of the zone much later is no longer treated as a reaction to it.")
exportTr = input.bool(false, "Export simulated trades to chart data", group=grp_t, display=display.none, tooltip="Writes each simulated trade's result (in R) and its conditions to the Data Window and Export chart data, on the bar where the trade closed. Nothing is drawn on the chart.")
tgtGap   = input.float(0.3, "Minimum target distance (x ATR)", minval=0.0, maxval=2.0, step=0.05, group=grp_t, display=display.none, tooltip="How far beyond the entry area Target 1 must be, and how far apart targets must be (main-timeframe ATR). Lower = closer targets, higher win rate, smaller wins. Higher = the opposite. Compare the win rate AND average R in the track record.")
tgtCapAdr = input.float(1.0, "Max target distance (x average daily range)", minval=0.0, maxval=5.0, step=0.25, group=grp_t, display=display.none, tooltip="Targets further than this from the entry area are not used as plan targets. The nearest one beyond it is shown separately as a 'larger target'. 0 = no limit.")
showTrack  = input.bool(false, "Show past results in the panel", group=grp_t, display=display.none, tooltip="Shows how past plans on the loaded chart history played out (win rate and average R). Results exclude spread, slippage and news, and are for testing settings, not a forecast.")
t1Cap      = input.float(1.0, "Quick target: at most x the risk (R)", minval=0.0, maxval=3.0, step=0.25, group=grp_t, display=display.none, tooltip="Target 1 is the nearest level OR this multiple of the risk (entry to stop), whichever is closer. 1.0 = a 1:1 quick target. 0 = off (nearest level only). Closer = higher win rate, smaller wins.")
strictConf = input.bool(true, "Strict confirmation", group=grp_t, display=display.none, tooltip="The rejection candle must also close beyond the previous candle's low (sell) or high (buy). Filters out weak rejections.")
statsRange = input.bool(false, "Include sideways setups in the track record", group=grp_t, display=display.none, tooltip="Sideways markets get a 'leaning' setup. Turn this off to judge only setups taken in a clear trend.")
stopBuf  = input.float(0.1, "Stop buffer beyond zone / wick (x ATR)", minval=0.0, maxval=2.0, step=0.05, group=grp_t, display=display.none, tooltip="Simulated stop = the zone's far edge or the highest / lowest price since entering the zone, whichever is further, plus this buffer (main-timeframe ATR).")
 
grp_m     = "Outside Markets & Conditions"
useUsd    = input.bool(true, "Dollar check", group=grp_m, display=display.none, tooltip="Gold usually moves opposite to the US Dollar. A rising dollar supports sell plans; a falling dollar supports buy plans.")
usdSym    = input.symbol("TVC:DXY", "Dollar symbol", group=grp_m, display=display.none, active=useUsd)
useYld    = input.bool(true, "Yield check", group=grp_m, display=display.none, tooltip="Rising US yields usually weigh on gold. Rising yields support sell plans; falling yields support buy plans.")
yldSym    = input.symbol("TVC:US10Y", "Yield symbol", group=grp_m, display=display.none, active=useYld)
imLen     = input.int(50, "Trend length for dollar / yields (EMA, main timeframe)", minval=10, maxval=200, group=grp_m, display=display.none, tooltip="Above its EMA = rising, below = falling. Uses completed main-timeframe bars only.")
volRegLen = input.int(100, "Volatility baseline (chart bars)", minval=20, maxval=500, group=grp_m, display=display.none, tooltip="Current ATR is compared with its average over this many bars.")
hiVolThr  = input.float(1.3, "High volatility = ATR at least x normal", minval=1.0, maxval=3.0, step=0.1, group=grp_m, display=display.none)
 
grp_n     = "News (enter each day)"
newsWin   = input.int(30, "Avoid trades within N minutes of news", minval=5, maxval=240, group=grp_n, display=display.none, tooltip="Pine Script can't read the economic calendar. Each morning, check a calendar (e.g. ForexFactory) and enter today's high-impact USD events below.")
news1     = input.time(0, "News 1 (date and time)", group=grp_n, display=display.none, tooltip="Click to pick the date and time of a high-impact event. Leave at the default (1970) for none.")
news2     = input.time(0, "News 2 (date and time)", group=grp_n, display=display.none)
news3     = input.time(0, "News 3 (date and time)", group=grp_n, display=display.none)
newsTz    = input.string("UTC", "Show news times in", options=["Australia/Sydney", "Australia/Melbourne", "Asia/Tokyo", "Asia/Singapore", "Europe/London", "America/New_York", "UTC"], group=grp_n, display=display.none)
 
grp_d     = "Display"
panelMode = input.string("Simple", "Panel detail", options=["Simple", "Compact", "Full"], group=grp_d, display=display.none, tooltip="Simple: the plan in plain language with a status line. Best for newer traders.\nCompact: short technical summary.\nFull: every factor, the evidence and the track record.")
chartStyle = input.string("Simple", "Chart drawings", options=["Simple", "All levels"], group=grp_d, display=display.none, tooltip="Simple: only the buy / sell zone, the targets, the cancel level and the main path.\nAll levels: every Fibonacci, previous day / week, wick, liquidity and zone level.")
showPlan  = input.bool(true, "Show analysis panel", group=grp_d, display=display.none, tooltip="The written analysis and plan.")
planPos   = input.string("Bottom Right", "Panel position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=grp_d, display=display.none, active=showPlan, tooltip="Where the panel sits on the chart.")
planSize  = input.string("Small", "Panel text size", options=["Tiny", "Small", "Normal"], group=grp_d, display=display.none, active=showPlan, tooltip="Smaller text keeps more of the chart visible.")
showFib   = input.bool(true, "Fibonacci levels", group=grp_d, display=display.none, tooltip="0.382, 0.5 and 0.618 of the last main-timeframe swing.")
showPrev  = input.bool(true, "Previous day / week high and low", group=grp_d, display=display.none, tooltip="Yesterday's and last week's high and low.")
lineExt   = input.int(25, "Line length (bars to the right)", minval=5, maxval=200, group=grp_d, display=display.none, tooltip="How far level lines extend to the right of the last candle. Labels sit at the end.")
lineW     = input.int(2, "Level line width", minval=1, maxval=4, group=grp_d, display=display.none, tooltip="Thicker lines are easier to see.")
labSizeS  = input.string("Normal", "Level label size", options=["Small", "Normal", "Large"], group=grp_d, display=display.none, tooltip="Size of the price labels at the end of each level.")
labBg     = input.bool(true, "Shaded background behind level labels", group=grp_d, display=display.none, tooltip="Makes labels easier to read over candles.")
mergeTol  = input.float(0.25, "Combine labels closer than (x ATR)", minval=0.0, maxval=1.0, step=0.01, group=grp_d, display=display.none, tooltip="Levels this close together share one label so text never overlaps. Raise it if labels overlap when zoomed out.")
 
grp_p     = "Projected Paths"
showPath  = input.bool(true, "Draw main scenario path", group=grp_p, display=display.none, tooltip="A zigzag from the current price through the plan's zone to its targets. A picture of the plan, not a forecast.")
showAlt   = input.bool(true, "Draw alternative path (dashed)", group=grp_p, display=display.none, tooltip="The path if there is no corrective move first. In a range, shows both breakout paths.")
paceMult  = input.float(1.0, "Path pacing", minval=0.3, maxval=3.0, step=0.1, group=grp_p, display=display.none, tooltip="Each step of the path is drawn over a number of bars based on its size compared with the chart's ATR. Higher = wider in time. Timing is illustrative, not a forecast.")
nearLen   = input.int(3, "Near-term swing strength (chart bars)", minval=2, maxval=10, group=grp_p, display=display.none, tooltip="Recent chart-timeframe swings are used as stepping stones for the short-term route.")
stonesN   = input.int(2, "Stepping stones per step", minval=0, maxval=4, group=grp_p, display=display.none, tooltip="Maximum recent swing levels the path pauses at on the way to each destination. 0 = straight to each level.")
stoneGap  = input.float(1.5, "Minimum step size (x chart ATR)", minval=0.5, maxval=5.0, step=0.25, group=grp_p, display=display.none, tooltip="Stepping stones closer than this to each other are skipped, so the path doesn't zigzag on noise.")
preMax    = input.float(2.5, "Max short-term counter-move (x chart ATR)", minval=0.0, maxval=6.0, step=0.25, group=grp_p, display=display.none, tooltip="When the chart's own short-term trend points the other way, the path first shows a small move to the nearest recent swing within this distance. 0 = off.")
pathAuto  = input.bool(true, "Main path colour follows chart theme", group=grp_p, display=display.none, tooltip="Black on a light chart, white on a dark chart. Turn off to pick a colour.")
colPathIn = input.color(#2563EB, "Main path (if not auto)", inline="pc", group=grp_p, display=display.none)
colAlt    = input.color(#F97316, "Alternative", inline="pc", group=grp_p, display=display.none)
routeStyle = input.string("Solid", "Route style", options=["Solid", "Solid near-term, dashed beyond"], group=grp_p, display=display.none, tooltip="Solid: the whole route is one line. The second option draws the move to the first destination solid and the rest dashed.")
extOnChart = input.bool(false, "Show larger target on the chart", group=grp_p, display=display.none, tooltip="The larger target (beyond the target distance limit) is always listed in the panel. Turning this on also draws it and extends the route to it, which can stretch the chart's price scale.")
pathW     = input.int(3, "Main path width", minval=1, maxval=5, group=grp_p, display=display.none, tooltip="Line thickness of the main path. The alternative is one step thinner.")
 
grp_al     = "Alerts (create one alert with: Any alert() function call)"
alZone     = input.bool(true, "Price enters the buy / sell zone", group=grp_al, display=display.none, tooltip="Fires once when a candle closes inside the zone.")
alReject   = input.bool(true, "Rejection confirmed", group=grp_al, display=display.none, tooltip="After visiting the zone, a candle closes back out of it in the direction of the bias. This is the plan's confirmation condition.")
alTarget   = input.bool(true, "First target reached", group=grp_al, display=display.none, tooltip="Price reaches the swing low (bearish plan) or swing high (bullish plan).")
alInvalid  = input.bool(true, "Structure invalidated", group=grp_al, display=display.none, tooltip="A main-timeframe close beyond the invalidation level.")
alBias     = input.bool(false, "Bias changes", group=grp_al, display=display.none, tooltip="The main-timeframe bias switches between bullish, bearish and neutral.")
alSweep    = input.bool(false, "Liquidity sweep near the zone", group=grp_al, display=display.none, tooltip="A sweep happens at or inside the buy / sell zone: often the first sign of a rejection.")
 
grp_x2     = "Extra Visuals"
showStruct = input.bool(true, "Structure breaks (BOS / CHoCH)", group=grp_x2, display=display.none, tooltip="Marks where a closed candle breaks the last chart-timeframe swing high or low. BOS = break in the direction of the current structure (continuation). CHoCH = change of character, the first break against it (possible turn).")
structKeep = input.int(6, "Structure breaks kept on chart", minval=1, maxval=30, group=grp_x2, display=display.none, active=showStruct)
showFvg    = input.bool(true, "Fair value gaps (unfilled)", group=grp_x2, display=display.none, tooltip="Three-candle price gaps on the chart timeframe that price hasn't traded back through yet. Removed once filled.")
fvgMin     = input.float(0.3, "Minimum gap size (x chart ATR)", minval=0.05, maxval=2.0, step=0.05, group=grp_x2, display=display.none, active=showFvg, tooltip="Smaller gaps are ignored.")
fvgKeep    = input.int(3, "Gaps kept per side", minval=1, maxval=10, group=grp_x2, display=display.none, active=showFvg)
showPDB    = input.bool(true, "Premium / discount bands", group=grp_x2, display=display.none, tooltip="Shades the top quarter (premium: better for sells) and bottom quarter (discount: better for buys) of the main-timeframe range.")
showPrevS  = input.bool(true, "Previous day high / low on the Simple chart", group=grp_x2, display=display.none)
colorBars  = input.bool(false, "Colour candles by short-term structure", group=grp_x2, display=display.none)
alStruct   = input.bool(false, "Alert on structure breaks", group=grp_x2, display=display.none)
 
grp_c   = "Colours"
colBull = input.color(#16A34A, "Bullish", inline="c1", group=grp_c, display=display.none)
colBear = input.color(#DC2626, "Bearish", inline="c1", group=grp_c, display=display.none)
colFib  = input.color(#B8860B, "Fibonacci", inline="c1", group=grp_c, display=display.none)
colPrev = input.color(#475569, "Prev day / week", inline="c2", group=grp_c, display=display.none)
colWick = input.color(#7C3AED, "Wicks", inline="c2", group=grp_c, display=display.none)
colLiq  = input.color(#0284C7, "Liquidity", inline="c2", group=grp_c, display=display.none)
 
//────────────────────────────────────────────
// TIMEFRAME SELECTION
//────────────────────────────────────────────
f_autoTfs() =>
    int  s  = timeframe.in_seconds()
    bool st = horizon == "Short-term"
    string c = "D"
    string m = "240"
    string t = "60"
    if st
        if s <= 60
            c := "15"
            m := "5"
            t := "1"
        else if s <= 300
            c := "60"
            m := "15"
            t := timeframe.period
        else if s <= 1800
            c := "240"
            m := "60"
            t := timeframe.period
        else if s <= 3600
            c := "D"
            m := "240"
            t := "60"
        else if s <= 14400
            c := "W"
            m := "D"
            t := "240"
        else
            c := "M"
            m := "W"
            t := "D"
    else
        if s <= 180
            c := "60"
            m := "15"
            t := "5"
        else if s <= 300
            c := "240"
            m := "60"
            t := "15"
        else if s <= 1800
            c := "D"
            m := "240"
            t := "60"
        else if s <= 3600
            c := "W"
            m := "D"
            t := "240"
        else
            c := "M"
            m := "W"
            t := "D"
    [c, m, t]
 
[autoHi, autoMain, autoLo] = f_autoTfs()
string htf  = useAuto ? autoMain : htfIn
string hiTf = useAuto ? autoHi : hiTfIn
string loTf = useAuto ? autoLo : loTfIn
 
//────────────────────────────────────────────
// DATA FUNCTIONS (run on the requested timeframe)
//────────────────────────────────────────────
f_struct(int len) =>
    float ph = ta.pivothigh(high, len, len)
    float pl = ta.pivotlow(low, len, len)
    var float h1 = na
    var float h2 = na
    var float l1 = na
    var float l2 = na
    var int   hT = na
    var int   lT = na
    // Lowest low since the last swing high, highest high since the last swing low:
    // the true end of the current leg, even before it is confirmed as a swing
    var float loSinceH = na
    var float hiSinceL = na
    float lowAfter  = ta.lowest(low, len)
    float highAfter = ta.highest(high, len)
    loSinceH := na(loSinceH) ? low : math.min(loSinceH, low)
    hiSinceL := na(hiSinceL) ? high : math.max(hiSinceL, high)
    if not na(ph)
        h2 := h1
        h1 := ph
        hT := time[len]
        loSinceH := lowAfter
    if not na(pl)
        l2 := l1
        l1 := pl
        lT := time[len]
        hiSinceL := highAfter
    float atr = ta.atr(14)
    float rsi = ta.rsi(close, 14)
    [h1[1], h2[1], l1[1], l2[1], hT[1], lT[1], close[1], atr[1], rsi[1], loSinceH[1], hiSinceL[1]]
 
// Most recent large upper and lower wicks that price has not yet traded back through
f_wicks(float minPct) =>
    float rng = high - low
    float upW = high - math.max(open, close)
    float dnW = math.min(open, close) - low
    var float uTop = na
    var float uBot = na
    var float lTop = na
    var float lBot = na
    if not na(uTop) and high >= uTop
        uTop := na
        uBot := na
    if not na(lBot) and low <= lBot
        lTop := na
        lBot := na
    if rng > 0 and upW / rng >= minPct
        uTop := high
        uBot := math.max(open, close)
    if rng > 0 and dnW / rng >= minPct
        lTop := math.min(open, close)
        lBot := low
    [uTop[1], uBot[1], lTop[1], lBot[1]]
 
// Nearest multi-touch zone above and below price, built from clustered swing highs AND lows
// (a level that was resistance and then support counts for both).
f_zones(int len, int memory, float tolMult, int minN) =>
    float ph = ta.pivothigh(high, len, len)
    float pl = ta.pivotlow(low, len, len)
    var float[] piv = array.new<float>()
    if not na(ph)
        piv.unshift(ph)
    if not na(pl)
        piv.unshift(pl)
    while piv.size() > memory
        piv.pop()
    float tol    = ta.atr(14) * tolMult
    float resLvl = na
    int   resN   = 0
    float supLvl = na
    int   supN   = 0
    int   sz     = piv.size()
    if sz > 0 and not na(tol)
        for i = 0 to sz - 1
            float p   = piv.get(i)
            int   n   = 0
            float sum = 0.0
            for j = 0 to sz - 1
                float q = piv.get(j)
                if math.abs(q - p) <= tol
                    n   += 1
                    sum += q
            if n >= minN
                float lvl = sum / n
                if lvl > close and (na(resLvl) or lvl < resLvl)
                    resLvl := lvl
                    resN   := n
                else if lvl < close and (na(supLvl) or lvl > supLvl)
                    supLvl := lvl
                    supN   := n
    [resLvl[1], resN[1], supLvl[1], supN[1], tol[1]]
 
//────────────────────────────────────────────
// REQUESTS
//────────────────────────────────────────────
[h1, h2, l1, l2, hT, lT, htfClose, htfAtr, htfRsi, legLo, legHi] = request.security(syminfo.tickerid, htf, f_struct(pivLen), lookahead=barmerge.lookahead_on)
[dh1, dh2, dl1, dl2, dhT, dlT, dClose, dAtr, dRsi, dLegLo, dLegHi] = request.security(syminfo.tickerid, hiTf, f_struct(pivLen), lookahead=barmerge.lookahead_on)
[th1, th2, tl1, tl2, thT, tlT, tClose, tAtr, tRsi, tLegLo, tLegHi] = request.security(syminfo.tickerid, loTf, f_struct(pivLen), lookahead=barmerge.lookahead_on)
[rHiTop, rHiBot, rLoTop, rLoBot] = request.security(syminfo.tickerid, htf, f_wicks(wickPct), lookahead=barmerge.lookahead_on)
[rRes, rResN, rSup, rSupN, rZTol] = request.security(syminfo.tickerid, zoneSrc == "Timing timeframe" ? loTf : htf, f_zones(pivLen, zoneMemory, zoneTol, minTouches), lookahead=barmerge.lookahead_on)
[rngHi, rngLo] = request.security(syminfo.tickerid, htf, [ta.highest(high, pdLen)[1], ta.lowest(low, pdLen)[1]], lookahead=barmerge.lookahead_on)
 
[pdh, pdl] = request.security(syminfo.tickerid, "D", [high[1], low[1]], lookahead=barmerge.lookahead_on)
[pwh, pwl] = request.security(syminfo.tickerid, "W", [high[1], low[1]], lookahead=barmerge.lookahead_on)
float adr = request.security(syminfo.tickerid, "D", ta.sma(high - low, adrLen)[1], lookahead=barmerge.lookahead_on)
[tdHigh, tdLow] = request.security(syminfo.tickerid, "D", [high, low], lookahead=barmerge.lookahead_off)
 
//────────────────────────────────────────────
// DERIVED VALUES
//────────────────────────────────────────────
f_bias(float a1, float a2, float b1, float b2, float c) =>
    int b = na(a2) or na(b2) ? 0 : a1 < a2 and b1 < b2 ? -1 : a1 > a2 and b1 > b2 ? 1 : 0
    b == -1 and c > a1 ? 0 : b == 1 and c < b1 ? 0 : b
 
int  rawBias    = na(h2) or na(l2) ? 0 : h1 < h2 and l1 < l2 ? -1 : h1 > h2 and l1 > l2 ? 1 : 0
bool bearBroken = rawBias == -1 and htfClose > h1
bool bullBroken = rawBias == 1 and htfClose < l1
int  structBias = bearBroken or bullBroken ? 0 : rawBias
int  hiBias     = f_bias(dh1, dh2, dl1, dl2, dClose)
int  loBias     = f_bias(th1, th2, tl1, tl2, tClose)
 
// When the main timeframe is sideways, lean towards the side most evidence points to
float leanPos   = not na(rngHi) and not na(rngLo) and rngHi > rngLo ? (close - rngLo) / (rngHi - rngLo) : 0.5
bool  legDown   = nz(lT) > nz(hT)
int   rsiVote   = na(htfRsi) ? 0 : htfRsi >= 55 ? 1 : htfRsi <= 45 ? -1 : 0
int   posVote   = leanPos >= 0.7 ? -1 : leanPos <= 0.3 ? 1 : 0
int   brkVote   = bearBroken ? 1 : bullBroken ? -1 : 0
int   leanScore = 2 * hiBias + loBias + (legDown ? -1 : 1) + rsiVote + posVote + brkVote
int   lean      = leanScore > 0 ? 1 : leanScore < 0 ? -1 : (leanPos >= 0.5 ? -1 : 1)
bool  isRange   = structBias == 0
int   bias      = isRange ? lean : structBias
string leanWhy  = ""
if isRange
    leanWhy := (hiBias == lean ? "higher timeframe trend, " : "") + (loBias == lean ? "lower timeframe trend, " : "") + ((legDown ? -1 : 1) == lean ? "last swing, " : "") + (rsiVote == lean ? "momentum, " : "") + (posVote == lean ? "position in the range, " : "") + (brkVote == lean ? "broken structure, " : "")
    leanWhy := str.length(leanWhy) > 2 ? str.substring(leanWhy, 0, str.length(leanWhy) - 2) : "position in the range"
string leanStrength = math.abs(leanScore) >= 3 ? "clearly" : "slightly"
 
// Fibonacci: downtrend measures the rally from the swing low,
// uptrend measures the pullback from the swing high, otherwise follow the last leg.
bool  lastLegDown = nz(lT) > nz(hT)
bool  fibFromLow  = bias == -1 or (bias == 0 and lastLegDown)
// Sell plan: the down leg runs from the last swing high to the lowest price since it.
// Buy plan: the up leg runs from the last swing low to the highest price since it.
float fibHi       = fibFromLow ? h1 : math.max(nz(legHi, h1), l1)
float fibLo       = fibFromLow ? math.min(nz(legLo, l1), h1) : l1
float swingRange  = fibHi - fibLo
 
f_fib(float f) =>
    fibFromLow ? fibLo + swingRange * f : fibHi - swingRange * f
 
float fib382 = f_fib(0.382)
float fib50  = f_fib(0.5)
float fib618 = f_fib(0.618)
float fib786 = f_fib(0.786)
float zInR   = zoneChoice == "0.618 – 0.786" ? 0.618 : zoneChoice == "0.382 – 0.618" ? 0.382 : 0.5
float zOutR  = zoneChoice == "0.618 – 0.786" ? 0.786 : 0.618
float zIn    = f_fib(zInR)    // zone edge nearest the current swing extreme's opposite (entered first)
float zOut   = f_fib(zOutR)   // far edge of the zone
 
float wHiTop = useWicks ? rHiTop : na
float wHiBot = useWicks ? rHiBot : na
float wLoTop = useWicks ? rLoTop : na
float wLoBot = useWicks ? rLoBot : na
 
bool  eqHighs = useLiq and not na(h2) and not na(htfAtr) and math.abs(h1 - h2) <= htfAtr * eqTol
bool  eqLows  = useLiq and not na(l2) and not na(htfAtr) and math.abs(l1 - l2) <= htfAtr * eqTol
float eqHiLvl = eqHighs ? math.max(h1, h2) : na
float eqLoLvl = eqLows ? math.min(l1, l2) : na
 
float zRes  = useZones ? rRes : na
float zSup  = useZones ? rSup : na
int   zResN = nz(rResN)
int   zSupN = nz(rSupN)
 
bool  pdOk  = usePD and not na(rngHi) and not na(rngLo) and rngHi > rngLo
float pdPos = pdOk ? (close - rngLo) / (rngHi - rngLo) : na
float pdEq  = pdOk ? (rngHi + rngLo) / 2 : na
 
//────────────────────────────────────────────
// TEXT HELPERS
//────────────────────────────────────────────
f_p(float x) =>
    na(x) ? "—" : str.tostring(x, format.mintick)
 
f_tfName(string tf) =>
    int s = timeframe.in_seconds(tf)
    s >= 2419200 ? "M" : s >= 604800 ? "W" : s >= 86400 ? "D" : s >= 3600 ? str.tostring(int(s / 3600)) + "H" : str.tostring(int(s / 60)) + "m"
 
f_bname(int b) =>
    b == 1 ? "bullish" : b == -1 ? "bearish" : "neutral"
 
string tfName = f_tfName(htf)
string chartTfName = f_tfName(timeframe.period)
 
//────────────────────────────────────────────
// NEAR-TERM STRUCTURE (chart timeframe)
//────────────────────────────────────────────
float nAtr = ta.atr(14)
float nPh  = ta.pivothigh(high, nearLen, nearLen)
float nPl  = ta.pivotlow(low, nearLen, nearLen)
var float[] nLvls = array.new<float>()
var float nH1 = na
var float nH2 = na
var float nL1 = na
var float nL2 = na
var int   nH1Bar = na
var int   nL1Bar = na
var bool  nHiBrk = false
var bool  nLoBrk = false
if not na(nPh)
    nLvls.unshift(nPh)
    nH2 := nH1
    nH1 := nPh
    nH1Bar := bar_index - nearLen
    nHiBrk := false
if not na(nPl)
    nLvls.unshift(nPl)
    nL2 := nL1
    nL1 := nPl
    nL1Bar := bar_index - nearLen
    nLoBrk := false
while nLvls.size() > 60
    nLvls.pop()
float nEmaF = ta.ema(close, 9)
float nEmaS = ta.ema(close, 21)
bool  nStructOk = not na(nH2) and not na(nL2)
int   nearDir = nStructOk and nH1 > nH2 and nL1 > nL2 ? 1 : nStructOk and nH1 < nH2 and nL1 < nL2 ? -1 : nEmaF >= nEmaS ? 1 : -1
 
//────────────────────────────────────────────
// STRUCTURE BREAKS (BOS / CHoCH, chart timeframe, closed candles)
//────────────────────────────────────────────
var int     sTrend   = 0
var line[]  sLines   = array.new<line>()
var label[] sLabels  = array.new<label>()
bool brkUp = barstate.isconfirmed and not na(nH1) and not nHiBrk and close > nH1
bool brkDn = barstate.isconfirmed and not na(nL1) and not nLoBrk and close < nL1
string brkTag = ""
if brkUp
    brkTag := sTrend == -1 ? "CHoCH" : "BOS"
    nHiBrk := true
    if showStruct
        sLines.push(line.new(nH1Bar, nH1, bar_index, nH1, color=color.new(#16A34A, 20), style=line.style_dashed, width=1))
        sLabels.push(label.new(int((nH1Bar + bar_index) / 2), nH1, brkTag, style=label.style_label_down, color=color(na), textcolor=#16A34A, size=size.small))
    sTrend := 1
if brkDn
    brkTag := sTrend == 1 ? "CHoCH" : "BOS"
    nLoBrk := true
    if showStruct
        sLines.push(line.new(nL1Bar, nL1, bar_index, nL1, color=color.new(#DC2626, 20), style=line.style_dashed, width=1))
        sLabels.push(label.new(int((nL1Bar + bar_index) / 2), nL1, brkTag, style=label.style_label_up, color=color(na), textcolor=#DC2626, size=size.small))
    sTrend := -1
while sLines.size() > structKeep
    line.delete(sLines.shift())
while sLabels.size() > structKeep
    label.delete(sLabels.shift())
if alStruct and (brkUp or brkDn)
    alert(syminfo.ticker + " (" + chartTfName + "): " + brkTag + " " + (brkUp ? "up, broke " + str.tostring(nH1, format.mintick) : "down, broke " + str.tostring(nL1, format.mintick)), alert.freq_once_per_bar_close)
barcolor(colorBars ? (sTrend == 1 ? #16A34A : sTrend == -1 ? #DC2626 : na) : na, title="Structure candle colour")
 
//────────────────────────────────────────────
// FAIR VALUE GAPS (chart timeframe, unfilled only)
//────────────────────────────────────────────
var box[]   fvgBx  = array.new<box>()
var float[] fvgTop = array.new<float>()
var float[] fvgBot = array.new<float>()
var int[]   fvgDir = array.new<int>()
if showFvg and barstate.isconfirmed and not na(nAtr)
    if low > high[2] and low - high[2] >= nAtr * fvgMin
        fvgBx.push(box.new(bar_index - 2, low, bar_index + 3, high[2], border_color=color.new(#16A34A, 75), bgcolor=color.new(#16A34A, 88), text="FVG", text_size=size.tiny, text_color=color.new(#16A34A, 30), text_halign=text.align_right))
        fvgTop.push(low)
        fvgBot.push(high[2])
        fvgDir.push(1)
    if high < low[2] and low[2] - high >= nAtr * fvgMin
        fvgBx.push(box.new(bar_index - 2, low[2], bar_index + 3, high, border_color=color.new(#DC2626, 75), bgcolor=color.new(#DC2626, 88), text="FVG", text_size=size.tiny, text_color=color.new(#DC2626, 30), text_halign=text.align_right))
        fvgTop.push(low[2])
        fvgBot.push(high)
        fvgDir.push(-1)
if fvgBx.size() > 0
    for i = fvgBx.size() - 1 to 0
        bool filled = fvgDir.get(i) == 1 ? low <= fvgBot.get(i) : high >= fvgTop.get(i)
        if filled
            box.delete(fvgBx.get(i))
            fvgBx.remove(i)
            fvgTop.remove(i)
            fvgBot.remove(i)
            fvgDir.remove(i)
        else
            box.set_right(fvgBx.get(i), bar_index + 3)
// keep only the newest gaps on each side
int nUpG = 0
int nDnG = 0
if fvgBx.size() > 0
    for i = fvgBx.size() - 1 to 0
        int d = fvgDir.get(i)
        bool drop = false
        if d == 1
            nUpG += 1
            drop := nUpG > fvgKeep
        else
            nDnG += 1
            drop := nDnG > fvgKeep
        if drop
            box.delete(fvgBx.get(i))
            fvgBx.remove(i)
            fvgTop.remove(i)
            fvgBot.remove(i)
            fvgDir.remove(i)
string tfHi   = f_tfName(hiTf)
string tfLo   = f_tfName(loTf)
string zoneTfName = zoneSrc == "Timing timeframe" ? tfLo : tfName
 
f_conf(float lvl) =>
    string out = ""
    if useConf and not na(lvl) and not na(htfAtr)
        float tol = htfAtr * confTol
        float[]  vals  = array.from(pdh, pdl, pwh, pwl, wHiTop, wHiBot, wLoTop, wLoBot, eqHiLvl, eqLoLvl, zRes, zSup)
        string[] names = array.from("prev day high", "prev day low", "prev week high", "prev week low", "unfilled wick", "unfilled wick", "unfilled wick", "unfilled wick", "equal highs", "equal lows", "resistance zone", "support zone")
        for i = 0 to vals.size() - 1
            float v = vals.get(i)
            string nm = names.get(i)
            if not na(v) and math.abs(v - lvl) <= tol and not str.contains(out, nm)
                out += (out == "" ? "" : ", ") + nm
    out
 
// Names of levels inside a price band (widened by the confluence distance)
f_confRange(float lo, float hi) =>
    string out = ""
    if useConf and not na(lo) and not na(hi) and not na(htfAtr)
        float tol = htfAtr * confTol
        float[]  vals  = array.from(pdh, pdl, pwh, pwl, wHiTop, wHiBot, wLoTop, wLoBot, eqHiLvl, eqLoLvl, zRes, zSup)
        string[] names = array.from("prev day high", "prev day low", "prev week high", "prev week low", "unfilled wick", "unfilled wick", "unfilled wick", "unfilled wick", "equal highs", "equal lows", "resistance zone", "support zone")
        for i = 0 to vals.size() - 1
            float v = vals.get(i)
            string nm = names.get(i)
            if not na(v) and v >= lo - tol and v <= hi + tol and not str.contains(out, nm)
                out += (out == "" ? "" : ", ") + nm
    out
 
f_join(string a, string b) =>
    a == "" ? b : b == "" or str.contains(a, b) ? a : a + ", " + b
 
// Up to three nearest targets below (dir = -1) or above (dir = 1) price: values and names, nearest first
f_pick(int dir, float ref = na) =>
    float r0 = na(ref) ? close : ref
    float capD = tgtCapAdr > 0 and not na(adr) ? adr * tgtCapAdr : na
    float[]  vals  = dir == -1 ? array.from(l1, pdl, pwl, eqLoLvl, wLoBot, zSup) : array.from(h1, pdh, pwh, eqHiLvl, wHiTop, zRes)
    string[] names = dir == -1 ? array.from("swing low", "prev day low", "prev week low", "equal lows", "wick low", "support zone") : array.from("swing high", "prev day high", "prev week high", "equal highs", "wick high", "resistance zone")
    bool[]   used   = array.new<bool>(vals.size(), false)
    float[]  picked = array.new<float>()
    string[] pickedNames = array.new<string>()
    float    minGap = math.max(nz(htfAtr, 0) * tgtGap, syminfo.mintick * 10)
    for k = 0 to 2
        int   best     = -1
        float bestDist = na
        for i = 0 to vals.size() - 1
            float v = vals.get(i)
            if not used.get(i) and not na(v) and (dir == -1 ? v < r0 - minGap : v > r0 + minGap) and (na(capD) or math.abs(v - r0) <= capD)
                bool nearPicked = false
                for pv in picked
                    if math.abs(pv - v) <= minGap
                        nearPicked := true
                if nearPicked
                    used.set(i, true)
                else
                    float d = math.abs(v - r0)
                    if best == -1 or d < bestDist
                        best     := i
                        bestDist := d
        if best >= 0
            used.set(best, true)
            picked.push(vals.get(best))
            pickedNames.push(names.get(best))
    [picked, pickedNames]
 
// Nearest level beyond the target distance limit (shown as a "larger target")
f_extended(int dir, float ref) =>
    float r0   = na(ref) ? close : ref
    float capD = tgtCapAdr > 0 and not na(adr) ? adr * tgtCapAdr : na
    float best = na
    if not na(capD) and dir != 0
        float[] vals = dir == -1 ? array.from(l1, pdl, pwl, eqLoLvl, wLoBot, zSup) : array.from(h1, pdh, pwh, eqHiLvl, wHiTop, zRes)
        for v in vals
            if not na(v) and math.abs(v - r0) > capD and (dir == -1 ? v < r0 : v > r0)
                if na(best) or math.abs(v - r0) < math.abs(best - r0)
                    best := v
    best
 
f_targets(int dir, float ref = na) =>
    [pv, pn] = f_pick(dir, ref)
    string out = ""
    if pv.size() > 0
        for i = 0 to pv.size() - 1
            out += (i > 0 ? " → " : "") + f_p(pv.get(i)) + " (" + pn.get(i) + ")"
    pv.size() == 0 ? "no clear level yet, manage the trade manually" : out
 
// Location in the range, read against the bias
f_location() =>
    string out = ""
    if pdOk
        string nm = pdPos >= 0.75 ? "premium (top quarter)" : pdPos >= 0.55 ? "upper half" : pdPos > 0.45 ? "equilibrium (middle)" : pdPos > 0.25 ? "lower half" : "discount (bottom quarter)"
        string rd = bias == -1 ? (pdPos >= 0.55 ? "Good location for sells." : pdPos > 0.25 ? "Weaker location for sells." : "Selling here is late; better to wait for a rally.") : bias == 1 ? (pdPos <= 0.45 ? "Good location for buys." : pdPos < 0.75 ? "Weaker location for buys." : "Buying here is late; better to wait for a pullback.") : (pdPos >= 0.75 ? "Near the top of the range." : pdPos <= 0.25 ? "Near the bottom of the range." : "Middle of the range: avoid.")
        out := "Location: " + str.tostring(math.max(math.min(pdPos, 1.0), 0.0) * 100, "#") + "% of the " + tfName + " range (" + f_p(rngLo) + " to " + f_p(rngHi) + "), " + nm + ". " + rd
    out
 
//────────────────────────────────────────────
// ALERTS (evaluated on closed candles)
//────────────────────────────────────────────
float zoneLo = math.min(zIn, zOut)
float zoneHi = math.max(zIn, zOut)
// Estimated quick target: entry at the zone edge, stop just beyond the far edge
float estEntry = bias == -1 ? zoneLo : zoneHi
float estStop  = bias == -1 ? zoneHi + nz(htfAtr) * stopBuf : zoneLo - nz(htfAtr) * stopBuf
float estT1    = t1Cap > 0 and not na(estEntry) and bias != 0 ? estEntry + bias * math.abs(estStop - estEntry) * t1Cap : na
string estTxt  = na(estT1) ? "" : "quick " + f_p(estT1) + " (" + str.tostring(t1Cap, "#.##") + "R), then "
// Targets are measured from the far side of the entry area, never from inside it
float refDn  = na(zoneLo) ? close : math.min(close, zoneLo)
float refUp  = na(zoneHi) ? close : math.max(close, zoneHi)
bool  inZone = bias != 0 and not na(zoneLo) and close >= zoneLo and close <= zoneHi
 
var bool  visited    = false
var int   visitBar   = na
var bool  zoneFailed = false
var bool  rejDone    = false
var float extSince   = na
if bias != nz(bias[1]) or zoneLo != zoneLo[1]
    visited    := false
    visitBar   := na
    zoneFailed := false
    rejDone    := false
    extSince   := na
bool zoneEntered = inZone and not visited and not zoneFailed
if inZone and not visited
    visited  := true
    visitBar := bar_index
if visited
    extSince := bias == -1 ? math.max(nz(extSince, high), high) : bias == 1 ? math.min(nz(extSince, low), low) : extSince
// zone fails if a candle closes beyond its far edge
if visited and (bias == -1 ? close > zoneHi : bias == 1 ? close < zoneLo : false)
    zoneFailed := true
float candleRng  = high - low
bool  strongBody = candleRng > 0 and math.abs(close - open) >= candleRng * rejBody
bool  inWindow   = visited and not na(visitBar) and bar_index - visitBar <= rejBars
bool  strongClose = not strictConf or (bias == -1 ? close < low[1] : close > high[1])
bool  rejected   = not rejDone and not zoneFailed and inWindow and strongBody and strongClose and (bias == -1 ? close < zoneLo and close < open : bias == 1 ? close > zoneHi and close > open : false)
if rejected
    rejDone := true
bool tgtHit   = bias == -1 ? low <= l1 and low[1] > l1 : bias == 1 ? high >= h1 and high[1] < h1 : false
bool invalid  = (bearBroken and not bearBroken[1]) or (bullBroken and not bullBroken[1])
bool biasChg  = bar_index > 0 and bias != bias[1]
 
//────────────────────────────────────────────
// VOLUME
//────────────────────────────────────────────
[xVol, xVolAvg] = request.security(volSym, timeframe.period, [volume, ta.sma(volume, volLen)], ignore_invalid_symbol=true)
float cVolAvg   = ta.sma(volume, volLen)
float vNow      = volExt ? xVol : volume
float vAvg      = volExt ? xVolAvg : cVolAvg
float relVol    = useVol and not na(vNow) and not na(vAvg) and vAvg > 0 ? vNow / vAvg : na
bool  strongVol = not na(relVol) and relVol >= volThr
 
//────────────────────────────────────────────
// LIQUIDITY SWEEPS (closed candles)
//────────────────────────────────────────────
float cph = ta.pivothigh(high, sweepLen, sweepLen)
float cpl = ta.pivotlow(low, sweepLen, sweepLen)
var float locHi = na
var float locLo = na
if not na(cph)
    locHi := cph
if not na(cpl)
    locLo := cpl
 
f_swUp(float lvl) =>
    not na(lvl) and high > lvl and close < lvl
 
f_swDn(float lvl) =>
    not na(lvl) and low < lvl and close > lvl
 
string swUpName = ""
string swDnName = ""
if useSweep and barstate.isconfirmed
    swUpName := f_swUp(eqHiLvl) ? "equal highs" : f_swUp(pdh) ? "prev day high" : f_swUp(h1) ? "swing high (" + tfName + ")" : f_swUp(zRes) ? "resistance zone" : f_swUp(wHiTop) ? "wick high" : f_swUp(locHi) ? "local swing high" : ""
    swDnName := f_swDn(eqLoLvl) ? "equal lows" : f_swDn(pdl) ? "prev day low" : f_swDn(l1) ? "swing low (" + tfName + ")" : f_swDn(zSup) ? "support zone" : f_swDn(wLoBot) ? "wick low" : f_swDn(locLo) ? "local swing low" : ""
bool sweepUp = swUpName != ""
bool sweepDn = swDnName != ""
if sweepUp
    locHi := na
if sweepDn
    locLo := na
 
plotshape(showSweepMk and sweepUp, "Sweep of a high", shape.xcross, location.abovebar, colLiq, size=size.tiny, display=display.pane)
plotshape(showSweepMk and sweepDn, "Sweep of a low", shape.xcross, location.belowbar, colLiq, size=size.tiny, display=display.pane)
 
//────────────────────────────────────────────
// PLAN TRACKING (follows each plan bar by bar, no repainting)
//────────────────────────────────────────────
var int  planDir   = 0
var int  planId    = 0
var bool pReached  = false
var bool pSweep    = false
var bool pRejected = false
var bool pRejVol   = false
var bool pRejSweep = false
var bool pTarget   = false
var bool pStopped  = false
var int[]  sDir      = array.new<int>()
var bool[] sReached  = array.new<bool>()
var bool[] sRejected = array.new<bool>()
var bool[] sTarget   = array.new<bool>()
var bool[] sRejVol   = array.new<bool>()
var bool[] sRejSweep = array.new<bool>()
 
bool newPlan = bias != planDir or (bias != 0 and zoneLo != zoneLo[1])
if newPlan
    if useStats and planDir != 0
        sDir.push(planDir)
        sReached.push(pReached)
        sRejected.push(pRejected)
        while sDir.size() > statsN * 4
            sDir.shift()
            sReached.shift()
            sRejected.shift()
    planDir   := bias
    planId    += 1
    pReached  := false
    pSweep    := false
    pRejected := false
    pRejVol   := false
    pRejSweep := false
    pTarget   := false
    pStopped  := false
 
bool nearZone = planDir == -1 ? high >= zoneLo : planDir == 1 ? low <= zoneHi : false
if planDir != 0
    if inZone
        pReached := true
    if nearZone and (planDir == -1 ? sweepUp : sweepDn)
        pSweep := true
    if rejected and not pRejected
        pRejected := true
        pRejVol   := strongVol
        pRejSweep := pSweep
 
bool sweepAtZone = nearZone and (planDir == -1 ? sweepUp : planDir == 1 ? sweepDn : false)
 
//────────────────────────────────────────────
// OUTSIDE MARKETS, VOLATILITY REGIME, NEWS
//────────────────────────────────────────────
int usdTrend = request.security(usdSym, htf, close[1] > ta.ema(close, imLen)[1] ? 1 : -1, lookahead=barmerge.lookahead_on, ignore_invalid_symbol=true)
int yldTrend = request.security(yldSym, htf, close[1] > ta.ema(close, imLen)[1] ? 1 : -1, lookahead=barmerge.lookahead_on, ignore_invalid_symbol=true)
int usdDir   = useUsd ? nz(usdTrend) : 0
int yldDir   = useYld ? nz(yldTrend) : 0
 
// A rising dollar / yield supports a sell plan (dir -1); falling supports a buy plan (dir 1)
f_supports(int mktDir, int planD) =>
    mktDir != 0 and planD != 0 and mktDir == -planD
 
float atrC     = ta.atr(14)
float volRatio = atrC / ta.sma(atrC, volRegLen)
bool  hiVol    = not na(volRatio) and volRatio >= hiVolThr
 
f_validNews(int t) =>
    t > 946684800000
 
f_nearNews(int t) =>
    int w = newsWin * 60000
    (f_validNews(news1) and math.abs(t - news1) <= w) or (f_validNews(news2) and math.abs(t - news2) <= w) or (f_validNews(news3) and math.abs(t - news3) <= w)
 
bool newsBar = f_nearNews(time)
bgcolor(newsBar ? color.new(#F59E0B, 85) : na, title="News window")
 
//────────────────────────────────────────────
// SIMULATED TRADES (entry on rejection close, stop beyond zone, first target)
//────────────────────────────────────────────
bool inLdnNy = not na(time(timeframe.period, "0800-1700", "Europe/London")) or not na(time(timeframe.period, "0800-1700", "America/New_York"))
 
var bool  tActive = false
var int   tDir    = 0
var float tEntry  = na
var float tStop   = na
var float tTgt    = na
var int   tBar    = na
var bool  tfAlign = false
var bool  tfSweep = false
var bool  tfVol   = false
var bool  tfSess  = false
var bool  tfLoc   = false
var bool  tfUsd   = false
var bool  tfYld   = false
var bool  tfHiVol = false
var bool  tfNews  = false
var bool  tfRange = false
var float tfVolR  = na
var float tfRelV  = na
var int   tTime   = na
var int   tPlan   = na
var int   lastRes   = na
var int   lastDir   = 0
var float lastEntry = na
var float lastExit  = na
var float[] rR     = array.new<float>()
var bool[]  rAlign = array.new<bool>()
var bool[]  rSweep = array.new<bool>()
var bool[]  rVol   = array.new<bool>()
var bool[]  rSess  = array.new<bool>()
var bool[]  rLoc   = array.new<bool>()
var bool[]  rUsd   = array.new<bool>()
var bool[]  rYld   = array.new<bool>()
var bool[]  rHiVol = array.new<bool>()
var bool[]  rNews  = array.new<bool>()
var bool[]  rRange = array.new<bool>()
 
bool  tradeWin  = false
bool  tradeLoss = false
float closedR   = na
int   heldBars  = na
if tActive and bar_index > tBar
    bool hitS = tDir == -1 ? high >= tStop : low <= tStop
    bool hitT = tDir == -1 ? low <= tTgt : high >= tTgt
    if hitS or hitT
        float risk = math.abs(tStop - tEntry)
        float r    = hitS ? -1.0 : risk > 0 ? math.abs(tTgt - tEntry) / risk : 0.0
        tradeWin  := not hitS
        tradeLoss := hitS
        closedR   := r
        heldBars  := bar_index - tBar
        if useStats and (statsRange or not tfRange)
            rR.push(r)
            rAlign.push(tfAlign)
            rSweep.push(tfSweep)
            rVol.push(tfVol)
            rSess.push(tfSess)
            rLoc.push(tfLoc)
            rUsd.push(tfUsd)
            rYld.push(tfYld)
            rHiVol.push(tfHiVol)
            rNews.push(tfNews)
            rRange.push(tfRange)
            while rR.size() > statsN * 2
                rR.shift()
                rAlign.shift()
                rSweep.shift()
                rVol.shift()
                rSess.shift()
                rLoc.shift()
                rUsd.shift()
                rYld.shift()
                rHiVol.shift()
                rNews.shift()
                rRange.shift()
        if tPlan == planId
            pTarget  := tradeWin
            pStopped := tradeLoss
        lastRes   := hitS ? -1 : 1
        lastDir   := tDir
        lastEntry := tEntry
        lastExit  := hitS ? tStop : tTgt
        tActive := false
 
// Trade export: one row per closed trade (Data Window + Export chart data)
bool exT = exportTr and useStats and (tradeWin or tradeLoss)
plot(exT ? closedR : na, "Trade R", display=display.data_window)
plot(exT ? tDir : na, "Trade dir (1 buy, -1 sell)", display=display.data_window)
plot(exT ? heldBars : na, "Trade bars held", display=display.data_window)
plot(exT ? hour(tTime, "UTC") : na, "Trade entry hour UTC", display=display.data_window)
plot(exT ? dayofweek(tTime, "UTC") : na, "Trade entry weekday (1 Sun..7 Sat)", display=display.data_window)
plot(exT ? (tfAlign ? 1 : 0) : na, "F higher TF agrees", display=display.data_window)
plot(exT ? (tfSweep ? 1 : 0) : na, "F sweep", display=display.data_window)
plot(exT ? (tfVol ? 1 : 0) : na, "F strong volume", display=display.data_window)
plot(exT ? tfRelV : na, "F relative volume", display=display.data_window)
plot(exT ? (tfSess ? 1 : 0) : na, "F London/NY hours", display=display.data_window)
plot(exT ? (tfLoc ? 1 : 0) : na, "F good location", display=display.data_window)
plot(exT ? (tfUsd ? 1 : 0) : na, "F dollar supports", display=display.data_window)
plot(exT ? (tfYld ? 1 : 0) : na, "F yields support", display=display.data_window)
plot(exT ? tfVolR : na, "F volatility ratio", display=display.data_window)
plot(exT ? (tfNews ? 1 : 0) : na, "F near news", display=display.data_window)
plot(exT ? tEntry : na, "Trade entry", display=display.data_window)
plot(exT ? tStop : na, "Trade stop", display=display.data_window)
plot(exT ? tTgt : na, "Trade target", display=display.data_window)
 
if rejected and not tActive and bias != 0
    [tv, tn] = f_pick(bias)
    float buf = nz(htfAtr) * stopBuf
    float st  = bias == -1 ? math.max(zoneHi, nz(extSince, zoneHi)) + buf : math.min(zoneLo, nz(extSince, zoneLo)) - buf
    float lvlT = tv.size() > 0 ? tv.get(0) : na
    float capT = t1Cap > 0 ? close + bias * math.abs(st - close) * t1Cap : na
    float useT = na(lvlT) ? capT : na(capT) ? lvlT : bias == -1 ? math.max(lvlT, capT) : math.min(lvlT, capT)
    if not na(useT) and (bias == -1 ? st > close and useT < close : st < close and useT > close)
        tActive := true
        tDir    := bias
        tEntry  := close
        tStop   := st
        tTgt    := useT
        tBar    := bar_index
        tfAlign := hiBias == bias
        tfSweep := pSweep
        tfVol   := strongVol
        tfSess  := inLdnNy
        tfLoc   := pdOk and (bias == -1 ? pdPos >= 0.5 : pdPos <= 0.5)
        tfUsd   := f_supports(usdDir, bias)
        tfYld   := f_supports(yldDir, bias)
        tfHiVol := hiVol
        tfNews  := newsBar
        tfRange := isRange
        tfVolR  := volRatio
        tfRelV  := relVol
        tTime   := time
        tPlan   := planId
 
string tag = syminfo.ticker + " (" + tfName + " plan): "
if alZone and zoneEntered
    alert(tag + "price entered the " + (bias == -1 ? "sell" : "buy") + " zone " + f_p(zoneLo) + " to " + f_p(zoneHi) + ". Wait for rejection before acting.", alert.freq_once_per_bar_close)
if alReject and rejected
    alert(tag + "rejection confirmed: candle closed back " + (bias == -1 ? "below " + f_p(zoneLo) : "above " + f_p(zoneHi)) + ". Targets: " + f_targets(bias == -1 ? -1 : 1), alert.freq_once_per_bar_close)
if alTarget and tradeWin
    alert(tag + "first target reached at " + f_p(tTgt) + ".", alert.freq_once_per_bar_close)
if alInvalid and invalid
    alert(tag + "structure invalidated: " + tfName + " closed " + (bearBroken ? "above " + f_p(h1) + ". Bearish plan is off." : "below " + f_p(l1) + ". Bullish plan is off."), alert.freq_once_per_bar_close)
if alBias and biasChg
    alert(tag + "bias changed to " + f_bname(bias) + ".", alert.freq_once_per_bar_close)
if alSweep and sweepAtZone
    alert(tag + "liquidity sweep of the " + (planDir == -1 ? swUpName : swDnName) + " at the " + (planDir == -1 ? "sell" : "buy") + " zone" + (strongVol ? " on strong volume" : "") + ". Watch for a close back " + (planDir == -1 ? "below " + f_p(zoneLo) : "above " + f_p(zoneHi)) + ".", alert.freq_once_per_bar_close)
 
// If a support / resistance zone sits inside the buy / sell zone, that is the most
// likely turning point, so the main path turns there instead of at the 0.618.
float zTolC   = nz(htfAtr, 0) * confTol
float turnLvl = bias == -1 and not na(zRes) and zRes >= zoneLo - zTolC and zRes <= zoneHi + zTolC ? zRes : bias == 1 and not na(zSup) and zSup >= zoneLo - zTolC and zSup <= zoneHi + zTolC ? zSup : na
 
//────────────────────────────────────────────
// TRACK RECORD + EVIDENCE HELPERS
//────────────────────────────────────────────
f_pct(int a, int b) =>
    b > 0 ? str.tostring(a * 100.0 / b, "#") + "% (" + str.tostring(a) + "/" + str.tostring(b) + ")" : "n/a"
 
// Reach / rejection counts for the most recent statsN plans in one direction
f_planStats(int dir) =>
    int n = 0
    int nReach = 0
    int nRej = 0
    int sz = sDir.size()
    if sz > 0
        for k = 0 to sz - 1
            int i = sz - 1 - k
            if sDir.get(i) == dir and n < statsN
                n += 1
                if sReached.get(i)
                    nReach += 1
                if sRejected.get(i)
                    nRej += 1
    [n, nReach, nRej]
 
// Simulated trade results. which: 0 all, 1 higher TF agrees, 2 sweep, 3 strong volume, 4 London/NY, 5 good location
f_tradeStats(int which, bool want) =>
    int   n    = 0
    int   w    = 0
    float sumR = 0.0
    int   sz   = rR.size()
    if sz > 0
        for i = 0 to sz - 1
            bool f = which == 1 ? rAlign.get(i) : which == 2 ? rSweep.get(i) : which == 3 ? rVol.get(i) : which == 4 ? rSess.get(i) : which == 5 ? rLoc.get(i) : which == 6 ? rUsd.get(i) : which == 7 ? rYld.get(i) : which == 8 ? rHiVol.get(i) : which == 9 ? rNews.get(i) : which == 10 ? not rRange.get(i) : true
            if which == 0 or f == want
                n    += 1
                sumR += rR.get(i)
                if rR.get(i) > 0
                    w += 1
    [n, w, sumR]
 
f_tsTxt(int n, int w, float sumR) =>
    n == 0 ? "no trades" : str.tostring(w * 100.0 / n, "#") + "% win, " + (sumR >= 0 ? "+" : "") + str.tostring(sumR / n, "#.##") + "R avg (" + str.tostring(n) + ")"
 
f_factorRow(string name, int which) =>
    [n1, w1, r1] = f_tradeStats(which, true)
    [n0, w0, r0] = f_tradeStats(which, false)
    name + ": with " + f_tsTxt(n1, w1, r1) + " · without " + f_tsTxt(n0, w0, r0)
 
f_targetsSimple(int dir, float ref = na) =>
    [pv, pn] = f_pick(dir, ref)
    string out = ""
    if pv.size() > 0
        for i = 0 to pv.size() - 1
            out += (i > 0 ? "  →  " : "") + f_p(pv.get(i))
    pv.size() == 0 ? "none clear yet" : out
 
f_add(string acc, bool cond, string reason) =>
    cond ? (acc == "" ? reason : acc + ", " + reason) : acc
 
f_cnt(string acc) =>
    acc == "" ? 0 : array.size(str.split(acc, ", "))
 
//────────────────────────────────────────────
// PROJECTED PATH HELPERS
//────────────────────────────────────────────
// Recent chart-timeframe swing levels: the stepping stones of the near-term route
f_stones(float a0, float b0, float gap, int maxN) =>
    float[] out = array.new<float>()
    if maxN > 0 and not na(a0) and not na(b0) and math.abs(b0 - a0) > gap * 2
        bool up = b0 > a0
        float[] cand = array.new<float>()
        for v in nLvls
            if up ? (v > a0 + gap and v < b0 - gap) : (v < a0 - gap and v > b0 + gap)
                cand.push(v)
        if cand.size() > 0
            cand.sort(up ? order.ascending : order.descending)
            float last = a0
            for v in cand
                if out.size() < maxN and math.abs(v - last) >= gap
                    out.push(v)
                    last := v
    out
 
// Nearest recent swing level in direction d, between minD and maxD away from price
f_nextLocal(int d, float minD, float maxD) =>
    float best = na
    for v in nLvls
        float dist = (v - close) * d
        if dist >= minD and dist <= maxD
            if na(best) or dist < (best - close) * d
                best := v
    best
 
// Destinations with stepping stones in between; nearN = levels up to the first destination
f_expand(float[] dests, float gap, int maxN) =>
    float[] lv = array.new<float>()
    float cur = close
    int nearN = 0
    if dests.size() > 0
        for i = 0 to dests.size() - 1
            float d = dests.get(i)
            float[] st = f_stones(cur, d, gap, maxN)
            for v in st
                lv.push(v)
            lv.push(d)
            if i == 0
                nearN := lv.size()
            cur := d
    [lv, nearN]
 
// Bars for one step, scaled by its size in chart ATRs
f_stepBars(float a, float b) =>
    int n = int(math.round(math.abs(b - a) / math.max(nz(nAtr), syminfo.mintick) * 1.5 * paceMult))
    math.max(3, math.min(n, 30))
 
// Chart points for a route; larger steps get a small pullback inside them
f_pathPoints(float[] lv) =>
    chart.point[] pts = array.new<chart.point>()
    int[] ends = array.new<int>()
    pts.push(chart.point.from_index(bar_index, close))
    int   x      = bar_index
    float cur    = close
    int   limitX = bar_index + 480
    int lastDir = 0
    for v in lv
        int stepDir = v > cur ? 1 : -1
        // Same direction as the last step: price pauses and pulls back a little at the level first
        if stepDir == lastDir and math.abs(v - cur) >= nz(nAtr)
            float pb = math.min(nz(nAtr) * 0.6, math.abs(v - cur) * 0.3)
            x += math.max(2, int(math.round(2 * paceMult)))
            cur := cur - stepDir * pb
            pts.push(chart.point.from_index(x, cur))
        lastDir := stepDir
        int n = math.min(f_stepBars(cur, v), math.max(limitX - x, 1))
        if math.abs(v - cur) >= nz(nAtr) * 2.5 and n >= 6
            pts.push(chart.point.from_index(x + int(n * 0.5), cur + (v - cur) * 0.62))
            pts.push(chart.point.from_index(x + int(n * 0.72), cur + (v - cur) * 0.42))
        x += n
        pts.push(chart.point.from_index(x, v))
        ends.push(pts.size() - 1)
        cur := v
    [pts, ends]
 
// "↑ 3851.20 → ↓ 3846.00" for the first nearN levels of a route
f_routeTxt(float[] lv, int n) =>
    string t = ""
    float cur = close
    if n > 0
        for i = 0 to n - 1
            float v = lv.get(i)
            t += (i > 0 ? "  →  " : "") + (v > cur ? "↑ " : "↓ ") + f_p(v)
            cur := v
    t
 
//────────────────────────────────────────────
// DRAWING
//────────────────────────────────────────────
color colPath = pathAuto ? chart.fg_color : colPathIn
labSize = labSizeS == "Small" ? size.small : labSizeS == "Large" ? size.large : size.normal
 
var line[]     lns   = array.new<line>()
var label[]    lbs   = array.new<label>()
var box[]      bxs   = array.new<box>()
var polyline[] paths = array.new<polyline>()
var float[]    lvY   = array.new<float>()
var string[]   lvTxt = array.new<string>()
var color[]    lvCol = array.new<color>()
 
f_level(float y, string txt, color c, string st) =>
    if not na(y)
        lns.push(line.new(bar_index - 1, y, bar_index + lineExt, y, color=c, style=st, width=lineW))
        lvY.push(y)
        lvTxt.push(txt + "  " + f_p(y))
        lvCol.push(c)
 
f_zone(float lvl, int n, float tol, color c, string nm) =>
    if not na(lvl) and not na(tol)
        bxs.push(box.new(bar_index - 30, lvl + tol / 2, bar_index + lineExt, lvl - tol / 2, border_color=color.new(c, 40), bgcolor=color.new(c, 85)))
        lvY.push(lvl)
        lvTxt.push(nm + " (" + zoneTfName + ", " + str.tostring(n) + " touches)  " + f_p(lvl))
        lvCol.push(c)
 
f_queue(float y, string txt, color c) =>
    if not na(y)
        lvY.push(y)
        lvTxt.push(txt)
        lvCol.push(c)
 
// One label per group of levels that sit close together, so text never overlaps
f_drawLabels(float tol) =>
    if lvY.size() > 0
        int[] idx = lvY.sort_indices(order.ascending)
        int i = 0
        while i < idx.size()
            int    first = idx.get(i)
            float  gLo   = lvY.get(first)
            float  gHi   = gLo
            string txt   = lvTxt.get(first)
            color  c     = lvCol.get(first)
            int j = i + 1
            while j < idx.size() and lvY.get(idx.get(j)) - gLo <= tol
                txt += "  ·  " + lvTxt.get(idx.get(j))
                gHi := lvY.get(idx.get(j))
                j += 1
            lbs.push(label.new(bar_index + lineExt, (gLo + gHi) / 2, txt, style=label.style_label_left, color=labBg ? color.new(c, 82) : color(na), textcolor=c, size=labSize))
            i := j
    lvY.clear()
    lvTxt.clear()
    lvCol.clear()
 
f_pos(string s) =>
    s == "Top Right" ? position.top_right : s == "Top Left" ? position.top_left : s == "Bottom Right" ? position.bottom_right : position.bottom_left
 
var table plan = na
 
if barstate.islast
    for l in lns
        l.delete()
    lns.clear()
    for lb in lbs
        lb.delete()
    lbs.clear()
    for b in bxs
        b.delete()
    bxs.clear()
    for p in paths
        p.delete()
    paths.clear()
 
    //──────────── levels ────────────
    float  extTgt   = f_extended(bias, bias == -1 ? refDn : refUp)
    string routeTxt = ""
    bool simpleChart = chartStyle == "Simple"
    // The plan (zone, cancel level, targets) is drawn in every chart mode
    if bias != 0
        color zc = bias == -1 ? colBear : colBull
        bool  zDone = pTarget or pStopped
        bxs.push(box.new(bar_index - 1, zoneHi, bar_index + lineExt, zoneLo, border_color=color.new(zc, zDone ? 75 : 30), bgcolor=color.new(zc, zDone ? 94 : 82)))
        f_queue((zoneLo + zoneHi) / 2, (bias == -1 ? "SELL ZONE  " : "BUY ZONE  ") + f_p(zoneLo) + " – " + f_p(zoneHi) + (zDone ? "  (used)" : pReached or inZone ? "  (reached)" : ""), zc)
        f_level(bias == -1 ? h1 : l1, (simpleChart ? "" : (bias == -1 ? "Lower high (" : "Higher low (") + tfName + ") · ") + "Plan cancelled if a " + tfName + " candle closes " + (bias == -1 ? "above" : "below"), colPrev, line.style_solid)
        [stV, stN] = f_pick(bias, bias == -1 ? refDn : refUp)
        if stV.size() > 0
            for i = 0 to stV.size() - 1
                f_level(stV.get(i), "Target " + str.tostring(i + 1), colLiq, line.style_dashed)
        if not na(extTgt) and extOnChart
            f_level(extTgt, "Larger target", colPrev, line.style_dotted)
        if not na(estT1)
            f_level(estT1, "Quick target (" + str.tostring(t1Cap, "#.##") + "R)", colLiq, line.style_dotted)
    if not simpleChart
        // The swing that is the cancel level is already drawn by the plan
        if bias != -1
            f_level(h1, "Swing high (" + tfName + ")", colBear, line.style_solid)
        if bias != 1
            f_level(l1, "Swing low (" + tfName + ")", colBull, line.style_solid)
        if showFib and not na(swingRange) and swingRange > 0
            f_level(fib382, "Fib 0.382", colFib, line.style_dashed)
            f_level(fib50, "Fib 0.5", colFib, line.style_dashed)
            f_level(fib618, "Fib 0.618", colFib, line.style_dashed)
            if zOutR > 0.7
                f_level(fib786, "Fib 0.786", colFib, line.style_dashed)
        if showPrev
            f_level(pdh, "Prev day high", colPrev, line.style_dotted)
            f_level(pdl, "Prev day low", colPrev, line.style_dotted)
            f_level(pwh, "Prev week high", colPrev, line.style_dotted)
            f_level(pwl, "Prev week low", colPrev, line.style_dotted)
        if not na(wHiTop)
            f_level(wHiTop, "Unfilled wick top (" + tfName + ")", colWick, line.style_dotted)
            f_level(wHiBot, "Unfilled wick base", colWick, line.style_dotted)
        if not na(wLoBot)
            f_level(wLoTop, "Unfilled wick base", colWick, line.style_dotted)
            f_level(wLoBot, "Unfilled wick bottom (" + tfName + ")", colWick, line.style_dotted)
        if eqHighs
            f_level(eqHiLvl, "Equal highs (liquidity)", colLiq, line.style_dashed)
        if eqLows
            f_level(eqLoLvl, "Equal lows (liquidity)", colLiq, line.style_dashed)
        if showEq and pdOk
            f_level(pdEq, "Equilibrium (" + tfName + " range)", colPrev, line.style_dashed)
        f_zone(zRes, zResN, rZTol, colBear, "Resistance zone")
        f_zone(zSup, zSupN, rZTol, colBull, "Support zone")
 
    //──────────── premium / discount bands ────────────
    if showPDB and pdOk
        float rq = (rngHi - rngLo) * 0.25
        bxs.push(box.new(bar_index - 80, rngHi, bar_index + lineExt, rngHi - rq, border_color=color(na), bgcolor=color.new(#DC2626, 93), text="Premium", text_size=size.tiny, text_color=color.new(#DC2626, 45), text_halign=text.align_left, text_valign=text.align_top))
        bxs.push(box.new(bar_index - 80, rngLo + rq, bar_index + lineExt, rngLo, border_color=color(na), bgcolor=color.new(#16A34A, 93), text="Discount", text_size=size.tiny, text_color=color.new(#16A34A, 45), text_halign=text.align_left, text_valign=text.align_bottom))
    if simpleChart and showPrevS
        f_level(pdh, "Prev day high", colPrev, line.style_dotted)
        f_level(pdl, "Prev day low", colPrev, line.style_dotted)
 
    //──────────── projected route ────────────
    bool canDraw = timeframe.in_seconds() < timeframe.in_seconds(htf) and not na(h2) and not na(l2) and not na(nAtr)
    if canDraw and (showPath or showAlt)
        [tDown, nDown] = f_pick(-1, refDn)
        [tUp, nUp]     = f_pick(1, refUp)
        int     dir         = bias
        float[] mainTargets = array.copy(dir == -1 ? tDown : tUp)
        if not na(extTgt) and (extOnChart or mainTargets.size() == 0)
            mainTargets.push(extTgt)
        bool    setupDone   = pTarget or pStopped
        // Price already at (or beyond) the zone: the route starts from here, not from the zone
        bool    zoneTouched = pReached or pRejected or inZone or (dir == -1 ? close >= zoneLo : close <= zoneHi)
        float   gapS        = nAtr * stoneGap
        float[] dests       = array.new<float>()
        string  firstName   = ""
        string  thenName    = ""
        if setupDone
            float nx = f_nextLocal(nearDir, nAtr * 0.5, nAtr * 4)
            if not na(nx)
                dests.push(nx)
                firstName := "near-term " + (nearDir == 1 ? "bounce" : "dip")
            f_queue(close, (pTarget ? "✔ Setup reached its first target" : "✖ Setup was stopped out") + ". Waiting for the next setup.", colPrev)
        else
            if not zoneTouched and not na(zoneLo)
                dests.push(na(turnLvl) ? (zoneLo + zoneHi) / 2 : turnLvl)
                firstName := "into the " + (dir == -1 ? "sell" : "buy") + " zone"
            for t in mainTargets
                dests.push(t)
            if zoneTouched and mainTargets.size() > 0
                firstName := "toward Target 1"
            // Short-term trend pointing the other way: show a small counter-move first
            if dests.size() > 0 and preMax > 0
                int firstDir = dests.first() > close ? 1 : -1
                if nearDir != firstDir
                    float pre = f_nextLocal(nearDir, nAtr * 0.5, nAtr * preMax)
                    if not na(pre)
                        thenName  := firstName
                        firstName := "short-term " + (nearDir == 1 ? "bounce" : "dip") + " first"
                        dests.unshift(pre)
        if showPath and dests.size() > 0
            [lvM, nearN] = f_expand(dests, gapS, stonesN)
            [ptsM, endsM] = f_pathPoints(lvM)
            int cut = endsM.get(nearN - 1)
            if routeStyle == "Solid" or ptsM.size() - cut < 2
                paths.push(polyline.new(ptsM, line_color=colPath, line_width=pathW))
            else
                paths.push(polyline.new(array.slice(ptsM, 0, cut + 1), line_color=colPath, line_width=pathW))
                paths.push(polyline.new(array.slice(ptsM, cut, ptsM.size()), line_color=color.new(colPath, 40), line_style=line.style_dashed, line_width=math.max(pathW - 1, 1)))
            routeTxt := f_routeTxt(lvM, nearN) + "  (" + firstName + (thenName != "" ? ", then " + thenName : "") + ")"
            if not setupDone
                f_queue(ptsM.last().price, isRange ? "◆ Most likely route ends" : "◆ Main scenario ends", colPath)
        if showAlt and not (chartStyle == "Simple") and not setupDone and not zoneTouched and mainTargets.size() > 0
            [lvA, nA] = f_expand(mainTargets, gapS, stonesN)
            [ptsA, endsA] = f_pathPoints(lvA)
            paths.push(polyline.new(ptsA, line_color=colAlt, line_style=line.style_dashed, line_width=math.max(pathW - 1, 1)))
            f_queue(ptsA.last().price, "◇ Alt (no " + (dir == -1 ? "bounce" : "pullback") + ") ends", colAlt)
 
    f_drawLabels(nz(htfAtr, 0) * mergeTol)
 
    //──────────── written analysis ────────────
    bool     full    = panelMode == "Full"
    string[] rows    = array.new<string>()
    int[]    rowKind = array.new<int>()   // 0 normal, 1 bias header, 2 section header
    color    headCol = bias == 1 ? colBull : bias == -1 ? colBear : #F59E0B
    string   locTxt  = f_location()
    string   zoneConf = f_confRange(zoneLo, zoneHi)
 
    // evidence
    string evMain = ""
    string evAlt  = ""
    string evShared = ""
    if bias == -1
        evMain := f_add(evMain, loBias == 1, tfLo + " bouncing")
        evMain := f_add(evMain, pdOk and pdPos <= 0.45, "room to rally (lower half of range)")
        evMain := f_add(evMain, not na(wHiTop) and wHiTop > close, "unfilled wick above")
        evMain := f_add(evMain, eqHighs and eqHiLvl > close, "equal highs above to sweep")
        evMain := f_add(evMain, zoneConf != "", "confluence in the sell zone")
        evMain := f_add(evMain, not na(htfRsi) and htfRsi <= 35, "momentum stretched (RSI low)")
        evAlt  := f_add(evAlt, loBias == -1, tfLo + " already falling")
        evAlt  := f_add(evAlt, pdOk and pdPos >= 0.55, "already high in the range")
        evAlt  := f_add(evAlt, not na(wLoBot) and wLoBot < close, "unfilled wick below")
        evAlt  := f_add(evAlt, eqLows and eqLoLvl < close, "equal lows below to sweep")
        evAlt  := f_add(evAlt, not na(htfRsi) and htfRsi > 35 and htfRsi < 50, "bearish momentum, not stretched")
    else if bias == 1
        evMain := f_add(evMain, loBias == -1, tfLo + " pulling back")
        evMain := f_add(evMain, pdOk and pdPos >= 0.55, "room to pull back (upper half of range)")
        evMain := f_add(evMain, not na(wLoBot) and wLoBot < close, "unfilled wick below")
        evMain := f_add(evMain, eqLows and eqLoLvl < close, "equal lows below to sweep")
        evMain := f_add(evMain, zoneConf != "", "confluence in the buy zone")
        evMain := f_add(evMain, not na(htfRsi) and htfRsi >= 65, "momentum stretched (RSI high)")
        evAlt  := f_add(evAlt, loBias == 1, tfLo + " already rising")
        evAlt  := f_add(evAlt, pdOk and pdPos <= 0.45, "already low in the range")
        evAlt  := f_add(evAlt, not na(wHiTop) and wHiTop > close, "unfilled wick above")
        evAlt  := f_add(evAlt, eqHighs and eqHiLvl > close, "equal highs above to sweep")
        evAlt  := f_add(evAlt, not na(htfRsi) and htfRsi > 50 and htfRsi < 65, "bullish momentum, not stretched")
    else
        evMain := f_add(evMain, loBias == 1, tfLo + " rising")
        evMain := f_add(evMain, not na(wHiTop) and wHiTop > close, "unfilled wick above")
        evMain := f_add(evMain, eqHighs and eqHiLvl > close, "equal highs above")
        evMain := f_add(evMain, not na(htfRsi) and htfRsi > 50, "RSI above 50")
        evMain := f_add(evMain, hiBias == 1, tfHi + " bullish")
        evAlt  := f_add(evAlt, loBias == -1, tfLo + " falling")
        evAlt  := f_add(evAlt, not na(wLoBot) and wLoBot < close, "unfilled wick below")
        evAlt  := f_add(evAlt, eqLows and eqLoLvl < close, "equal lows below")
        evAlt  := f_add(evAlt, not na(htfRsi) and htfRsi < 50, "RSI below 50")
        evAlt  := f_add(evAlt, hiBias == -1, tfHi + " bearish")
    if bias != 0
        evShared := hiBias == bias ? "Both scenarios: " + tfHi + " agrees with the " + tfName + " trend ✓" : hiBias == -bias ? "Both scenarios: " + tfHi + " disagrees with the " + tfName + " trend ✗ (lower conviction)" : "Both scenarios: " + tfHi + " has no clear trend."
 
    // outside markets
    string usdWord = usdDir == 1 ? "rising" : usdDir == -1 ? "falling" : "n/a"
    string yldWord = yldDir == 1 ? "rising" : yldDir == -1 ? "falling" : "n/a"
    string imTxt = ""
    if bias != 0 and (useUsd or useYld)
        string pw = bias == -1 ? "sells" : "buys"
        imTxt := "Outside markets: " + (useUsd ? "dollar " + usdWord + (f_supports(usdDir, bias) ? " (supports " + pw + " ✓)" : usdDir != 0 ? " (against " + pw + " ✗)" : "") : "") + (useUsd and useYld ? " · " : "") + (useYld ? "US yields " + yldWord + (f_supports(yldDir, bias) ? " (supports " + pw + " ✓)" : yldDir != 0 ? " (against " + pw + " ✗)" : "") : "") + "."
    else if useUsd or useYld
        imTxt := "Outside markets: dollar " + usdWord + " · US yields " + yldWord + "."
    string simpleIm = ""
    if bias != 0 and (useUsd or useYld)
        int nSup = (f_supports(usdDir, bias) ? 1 : 0) + (f_supports(yldDir, bias) ? 1 : 0)
        int nChk = (useUsd and usdDir != 0 ? 1 : 0) + (useYld and yldDir != 0 ? 1 : 0)
        simpleIm := nChk == 0 ? "" : nSup == nChk ? "Outside markets (dollar, yields) support this plan ✓" : nSup == 0 ? "Outside markets (dollar, yields) are against this plan ✗. Extra caution." : "Outside markets are mixed: one supports this plan, one doesn't."
 
    // news warning: nearest event that hasn't finished yet
    string newsTxt = ""
    int    nextNews = na
    for nt in array.from(news1, news2, news3)
        if f_validNews(nt) and nt + newsWin * 60000 >= timenow and (na(nextNews) or nt < nextNews)
            nextNews := nt
    if not na(nextNews)
        int minsTo = int((nextNews - timenow) / 60000)
        string whenTxt = minsTo > 0 ? "in " + (minsTo >= 60 ? str.tostring(int(minsTo / 60)) + "h " : "") + str.tostring(minsTo % 60) + "m" : "now"
        newsTxt := "⚠ High-impact news at " + str.format_time(nextNews, "HH:mm", newsTz) + " " + newsTz + " (" + whenTxt + "). Avoid new trades from " + str.format_time(nextNews - newsWin * 60000, "HH:mm", newsTz) + " to " + str.format_time(nextNews + newsWin * 60000, "HH:mm", newsTz) + "."
 
    // live confirmation checklist for the current plan
    string confTxt = bias == 0 ? "" : "Confirmation so far: zone " + (pReached ? "✓" : "✗") + " · sweep " + (pSweep ? "✓" : "✗") + " · rejection " + (pRejected ? "✓" : "✗") + " · volume " + (pRejected ? (pRejVol ? "✓" : "✗") : "–")
 
    // track record
    string[] trackRows = array.new<string>()
    string   trackTxt  = ""
    string   simpleTrack = ""
    if useStats
        int dirT = bias != 0 ? bias : -1
        [n, nReach, nRej] = f_planStats(dirT)
        string dName = dirT == -1 ? "bearish" : "bullish"
        [tn0, tw0, tr0] = f_tradeStats(0, true)
        if n > 0
            trackRows.push("Last " + str.tostring(n) + " " + dName + " plans: zone reached " + f_pct(nReach, n) + " · strict rejection " + f_pct(nRej, nReach) + " of those.")
        else
            trackRows.push("No completed " + dName + " plans in the loaded history yet.")
        if tn0 > 0
            trackRows.push("Simulated trades (entry on rejection, stop beyond zone, first target): " + f_tsTxt(tn0, tw0, tr0) + ". Expectancy " + (tr0 >= 0 ? "+" : "") + str.tostring(tr0 / tn0, "#.##") + "R per trade.")
            trackRows.push(f_factorRow(tfHi + " agrees", 1))
            if useSweep
                trackRows.push(f_factorRow("Sweep before rejection", 2))
            if useVol
                trackRows.push(f_factorRow("Strong volume on rejection", 3))
            trackRows.push(f_factorRow("London / NY hours", 4))
            if usePD
                trackRows.push(f_factorRow("Good location", 5))
            if useUsd
                trackRows.push(f_factorRow("Dollar supports the plan", 6))
            if useYld
                trackRows.push(f_factorRow("Yields support the plan", 7))
            trackRows.push(f_factorRow("High volatility", 8))
            if statsRange
                trackRows.push(f_factorRow("Trending setup (vs sideways lean)", 10))
            if tn0 < 20
                trackRows.push("Small sample (" + str.tostring(tn0) + " trades): treat with caution. Load more history for better stats.")
            trackRows.push("Excludes spread, slippage and news. Use it to compare settings, not as a forecast.")
            trackTxt    := "Simulated trades: " + f_tsTxt(tn0, tw0, tr0) + "."
            [tnT, twT, trT] = f_tradeStats(10, true)
            [tnS, twS, trS] = f_tradeStats(10, false)
            simpleTrack := "Past results: " + str.tostring(tw0) + " of " + str.tostring(tn0) + " reached Target 1, avg " + (tr0 >= 0 ? "+" : "") + str.tostring(tr0 / tn0, "#.##") + "R per trade." + (statsRange and tnS > 0 ? " Trending: " + str.tostring(twT) + "/" + str.tostring(tnT) + (tnT > 0 ? " (" + (trT >= 0 ? "+" : "") + str.tostring(trT / tnT, "#.##") + "R)" : "") + " · Sideways: " + str.tostring(twS) + "/" + str.tostring(tnS) + " (" + (trS >= 0 ? "+" : "") + str.tostring(trS / tnS, "#.##") + "R)." : "")
        else
            trackRows.push("No simulated trades yet in the loaded history.")
            trackTxt := "Simulated trades: none yet."
 
    if timeframe.in_seconds() >= timeframe.in_seconds(htf)
        rows.push("Use a chart timeframe lower than the main timeframe (" + tfName + ").")
        rowKind.push(0)
    else if na(h2) or na(l2)
        rows.push("Not enough " + tfName + " swings yet. Load more history or lower the swing strength.")
        rowKind.push(0)
    else
        if panelMode == "Simple"
            string zw = bias == -1 ? "sell" : "buy"
            rows.push(isRange ? "TREND: SIDEWAYS, LEANING " + (bias == -1 ? "DOWN ▼" : "UP ▲") : bias == -1 ? "TREND: DOWN ▼" : "TREND: UP ▲")
            rowKind.push(1)
            rows.push(isRange ? "No clear trend on the " + tfName + " chart, but the evidence " + leanStrength + " points " + (bias == -1 ? "down" : "up") + " (" + leanWhy + ")." : bias == -1 ? "Price keeps making lower highs and lower lows on the " + tfName + " chart." : "Price keeps making higher highs and higher lows on the " + tfName + " chart.")
            rowKind.push(0)
            if pdOk
                string where = bias == -1 ? (pdPos <= 0.25 ? "price is near the bottom of its range. Too late to sell here." : pdPos <= 0.55 ? "price is in the lower half of its range. Better to wait for a rise." : "price is high in its range. A good area to look for sells.") : bias == 1 ? (pdPos >= 0.75 ? "price is near the top of its range. Too late to buy here." : pdPos >= 0.45 ? "price is in the upper half of its range. Better to wait for a dip." : "price is low in its range. A good area to look for buys.") : (pdPos >= 0.75 ? "price is near the top of its range." : pdPos <= 0.25 ? "price is near the bottom of its range." : "price is in the middle of its range. Best to wait.")
                rows.push("Right now: " + where)
                rowKind.push(0)
            if routeTxt != ""
                rows.push("Next move (" + chartTfName + "): " + routeTxt)
                rowKind.push(0)
            if simpleIm != ""
                rows.push(simpleIm)
                rowKind.push(0)
            if newsTxt != ""
                rows.push(newsTxt)
                rowKind.push(3)
            rows.push("THE PLAN")
            rowKind.push(2)
            if bias == -1
                rows.push("1. Wait for price to rise into the sell zone: " + f_p(zoneLo) + " – " + f_p(zoneHi) + ".")
                rowKind.push(0)
                rows.push("2. Sell signal: a candle closes back below " + f_p(zoneLo) + ".")
                rowKind.push(0)
                rows.push("3. Targets: " + estTxt + f_targetsSimple(-1, refDn))
                rowKind.push(0)
                if not na(extTgt)
                    rows.push("   Larger target: " + f_p(extTgt) + ". Beyond a typical day's range, so it may take longer.")
                    rowKind.push(0)
                rows.push("Plan cancelled if a " + tfName + " candle closes above " + f_p(h1) + ".")
                rowKind.push(0)
            else if bias == 1
                rows.push("1. Wait for price to dip into the buy zone: " + f_p(zoneLo) + " – " + f_p(zoneHi) + ".")
                rowKind.push(0)
                rows.push("2. Buy signal: a candle closes back above " + f_p(zoneHi) + ".")
                rowKind.push(0)
                rows.push("3. Targets: " + estTxt + f_targetsSimple(1, refUp))
                rowKind.push(0)
                if not na(extTgt)
                    rows.push("   Larger target: " + f_p(extTgt) + ". Beyond a typical day's range, so it may take longer.")
                    rowKind.push(0)
                rows.push("Plan cancelled if a " + tfName + " candle closes below " + f_p(l1) + ".")
                rowKind.push(0)
            else
                rows.push("Wait. Only trade if price breaks out of " + f_p(l1) + " – " + f_p(h1) + ".")
                rowKind.push(0)
                rows.push("Break above " + f_p(h1) + " → targets: " + f_targetsSimple(1, refUp))
                rowKind.push(0)
                rows.push("Break below " + f_p(l1) + " → targets: " + f_targetsSimple(-1, refDn))
                rowKind.push(0)
            if bias != 0
                string status = pTarget ? "First target reached. This setup is done; waiting for the next one." : pStopped ? "Signal failed: price hit the stop. Waiting for the next setup." : pRejected ? "Price has turned. Targets are active" + (tActive and tPlan == planId ? " (stop " + f_p(tStop) + ")." : ".") : inZone ? "Price is in the " + zw + " zone. Watch for the " + zw + " signal." : pReached ? "Price visited the " + zw + " zone. Watch for the " + zw + " signal." : "Waiting for price to reach the " + zw + " zone."
                rows.push("STATUS: " + status)
                rowKind.push(3)
            bool otherActive = tActive and tPlan != planId
            if otherActive
                rows.push("Earlier signal still running: " + (tDir == -1 ? "sold" : "bought") + " at " + f_p(tEntry) + ", stop " + f_p(tStop) + ", target " + f_p(tTgt) + ".")
                rowKind.push(0)
            else if not na(lastRes) and not pTarget and not pStopped and not (tActive and tPlan == planId)
                rows.push("Last signal: " + (lastDir == -1 ? "sold" : "bought") + " at " + f_p(lastEntry) + " → " + (lastRes == 1 ? "target reached at " : "stopped at ") + f_p(lastExit) + ".")
                rowKind.push(0)
            if showTrack and simpleTrack != ""
                rows.push(simpleTrack)
                rowKind.push(0)
            rows.push("More detail: set Panel detail to Full.")
            rowKind.push(0)
        else
            // ── bias ──
            rows.push(isRange ? "BIAS: RANGE on " + tfName + ", leaning " + (bias == -1 ? "BEARISH" : "BULLISH") + " (" + leanStrength + "): " + leanWhy + "." : bias == -1 ? "BIAS: BEARISH. Lower highs and lower lows on " + tfName + "." : "BIAS: BULLISH. Higher highs and higher lows on " + tfName + ".")
            rowKind.push(1)
 
            if not full
                // ── compact ──
                if locTxt != ""
                    rows.push(locTxt)
                    rowKind.push(0)
                if bias != 0
                    rows.push("Evidence: main " + str.tostring(f_cnt(evMain)) + " · alt " + str.tostring(f_cnt(evAlt)) + ". " + confTxt)
                    rowKind.push(0)
                if imTxt != ""
                    rows.push(imTxt)
                    rowKind.push(0)
                if newsTxt != ""
                    rows.push(newsTxt)
                    rowKind.push(3)
                if showTrack and trackTxt != ""
                    rows.push(trackTxt)
                    rowKind.push(0)
                if bias == -1
                    rows.push("Sell zone: " + f_p(zIn) + " to " + f_p(zOut) + (zoneConf != "" ? " ★ " + zoneConf : "") + ". Act only on rejection and a close back below " + f_p(zIn) + ".")
                    rowKind.push(0)
                    rows.push("Targets: " + f_targets(-1, refDn))
                    rowKind.push(0)
                    rows.push("Invalidation: " + tfName + " close above " + f_p(h1) + ".")
                    rowKind.push(0)
                else if bias == 1
                    rows.push("Buy zone: " + f_p(zOut) + " to " + f_p(zIn) + (zoneConf != "" ? " ★ " + zoneConf : "") + ". Act only on rejection and a close back above " + f_p(zIn) + ".")
                    rowKind.push(0)
                    rows.push("Targets: " + f_targets(1, refUp))
                    rowKind.push(0)
                    rows.push("Invalidation: " + tfName + " close below " + f_p(l1) + ".")
                    rowKind.push(0)
                else
                    rows.push("Range: " + f_p(l1) + " to " + f_p(h1) + ". Wait for a " + tfName + " close outside it.")
                    rowKind.push(0)
                    rows.push("Above " + f_p(h1) + ": " + f_targets(1, refUp))
                    rowKind.push(0)
                    rows.push("Below " + f_p(l1) + ": " + f_targets(-1, refDn))
                    rowKind.push(0)
            else
                // ── context ──
                rows.push("CONTEXT")
                rowKind.push(2)
                string alignRead = bias != 0 and hiBias == bias and loBias == bias ? "All three agree: strongest conditions for trading with the trend." : bias != 0 and hiBias == bias and loBias == -bias ? tfLo + " is moving against the higher timeframes: likely a corrective move into the zone." : bias != 0 and hiBias == -bias ? tfHi + " disagrees with " + tfName + ": lower conviction, consider smaller size or waiting." : bias == 0 ? "No clear trend on " + tfName + ": range rules apply." : "Mixed signals: be selective."
                if newsTxt != ""
                    rows.push(newsTxt)
                    rowKind.push(3)
                if imTxt != ""
                    rows.push(imTxt)
                    rowKind.push(0)
                rows.push("Volatility regime: ATR " + (na(volRatio) ? "—" : str.tostring(volRatio, "#.##")) + "x normal" + (hiVol ? " (high: wider swings, stops get hit more easily)." : "."))
                rowKind.push(0)
                rows.push("Alignment: " + tfHi + " " + f_bname(hiBias) + " · " + tfName + " " + f_bname(bias) + " · " + tfLo + " " + f_bname(loBias) + ". " + alignRead)
                rowKind.push(0)
                if locTxt != ""
                    rows.push(locTxt)
                    rowKind.push(0)
                if useRsi and not na(htfRsi)
                    string mom = htfRsi >= 70 ? "overbought, upside may be stretched" : htfRsi <= 30 ? "oversold, downside may be stretched" : htfRsi >= 50 ? "leaning bullish" : "leaning bearish"
                    rows.push("Momentum: " + tfName + " RSI " + str.tostring(htfRsi, "#") + ", " + mom + ".")
                    rowKind.push(0)
                if useAdr and not na(adr) and adr > 0
                    float adrPct = (tdHigh - tdLow) / adr * 100
                    string volTxt = adrPct >= 100 ? " Average range already reached: big extensions are less likely today." : " Typical room today: up to ~" + f_p(tdLow + adr) + ", down to ~" + f_p(tdHigh - adr) + "."
                    rows.push("Volatility: today's range is " + str.tostring(adrPct, "#") + "% of ADR (" + f_p(adr) + ")." + volTxt)
                    rowKind.push(0)
 
                // ── evidence ──
                rows.push("EVIDENCE  (a count of reasons, not a probability)")
                rowKind.push(2)
                if bias != 0
                    rows.push("Main (" + (bias == -1 ? "bounce, then sell" : "pullback, then buy") + "): " + str.tostring(f_cnt(evMain)) + (evMain != "" ? ". " + evMain + "." : "."))
                    rowKind.push(0)
                    rows.push("Alternative (" + (bias == -1 ? "no bounce, straight down" : "no pullback, straight up") + "): " + str.tostring(f_cnt(evAlt)) + (evAlt != "" ? ". " + evAlt + "." : "."))
                    rowKind.push(0)
                    rows.push(evShared)
                    rowKind.push(0)
                    rows.push(confTxt)
                    rowKind.push(0)
                else
                    rows.push("Upside break: " + str.tostring(f_cnt(evMain)) + (evMain != "" ? ". " + evMain + "." : "."))
                    rowKind.push(0)
                    rows.push("Downside break: " + str.tostring(f_cnt(evAlt)) + (evAlt != "" ? ". " + evAlt + "." : "."))
                    rowKind.push(0)
                if useVol and not na(relVol)
                    rows.push("Volume: last candle " + str.tostring(relVol, "#.#") + "x average" + (relVol >= volThr ? " (strong)." : relVol < 0.7 ? " (weak)." : ".") + (volExt ? " Source: " + volSym + "." : " Spot gold volume is broker tick volume."))
                    rowKind.push(0)
 
                // ── track record ──
                if useStats and showTrack
                    rows.push("TRACK RECORD  (" + syminfo.ticker + ", " + tfName + " plans, loaded history)")
                    rowKind.push(2)
                    for tr in trackRows
                        rows.push(tr)
                        rowKind.push(0)
 
                // ── levels ──
                bool anyLevel = not na(zRes) or not na(zSup) or not na(wHiTop) or not na(wLoBot) or eqHighs or eqLows
                if anyLevel
                    rows.push("KEY LEVELS")
                    rowKind.push(2)
                    if not na(zRes)
                        rows.push("Resistance zone near " + f_p(zRes) + " (" + zoneTfName + ", " + str.tostring(zResN) + " touches). Price has turned here " + (zResN >= 3 ? "repeatedly." : "before."))
                        rowKind.push(0)
                    if not na(zSup)
                        rows.push("Support zone near " + f_p(zSup) + " (" + zoneTfName + ", " + str.tostring(zSupN) + " touches). Price has turned here " + (zSupN >= 3 ? "repeatedly." : "before."))
                        rowKind.push(0)
                    if not na(wHiTop)
                        rows.push("Unfilled " + tfName + " wick above: " + f_p(wHiBot) + " to " + f_p(wHiTop) + ". Often revisited, not guaranteed.")
                        rowKind.push(0)
                    if not na(wLoBot)
                        rows.push("Unfilled " + tfName + " wick below: " + f_p(wLoBot) + " to " + f_p(wLoTop) + ". Often revisited, not guaranteed.")
                        rowKind.push(0)
                    if eqHighs
                        rows.push("Equal highs near " + f_p(eqHiLvl) + ": stops likely above. A sweep above then rejection is a classic short trigger.")
                        rowKind.push(0)
                    if eqLows
                        rows.push("Equal lows near " + f_p(eqLoLvl) + ": stops likely below. A sweep below then rejection is a classic long trigger.")
                        rowKind.push(0)
 
                // ── plan ──
                rows.push("PLAN")
                rowKind.push(2)
                if routeTxt != ""
                    rows.push("Next move (" + chartTfName + "): " + routeTxt)
                    rowKind.push(0)
                if not na(extTgt)
                    rows.push("Larger target beyond " + str.tostring(tgtCapAdr, "#.##") + "x the daily range: " + f_p(extTgt) + ".")
                    rowKind.push(0)
                if bias == -1
                    rows.push("Rallies are corrective until a " + tfName + " close above " + f_p(h1) + ".")
                    rowKind.push(0)
                    rows.push("1. Corrective bounce: acceptance above " + f_p(fib382) + " (0.382) opens " + f_p(zIn) + " to " + f_p(zOut) + ".")
                    rowKind.push(0)
                    rows.push("2. Sell zone: " + f_p(zIn) + " to " + f_p(zOut) + ". Wait for rejection and a candle close back below " + f_p(zIn) + ".")
                    rowKind.push(0)
                    if zoneConf != ""
                        rows.push("   ★ Zone confluence: " + zoneConf + ".")
                        rowKind.push(0)
                    if not na(turnLvl)
                        rows.push("   Key level: resistance zone at " + f_p(turnLvl) + " (" + str.tostring(zResN) + " touches) sits inside the sell zone. Most likely turning point.")
                        rowKind.push(0)
                    rows.push("   Targets: " + f_targets(-1, refDn))
                    rowKind.push(0)
                    rows.push("3. No bounce: if price can't hold above " + f_p(fib382) + ", don't force a buy. Watch for continuation below " + f_p(l1) + ".")
                    rowKind.push(0)
                    rows.push("4. Invalidation: " + tfName + " close above " + f_p(h1) + " breaks the bearish structure. Stand aside.")
                    rowKind.push(0)
                else if bias == 1
                    rows.push("Dips are corrective until a " + tfName + " close below " + f_p(l1) + ".")
                    rowKind.push(0)
                    rows.push("1. Corrective pullback: acceptance below " + f_p(fib382) + " (0.382) opens " + f_p(zIn) + " to " + f_p(zOut) + ".")
                    rowKind.push(0)
                    rows.push("2. Buy zone: " + f_p(zOut) + " to " + f_p(zIn) + ". Wait for rejection and a candle close back above " + f_p(zIn) + ".")
                    rowKind.push(0)
                    if zoneConf != ""
                        rows.push("   ★ Zone confluence: " + zoneConf + ".")
                        rowKind.push(0)
                    if not na(turnLvl)
                        rows.push("   Key level: support zone at " + f_p(turnLvl) + " (" + str.tostring(zSupN) + " touches) sits inside the buy zone. Most likely turning point.")
                        rowKind.push(0)
                    rows.push("   Targets: " + f_targets(1, refUp))
                    rowKind.push(0)
                    rows.push("3. No pullback: if price holds above " + f_p(fib382) + ", don't chase. Watch for continuation above " + f_p(h1) + ".")
                    rowKind.push(0)
                    rows.push("4. Invalidation: " + tfName + " close below " + f_p(l1) + " breaks the bullish structure. Stand aside.")
                    rowKind.push(0)
                else
                    string why = bearBroken ? "The last lower high (" + f_p(h1) + ") was broken on a " + tfName + " close. Bearish structure is in doubt." : bullBroken ? "The last higher low (" + f_p(l1) + ") was broken on a " + tfName + " close. Bullish structure is in doubt." : "Swings are mixed: no clear trend."
                    rows.push(why)
                    rowKind.push(0)
                    rows.push("Range: " + f_p(l1) + " to " + f_p(h1) + ". Middle: " + f_p((h1 + l1) / 2) + ".")
                    rowKind.push(0)
                    rows.push("1. Upside break: " + tfName + " close above " + f_p(h1) + ", then a retest that holds. Targets: " + f_targets(1, refUp))
                    rowKind.push(0)
                    rows.push("2. Downside break: " + tfName + " close below " + f_p(l1) + ", then a retest that holds. Targets: " + f_targets(-1, refDn))
                    rowKind.push(0)
                    rows.push("3. Inside the range: avoid the middle. Only consider the edges with clear rejection.")
                    rowKind.push(0)
 
    rows.push("Price now: " + f_p(close) + ". Planning tool, not a signal.")
    rowKind.push(0)
 
    if showPlan
        if not na(plan)
            table.delete(plan)
        plan := table.new(f_pos(planPos), 1, rows.size() + 1, bgcolor=color.new(#0F1115, 5), border_color=color.new(#2A2F37, 0), border_width=1, frame_color=color.new(#2A2F37, 0), frame_width=1)
        txtSize = planSize == "Tiny" ? size.tiny : planSize == "Normal" ? size.normal : size.small
        table.cell(plan, 0, 0, "MARKET MAP  ·  GoldenDream  ·  " + syminfo.ticker + "  ·  " + tfHi + " / " + tfName + " / " + tfLo, text_color=#D4AF37, bgcolor=color.new(#1C2027, 0), text_size=txtSize, text_halign=text.align_left)
        for i = 0 to rows.size() - 1
            int kind = rowKind.get(i)
            color tc = kind == 1 ? headCol : kind == 2 ? #8A919E : #E6E8EB
            color bg = kind == 2 ? color.new(#1C2027, 0) : kind == 3 ? color.new(#D4AF37, 75) : color(na)
            table.cell(plan, 0, i + 1, rows.get(i), text_color=tc, bgcolor=bg, text_size=txtSize, text_halign=text.align_left)

← 返回列表