PO3 Fractal Matrix+ (M1D)

mayb1dayy · study · 2575 行 · 点赞 663 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © M1D
 
//@version=6
indicator("PO3 Fractal Matrix+ (M1D)", "PO3 Fractalized", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
 
// The fractal model on one HTF candle timeframe: C1-C4 sequence, T-Spot EQ, CISD, SMT, PSP, HTF candles.
// The CISD reading is the CISD Order Block+ (M1D) one, drawn lines only.
 
// == CONSTANTS ==
// Ink follows the chart: black on a light background, white on a dark one.
bool  DARK   = color.r(chart.bg_color) + color.g(chart.bg_color) + color.b(chart.bg_color) < 384
color INK    = DARK ? #FFFFFF : #000000
// Violet marks what is on, live or projected; OPENS is the reference grey, lighter on a dark chart; WASH is the title row fill.
color LIVE   = #7246CE
color OPENS  = DARK ? #B2B5BE : #4A4A4A
color WASH   = DARK ? #2A2E39 : #F0F2F5
// Violet: the SMT lines and the outline of the live HTF candle.
color LILAC  = #7246CE
 
// == INPUTS ==
string GRP_A = "Assets"
string GRP_M = "SMT"
string GRP_S = "Style"
 
string aModeIn = input.string("Auto", "Assets", options = ["Auto", "Manual"], group = GRP_A, inline = "am")
string aDivIn  = input.string("Tetrad", "", options = ["Dyad", "Triad", "Triad (GXT)", "Tetrad"], group = GRP_A, inline = "am", tooltip = "Auto picks the correlated assets for the chart symbol: index futures, metals, energy, bonds, FX with DXY, CME micro bitcoin and ether, BTC and ETH. Dyad = 1 asset, Triad = 2, Tetrad = 3. GXT swaps the second asset. A symbol not in the list, or Manual, uses the rows below.")
bool   aOn1  = input.bool(true, "1", group = GRP_A, inline = "a1")
string aSym1 = input.symbol("CME_MINI:MES1!", "", group = GRP_A, inline = "a1")
bool   aInv1 = input.bool(false, "Invert", group = GRP_A, inline = "a1")
bool   aOn2  = input.bool(true, "2", group = GRP_A, inline = "a2")
string aSym2 = input.symbol("CBOT_MINI:MYM1!", "", group = GRP_A, inline = "a2")
bool   aInv2 = input.bool(false, "Invert", group = GRP_A, inline = "a2")
bool   aOn3  = input.bool(false, "3", group = GRP_A, inline = "a3")
string aSym3 = input.symbol("CME_MINI:M2K1!", "", group = GRP_A, inline = "a3")
bool   aInv3 = input.bool(false, "Invert", group = GRP_A, inline = "a3")
bool   aOn4  = input.bool(false, "4", group = GRP_A, inline = "a4")
string aSym4 = input.symbol("TVC:DXY", "", group = GRP_A, inline = "a4")
bool   aInv4 = input.bool(true, "Invert", group = GRP_A, inline = "a4", tooltip = "Asset 4 is always manual and is added on top of Auto.")
 
bool   smtOn    = input.bool(true, "Show SMT", group = GRP_M, tooltip = "Candles of each ticked timeframe built from chart bars, the chart symbol's and each asset's side by side. The forming candle against each candle before it, back to the lookback, whose high or low nothing has reached since: the chart takes that level and a asset fails, or a asset takes it and the chart fails. It feeds the T-Spot filter; off, a filter that needs a SMT finds none.")
bool   p3SmtLn  = input.bool(true, "Lines on chart", group = GRP_M, tooltip = "Each SMT drawn from the reference candle's high or low to the candle that took it. Dashed when it is a SSMT. It stays until a candle trades back through it.")
string smtLblIn = input.string("Assets", "Labels", options = ["Off", "HTF", "Assets", "HTF + Assets"], group = GRP_M, inline = "sl", tooltip = "Past the newest swing's wick, in the line's colour: its timeframe, the assets that diverged, or both, e.g. ES+YM or 4H SMT · ES+YM.")
bool   smtDot   = input.bool(true, "Reference dot", group = GRP_M, inline = "sl")
bool   smt15    = input.bool(true, "15m", group = GRP_M, inline = "t1")
bool   smt30    = input.bool(false, "30m", group = GRP_M, inline = "t1")
bool   smt60    = input.bool(true, "1H", group = GRP_M, inline = "t1")
bool   smt90    = input.bool(false, "90m", group = GRP_M, inline = "t1")
bool   smt240   = input.bool(true, "4H", group = GRP_M, inline = "t2")
bool   smt360   = input.bool(false, "6H", group = GRP_M, inline = "t2")
bool   smtD     = input.bool(true, "1D", group = GRP_M, inline = "t2", tooltip = "A ticked timeframe reads only while it holds between the ratio min and max in chart candles.")
bool   p3Ssmt   = input.bool(false, "SSMT on 90m and 6H", group = GRP_M, inline = "ss", tooltip = "The forming 90m or 6H candle against the one right before it: the chart or a asset trades through that candle's high or low and the other does not. Needs 90m or 6H ticked. Drawn dashed. Counts as a SMT for the T-Spot filter. With Filter on, a live sequence must agree with the newest SSMT.")
bool   p3SsmtF  = input.bool(true, "Filter", group = GRP_M, inline = "ss", active = p3Ssmt)
bool   smtAll   = input.bool(false, "Every asset must diverge", group = GRP_M)
string smtModeIn = input.string("Clean", "Filtering", options = ["Clean", "Balanced", "Full"], group = GRP_M, tooltip = "Clean: a reference is a candle whose high or low nothing has reached since, one SMT per side per timeframe each candle, and a higher timeframe removes a lower one that shares its end, shares its reference, or sits inside it (1H and below), unless the lower one is newer and runs further. Balanced: a reference may also be a candle whose high or low stands above (below) both neighbours; only the exact same SMT on two timeframes is removed, and each timeframe keeps its newest closed SMT plus one older one at least the span multiple wider. Full: every candle in the lookback is a reference and nothing is removed across timeframes.")
bool   smtPerTf = input.bool(true, "Lookback per timeframe", group = GRP_M, tooltip = "On: 15m 4, 30m 4, 1H 6, 90m 6, 4H 14, 6H 10, 1D 10 candles back (the 90m and 6H counts are this script's picks). Off: the Lookback below for every timeframe.")
int    smtLook  = input.int(3, "Lookback", minval = 1, maxval = 20, group = GRP_M, inline = "sk", active = not smtPerTf, tooltip = "How many candles back a reference may be.")
int    smtMaxDir = input.int(2, "Per side per scan", minval = 1, maxval = 5, group = GRP_M, inline = "sk", active = smtModeIn != "Clean", tooltip = "SMTs one timeframe may read per side on one candle. Clean reads one.")
int    smtKeep  = input.int(1, "Kept per side", minval = 1, maxval = 10, group = GRP_M, inline = "sp", tooltip = "SMTs held per timeframe and side. A SSMT keeps two.")
float  smtSpan  = input.float(2.5, "Balanced span multiple", minval = 1.25, maxval = 10.0, step = 0.25, group = GRP_M, inline = "sp", active = smtModeIn == "Balanced", tooltip = "Balanced keeps a older closed SMT beside the newest only when it spans at least this many times as long.")
bool   smtClose = input.bool(false, "Close back inside the reference", group = GRP_M, tooltip = "A SMT needs the chart to close back inside the reference candle's high (bearish) or low (bullish).")
float  smtRMin  = input.float(6.0, "TF ratio min", minval = 2.0, maxval = 60.0, group = GRP_M, inline = "sr", tooltip = "SMT timeframe ÷ chart timeframe. 6 to 100: 30m and up on a 5m chart, 15m to 90m on a 1m chart.")
float  smtRMax  = input.float(100.0, "max", minval = 6.0, maxval = 2000.0, group = GRP_M, inline = "sr")
 
color  C_UP    = input.color(#7246CE, "Bullish", group = GRP_S, inline = "dc", tooltip = "The sequence's hues: T-Spots and their EQ lines, PSP candles, FVGs and the sequence CISD. The default dark grey turns light grey on a dark chart.")
color  C_DN_IN = input.color(#4A4A4A, "Bearish", group = GRP_S, inline = "dc")
bool   dirCols = input.bool(false, "Direction colours on CISD", group = GRP_S, inline = "cx", tooltip = "Off: the CISD lines and names follow the chart ink. On: the two colours beside it.")
color  C_BULL  = input.color(#7246CE, "", group = GRP_S, inline = "cx")
color  C_BEAR_IN = input.color(#4A4A4A, "", group = GRP_S, inline = "cx")
color  K_REF_IN = input.color(#4A4A4A, "Dividers and midpoints", group = GRP_S, tooltip = "The HTF candle dividers and their names, candle midpoints and the origin lines.")
string lblSizeIn = input.string("normal", "Text scale", options = ["tiny", "small", "normal"], group = GRP_S, tooltip = "Every name and table on the chart, in points. tiny = Compact (one point smaller), small = Regular (7 for times and tags, 8 for names, 10 for headings), normal = Large (two points bigger).")
 
string GRP_C = "CISD"
bool   cOn       = input.bool(true, "Show CISD", group = GRP_C)
string cDirIn    = input.string("Both", "Direction", options = ["Both", "Bullish", "Bearish"], group = GRP_C)
string cWaitIn   = input.string("Standard", "Confirmation window", options = ["Standard", "Max"], group = GRP_C, tooltip = "How many chart candles after a run ends a close back through its level still counts. Standard 20, Max 40.")
bool   cSizeOn   = input.bool(true, "Size filter", group = GRP_C, inline = "sz")
string cSizeIn   = input.string("Medium", "", options = ["Tiny", "Small", "Medium", "Large", "Extra large"], group = GRP_C, inline = "sz", active = cSizeOn, tooltip = "Ignores a run whose origin candle, the run's extreme body, is smaller than this share of ATR(14): Tiny 0.05, Small 0.075, Medium 0.1, Large 0.25, Extra large 0.5.")
bool   cPotential = input.bool(false, "Draw pending CISD", group = GRP_C, tooltip = "The newest run on each side still waiting for its close, drawn dotted from its origin candle to the current candle. It goes when it confirms or its window runs out.")
bool   cKeepFail = input.bool(false, "Keep failed CISD", group = GRP_C, tooltip = "A confirmed CISD that price closes back through stays on the chart, dotted and faded, instead of being removed.")
string cExtend   = input.string("Confirm bar", "Extend to", options = ["Confirm bar", "Current bar", "Extend right"], group = GRP_C)
int    cOffset   = input.int(4, "Label offset (bars)", minval = 0, maxval = 50, group = GRP_C, tooltip = "With Current bar or Extend right, the CISD line runs this many bars past the live candle and its name sits at that end. With Confirm bar the line stops 6 bars past the confirming candle and its name sits there.")
int    cMaxKeep  = input.int(3, "Max kept per side", minval = 1, maxval = 50, group = GRP_C)
int    cWidth    = input.int(2, "Confirmed line width", minval = 1, maxval = 4, group = GRP_C, tooltip = "A PB (propulsion CISD) always draws at width 1.")
 
string GRP_F = "Deviations"
bool   cFibOn    = input.bool(true, "Show deviations", group = GRP_F, tooltip = "Standard deviation stubs: short dotted lines just left of the confirming candle, each a multiple of the run's range past the CISD level. One range = the CISD level to the run's far end.")
string cFibFrom  = input.string("Body", "Measured from", options = ["Body", "Wick"], group = GRP_F, active = cFibOn, tooltip = "Body: the CISD level to the run's furthest close. Wick: the CISD level to the run's furthest wick.")
bool   cFibNew   = input.bool(true, "Newest only", group = GRP_F, active = cFibOn, tooltip = "Only the most recent CISD keeps its stubs; a older one's are removed when a new one confirms. Off: each side keeps up to the number below.")
bool   cBigKeep  = input.bool(false, "Keep big blocks", group = GRP_F, inline = "big", active = cFibOn and cFibNew)
float  cBigPts   = input.float(40, "", minval = 1, step = 5, group = GRP_F, inline = "big", active = cFibOn and cFibNew and cBigKeep, tooltip = "With Newest only, a older CISD whose stubs reach at least this many points from its level keeps them for the hours below. The newest three such blocks are kept.")
int    cBigHrs   = input.int(4, "Keep big blocks for (hours)", minval = 1, maxval = 72, group = GRP_F, active = cFibOn and cFibNew and cBigKeep, tooltip = "A kept block's stubs leave once this many hours have passed since its CISD confirmed.")
int    cFibMax   = input.int(5, "Max per side", minval = 1, maxval = 10, group = GRP_F, active = cFibOn and not cFibNew)
bool   cOrigin   = input.bool(true, "0.5 of the run", group = GRP_F, inline = "co", tooltip = "A dashed line at the middle of the run's range, from the origin candle along the CISD line, in the colour beside it.")
color  CX_MID_COL = input.color(#7246CE, "", group = GRP_F, inline = "co")
bool   cZ1       = input.bool(true, "1.27", group = GRP_F, active = cFibOn)
bool   cZ2       = input.bool(true, "1.68 and 2.27", group = GRP_F, active = cFibOn)
bool   cZ3       = input.bool(true, "3 and 4", group = GRP_F, active = cFibOn)
int    cZoneT    = input.int(100, "Fill between 1.68 and 2.27", minval = 0, maxval = 100, group = GRP_F, active = cFibOn, tooltip = "Transparency of a fill between the 1.68 and 2.27 stubs. 100 draws no fill, lines only.")
 
string GRP_H = "Header"
bool   hTitleOn = input.bool(false, "Title", group = GRP_H, inline = "ht")
string hTitle   = input.string("PO3 Fractal Matrix+ by M1D", "", group = GRP_H, inline = "ht")
bool   hCardOn  = input.bool(true, "Symbol card", group = GRP_H, inline = "hc", tooltip = "Top right: the name above, the chart symbol, and the chart timeframe.")
string hBrand   = input.string("M1D", "", group = GRP_H, inline = "hc")
 
string GRP_K = "HTF candles"
bool   kOn      = input.bool(true, "Show HTF candles", group = GRP_K, tooltip = "One higher timeframe of candles beside live price, the one the fractal model runs on, with the time left on its forming candle. Auto takes the first of these with at least 12 chart candles to each of its candles: under 5m 15m · 1H · 4H, 5m to 14m 1H · 4H · 1D, 15m to 59m 4H · 1D · 1W, 1H and above 1D · 1W · 1M.")
bool   kAuto    = input.bool(true, "Auto timeframe", group = GRP_K)
string kTfA     = input.timeframe("D", "Timeframe", group = GRP_K, active = not kAuto)
int    kCount   = input.int(5, "Candles", minval = 1, maxval = 15, group = GRP_K)
int    kOffset  = input.int(10, "Bars right of price", minval = 1, maxval = 100, group = GRP_K)
int    kWidth   = input.int(3, "Candle width (bars)", minval = 1, maxval = 9, step = 2, group = GRP_K)
bool   kTimer   = input.bool(true, "Countdown", group = GRP_K)
bool   kPrevHL  = input.bool(true, "Previous high and low", group = GRP_K, tooltip = "A line from the previous candle at its high and low, running right past the block and named there: PDH and PDL, PWH and PWL, PMH and PML, and 4H H and 4H L below a day.")
bool   kChartPD = input.bool(true, "PDH and PDL on the chart", group = GRP_K, tooltip = "The previous day's high and low across the live chart, from the candle that made each one, named at the right. Solid while open, dotted once price has traded through. Not drawn while a daily block is showing its own PDH and PDL, so one price never carries two names. Intraday charts only.")
bool   kPrevQ   = input.bool(true, "Previous range 25 / 50 / 75", group = GRP_K, tooltip = "On the daily, weekly and monthly blocks only: lines across the block at a quarter, half and three quarters of the previous candle's range, measured up from its low, named at the right, e.g. D 25%. Drawn in black.")
bool   kMid     = input.bool(true, "Candle midpoints", group = GRP_K, tooltip = "A short dotted line across each candle at the middle of its high-to-low range.")
bool   kSweep   = input.bool(true, "Sweeps", group = GRP_K, tooltip = "A solid line at the prior candle's high or low when a closed candle wicks through it and closes back inside. The candle still forming is not marked until it closes.")
bool   kHlTimes = input.bool(true, "High and low times", group = GRP_K, tooltip = "The New York open time of the candle that made each block's high and low, above the high and below the low. On a daily or higher chart, its date.")
bool   kOrigin  = input.bool(false, "Origin lines", group = GRP_K, tooltip = "Dashed lines from the chart candles that made the forming HTF candle's high and low across to that candle on the block.")
bool   kOpenEq  = input.bool(true, "Open and previous EQ", group = GRP_K, tooltip = "The forming HTF candle's open, dotted, and the previous candle's EQ (the middle of its high and low), from where each formed to the block. The EQ is solid while every chart close since the open sits on the side the candle opened, dotted once one closes across it.")
color  K_BULL_BODY = input.color(#FFFFFF, "Up", group = GRP_K, inline = "kc")
color  K_BEAR_BODY = input.color(#505050, "Down", group = GRP_K, inline = "kc")
color  kInkIn      = input.color(#000000, "Wick and outline", group = GRP_K, inline = "kc", tooltip = "The HTF candle bodies and their wicks and outlines. Black wicks turn white on a dark chart.")
string kBadge   = input.string("Top", "Name and countdown", options = ["Top", "Bottom"], group = GRP_K, tooltip = "The block's timeframe is named above and below it; this picks the side that carries the countdown. The block the fractal model runs on is marked with a circle.")
 
string GRP_P3 = "Fractal model"
bool   p3On      = input.bool(true, "Show fractal model", group = GRP_P3, tooltip = "C1, C2, C3 and C4 on one HTF candle timeframe: the first of the three with at least 12 chart candles to each of its candles. C2 closure: C2 trades through one side of C1, wherever it opens, and closes back inside C1's body. A doji C1 (body under a tenth of its range) gives way to the candle before it; two dojis in a row and the C2 is skipped. C3 closure: C2 closed beyond that side, then C3 closed through C2's body. A C2 or C3 still forming is tagged C2? or C3? and alerts wait for its close. The swing holds until a later candle trades through C2's extreme. One sequence draws on the chart at a time: the newest that passes the T-Spot filter.")
bool   p3C3On    = input.bool(true, "C3 closures", group = GRP_P3, tooltip = "Sequences where C2 did not reverse and C3 closed through C2's body instead. Off: C2 closures only.")
string p3DirIn   = input.string("Both", "Sequence direction", options = ["Both", "Bullish only", "Bearish only"], group = GRP_P3)
string p3GateIn  = input.string("Wait for xC2", "C2 through both sides", options = ["Wait for xC2", "Immediate"], group = GRP_P3, tooltip = "xC2 is a C2 that traded through both sides of C1. Wait: only the side that survives once price trades through one of C2's extremes draws. Immediate: both draw.")
string p3TagsIn  = input.string("C1/C2/C3/C4", "Tags on HTF candles", options = ["Off", "C1/C2/C3", "C1/C2/C3/C4"], group = GRP_P3)
bool   p3Sweep   = input.bool(true, "C1 sweep line", group = GRP_P3, tooltip = "C1's high or low that C2 traded through: on the HTF candles, and on the chart from the bar that made it to C3's open.")
bool   p3ChartTags = input.bool(true, "Sequence tags on the chart", group = GRP_P3, tooltip = "C1, C2, C3 and C4 at the extremes that made them, on the sequence's side: above the highs for a bearish sequence, below the lows for a bullish one. C2 reads PSP when its candle closed the other way to a correlated asset.")
bool   p3SeqCx   = input.bool(true, "Sequence CISD", group = GRP_P3, tooltip = "The CISD that confirmed the sequence after C2's extreme: a close back through the open where the opposing run of candles began. Drawn from that open to the confirming candle, in the sequence's colour. Not drawn when a CISD line already sits on that price.")
bool   p3Spot    = input.bool(true, "T-Spot", group = GRP_P3, inline = "ts")
string p3SpotIn  = input.string("Medium", "", options = ["Open", "Easy", "Medium", "Hard", "Max"], group = GRP_P3, inline = "ts", tooltip = "Which sequence draws. Open: any. Easy: a CISD after C2's extreme, or a SMT in the sequence direction during C2 on a timeframe at or below the profile's (the SMT group; needs Show SMT on). Medium: both. Hard: both, and C2 is a PSP. Max: Hard, C2 closes past C1's midpoint, C2 runs C1 by at least a tenth of C1's range, and C2 did not trade through both sides. Easy and up remove a T-Spot once it is spent: in EQ mode when its own HTF candle closes through the EQ, in Depth % on any chart close through its far side. The CISD read is this script's own, so a filter that needs one needs Show CISD on.")
string p3ZoneIn  = input.string("EQ", "T-Spot measured", options = ["EQ", "Depth %"], group = GRP_P3, tooltip = "EQ: the half of the candle where the next one should form its wick. C2 closing against its swing is measured close to wick, closing with it on its full range; C3 on its full range, and only after a strong closure beyond C2. In EQ mode a T-Spot is spent only when its own candle closes through the EQ. Depth %: from the close back into the candle by the shares below; spent on any chart close through it.")
float  p3D3      = input.float(50.0, "Depth C3 %", minval = 5.0, maxval = 100.0, group = GRP_P3, inline = "td", active = p3ZoneIn == "Depth %", tooltip = "C3's T-Spot runs from C2's close back into C2's range by this share of it. C4's runs from C3's close back into C3's range by the second share.")
float  p3D4      = input.float(25.0, "C4 %", minval = 5.0, maxval = 100.0, group = GRP_P3, inline = "td", active = p3ZoneIn == "Depth %")
bool   p3Keep3   = input.bool(true, "Keep C3 T-Spot during C4", group = GRP_P3)
bool   p3SpotEq  = input.bool(true, "T-Spot EQ line", group = GRP_P3, inline = "teq", tooltip = "The T-Spot's edge nearest the swing, as a solid line: the price the next candle's wick should hold.")
bool   p3SpotK   = input.bool(true, "On the HTF candles", group = GRP_P3, inline = "teq", tooltip = "The live T-Spot drawn across its candle on the HTF block too.")
bool   p3XOn     = input.bool(true, "Failed T-Spot marks", group = GRP_P3, inline = "xo", tooltip = "Once a T-Spot is spent, a dotted line stays at its EQ named XC3 or XC4, in place of the zone.")
color  P3_XC3_IN = input.color(#4A4A4A, "XC3", group = GRP_P3, inline = "xo")
color  P3_XC4_IN = input.color(#4A4A4A, "XC4", group = GRP_P3, inline = "xo")
bool   p3DivOn   = input.bool(true, "HTF candle dividers", group = GRP_P3, inline = "dv", tooltip = "A dotted vertical line where each candle of the fractal timeframe opens, as many as the HTF candles shown. Every line runs from the highest high to the lowest low of those candles. Names: the day for a daily profile, the date for weekly and monthly, the New York open time below a day, centred above each line.")
bool   p3DivLbl  = input.bool(true, "Names", group = GRP_P3, inline = "dv")
int    p3Fill    = input.int(88, "T-Spot fill transparency", minval = 0, maxval = 100, group = GRP_P3)
bool   p3Psp     = input.bool(true, "PSP candles", group = GRP_P3, tooltip = "A HTF candle that traded through the high or low of the candle before it and closed the other way to a correlated asset fills in its own direction's colour.")
bool   p3PspAll  = input.bool(false, "Every asset must disagree", group = GRP_P3, active = p3Psp, tooltip = "A PSP needs every correlated asset to close the other way, not just one. Also governs PSP on C2.")
bool   hFvgOn    = input.bool(true, "HTF FVGs", group = GRP_P3, inline = "hfvg", tooltip = "Fair value gaps on the HTF candle timeframe, read once each of its candles closes, drawn from the candle that left the gap with a dotted midline. Each stays until a chart candle closes through its far side. The number is how many of the newest stay drawn.")
int    hFvgMax   = input.int(3, "", minval = 1, maxval = 30, group = GRP_P3, inline = "hfvg")
bool   p3Stdv    = input.bool(false, "STDV in sequence", group = GRP_P3, inline = "sd", tooltip = "Levels off the sequence CISD, one range = the CISD level to C2's extreme. The pairs are shaded: -2 to -2.5 and -4 to -4.5 by default.")
string p3StdvIn  = input.string("-2, -2.5, -4, -4.5", "", group = GRP_P3, inline = "sd", active = p3Stdv)
color  P3_STDV  = input.color(#7246CE, "STDV colour", group = GRP_P3, active = p3Stdv)
bool   p3List    = input.bool(true, "Checklist", group = GRP_P3, inline = "cl", tooltip = "The profile timeframe, the phase, and whether C2 closed, the CISD, the SMT and the PSP are in.")
string p3ListAt  = input.string("Bottom center", "", options = ["Bottom center", "Bottom right", "Middle left", "Middle right", "Bottom left", "Top left"], group = GRP_P3, inline = "cl")
 
//@function The default dark grey turns light grey on a dark chart; any other colour is used as set.
//@param c (color) The set colour.
//@returns (color) The colour to draw.
f_mute(color c) =>
    DARK and c == #4A4A4A ? #B2B5BE : c
color C_DN   = f_mute(C_DN_IN)
color C_BEAR = f_mute(C_BEAR_IN)
color K_REF  = f_mute(K_REF_IN)
color P3_XC3 = f_mute(P3_XC3_IN)
color P3_XC4 = f_mute(P3_XC4_IN)
 
// Text in points: meta 7, body 8, head 10, moved together by the Text scale input.
int TXT_ADJ = lblSizeIn == "tiny" ? -1 : lblSizeIn == "normal" ? 2 : 0
int SZ_META = 7 + TXT_ADJ
int SZ_BODY = 8 + TXT_ADJ
int SZ_HEAD = 10 + TXT_ADJ
 
string layoutIn = input.string("Desktop", "Layout", options = ["Desktop", "Phone"], group = GRP_P3, tooltip = "Phone: the table in tiny text with its main rows only, for a narrow portrait screen. Nothing else on the chart changes.")
bool   phone    = layoutIn == "Phone"
int    TBL_SZ = phone ? SZ_META : SZ_BODY
 
bool   hStripOn = input.bool(true, "Header strip", group = GRP_H, tooltip = "Top centre: the chart timeframe and the HTF candle timeframe the model runs on, the phase of the sequence on the chart in teal, and the assets read with the chart symbol. Off on the Phone layout and while the Title is on.")
bool   smtK     = input.bool(true, "SMT on the HTF candles", group = GRP_M, tooltip = "C2 against C1 on the HTF candle timeframe (the block's: 1H, 4H, 1D, 1W...), read from each asset's own candles on that timeframe, so the TF ratio does not limit it: the chart symbol's C2 takes C1's high (low) and a asset's C2 does not. Tags C2+SMT, draws C1 to C2 on the block and on the chart named with the asset, and counts as a SMT for the T-Spot filter and the checklist once C2 has closed.")
bool   spOn     = input.bool(true, "Spacious view", group = GRP_S, tooltip = "Less on the chart: the checklist drops the rows the header strip already shows (instrument, timeframe, assets), the dividers keep their day name but lose the time under each foot (the time axis has it), and the SMT asset goes into the C2 tag instead of a second label, with C1's tag left off when it sits on C2's candle. Off: the full view.")
 
// Resolved once: timeframe.in_seconds() takes a simple string.
int CHART_SEC = timeframe.in_seconds()
 
// == ASSETS ==
// Up to four correlated assets, each read on the chart timeframe and folded into the candles beside the
// chart symbol's own. A inverse asset agrees with the chart when it moves the other way.
 
//@function The correlated assets for the chart symbol, from the table below: three symbols and which of
//          them read inverse. Each row is the symbols for Triad and Tetrad, the second symbol Triad (GXT)
//          uses instead, and a inverse flag per symbol. CME micro bitcoin and ether pair with each other;
//          spot BTC and ETH pair with each other, SOL and BNB on the same exchange.
//@returns (tuple) Three symbols (empty when not listed) and whether each reads inverse.
f_aAuto() =>
    string r   = syminfo.root
    string row = switch r
        "NQ"     => "CME_MINI:MES1! CBOT_MINI:MYM1! CME_MINI:M2K1! CME_MINI:M2K1! 000"
        "MNQ"    => "CME_MINI:MES1! CBOT_MINI:MYM1! CME_MINI:M2K1! CME_MINI:M2K1! 000"
        "ES"     => "CME_MINI:MNQ1! CBOT_MINI:MYM1! CME_MINI:M2K1! CME_MINI:M2K1! 000"
        "MES"    => "CME_MINI:MNQ1! CBOT_MINI:MYM1! CME_MINI:M2K1! CME_MINI:M2K1! 000"
        "YM"     => "CME_MINI:MES1! CME_MINI:MNQ1! CME_MINI:M2K1! CME_MINI:M2K1! 000"
        "MYM"    => "CME_MINI:MES1! CME_MINI:MNQ1! CME_MINI:M2K1! CME_MINI:M2K1! 000"
        "RTY"    => "CME_MINI:MES1! CME_MINI:MNQ1! CBOT_MINI:MYM1! CME_MINI:MNQ1! 000"
        "M2K"    => "CME_MINI:MES1! CME_MINI:MNQ1! CBOT_MINI:MYM1! CME_MINI:MNQ1! 000"
        "GC"     => "COMEX:SIL1! OANDA:XAUEUR OANDA:XAUGBP OANDA:XAUGBP 000"
        "MGC"    => "COMEX:SIL1! OANDA:XAUEUR OANDA:XAUGBP OANDA:XAUGBP 000"
        "XAUUSD" => "COMEX:SIL1! OANDA:XAUEUR OANDA:XAUGBP OANDA:XAUGBP 000"
        "SI"     => "COMEX:MGC1! COMEX:HG1! NYMEX:PL1! COMEX:HG1! 000"
        "SIL"    => "COMEX:MGC1! COMEX:HG1! NYMEX:PL1! COMEX:HG1! 000"
        "XAGUSD" => "COMEX:MGC1! COMEX:HG1! NYMEX:PL1! COMEX:HG1! 000"
        "HG"     => "COMEX:MGC1! COMEX:SIL1! NYMEX:PL1! COMEX:SIL1! 000"
        "CL"     => "NYMEX:RB1! NYMEX:HO1! ICEEUR:BRN1! NYMEX:HO1! 000"
        "MCL"    => "NYMEX:RB1! NYMEX:HO1! ICEEUR:BRN1! NYMEX:HO1! 000"
        "RB"     => "NYMEX:MCL1! NYMEX:HO1! ICEEUR:BRN1! NYMEX:HO1! 000"
        "HO"     => "NYMEX:MCL1! NYMEX:RB1! ICEEUR:BRN1! NYMEX:RB1! 000"
        "ZB"     => "CBOT:ZN1! CBOT:ZF1! CBOT:ZT1! CBOT:ZF1! 000"
        "UB"     => "CBOT:ZN1! CBOT:ZF1! CBOT:ZT1! CBOT:ZF1! 000"
        "ZN"     => "CBOT:ZB1! CBOT:ZF1! CBOT:ZT1! CBOT:ZF1! 000"
        "ZF"     => "CBOT:ZN1! CBOT:ZB1! CBOT:ZT1! CBOT:ZB1! 000"
        "EURUSD" => "OANDA:GBPUSD TVC:DXY OANDA:USDCHF TVC:DXY 011"
        "GBPUSD" => "OANDA:EURUSD TVC:DXY OANDA:USDCHF TVC:DXY 011"
        "AUDUSD" => "OANDA:NZDUSD TVC:DXY OANDA:EURUSD TVC:DXY 010"
        "NZDUSD" => "OANDA:AUDUSD TVC:DXY OANDA:GBPUSD TVC:DXY 010"
        "USDJPY" => "OANDA:USDCHF TVC:DXY OANDA:USDCAD TVC:DXY 000"
        "USDCHF" => "OANDA:USDJPY TVC:DXY OANDA:USDCAD TVC:DXY 000"
        "USDCAD" => "OANDA:USDJPY TVC:DXY OANDA:USDCHF TVC:DXY 000"
        "DXY"    => "OANDA:EURUSD OANDA:GBPUSD OANDA:USDJPY OANDA:GBPUSD 110"
        "MBT"    => "CME:MET1! - - - 000"
        "MET"    => "CME:MBT1! - - - 000"
        => ""
    if row == "" and syminfo.type == "crypto" and (syminfo.basecurrency == "BTC" or syminfo.basecurrency == "ETH")
        string ex = syminfo.prefix + ":"
        string q  = syminfo.currency
        row := ex + (syminfo.basecurrency == "BTC" ? "ETH" : "BTC") + q + " " + ex + "SOL" + q + " " + ex + "BNB" + q + " " + ex + "SOL" + q + " 000"
    string a  = ""
    string b  = ""
    string c  = ""
    string fl = "000"
    if row != ""
        array<string> f = str.split(row, " ")
        a  := f.get(0)
        b  := aDivIn == "Triad (GXT)" ? f.get(3) : f.get(1)
        c  := f.get(2)
        fl := f.get(4)
    a := a == "-" ? "" : a
    b := b == "-" ? "" : b
    c := c == "-" ? "" : c
    [a, b, c, str.substring(fl, 0, 1) == "1", str.substring(fl, 1, 2) == "1", str.substring(fl, 2, 3) == "1"]
 
[aAutoA, aAutoB, aAutoC, aAutoIA, aAutoIB, aAutoIC] = f_aAuto()
bool   aAutoHit = aModeIn == "Auto" and aAutoA != ""
int    aAutoCnt = aDivIn == "Dyad" ? 1 : aDivIn == "Tetrad" ? 3 : 2
string aS1 = aAutoHit ? aAutoA : aSym1
string aS2 = aAutoHit ? aAutoB : aSym2
string aS3 = aAutoHit ? aAutoC : aSym3
string aS4 = aSym4
bool   aI1 = aAutoHit ? aAutoIA : aInv1
bool   aI2 = aAutoHit ? aAutoIB : aInv2
bool   aI3 = aAutoHit ? aAutoIC : aInv3
bool   aI4 = aInv4
// The assets feed the SMT read and PSP only: with both off, none is read (a request runs whether its
// result is read or not).
bool   aNeed = smtOn or p3On
bool   aUse1 = aNeed and (aAutoHit ? aAutoCnt >= 1 : aOn1) and str.length(aS1) > 0
bool   aUse2 = aNeed and (aAutoHit ? aAutoCnt >= 2 : aOn2) and str.length(aS2) > 0
bool   aUse3 = aNeed and (aAutoHit ? aAutoCnt >= 3 : aOn3) and str.length(aS3) > 0
bool   aUse4 = aNeed and aOn4 and str.length(aS4) > 0
 
//@function A asset's ticker, back-adjusted like the chart's continuous contract.
//@returns (string) The ticker id.
f_aTicker(string sym) =>
    ticker.modify(ticker.inherit(syminfo.tickerid, sym), backadjustment = backadjustment.on)
 
//@function One asset on the chart timeframe, with its bar times so a bar is only used when it lines up.
//@returns (tuple) Open time, close time, open, high, low, close.
f_aRead(string tkr) =>
    request.security(tkr, timeframe.period, [time, time_close, open, high, low, close], gaps = barmerge.gaps_on, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
 
// A request runs whether its result is read or not, so a asset that is off reads the chart symbol.
[a1T, a1Tc, a1O, a1H, a1L, a1C] = f_aRead(aUse1 ? f_aTicker(aS1) : syminfo.tickerid)
[a2T, a2Tc, a2O, a2H, a2L, a2C] = f_aRead(aUse2 ? f_aTicker(aS2) : syminfo.tickerid)
[a3T, a3Tc, a3O, a3H, a3L, a3C] = f_aRead(aUse3 ? f_aTicker(aS3) : syminfo.tickerid)
[a4T, a4Tc, a4O, a4H, a4L, a4C] = f_aRead(aUse4 ? f_aTicker(aS4) : syminfo.tickerid)
 
//@function A asset's short name for labels: the root with the exchange and contract month taken off,
//          a micro contract named as its full-size one. CME_MINI:MES1! reads es, TVC:DXY dxy.
//@returns (string) The name.
f_aLogo(string s) =>
    array<string> parts = str.split(s, ":")
    string root = str.upper(parts.size() > 0 ? parts.last() : s)
    root := str.replace_all(str.replace_all(root, "1!", ""), "2!", "")
    string full = switch root
        "MES" => "ES"
        "MNQ" => "NQ"
        "MYM" => "YM"
        "M2K" => "RTY"
        "MGC" => "GC"
        "SIL" => "SI"
        "MCL" => "CL"
        => root
    str.lower(full)
 
// A correlated asset's side of a candle: its own open, high, low and close, once it has printed inside it.
type Peer
    float o    = na
    float h    = na
    float l    = na
    float c    = na
    bool  seen = false
 
//@function This bar of one asset, empty when it is off or its bar does not line up with the chart's.
//@returns (Peer) The sample.
f_peer(bool use, int t, int tc, float o, float h, float l, float c) =>
    bool ok = use and t == time and tc == time_close and not na(o) and not na(h) and not na(l) and not na(c)
    ok ? Peer.new(o = o, h = h, l = l, c = c, seen = true) : Peer.new()
 
array<Peer> p3Now = array.from(f_peer(aUse1, a1T, a1Tc, a1O, a1H, a1L, a1C), f_peer(aUse2, a2T, a2Tc, a2O, a2H, a2L, a2C), f_peer(aUse3, a3T, a3Tc, a3O, a3H, a3L, a3C), f_peer(aUse4, a4T, a4Tc, a4O, a4H, a4L, a4C))
var array<bool>   p3AOn   = array.from(aUse1, aUse2, aUse3, aUse4)
var array<bool>   p3AInv  = array.from(aI1, aI2, aI3, aI4)
var array<string> p3ALogo = array.from(f_aLogo(aS1), f_aLogo(aS2), f_aLogo(aS3), f_aLogo(aS4))
 
//@function The assets in use, for the table: ES · YM · DXY inverse.
//@returns (string) The list, or none.
f_aList() =>
    string s = ""
    for k = 0 to 3
        if p3AOn.get(k)
            s := s + (s == "" ? "" : " · ") + str.upper(p3ALogo.get(k)) + (p3AInv.get(k) ? " inverse" : "")
    s == "" ? "none" : s
 
// == CISD ==
// The CISD Order Block+ (M1D) reading, drawn lines only. A run is every consecutive candle of one colour
// into a swing; its origin is the run's extreme body. When the run ends, a later close back through the
// origin's body edge, inside the window, is the CISD. That edge is the CISD level. Drawn as one line at
// the level with its name, plus standard deviation stubs of the run's range. Read on the chart's own
// candles, on closed candles only.
const int CX_MIN_RUN  = 1
const int CX_MAX_RUN  = 30
const int CX_MIN_WIN  = 1
const int CX_MIN_GAP  = 5
const int CX_EXT_BARS = 6
const int CX_STUB_LEN = 2
const int CX_STUB_OFF = -2
const int CX_KEEP_MAX = 3
const int CX_PEND_MAX = 20
 
//@type A CISD run, pending or confirmed.
//@field bull     True for a bullish CISD (a down run reclaimed).
//@field lvl      The origin candle's body edge: the CISD level.
//@field far      The run's far close: one standard deviation unit measured on the bodies.
//@field wick     The run's far wick: the unit measured on the wicks.
//@field oTime    Bar time of the origin candle.
//@field oBar     bar_index of the origin candle.
//@field endBar   bar_index of the run's last candle.
//@field xBar     bar_index of the run's far wick.
//@field prop     True for a propulsion CISD (PB): its run traded back into a earlier live one of the same direction.
//@field okTime   Bar time of the confirming close.
//@field okBar    bar_index of the confirming close.
//@field dead     True once a close has gone back through the level and the line is kept faded.
//@field ln       The CISD line.
//@field lb       Its name.
//@field mid      The run's 0.5, when drawn.
//@field sdL      Standard deviation stubs.
//@field sdB      Their names.
//@field sdZ      The fill between the 2 and 2.5 stubs.
//@field span     Price distance from the level to the furthest stub.
//@field kept     True while its stubs stay on as a big block.
type CisdRun
    bool  bull
    float lvl
    float far
    float wick
    int   oTime
    int   oBar
    int   endBar
    int   xBar   = na
    bool  prop   = false
    int   okTime = na
    int   okBar  = na
    bool  dead   = false
    line  ln     = na
    label lb     = na
    line  mid    = na
    array<line>  sdL = na
    array<label> sdB = na
    array<box>   sdZ = na
    float span   = na
    bool  kept   = false
 
var array<CisdRun> cxBullPend = array.new<CisdRun>()
var array<CisdRun> cxBearPend = array.new<CisdRun>()
var array<CisdRun> cxDone     = array.new<CisdRun>()
// Older sets whose stubs stay on as a big block.
var array<CisdRun> cxKept     = array.new<CisdRun>()
 
bool  cxBull   = cDirIn != "Bearish"
bool  cxBear   = cDirIn != "Bullish"
int   cxMaxWin = cWaitIn == "Max" ? 40 : 20
float cxMinBody = not cSizeOn ? 0.0 : cSizeIn == "Tiny" ? 0.05 : cSizeIn == "Small" ? 0.075 : cSizeIn == "Large" ? 0.25 : cSizeIn == "Extra large" ? 0.5 : 0.10
float cxAtr    = ta.atr(14)
int   cxMs     = CHART_SEC * 1000
// The two stubs the fill sits between.
float CX_FILL_LO = 1.68
float CX_FILL_HI = 2.27
array<float> cxMults = array.new<float>()
if cZ1
    cxMults.push(1.27)
if cZ2
    cxMults.push(CX_FILL_LO)
    cxMults.push(CX_FILL_HI)
if cZ3
    cxMults.push(3.0)
    cxMults.push(4.0)
 
// Bar-time drawings reach up to 4900 bars back.
max_bars_back(time, 5000)
 
// The runs in progress: length, the extreme body's edges, its time and bar, the far close, the far wick,
// the far wick's bar, and the wick of the candle before the run.
var int   cxDnLoB = 0
var int   cxUpHiB = 0
var int   cxDnRun = 0
var float cxDnTop = na
var float cxDnBot = na
var int   cxDnT   = 0
var int   cxDnB   = 0
var float cxDnFar = na
var float cxDnLo  = na
var float cxDnPre = na
var int   cxUpRun = 0
var float cxUpBot = na
var float cxUpTop = na
var int   cxUpT   = 0
var int   cxUpB   = 0
var float cxUpFar = na
var float cxUpHi  = na
var float cxUpPre = na
var int   cxLastBull = -1
var int   cxLastBear = -1
var line  cxPotBullLn = na
var label cxPotBullLb = na
var line  cxPotBearLn = na
var label cxPotBearLb = na
 
//@function The colour a CISD draws in.
//@param bull (bool) Direction.
//@returns (color) The colour.
f_cxCol(bool bull) =>
    dirCols ? (bull ? C_BULL : C_BEAR) : INK
 
//@function A CISD's name at the right end of its line.
//@param x (int) Bar time.
//@param px (float) Price.
//@param txt (string) Text.
//@param bold (bool) Bold for a confirmed CISD.
//@returns (label) The label.
f_cxLabel(int x, float px, string txt, bool bold) =>
    label lb = label.new(x, px, txt, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(#FFFFFF, 100), textcolor = INK, size = SZ_BODY, text_formatting = bold ? text.format_bold : text.format_none)
    label.set_text_font_family(lb, font.family_monospace)
    lb
 
//@function Removes a CISD's standard deviation stubs.
//@param r (CisdRun) The CISD.
//@returns (bool) Always true.
f_cxSdKill(CisdRun r) =>
    if not na(r.sdL)
        for l in r.sdL
            line.delete(l)
        for b in r.sdB
            label.delete(b)
        for z in r.sdZ
            box.delete(z)
        r.sdL := na
        r.sdB := na
        r.sdZ := na
    true
 
//@function Removes all of a CISD's drawings.
//@param r (CisdRun) The CISD.
//@returns (bool) Always true.
f_cxDrop(CisdRun r) =>
    line.delete(r.ln)
    label.delete(r.lb)
    line.delete(r.mid)
    f_cxSdKill(r)
 
//@function Draws a CISD's standard deviation stubs: short dotted lines just left of the confirming candle,
//          each a multiple of the run's range past the CISD level, named at their left end.
//@param r (CisdRun) The confirmed CISD.
//@returns (bool) Always true.
f_cxSd(CisdRun r) =>
    float unit = math.abs(r.lvl - (cFibFrom == "Wick" ? r.wick : r.far))
    if unit > 0 and cxMults.size() > 0
        color col = f_cxCol(r.bull)
        int   x1  = r.okTime + CX_STUB_OFF * cxMs
        int   x2  = x1 + CX_STUB_LEN * cxMs
        r.sdL := array.new<line>()
        r.sdB := array.new<label>()
        r.sdZ := array.new<box>()
        for m in cxMults
            float px = r.bull ? r.lvl + unit * m : r.lvl - unit * m
            r.sdL.push(line.new(x1, px, x2, px, xloc = xloc.bar_time, color = col, style = line.style_dotted, width = 1))
            label lb = label.new(x1, px, str.tostring(m), xloc = xloc.bar_time, style = label.style_label_right, color = color.new(#FFFFFF, 100), textcolor = INK, size = SZ_META, textalign = text.align_right)
            label.set_text_font_family(lb, font.family_monospace)
            r.sdB.push(lb)
        if cZ2 and cZoneT < 100
            float a = r.bull ? r.lvl + unit * CX_FILL_LO : r.lvl - unit * CX_FILL_LO
            float b = r.bull ? r.lvl + unit * CX_FILL_HI : r.lvl - unit * CX_FILL_HI
            r.sdZ.push(box.new(x1, math.max(a, b), x2, math.min(a, b), xloc = xloc.bar_time, bgcolor = color.new(col, cZoneT), border_color = color.new(col, 100), border_width = 0))
        r.span := unit * cxMults.max()
    true
 
//@function Whether a older set's stubs stay on as a big block beside the newest.
//@param r (CisdRun) The older set.
//@returns (bool) True to keep its stubs.
f_cxBig(CisdRun r) =>
    cBigKeep and not na(r.sdL) and not na(r.span) and r.span >= cBigPts and time - r.okTime < cBigHrs * 3600000
 
//@function Whether a CISD's run traded back into a earlier live CISD of the same direction, between that
//          one's level and its run's far wick, within the confirmation window of it confirming.
//@param r (CisdRun) The candidate that just confirmed.
//@returns (bool) True for a propulsion CISD.
f_cxProp(CisdRun r) =>
    bool prop = false
    for c in cxDone
        int age = r.xBar - c.okBar
        if not c.dead and c.bull == r.bull and age >= 0 and age <= cxMaxWin
            if r.wick >= math.min(c.lvl, c.wick) and r.wick <= math.max(c.lvl, c.wick)
                prop := true
                break
    prop
 
//@function Draws a confirmed CISD and banks it.
//@param r (CisdRun) The candidate that just confirmed.
//@returns (bool) Always true.
f_cxConfirm(CisdRun r) =>
    r.okTime := time
    r.okBar  := bar_index
    r.prop   := f_cxProp(r)
    // A set landing on a live one at the same price is the same level found again: it replaces it.
    if cxDone.size() > 0
        for i = cxDone.size() - 1 to 0
            CisdRun o = cxDone.get(i)
            if math.abs(o.lvl - r.lvl) <= syminfo.mintick
                f_cxDrop(o)
                cxDone.remove(i)
    color col  = f_cxCol(r.bull)
    bool  atOk = cExtend == "Confirm bar"
    int   endT = atOk ? time + CX_EXT_BARS * cxMs : time + cOffset * cxMs
    r.ln := line.new(r.oTime, r.lvl, endT, r.lvl, xloc = xloc.bar_time, color = col, style = line.style_solid, width = r.prop ? 1 : cWidth)
    r.lb := f_cxLabel(endT, r.lvl, r.prop ? "PB" : "CISD", true)
    if cOrigin
        float farPx = cFibFrom == "Wick" ? r.wick : r.far
        r.mid := line.new(r.oTime, math.avg(r.lvl, farPx), endT, math.avg(r.lvl, farPx), xloc = xloc.bar_time, color = CX_MID_COL, style = line.style_dashed, width = 1)
    // A PB draws no standard deviations.
    if cFibOn and not r.prop
        if cFibNew
            // Newest only: every other set's stubs go, unless it is a big block still inside its hours.
            for o in cxDone
                if f_cxBig(o)
                    if not o.kept
                        o.kept := true
                        cxKept.push(o)
                else
                    f_cxSdKill(o)
            while cxKept.size() > CX_KEEP_MAX
                CisdRun k = cxKept.shift()
                k.kept := false
                f_cxSdKill(k)
        f_cxSd(r)
        if not cFibNew and cxDone.size() > 0
            // Each side keeps stubs on its newest sets only.
            int n = 0
            for i = cxDone.size() - 1 to 0
                CisdRun o = cxDone.get(i)
                if o.bull == r.bull and not na(o.sdL)
                    n += 1
                    if n >= cFibMax
                        f_cxSdKill(o)
    cxDone.push(r)
    // Each side keeps its newest sets.
    int kept = 0
    for i = cxDone.size() - 1 to 0
        CisdRun o = cxDone.get(i)
        if o.bull == r.bull
            kept += 1
            if kept > cMaxKeep
                f_cxDrop(o)
                cxDone.remove(i)
    true
 
if cOn and barstate.isconfirmed
    bool isDown = close < open
    bool isUp   = close > open
 
    // Runs. The origin is the run's extreme body, not simply its first candle: on a gap or a outside bar a
    // later candle can carry the higher body top, and that is the level whose reclaim reverses delivery.
    if isDown
        if cxDnRun == 0
            cxDnTop := open
            cxDnBot := close
            cxDnT   := time
            cxDnB   := bar_index
            cxDnFar := close
            cxDnLo  := low
            cxDnLoB := bar_index
            cxDnPre := low[1]
        else if low < cxDnLo
            cxDnLo  := low
            cxDnLoB := bar_index
        if cxDnRun > 0 and (open > cxDnTop or (open == cxDnTop and open - close > cxDnTop - cxDnBot))
            cxDnTop := open
            cxDnBot := close
            cxDnT   := time
            cxDnB   := bar_index
        cxDnFar := math.min(cxDnFar, close)
        cxDnRun += 1
    else
        bool big   = na(cxAtr) or cxMinBody <= 0 or math.abs(cxDnTop - cxDnBot) >= cxMinBody * cxAtr
        // The run must go somewhere: its low under the candle before it.
        bool swing = cxDnRun > 0 and (na(cxDnPre) or cxDnLo < cxDnPre)
        if cxBull and cxDnRun >= CX_MIN_RUN and cxDnRun <= CX_MAX_RUN and big and swing
            cxBullPend.push(CisdRun.new(bull = true, lvl = cxDnTop, far = cxDnFar, wick = cxDnLo, oTime = cxDnT, oBar = cxDnB, endBar = bar_index - 1, xBar = cxDnLoB))
        cxDnRun := 0
 
    if isUp
        if cxUpRun == 0
            cxUpBot := open
            cxUpTop := close
            cxUpT   := time
            cxUpB   := bar_index
            cxUpFar := close
            cxUpHi  := high
            cxUpHiB := bar_index
            cxUpPre := high[1]
        else if high > cxUpHi
            cxUpHi  := high
            cxUpHiB := bar_index
        if cxUpRun > 0 and (open < cxUpBot or (open == cxUpBot and close - open > cxUpTop - cxUpBot))
            cxUpBot := open
            cxUpTop := close
            cxUpT   := time
            cxUpB   := bar_index
        cxUpFar := math.max(cxUpFar, close)
        cxUpRun += 1
    else
        bool big   = na(cxAtr) or cxMinBody <= 0 or math.abs(cxUpTop - cxUpBot) >= cxMinBody * cxAtr
        bool swing = cxUpRun > 0 and (na(cxUpPre) or cxUpHi > cxUpPre)
        if cxBear and cxUpRun >= CX_MIN_RUN and cxUpRun <= CX_MAX_RUN and big and swing
            cxBearPend.push(CisdRun.new(bull = false, lvl = cxUpBot, far = cxUpFar, wick = cxUpHi, oTime = cxUpT, oBar = cxUpB, endBar = bar_index - 1, xBar = cxUpHiB))
        cxUpRun := 0
 
    // Bullish reclaim: of the pending runs a close has gone back above, the one with the highest level.
    CisdRun bestBull = na
    bool bullGap = cxLastBull < 0 or bar_index - cxLastBull >= CX_MIN_GAP
    if cxBullPend.size() > 0
        for i = cxBullPend.size() - 1 to 0
            CisdRun c = cxBullPend.get(i)
            int age = bar_index - c.endBar
            if age > cxMaxWin
                cxBullPend.remove(i)
            else if bullGap and age >= CX_MIN_WIN and close > c.lvl
                if na(bestBull) or c.lvl > bestBull.lvl
                    bestBull := c
                cxBullPend.remove(i)
    if not na(bestBull)
        cxLastBull := bar_index
        cxBullPend.clear()
        f_cxConfirm(bestBull)
 
    // Bearish reclaim.
    CisdRun bestBear = na
    bool bearGap = cxLastBear < 0 or bar_index - cxLastBear >= CX_MIN_GAP
    if cxBearPend.size() > 0
        for i = cxBearPend.size() - 1 to 0
            CisdRun c = cxBearPend.get(i)
            int age = bar_index - c.endBar
            if age > cxMaxWin
                cxBearPend.remove(i)
            else if bearGap and age >= CX_MIN_WIN and close < c.lvl
                if na(bestBear) or c.lvl < bestBear.lvl
                    bestBear := c
                cxBearPend.remove(i)
    if not na(bestBear)
        cxLastBear := bar_index
        cxBearPend.clear()
        f_cxConfirm(bestBear)
 
    // A close back through the CISD level ends it: removed, or kept dotted and faded.
    if cxDone.size() > 0
        for i = cxDone.size() - 1 to 0
            CisdRun c = cxDone.get(i)
            if not c.dead and bar_index > c.okBar and (c.bull ? close < c.lvl : close > c.lvl)
                if cKeepFail
                    c.dead := true
                    line.set_style(c.ln, line.style_dotted)
                    line.set_color(c.ln, color.new(f_cxCol(c.bull), 55))
                    line.set_extend(c.ln, extend.none)
                    label.set_textcolor(c.lb, color.new(INK, 55))
                    label.set_text_formatting(c.lb, text.format_none)
                    line.delete(c.mid)
                    f_cxSdKill(c)
                else
                    f_cxDrop(c)
                    cxDone.remove(i)
 
    // Big blocks leave once their hours are up.
    if cxKept.size() > 0
        for i = cxKept.size() - 1 to 0
            CisdRun k = cxKept.get(i)
            if not f_cxBig(k)
                k.kept := false
                f_cxSdKill(k)
                cxKept.remove(i)
 
    while cxBullPend.size() > CX_PEND_MAX
        cxBullPend.shift()
    while cxBearPend.size() > CX_PEND_MAX
        cxBearPend.shift()
 
    // Pending: the newest run on each side waiting for its close, drawn dotted to the current candle.
    line.delete(cxPotBullLn)
    label.delete(cxPotBullLb)
    line.delete(cxPotBearLn)
    label.delete(cxPotBearLb)
    if cPotential and cxBullPend.size() > 0
        CisdRun p = cxBullPend.last()
        cxPotBullLn := line.new(p.oTime, p.lvl, time, p.lvl, xloc = xloc.bar_time, color = f_cxCol(true), style = line.style_dotted, width = 1)
        cxPotBullLb := f_cxLabel(time, p.lvl, "CISD", false)
    if cPotential and cxBearPend.size() > 0
        CisdRun p = cxBearPend.last()
        cxPotBearLn := line.new(p.oTime, p.lvl, time, p.lvl, xloc = xloc.bar_time, color = f_cxCol(false), style = line.style_dotted, width = 1)
        cxPotBearLb := f_cxLabel(time, p.lvl, "CISD", false)
 
// A confirmed level runs as far as the extend setting says.
if barstate.islast and cExtend != "Confirm bar" and cxDone.size() > 0
    int endT = time + cOffset * cxMs
    for c in cxDone
        if not c.dead
            line.set_x2(c.ln, endT)
            label.set_x(c.lb, endT)
            if not na(c.mid)
                line.set_x2(c.mid, endT)
            if cExtend == "Extend right"
                line.set_extend(c.ln, extend.right)
 
// == HEADER ==
//@function The chart timeframe written out: 1m, 15m, 1H, 4H, 1D, 1W, 1M.
//@returns (string) The name.
f_tfName() =>
    string tf = timeframe.period
    timeframe.isseconds ? tf : timeframe.isminutes ? (timeframe.multiplier % 60 == 0 ? str.tostring(timeframe.multiplier / 60) + "H" : tf + "m") : timeframe.isdaily ? str.tostring(timeframe.multiplier) + "D" : timeframe.isweekly ? str.tostring(timeframe.multiplier) + "W" : str.tostring(timeframe.multiplier) + "M"
 
var table hTitleTbl = hTitleOn ? table.new(position.top_center, 1, 1, frame_color = INK, frame_width = 1) : na
var table hCardTbl  = hCardOn and not phone ? table.new(position.top_right, 1, 3, frame_color = INK, frame_width = 1) : na
if barstate.islast
    if hTitleOn
        table.cell(hTitleTbl, 0, 0, hTitle, text_color = INK, text_size = SZ_HEAD)
    if hCardOn and not phone
        table.cell(hCardTbl, 0, 0, str.upper(hBrand), text_color = INK, text_size = SZ_META)
        table.cell(hCardTbl, 0, 1, syminfo.ticker, text_color = INK, text_size = SZ_HEAD + 2)
        table.cell(hCardTbl, 0, 2, f_tfName() + " TIMEFRAME", text_color = INK, text_size = SZ_META)
 
// == HTF CANDLES ==
// Higher-timeframe candles drawn beside price, with a countdown to each close.
// Black wicks follow the chart: white on a dark background.
color K_INK = kInkIn == #000000 ? INK : kInkIn
 
int    kSec  = timeframe.in_seconds()
string kAutoA = kSec < 300 ? "15" : kSec < 900 ? "60" : kSec < 3600 ? "240" : "D"
string kAutoB = kSec < 300 ? "60" : kSec < 900 ? "240" : kSec < 3600 ? "D" : "W"
string kAutoC = kSec < 300 ? "240" : kSec < 900 ? "D" : kSec < 3600 ? "W" : "M"
string kA = kAuto ? kAutoA : kTfA
string kB = kAuto ? kAutoB : kTfA
string kC = kAuto ? kAutoC : kTfA
 
// The one block drawn and the timeframe the fractal model runs on: the first with at least 12 chart
// candles to each of its candles, else the highest above the chart timeframe.
float  kRA  = float(timeframe.in_seconds(kA)) / kSec
float  kRB  = float(timeframe.in_seconds(kB)) / kSec
float  kRC  = float(timeframe.in_seconds(kC)) / kSec
int    kSrc = not kAuto ? (kRA > 1 ? 0 : -1) : kRA >= 12 ? 0 : kRB >= 12 ? 1 : kRC >= 12 ? 2 : kRC > 1 ? 2 : kRB > 1 ? 1 : kRA > 1 ? 0 : -1
string kTf  = kSrc == 1 ? kB : kSrc == 2 ? kC : kA
 
//@function The last 15 candles of one timeframe, newest first, the forming candle's close time, and
//          each candle's open time.
//@returns (tuple) Open, high, low and close for offsets 0 to 14, the close time, then open times 0 to 14.
f_kRead() =>
    [open, high, low, close, open[1], high[1], low[1], close[1], open[2], high[2], low[2], close[2], open[3], high[3], low[3], close[3], open[4], high[4], low[4], close[4], open[5], high[5], low[5], close[5], open[6], high[6], low[6], close[6], open[7], high[7], low[7], close[7], open[8], high[8], low[8], close[8], open[9], high[9], low[9], close[9], open[10], high[10], low[10], close[10], open[11], high[11], low[11], close[11], open[12], high[12], low[12], close[12], open[13], high[13], low[13], close[13], open[14], high[14], low[14], close[14], time_close, time, time[1], time[2], time[3], time[4], time[5], time[6], time[7], time[8], time[9], time[10], time[11], time[12], time[13], time[14]]
 
[kO0, kH0, kL0, kC0, kO1, kH1, kL1, kC1, kO2, kH2, kL2, kC2, kO3, kH3, kL3, kC3, kO4, kH4, kL4, kC4, kO5, kH5, kL5, kC5, kO6, kH6, kL6, kC6, kO7, kH7, kL7, kC7, kO8, kH8, kL8, kC8, kO9, kH9, kL9, kC9, kO10, kH10, kL10, kC10, kO11, kH11, kL11, kC11, kO12, kH12, kL12, kC12, kO13, kH13, kL13, kC13, kO14, kH14, kL14, kC14, kTc, kT0, kT1, kT2, kT3, kT4, kT5, kT6, kT7, kT8, kT9, kT10, kT11, kT12, kT13, kT14] = request.security(syminfo.tickerid, kTf, f_kRead(), lookahead = barmerge.lookahead_off)
 
// == HTF CANDLE SMT ==
// Each asset's own candles on the HTF candle timeframe, so a 4H, 1D or 1W SMT reads on any chart.
//@function One asset's last 8 candles on the HTF candle timeframe: highs, lows and open times, newest first.
//@returns (tuple) Highs 0 to 7, lows 0 to 7, open times 0 to 7.
f_aKRead() =>
    [high, high[1], high[2], high[3], high[4], high[5], high[6], high[7], low, low[1], low[2], low[3], low[4], low[5], low[6], low[7], time, time[1], time[2], time[3], time[4], time[5], time[6], time[7]]
 
bool aKNeed = smtK and (kOn or p3On)
[k1H0, k1H1, k1H2, k1H3, k1H4, k1H5, k1H6, k1H7, k1L0, k1L1, k1L2, k1L3, k1L4, k1L5, k1L6, k1L7, k1T0, k1T1, k1T2, k1T3, k1T4, k1T5, k1T6, k1T7] = request.security(aKNeed and aUse1 ? f_aTicker(aS1) : syminfo.tickerid, kTf, f_aKRead(), lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
[k2H0, k2H1, k2H2, k2H3, k2H4, k2H5, k2H6, k2H7, k2L0, k2L1, k2L2, k2L3, k2L4, k2L5, k2L6, k2L7, k2T0, k2T1, k2T2, k2T3, k2T4, k2T5, k2T6, k2T7] = request.security(aKNeed and aUse2 ? f_aTicker(aS2) : syminfo.tickerid, kTf, f_aKRead(), lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
[k3H0, k3H1, k3H2, k3H3, k3H4, k3H5, k3H6, k3H7, k3L0, k3L1, k3L2, k3L3, k3L4, k3L5, k3L6, k3L7, k3T0, k3T1, k3T2, k3T3, k3T4, k3T5, k3T6, k3T7] = request.security(aKNeed and aUse3 ? f_aTicker(aS3) : syminfo.tickerid, kTf, f_aKRead(), lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
[k4H0, k4H1, k4H2, k4H3, k4H4, k4H5, k4H6, k4H7, k4L0, k4L1, k4L2, k4L3, k4L4, k4L5, k4L6, k4L7, k4T0, k4T1, k4T2, k4T3, k4T4, k4T5, k4T6, k4T7] = request.security(aKNeed and aUse4 ? f_aTicker(aS4) : syminfo.tickerid, kTf, f_aKRead(), lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
// Rows are the assets, columns the offsets.
matrix<float> kAH = matrix.new<float>(0, 8)
matrix<float> kAL = matrix.new<float>(0, 8)
matrix<int>   kAT = matrix.new<int>(0, 8)
kAH.add_row(kAH.rows(), array.from(k1H0, k1H1, k1H2, k1H3, k1H4, k1H5, k1H6, k1H7))
kAL.add_row(kAL.rows(), array.from(k1L0, k1L1, k1L2, k1L3, k1L4, k1L5, k1L6, k1L7))
kAT.add_row(kAT.rows(), array.from(k1T0, k1T1, k1T2, k1T3, k1T4, k1T5, k1T6, k1T7))
kAH.add_row(kAH.rows(), array.from(k2H0, k2H1, k2H2, k2H3, k2H4, k2H5, k2H6, k2H7))
kAL.add_row(kAL.rows(), array.from(k2L0, k2L1, k2L2, k2L3, k2L4, k2L5, k2L6, k2L7))
kAT.add_row(kAT.rows(), array.from(k2T0, k2T1, k2T2, k2T3, k2T4, k2T5, k2T6, k2T7))
kAH.add_row(kAH.rows(), array.from(k3H0, k3H1, k3H2, k3H3, k3H4, k3H5, k3H6, k3H7))
kAL.add_row(kAL.rows(), array.from(k3L0, k3L1, k3L2, k3L3, k3L4, k3L5, k3L6, k3L7))
kAT.add_row(kAT.rows(), array.from(k3T0, k3T1, k3T2, k3T3, k3T4, k3T5, k3T6, k3T7))
kAH.add_row(kAH.rows(), array.from(k4H0, k4H1, k4H2, k4H3, k4H4, k4H5, k4H6, k4H7))
kAL.add_row(kAL.rows(), array.from(k4L0, k4L1, k4L2, k4L3, k4L4, k4L5, k4L6, k4L7))
kAT.add_row(kAT.rows(), array.from(k4T0, k4T1, k4T2, k4T3, k4T4, k4T5, k4T6, k4T7))
array<int> kTs = array.from(kT0, kT1, kT2, kT3, kT4, kT5, kT6, kT7, kT8, kT9, kT10, kT11, kT12, kT13, kT14)
// The SMT read on the drawn sequence, set on the last bar once it is picked.
var bool   kSmtHit = false
var string kSmtWho = ""
 
//@function A timeframe's short name: 15m, 1H, 4H, 1D, 1W, 1M.
//@returns (string) The name.
f_kName(string tf) =>
    int sec = timeframe.in_seconds(tf)
    sec >= 2419200 ? str.tostring(math.round(sec / 2629800)) + "M" : sec >= 604800 ? str.tostring(math.round(sec / 604800)) + "W" : sec >= 86400 ? str.tostring(math.round(sec / 86400)) + "D" : sec >= 3600 and sec % 3600 == 0 ? str.tostring(int(sec / 3600)) + "H" : sec >= 60 ? str.tostring(int(math.round(sec / 60.0))) + "m" : str.tostring(sec) + "s"
 
int    p3Key     = time(kTf)
 
// == FRACTAL MODEL ==
// The fractal sequence, its T-Spots and filter, PSP and the SMT read on candles of several timeframes.
// Every candle here is folded from chart bars, so each extreme keeps the chart bar that printed it, and a correlated asset costs one chart-timeframe request and nothing more.
 
// One candle of a timeframe, folded from chart bars, with each correlated asset's own side of it.
type Candle
    int   t
    float o
    float h
    float l
    float c
    int   hiB
    int   loB
    int   hiT
    int   loT
    int   oB
    // False for the first candle a book builds: it opened before the chart's history.
    bool  full = true
    array<Peer> peers
 
// A sequence found on the book: the indexes of its C1 and C2, how far it has run and how it closed.
type Hit
    int  side
    int  c1    = -1
    int  c2    = -1
    int  phase = 0
    bool both  = false
    bool viaC3 = false
    bool found = false
 
// A sequence as it was last read: its four candles as they stood then, its state, and the CISD tied to it.
type Seq
    int    side
    Candle c1
    Candle c2
    Candle c3
    Candle c4
    int    phase  = 0
    bool   live   = false
    bool   both   = false
    bool   viaC3  = false
    bool   psp    = false
    bool   smt    = false
    bool   spent3 = false
    bool   spent4 = false
    int    doneT
    int    cxB
    int    cxT
    int    cxStartT
    float  cxLvl
    int    cxBrokeT
 
// A SMT: the reference candle's extreme on one timeframe and the candle that took it (or failed to).
type Div
    int    sec
    int    dir
    int    refOpen
    int    takeOpen
    float  refPx
    float  takePx
    int    refAt
    int    takeAt
    string who
    bool   ssmt
    int    seen
 
// A fair value gap tied to a sequence (owner) or to the HTF candles (owner 0).
type Gap
    int   owner
    int   fromT
    float top
    float bot
    bool  bull
    int   toT
    bool  first
 
// One SMT timeframe: its book of candles and how far back a reference may be.
type Rung
    string tf
    int    sec
    bool   qtr
    bool   on
    int    depth
    array<Candle> book
 
//@function Chart candles to one candle of a timeframe.
//@param tf (string) The timeframe.
//@returns (float) The ratio.
f_p3Ratio(string tf) =>
    float(timeframe.in_seconds(tf)) / timeframe.in_seconds()
 
// The profile runs on the HTF candle timeframe drawn: kTf.
int    p3SrcIdx = kSrc
string p3Tf     = kTf
bool   p3Ok     = p3On and p3SrcIdx >= 0
int    p3SrcSec = timeframe.in_seconds(p3Tf)
 
//@function A candle's extreme on a side: the high for -1, the low for 1.
//@returns (float) The price.
f_ext(Candle g, int side) =>
    side == -1 ? g.h : g.l
 
//@function When a candle's extreme on a side printed.
//@returns (int) The chart bar's time.
f_extT(Candle g, int side) =>
    side == -1 ? g.hiT : g.loT
 
//@function Which chart bar printed a candle's extreme on a side.
//@returns (int) The bar index.
f_extB(Candle g, int side) =>
    side == -1 ? g.hiB : g.loB
 
//@function The HTF candle a time falls in: its offset on the block, -1 outside the last 15.
//@returns (int) The offset.
f_kOffAt(int t) =>
    int out = -1
    if not na(t)
        for k = 0 to 14
            int op = kTs.get(k)
            if out < 0 and not na(op) and op <= t
                out := k
    out
 
//@function A asset's candle opening with a chart candle, within half a candle (FX and CME open one hour apart).
//@returns (int) Its offset, -1 for none.
f_aKOff(int a, int t) =>
    int out  = -1
    int half = timeframe.in_seconds(kTf) * 500
    if not na(t)
        for j = 0 to 7
            int at = kAT.get(a, j)
            if out < 0 and not na(at) and math.abs(at - t) < half
                out := j
    out
 
//@function The HTF candle SMT at C2: the chart's C2 took C1's high (low) and a asset's C2 did not. A
//          inverse asset is read on its other side.
//@returns ([bool, string, int]) Whether it reads (every asset, with Every asset must diverge), the
//          assets that diverged, and C2's offset (0 while it forms).
f_kSmt(Seq rc) =>
    bool   ok  = false
    string who = ""
    int    o2  = -1
    if smtK and not na(rc) and not na(f_extT(rc.c1, rc.side))
        int o1 = f_kOffAt(f_extT(rc.c1, rc.side))
        o2 := f_kOffAt(rc.c2.t)
        if o2 >= 0 and o1 > o2
            int valid = 0
            int div   = 0
            for a = 0 to 3
                if p3AOn.get(a)
                    int j1 = f_aKOff(a, kTs.get(o1))
                    int j2 = f_aKOff(a, kTs.get(o2))
                    if j1 >= 0 and j2 >= 0 and j1 > j2
                        bool  hiSide = (rc.side == -1) != p3AInv.get(a)
                        float r1 = hiSide ? kAH.get(a, j1) : kAL.get(a, j1)
                        float r2 = hiSide ? kAH.get(a, j2) : kAL.get(a, j2)
                        if not na(r1) and not na(r2)
                            valid += 1
                            if hiSide ? r2 <= r1 : r2 >= r1
                                div += 1
                                who := who + (who == "" ? "" : " · ") + str.upper(p3ALogo.get(a))
            ok := valid > 0 and (smtAll ? div == valid : div > 0)
    [ok, who, o2]
 
//@function Whether a SMT timeframe reads on this chart: ticked, and holding between the ratio min and
//          max in chart candles.
//@returns (bool) True when it reads.
f_p3LaneOn(bool tick, float ratio) =>
    smtOn and timeframe.isintraday and tick and ratio >= smtRMin and ratio <= smtRMax
 
//@function How many candles back a SMT reference may be on one timeframe.
//@param sec (int) The timeframe in seconds.
//@returns (int) The lookback.
f_p3Look(int sec) =>
    not smtPerTf ? smtLook : sec == 900 ? 4 : sec == 1800 ? 4 : sec == 3600 ? 6 : sec == 5400 ? 6 : sec == 14400 ? 14 : sec == 21600 ? 10 : 10
 
//@function A SMT timeframe with a empty book.
//@returns (Rung) The timeframe.
f_rung(string tf, bool tick, bool qtr) =>
    int sec = timeframe.in_seconds(tf)
    Rung.new(tf = tf, sec = sec, qtr = qtr, on = f_p3LaneOn(tick, f_p3Ratio(tf)), depth = f_p3Look(sec), book = array.new<Candle>())
 
var array<Candle> p3Cs    = array.new<Candle>()
var array<Seq>    p3Recs  = array.new<Seq>()
var array<Div>    p3Marks = array.new<Div>()
// The SMT timeframes. The 90m and 6H carry the quarter flag a SSMT is read on.
var array<Rung>   p3Lanes = array.from(f_rung("15", smt15, false), f_rung("30", smt30, false), f_rung("60", smt60, false), f_rung("90", smt90, true), f_rung("240", smt240, false), f_rung("360", smt360, true), f_rung("1D", smtD, false))
// Each SMT timeframe's open time on this bar, in the same order.
array<int> p3LaneT = array.from(time("15"), time("30"), time("60"), time("90"), time("240"), time("360"), time("1D"))
 
//@function A fresh copy of this bar's asset sample, one entry per asset.
//@returns (array<Peer>) The copy.
f_peersNow() =>
    array<Peer> out = array.new<Peer>()
    for pr in p3Now
        out.push(Peer.new(o = pr.o, h = pr.h, l = pr.l, c = pr.c, seen = pr.seen))
    out
 
//@function Adds the chart bar to a book: a new candle when the timeframe's open time moves on, else the
//          running candle grows. A asset joins a candle on the first bar it prints inside it.
//@param book (array<Candle>) The book.
//@param openT (int) The timeframe's open time on this bar.
//@param cap (int) Candles kept.
//@returns (bool) Always true.
f_p3Ingest(array<Candle> book, int openT, int cap) =>
    if not na(openT)
        bool fresh = book.size() == 0
        if not fresh
            fresh := book.last().t != openT
        if fresh
            book.push(Candle.new(t = openT, o = open, h = high, l = low, c = close, hiB = bar_index, loB = bar_index, hiT = time, loT = time, oB = bar_index, full = book.size() > 0, peers = f_peersNow()))
            while book.size() > cap
                book.shift()
        else
            Candle g = book.last()
            g.c := close
            if high > g.h
                g.h   := high
                g.hiB := bar_index
                g.hiT := time
            if low < g.l
                g.l   := low
                g.loB := bar_index
                g.loT := time
            for [k, pr] in g.peers
                Peer now = p3Now.get(k)
                if now.seen
                    if pr.seen
                        pr.h := math.max(pr.h, now.h)
                        pr.l := math.min(pr.l, now.l)
                    else
                        pr.o    := now.o
                        pr.h    := now.h
                        pr.l    := now.l
                        pr.seen := true
                    pr.c := now.c
    true
 
//@function Whether a candle closed the other way to a correlated asset (to every one, with Every asset
//          must disagree). A inverse asset is read flipped: it disagrees when it closed the SAME way.
//@param g (Candle) The candle.
//@returns (bool) True for a PSP.
f_p3Psp(Candle g) =>
    float me      = math.sign(g.c - g.o)
    int   read    = 0
    int   against = 0
    for [k, pr] in g.peers
        if p3AOn.get(k) and pr.seen and not na(pr.o)
            read += 1
            float them = math.sign(pr.c - pr.o) * (p3AInv.get(k) ? -1 : 1)
            if them != me
                against += 1
    read > 0 and (p3PspAll ? against == read : against > 0)
 
//@function Whether a candle is a doji for C1: its body is under a tenth of its range.
//@returns (bool) True for a doji.
f_p3Thin(Candle g) =>
    math.abs(g.c - g.o) < (g.h - g.l) * 0.1
 
//@function C1 for a C2 at book index i: the candle before it, or the one before that when it is a doji.
//@returns (int) The index, -1 when both are dojis or the book is too short.
f_c1Of(int i) =>
    int res = -1
    if i >= 1
        if not f_p3Thin(p3Cs.get(i - 1))
            res := i - 1
        else if i >= 2 and not f_p3Thin(p3Cs.get(i - 2))
            res := i - 2
    res
 
//@function Whether every candle after book index i stayed inside its extreme on a side.
//@returns (bool) True when nothing traded past it.
f_holds(int i, int side) =>
    int   n   = p3Cs.size()
    float ext = f_ext(p3Cs.get(i), side)
    bool  ok  = true
    if i < n - 1
        for j = i + 1 to n - 1
            float x = f_ext(p3Cs.get(j), side)
            if side == -1 ? x > ext : x < ext
                ok := false
    ok
 
//@function The sequence whose C2 sits at book index i, on one side. A C2 closure: C2 traded through
//          C1's extreme on that side and closed inside C1's body (a C2 still forming is taken as it
//          stands and tagged C2?). A C3 closure: C2 closed beyond C1's extreme and C3 closed back
//          through C2's body. Either way no later candle may have traded past C2's extreme.
//@param side (int) -1 bearish, 1 bullish.
//@param i (int) C2's book index.
//@returns (Hit) The sequence; found is false when there is none.
f_seqAt(int side, int i) =>
    Hit h = Hit.new(side = side)
    int n = p3Cs.size()
    int j = f_c1Of(i)
    if j >= 0
        Candle a       = p3Cs.get(j)
        Candle b       = p3Cs.get(i)
        bool   forming = i == n - 1
        bool   took    = side == -1 ? b.h > a.h : b.l < a.l
        bool   tookFar = side == -1 ? b.l < a.l : b.h > a.h
        bool   inBody  = b.c < math.max(a.o, a.c) and b.c > math.min(a.o, a.c)
        if took and (forming or inBody)
            if f_holds(i, side)
                h := Hit.new(side = side, c1 = j, c2 = i, phase = n - 1 - i + 2, both = tookFar, found = true)
        else if p3C3On and took and not forming
            Candle d    = p3Cs.get(i + 1)
            bool   past = side == -1 ? b.c > a.h : b.c < a.l
            bool   back = side == -1 ? d.c < math.min(b.o, b.c) : d.c > math.max(b.o, b.c)
            if past and back and f_holds(i, side)
                h := Hit.new(side = side, c1 = j, c2 = i, phase = n - 1 - i + 2, viaC3 = true, found = true)
    h
 
//@function The live sequence on one side: C2 is the newest candle or one of the two before it, the
//          newest that qualifies.
//@param side (int) -1 bearish, 1 bullish.
//@returns (Hit) The sequence; found is false when there is none.
f_p3Eval(int side) =>
    Hit res = Hit.new(side = side)
    int n   = p3Cs.size()
    if n >= 2
        for i = n - 1 to math.max(1, n - 3)
            if not res.found
                Hit h = f_seqAt(side, i)
                if h.found
                    res := h
    res
 
//@function Whether a sequence's closure candle is still forming: C2 (phase 2) or, for a C3 closure, C3.
//@returns (bool) True while it is forming.
f_p3Forming(Seq rc) =>
    rc.live and rc.phase == (rc.viaC3 ? 3 : 2)
 
//@function A copy of a candle as it stands now, without its assets.
//@returns (Candle) The copy.
f_snap(Candle g) =>
    Candle.new(t = g.t, o = g.o, h = g.h, l = g.l, c = g.c, hiB = g.hiB, loB = g.loB, hiT = g.hiT, loT = g.loT, oB = g.oB, full = g.full)
 
//@function Writes the live sequence of one side into its record (a new one for a new C2, ten kept), and
//          marks done the records on that side it no longer is.
//@param h (Hit) The live sequence.
//@returns (bool) Always true.
f_p3Sync(Hit h) =>
    int liveC2 = na
    if h.found
        Candle a = p3Cs.get(h.c1)
        Candle b = p3Cs.get(h.c2)
        liveC2 := b.t
        Seq s = na
        for x in p3Recs
            if x.side == h.side and x.c2.t == b.t
                s := x
        if na(s)
            s := Seq.new(side = h.side, c1 = Candle.new(), c2 = Candle.new(), c3 = Candle.new(), c4 = Candle.new())
            p3Recs.push(s)
            if p3Recs.size() > 10
                p3Recs.shift()
        s.c1    := f_snap(a)
        s.c2    := f_snap(b)
        s.both  := h.both
        s.viaC3 := h.viaC3
        s.phase := math.max(s.phase, h.phase)
        s.live  := true
        // C2 printing a new extreme after the CISD voids that CISD.
        if not na(s.cxB) and s.cxB <= f_extB(s.c2, s.side)
            s.cxB      := na
            s.cxT      := na
            s.cxStartT := na
            s.cxLvl    := na
            s.cxBrokeT := na
        if h.phase >= 3
            s.c3 := f_snap(p3Cs.get(h.c2 + 1))
        if h.phase >= 4
            s.c4 := f_snap(p3Cs.get(h.c2 + 2))
        s.psp := f_p3Psp(b)
    for x in p3Recs
        if x.side == h.side
            bool still = h.found and x.c2.t == liveC2
            if x.live and not still
                x.doneT := time
            x.live := still
    true
 
//@function A sequence's T-Spot for C3 (which = 3, measured on C2) or C4 (which = 4, measured on C3).
//          EQ: between the candle's EQ and its far edge; a C2 that closed against the swing is halved
//          from its close to its wick. C4's only once C3 closed beyond C2 (or for a C3 closure). Depth %:
//          from the close back into the candle by the depth input. A C3 closure has no C3 T-Spot.
//@returns ([float, float]) Top and bottom, na when not known or not earned.
f_p3Zone(Seq rc, int which) =>
    float  top = na
    float  bot = na
    Candle g   = which == 3 ? rc.c2 : rc.c3
    if not (which == 3 and rc.viaC3) and not na(g.c)
        if p3ZoneIn == "EQ"
            float far = na
            float mid = na
            if which == 3
                bool against = rc.side == 1 ? g.c <= g.o : g.c >= g.o
                far := against ? g.c : f_ext(g, -rc.side)
                mid := against ? (g.c + f_ext(g, rc.side)) / 2.0 : (g.h + g.l) / 2.0
            else if rc.viaC3 or (rc.side == 1 ? g.c > rc.c2.h : g.c < rc.c2.l)
                far := f_ext(g, -rc.side)
                mid := (g.h + g.l) / 2.0
            top := math.max(far, mid)
            bot := math.min(far, mid)
        else
            float depth = (which == 3 ? p3D3 : p3D4) / 100.0
            float inner = g.c - rc.side * (g.h - g.l) * depth
            top := math.max(g.c, inner)
            bot := math.min(g.c, inner)
    [top, bot]
 
//@function The close of the profile candle that opened at t, once a later candle has opened.
//@param t (int) The candle's open time.
//@returns (float) Its close, na while it is forming or no longer in the book.
f_p3ClosedC(int t) =>
    float res = na
    int   n   = p3Cs.size()
    if not na(t) and n >= 2
        for i = 0 to n - 2
            if p3Cs.get(i).t == t
                res := p3Cs.get(i).c
    res
 
//@function A T-Spot's EQ: its edge nearest the swing.
//@returns (float) The price.
f_p3Eq(Seq rc, float top, float bot) =>
    rc.side == 1 ? bot : top
 
//@function Whether C2 closed past C1's EQ and ran at least a tenth of C1's range beyond C1.
//@returns (bool) True when it did.
f_c2Strong(Seq rc) =>
    float span = rc.c1.h - rc.c1.l
    float eq   = (rc.c1.h + rc.c1.l) / 2.0
    float run  = rc.side == 1 ? rc.c1.l - rc.c2.l : rc.c2.h - rc.c1.h
    bool  past = rc.side == 1 ? rc.c2.c > eq : rc.c2.c < eq
    past and span > 0 and run >= span * 0.1
 
//@function Whether a sequence passes the T-Spot filter.
//@returns (bool) True when it passes.
f_p3SpotOk(Seq rc) =>
    bool cx = not na(rc.cxB)
    switch p3SpotIn
        "Easy"   => cx or rc.smt
        "Medium" => cx and rc.smt
        "Hard"   => cx and rc.smt and rc.psp
        "Max"    => cx and rc.smt and rc.psp and not rc.both and f_c2Strong(rc)
        => true
 
//@function Stores a SMT, or refreshes the one already held for the same timeframe, side and candles.
//@returns (bool) Always true.
f_divPut(int sec, int dir, Candle ref, Candle take, string who, bool ssmt) =>
    Div d = na
    for x in p3Marks
        if x.sec == sec and x.dir == dir and x.refOpen == ref.t and x.takeOpen == take.t
            d := x
    if na(d)
        d := Div.new(sec = sec, dir = dir, refOpen = ref.t, takeOpen = take.t)
        p3Marks.push(d)
    d.refPx  := f_ext(ref, dir)
    d.takePx := f_ext(take, dir)
    d.refAt  := f_extT(ref, dir)
    d.takeAt := f_extT(take, dir)
    d.who    := who
    d.ssmt   := ssmt
    d.seen   := bar_index
    true
 
//@function Whether a level is within two ticks of one already read this scan.
//@returns (bool) True when it is.
f_p3Used(array<float> used, float lv) =>
    bool hit = false
    for u in used
        hit := hit or math.abs(u - lv) <= syminfo.mintick * 2
    hit
 
//@function Whether a candle's extreme on a side stands at or beyond both closed neighbours, within two
//          ticks. The candle right before the forming one always counts.
//@param book (array<Candle>) The book.
//@param r (int) The candle's index.
//@param dir (int) -1 high, 1 low.
//@returns (bool) True for a local swing.
f_p3Swing(array<Candle> book, int r, int dir) =>
    float tol = syminfo.mintick * 2
    float v   = f_ext(book.get(r), dir)
    bool  ok  = true
    if r < book.size() - 2
        for nb in array.from(r + 1, r - 1)
            if ok and nb >= 0
                float w = f_ext(book.get(nb), dir)
                ok := dir == -1 ? v >= w - tol : v <= w + tol
    ok
 
//@function Whether nothing between a reference candle and the forming one reached its extreme.
//@returns (bool) True when untouched.
f_untouched(array<Candle> book, int r, int dir) =>
    int   n  = book.size()
    float lv = f_ext(book.get(r), dir)
    bool  ok = true
    if r < n - 2
        for j = r + 1 to n - 2
            float x = f_ext(book.get(j), dir)
            if dir == -1 ? x >= lv : x <= lv
                ok := false
    ok
 
//@function The assets against a reference: how many could be read, how many went the other way to the
//          chart, and their names. A inverse asset is read on the opposite extreme.
//@returns ([int, int, string]) Read, diverging, names joined by +.
f_divRead(Candle ref, Candle take, int dir, bool chartTook) =>
    int    read = 0
    int    off  = 0
    string who  = ""
    for k = 0 to 3
        Peer pr = ref.peers.get(k)
        Peer pt = take.peers.get(k)
        if p3AOn.get(k) and pr.seen and pt.seen
            read += 1
            int  aDir = p3AInv.get(k) ? -dir : dir
            bool took = aDir == -1 ? pt.h > pr.h : pt.l < pr.l
            if took != chartTook
                off += 1
                who := who + (who == "" ? "" : "+") + p3ALogo.get(k)
    [read, off, who]
 
//@function The SMT read on one timeframe: the forming candle against each candle before it, back to its
//          lookback. Clean takes a candle whose extreme nothing has reached since, Balanced also a local
//          swing, Full any. A SMT is the chart taking that extreme while a asset does not, or the other
//          way round. A candle the book did not see open is never a reference. Read against the candle
//          right before it on the 90m or 6H with SSMT on, it is stored as a SSMT.
//@param rg (Rung) The timeframe.
//@returns (bool) Always true.
f_p3Scan(Rung rg) =>
    array<Candle> book = rg.book
    int n = book.size()
    if n >= 2
        Candle take = book.last()
        int    most = smtModeIn == "Clean" ? 1 : smtMaxDir
        for dir in array.from(-1, 1)
            int          got  = 0
            array<float> used = array.new<float>()
            for back = 1 to rg.depth
                int r = n - 1 - back
                if r >= 0 and got < most and book.get(r).full
                    Candle ref = book.get(r)
                    float  lv  = f_ext(ref, dir)
                    bool   can = smtModeIn == "Full" or f_untouched(book, r, dir) or (smtModeIn == "Balanced" and f_p3Swing(book, r, dir))
                    if can and smtClose
                        can := dir == -1 ? close < lv : close > lv
                    if can
                        bool chartTook = dir == -1 ? take.h > lv : take.l < lv
                        [read, off, who] = f_divRead(ref, take, dir, chartTook)
                        if read > 0 and (smtAll ? off == read : off > 0) and not f_p3Used(used, lv)
                            got += 1
                            used.push(lv)
                            f_divPut(rg.sec, dir, ref, take, who, p3Ssmt and rg.qtr and back == 1)
    true
 
//@function The SMT timeframe a SMT was read on.
//@param sec (int) Its timeframe in seconds.
//@returns (Rung) The timeframe, or na.
f_p3LaneOf(int sec) =>
    Rung res = na
    for rg in p3Lanes
        if rg.sec == sec
            res := rg
    res
 
//@function Whether a SMT is on the forming candle of its timeframe.
//@returns (bool) True while it is.
f_divLive(Div d) =>
    Rung rg = f_p3LaneOf(d.sec)
    not na(rg) and rg.book.size() > 0 and d.takeOpen == rg.book.last().t
 
//@function Whether a SMT has ended: its timeframe is off, its reference has left the book, it is live and
//          the forming candle no longer shows it, or it is closed and a chart bar traded past both ends.
//@returns (bool) True when it has ended.
f_divGone(Div d) =>
    Rung rg   = f_p3LaneOf(d.sec)
    bool gone = na(rg) or not rg.on or rg.book.size() == 0
    if not gone
        bool live = d.takeOpen == rg.book.last().t
        gone := d.refOpen < rg.book.first().t or (live and d.seen != bar_index) or (not live and (d.dir == -1 ? high > math.max(d.refPx, d.takePx) : low < math.min(d.refPx, d.takePx)))
    gone
 
//@function Whether SMT b outranks SMT a as the same divergence: a higher timeframe, or on the same one a
//          SSMT over a SMT. Clean also lets a higher timeframe take a lower one that shares its end, shares
//          its reference, or sits inside both its candles (1H and below), unless the lower one is newer and
//          runs further.
//@returns (bool) True when a goes.
f_divCovered(Div a, Div b) =>
    bool res = false
    if b.dir == a.dir and (b.sec > a.sec or (b.sec == a.sec and b.ssmt and not a.ssmt))
        float tol     = syminfo.mintick * 2
        bool  sameEnd = b.takeAt == a.takeAt and math.abs(b.takePx - a.takePx) <= tol
        bool  sameRef = b.refAt == a.refAt and math.abs(b.refPx - a.refPx) <= tol
        if sameEnd and sameRef
            res := true
        else if smtModeIn == "Clean" and b.sec > a.sec
            bool further = a.takeAt > b.takeAt and (a.dir == -1 ? a.takePx > b.takePx : a.takePx < b.takePx)
            int  bEnd    = b.sec * 1000
            bool inside  = a.sec <= 3600 and a.refAt >= b.refOpen and a.refAt < b.refOpen + bEnd and a.takeAt >= b.takeOpen and a.takeAt < b.takeOpen + bEnd
            res := sameEnd or ((sameRef or inside) and not further)
    res
 
//@function A key per timeframe and side, with SSMTs apart when ss is true.
//@returns (int) The key.
f_divKey(Div d, bool ss) =>
    (d.sec * 2 + (ss and d.ssmt ? 1 : 0)) * d.dir
 
//@function Keeps the SMTs that still count. Ended ones go; across timeframes the outranked one goes
//          (every mode but Full); then per timeframe and side Clean and Full keep the newest up to Kept,
//          and Balanced keeps the newest closed SMT, the widest older one at least the span multiple
//          longer, and any still forming. A SSMT keeps two.
//@returns (bool) Always true.
f_p3MarkClean() =>
    int cnt = p3Marks.size()
    if cnt > 0
        for i = cnt - 1 to 0
            if f_divGone(p3Marks.get(i))
                p3Marks.remove(i)
    cnt := p3Marks.size()
    if smtModeIn != "Full" and cnt > 1
        array<bool> covered = array.new<bool>(cnt, false)
        for [i, a] in p3Marks
            for b in p3Marks
                if not covered.get(i) and f_divCovered(a, b)
                    covered.set(i, true)
        for i = cnt - 1 to 0
            if covered.get(i)
                p3Marks.remove(i)
    cnt := p3Marks.size()
    if cnt > 0
        bool        bal  = smtModeIn == "Balanced"
        array<bool> live = array.new<bool>(cnt, false)
        array<bool> cut  = array.new<bool>(cnt, false)
        for [i, d] in p3Marks
            live.set(i, f_divLive(d))
        if bal and smtKeep >= 2
            // The newest closed SMT per timeframe and side, then the widest older one wide enough beside it.
            map<int, int> newest = map.new<int, int>()
            map<int, int> widest = map.new<int, int>()
            for [i, d] in p3Marks
                if not live.get(i) and not d.ssmt
                    int k = f_divKey(d, false)
                    if not newest.contains(k)
                        newest.put(k, i)
                    else
                        Div nw = p3Marks.get(newest.get(k))
                        if d.takeAt > nw.takeAt or (d.takeAt == nw.takeAt and d.refAt > nw.refAt)
                            newest.put(k, i)
            for [i, d] in p3Marks
                if not live.get(i) and not d.ssmt
                    int k = f_divKey(d, false)
                    if newest.get(k) != i
                        Div   nw   = p3Marks.get(newest.get(k))
                        float need = math.max(nw.sec * 1000, nw.takeAt - nw.refAt) * smtSpan
                        bool  wide = d.refAt < nw.refAt and (d.takeAt - d.refAt) >= need
                        cut.set(i, not wide)
                        if wide and (not widest.contains(k) or (d.takeAt - d.refAt) > (p3Marks.get(widest.get(k)).takeAt - p3Marks.get(widest.get(k)).refAt))
                            widest.put(k, i)
            for [i, d] in p3Marks
                if not live.get(i) and not d.ssmt and not cut.get(i)
                    int k = f_divKey(d, false)
                    if newest.get(k) != i and widest.get(k) != i
                        cut.set(i, true)
        else if bal
            // With Kept at 1 only the newest closed SMT per timeframe and side stays.
            map<int, int> newest = map.new<int, int>()
            for [i, d] in p3Marks
                if not live.get(i) and not d.ssmt
                    int k = f_divKey(d, false)
                    if not newest.contains(k)
                        newest.put(k, i)
                    else
                        Div nw = p3Marks.get(newest.get(k))
                        if d.takeAt > nw.takeAt or (d.takeAt == nw.takeAt and d.refAt > nw.refAt)
                            newest.put(k, i)
            for [i, d] in p3Marks
                if not live.get(i) and not d.ssmt and newest.get(f_divKey(d, false)) != i
                    cut.set(i, true)
        map<int, int> seen = map.new<int, int>()
        for i = cnt - 1 to 0
            Div  d    = p3Marks.get(i)
            int  k    = f_divKey(d, true)
            bool free = bal and live.get(i)
            int  c    = (seen.contains(k) ? seen.get(k) : 0) + (free ? 0 : 1)
            seen.put(k, c)
            if cut.get(i) or (not free and c > (d.ssmt ? 2 : smtKeep))
                p3Marks.remove(i)
    while p3Marks.size() > 50
        p3Marks.shift()
    true
 
//@function The newest SSMT's direction.
//@returns (int) -1 bearish, 1 bullish, 0 when there is none.
f_p3SsDir() =>
    int dir = 0
    int at  = 0
    for d in p3Marks
        if d.ssmt and d.takeAt > at
            at  := d.takeAt
            dir := d.dir
    dir
 
//@function A SMT timeframe's short name: 15m, 30m, 1H, 90m, 4H, 6H, D, 3D, W, M.
//@returns (string) The name.
f_p3TfLogo(int sec) =>
    sec < 60 ? str.tostring(sec) + "s" : sec < 3600 or (sec < 86400 and sec % 3600 != 0) ? str.tostring(int(math.round(sec / 60.0))) + "m" : sec < 86400 ? str.tostring(int(sec / 3600)) + "H" : sec < 604800 ? (int(math.round(sec / 86400.0)) == 1 ? "D" : str.tostring(int(math.round(sec / 86400.0))) + "D") : sec < 2419200 ? (int(math.round(sec / 604800.0)) == 1 ? "W" : str.tostring(int(math.round(sec / 604800.0))) + "W") : int(math.round(sec / 2629800.0)) == 1 ? "M" : str.tostring(int(math.round(sec / 2629800.0))) + "M"
 
// HTF candle dividers: a dotted vertical line at the open of each of the last fractal candles, as many as the
// HTF block shows, all one height: the highest high to the lowest low of those candles.
var array<line>  p3Divs  = array.new<line>()
var array<int>   p3DivTs = array.new<int>()
var array<float> p3DivHi = array.new<float>()
var array<float> p3DivLo = array.new<float>()
int p3DivKey = time(p3Tf)
if p3Ok and p3DivOn and not na(p3DivKey) and p3DivKey != p3DivKey[1]
    p3Divs.push(line.new(time, high, time, low, xloc = xloc.bar_time, color = K_REF, style = line.style_dotted, width = 1))
    p3DivTs.push(p3DivKey)
    p3DivHi.push(high)
    p3DivLo.push(low)
    if p3Divs.size() > kCount
        line.delete(p3Divs.shift())
        p3DivTs.shift()
        p3DivHi.shift()
        p3DivLo.shift()
if p3DivHi.size() > 0
    p3DivHi.set(p3DivHi.size() - 1, math.max(p3DivHi.last(), high))
    p3DivLo.set(p3DivLo.size() - 1, math.min(p3DivLo.last(), low))
if barstate.islast and p3Divs.size() > 0
    float dvHi = p3DivHi.max()
    float dvLo = p3DivLo.min()
    for dv in p3Divs
        line.set_y1(dv, dvHi)
        line.set_y2(dv, dvLo)
 
// Kept from the last closed chart bar, so a live tick never flips the sequence.
var Hit p3Bear = Hit.new(side = -1)
var Hit p3Bull = Hit.new(side = 1)
int   p3SsmtDir = 0
if p3On
    f_p3Ingest(p3Cs, p3Key, 17)
// The previous profile candle's EQ: which side the forming candle opened on, and whether a chart close
// has crossed it since.
var int  p3EqKey    = na
var int  p3EqSide   = 0
var bool p3EqBroken = false
float    p3PrevEq   = p3Cs.size() >= 2 ? math.avg(p3Cs.get(p3Cs.size() - 2).h, p3Cs.get(p3Cs.size() - 2).l) : na
if p3On and p3Cs.size() >= 2 and not na(p3PrevEq)
    if p3Cs.last().t != p3EqKey
        p3EqKey    := p3Cs.last().t
        p3EqSide   := p3Cs.last().o >= p3PrevEq ? 1 : -1
        p3EqBroken := false
    if barstate.isconfirmed and (p3EqSide == 1 ? close < p3PrevEq : close > p3PrevEq)
        p3EqBroken := true
 
// The sequence CISD: a close back through the open of the run of opposing candles before it (two or more,
// the run started no more than 60 bars back).
type Run
    float o = na
    int   b = na
    int   t = na
    int   n = 0
 
//@function Grows a run of same-direction candles, or starts one when the bar before went the other way.
//@returns (bool) Always true.
f_runStep(Run r, bool same, bool sameBefore) =>
    if same
        if sameBefore
            r.n += 1
        else
            r.n := 1
            r.o := open
            r.b := bar_index
            r.t := time
    true
 
//@function Whether this close went back through a run's open: the CISD. A run that confirms is used up.
//@returns (bool) True on the confirming bar.
f_runBroke(Run r, bool upClose) =>
    bool hit = not na(r.o) and r.n >= 2 and bar_index - r.b <= 60 and (upClose ? close > open and close > r.o : close < open and close < r.o)
    hit
 
var Run p3DnRun = Run.new()
var Run p3UpRun = Run.new()
f_runStep(p3DnRun, close < open, close[1] < open[1])
f_runStep(p3UpRun, close > open, close[1] > open[1])
int   p3CxSide = 0
float p3CxLvl  = na
int   p3CxT0   = na
for [side, r] in array.from(p3DnRun, p3UpRun)
    if p3CxSide == 0 and f_runBroke(r, side == 0)
        p3CxSide := side == 0 ? 1 : -1
        p3CxLvl  := r.o
        p3CxT0   := r.t
        r.o      := na
        r.n      := 0
 
// Read once each chart bar closes: a live tick through C1 or C2 never swaps the sequence in and out.
if p3Ok and barstate.isconfirmed
    p3Bear := f_p3Eval(-1)
    p3Bull := f_p3Eval(1)
    f_p3Sync(p3Bear)
    f_p3Sync(p3Bull)
    // A CISD confirmed on this bar ties to each live sequence on its side that has none, after C2's extreme.
    if p3CxSide != 0
        for rc in p3Recs
            if rc.live and rc.side == p3CxSide and na(rc.cxB) and not na(f_extB(rc.c2, rc.side)) and bar_index > f_extB(rc.c2, rc.side)
                rc.cxB      := bar_index
                rc.cxT      := time
                rc.cxStartT := p3CxT0
                rc.cxLvl    := p3CxLvl
 
// The SMT read: each timeframe folds the chart bar in, then reads its forming candle.
if smtOn
    for [i, rg] in p3Lanes
        if rg.on
            f_p3Ingest(rg.book, p3LaneT.get(i), rg.depth + 2)
            f_p3Scan(rg)
    f_p3MarkClean()
    p3SsmtDir := f_p3SsDir()
 
//@function Whether a T-Spot is spent: price closed through its far side. EQ mode reads the close of the
//          candle the T-Spot belongs to, so a candle that went deep and closed back held; Depth % reads
//          each chart close while that candle forms.
//@returns (bool) True once spent.
f_spentNow(Seq rc, int which) =>
    bool   res = false
    Candle g   = which == 3 ? rc.c3 : rc.c4
    if not na(g.t)
        [zt, zb] = f_p3Zone(rc, which)
        float cl = na
        if p3ZoneIn == "EQ"
            cl := f_p3ClosedC(g.t)
        else if rc.phase >= which and time >= g.t and (which == 4 or na(rc.c4.t) or time < rc.c4.t)
            cl := close
        res := not na(cl) and not na(zt) and (rc.side == 1 ? cl < zb : cl > zt)
    res
 
if p3Ok
    for rc in p3Recs
        // Support for the filter: a HTF candle SMT at C2 once C2 has closed, or a chart SMT in the
        // sequence direction taken during C2 on a timeframe at or below the profile's.
        if rc.live and not rc.smt and smtK
            [smOk, smWho, smO2] = f_kSmt(rc)
            rc.smt := smOk and smO2 >= 1
    for rc in p3Recs
        if rc.live and not rc.smt
            for d in p3Marks
                if d.dir == rc.side and d.sec <= p3SrcSec and d.takeAt >= rc.c2.t and (na(rc.c3.t) or d.takeAt < rc.c3.t)
                    rc.smt := true
    for rc in p3Recs
        // A sequence CISD fails once a candle closes back through it.
        if not na(rc.cxB) and na(rc.cxBrokeT) and bar_index > rc.cxB and (rc.side == 1 ? close < rc.cxLvl : close > rc.cxLvl)
            rc.cxBrokeT := time
        rc.spent3 := rc.spent3 or f_spentNow(rc, 3)
        rc.spent4 := rc.spent4 or f_spentNow(rc, 4)
 
//@function Whether the direction input allows a side.
//@returns (bool) True when allowed.
f_p3SideOk(int side) =>
    p3DirIn == "Both" or (p3DirIn == "Bullish only" ? side == 1 : side == -1)
 
//@function Whether the newest SSMT, with its filter on, agrees with a side.
//@returns (bool) True when it agrees or does not apply.
f_p3SsmtOk(int side) =>
    not (p3Ssmt and p3SsmtF) or p3SsmtDir == 0 or p3SsmtDir == side
 
//@function Whether the other side of the same C2 is still live.
//@returns (bool) True when it is.
f_p3OtherAlive(Seq rc) =>
    bool res = false
    for o in p3Recs
        res := res or (o.side == -rc.side and o.c2.t == rc.c2.t and o.live)
    res
 
//@function Whether a record may draw: direction, SSMT filter, and the xC2 wait.
//@returns (bool) True when it may.
f_p3Visible(Seq rc) =>
    bool ok = f_p3SideOk(rc.side) and (not rc.live or f_p3SsmtOk(rc.side))
    if ok and rc.both and p3GateIn == "Wait for xC2"
        ok := rc.live ? not f_p3OtherAlive(rc) : rc.phase >= 4
    ok
 
// Both sides live off one C2 and the gate waits for xC2: nothing draws until one side is gone.
bool p3Pending = p3GateIn != "Immediate" and p3Bear.found and p3Bull.found and p3Bear.c2 == p3Bull.c2 and f_p3SideOk(-1) and f_p3SideOk(1) and f_p3SsmtOk(-1) and f_p3SsmtOk(1)
 
int p3CloseT = time_close(p3Tf)
 
var array<box>   p3Boxes = array.new<box>()
var array<line>  p3Lines = array.new<line>()
var array<label> p3Lbls  = array.new<label>()
 
//@function The colour a sequence draws in, following Direction colours.
//@returns (color) The colour.
f_p3Col(int side) =>
    dirCols ? (side == 1 ? C_BULL : C_BEAR) : INK
 
//@function A T-Spot's fill: light violet under a bullish sequence, light grey under a bearish one.
//@param side (int) 1 bullish, -1 bearish.
//@returns (color) The fill.
f_p3SpotCol(int side) =>
    color.new(side == 1 ? C_UP : C_DN, DARK ? math.max(0, p3Fill - 12) : p3Fill)
 
//@function A transparent monospace label, kept in the Po3 store.
//@returns (label) The label.
f_p3Lbl(int x, float y, string txt, string sty, string align) =>
    label lb = label.new(x, y, txt, xloc = xloc.bar_time, style = sty, color = color.new(#FFFFFF, 100), textcolor = INK, size = SZ_BODY, textalign = align)
    label.set_text_font_family(lb, font.family_monospace)
    p3Lbls.push(lb)
    lb
 
//@function A zone with its caption beside it, on its centre line, past its right edge.
//@returns (bool) Always true.
f_p3Box(int x1, float top, int x2, float bot, color fill, string cap) =>
    p3Boxes.push(box.new(x1, top, x2, bot, xloc = xloc.bar_time, bgcolor = fill, border_color = fill, border_width = 1))
    if cap != ""
        f_p3Lbl(x2, math.avg(top, bot), cap, label.style_label_left, text.align_left)
    true
 
//@function C2's tag: xC2 when it took both sides, +SMT with a HTF candle SMT, ? while forming, PSP.
//@returns (string) The tag.
f_p3C2Tag(Seq rc) =>
    (rc.both ? "xC2" : "C2") + (kSmtHit or rc.smt ? "+SMT" : "") + (f_p3Forming(rc) and not rc.viaC3 ? "?" : "") + (rc.psp and p3Psp ? " PSP" : "")
 
//@function The sequence's marks at its extremes: C1's sweep line to C3's open, the C1 to C4 tags past
//          each extreme on the sequence's side, and the HTF candle SMT from C1 to C2.
//@param rc (Seq) The sequence.
//@returns (bool) Always true.
f_p3DrawTags(Seq rc) =>
    int    s   = rc.side
    int    t1  = f_extT(rc.c1, s)
    int    t2  = f_extT(rc.c2, s)
    float  p1  = f_ext(rc.c1, s)
    float  p2  = f_ext(rc.c2, s)
    string sty = s == -1 ? label.style_label_down : label.style_label_up
    if p3Sweep and not na(t1)
        int sweepTo = rc.phase >= 3 and not na(rc.c3.t) ? rc.c3.t : time
        if sweepTo > t1
            p3Lines.push(line.new(t1, p1, sweepTo, p1, xloc = xloc.bar_time, color = INK, width = 1, style = line.style_solid))
    if p3ChartTags and not na(t1) and not na(t2)
        f_p3Lbl(t2, p2, f_p3C2Tag(rc) + (spOn and kSmtHit and kSmtWho != "" ? " " + kSmtWho : ""), sty, text.align_center)
        // Spacious: C1's tag goes when it sits within a few chart bars of C2's; the sweep line marks it.
        if not spOn or math.abs(t2 - t1) > CHART_SEC * 1000 * 6
            f_p3Lbl(t1, p1, "C1", sty, text.align_center)
        // C3 and C4 sit at the middle of their own candle, past its extreme, clear of every chart candle in
        // it. A C3 T-Spot kept past C4 is named where C4 opens, so C4's tag stays off there.
        [t3, b3] = f_p3Zone(rc, 3)
        bool c3Kept = p3Spot and not (p3SpotIn != "Open" and rc.spent3) and rc.phase >= 4 and p3Keep3 and not na(t3) and not na(rc.c3.t) and not na(rc.c4.t) and rc.c4.t > rc.c3.t
        int  halfC  = p3SrcSec * 500
        if rc.phase >= 3 and not na(f_extT(rc.c3, s))
            f_p3Lbl(rc.c3.t + halfC, f_ext(rc.c3, s), "C3" + (rc.viaC3 and f_p3Forming(rc) ? "?" : ""), sty, text.align_center)
        if rc.phase >= 4 and not na(f_extT(rc.c4, s)) and not c3Kept
            f_p3Lbl(rc.c4.t + halfC, f_ext(rc.c4, s), "C4", sty, text.align_center)
    if kSmtHit and not na(t1) and not na(t2) and t2 > t1
        color col = f_p3Col(s)
        p3Lines.push(line.new(t1, p1, t2, p2, xloc = xloc.bar_time, color = col, width = 1))
        if kSmtWho != "" and not spOn
            label sl = f_p3Lbl(t1 + (t2 - t1) / 2, math.avg(p1, p2), "SMT · " + kSmtWho, sty, text.align_center)
            label.set_textcolor(sl, col)
    true
 
//@function Where a T-Spot's window ends: C3's where C4 opens once C4 is in, else the live candle's close
//          while the sequence runs, or where the sequence ended.
//@returns (int) The time, never past cap.
f_spotEnd(Seq rc, int w, int liveEnd, int cap) =>
    int t = w == 3 and rc.phase >= 4 and not na(rc.c4.t) ? rc.c4.t : rc.live or na(rc.doneT) ? liveEnd : rc.doneT
    math.min(t, cap)
 
//@function The C3 and C4 T-Spots: the zone across its candle with its EQ line while it holds; once spent
//          (with a filter on), a dotted line at its EQ named XC3 or XC4 instead.
//@returns (bool) Always true.
f_p3DrawSpots(Seq rc, int liveEnd, int cap) =>
    bool filtered = p3SpotIn != "Open"
    if p3Spot
        for w in array.from(3, 4)
            Candle g     = w == 3 ? rc.c3 : rc.c4
            bool   spent = w == 3 ? rc.spent3 : rc.spent4
            int    x2    = f_spotEnd(rc, w, liveEnd, cap)
            if not na(g.t) and x2 > g.t
                [zt, zb] = f_p3Zone(rc, w)
                if not na(zt)
                    float eq = f_p3Eq(rc, zt, zb)
                    if spent and filtered
                        if p3XOn
                            color xc = w == 3 ? P3_XC3 : P3_XC4
                            p3Lines.push(line.new(g.t, eq, x2, eq, xloc = xloc.bar_time, color = xc, width = 1, style = line.style_dotted))
                            label xl = f_p3Lbl(g.t, eq, "XC" + str.tostring(w), rc.side == 1 ? label.style_label_upper_left : label.style_label_lower_left, text.align_left)
                            label.set_textcolor(xl, xc)
                    else if rc.phase >= w and (w == 4 or rc.phase < 4 or p3Keep3)
                        f_p3Box(g.t, zt, x2, zb, f_p3SpotCol(rc.side), "C" + str.tostring(w) + " T-Spot")
                        if p3SpotEq
                            p3Lines.push(line.new(g.t, eq, x2, eq, xloc = xloc.bar_time, color = color.new(rc.side == 1 ? C_UP : C_DN, 0), width = 1, style = line.style_solid))
    true
 
//@function The sequence STDV: each listed multiple of the CISD level to C2's extreme, from the CISD on,
//          named at its left, the pairs shaded. Dotted once the CISD failed or the sequence ended.
//@returns (bool) Always true.
f_p3DrawStdv(Seq rc, int edge) =>
    float wick = f_ext(rc.c2, rc.side)
    if p3Stdv and not na(rc.cxB) and not na(wick)
        int   barMs = CHART_SEC * 1000
        bool  over  = not rc.live or not na(rc.cxBrokeT)
        int   until = not na(rc.cxBrokeT) ? rc.cxBrokeT : not rc.live and not na(rc.doneT) ? rc.doneT : time + barMs * 3
        int   x2    = math.max(math.min(until, edge), rc.cxT + barMs)
        float prev  = na
        int   cnt   = 0
        for p in str.split(str.replace_all(p3StdvIn, " ", ""), ",")
            float m = str.tonumber(p)
            if not na(m)
                float px = rc.cxLvl + m * (wick - rc.cxLvl)
                cnt += 1
                p3Lines.push(line.new(rc.cxT, px, x2, px, xloc = xloc.bar_time, color = P3_STDV, width = 1, style = over ? line.style_dotted : line.style_solid))
                label sl = f_p3Lbl(rc.cxT, px, p, label.style_label_right, text.align_right)
                label.set_textcolor(sl, P3_STDV)
                label.set_size(sl, SZ_META)
                if cnt % 2 == 0
                    color sh = color.new(P3_STDV, 88)
                    p3Boxes.push(box.new(rc.cxT, math.max(prev, px), x2, math.min(prev, px), xloc = xloc.bar_time, bgcolor = sh, border_color = sh, border_width = 1))
                prev := px
    true
 
//@function Draws the one sequence on the chart: its tags and sweep, its T-Spots and its STDV.
//@param rc (Seq) The sequence.
//@returns (bool) Always true.
f_p3Draw(Seq rc) =>
    int barMs = CHART_SEC * 1000
    int cap   = time + barMs * 400
    // Nothing reaches the HTF candles: zones stop a few bars short of them, room left for a caption.
    int edge  = kOn ? time + barMs * math.max(1, kOffset - 7) : cap
    cap := math.min(cap, edge)
    int liveEnd = math.min(na(p3CloseT) ? time + barMs * 20 : p3CloseT, cap)
    f_p3DrawTags(rc)
    f_p3DrawSpots(rc, liveEnd, cap)
    f_p3DrawStdv(rc, edge)
    true
 
// The one sequence on the chart, on the HTF candles and in the checklist: the newest that passes the
// T-Spot filter. A running closed sequence comes first: a C2? or C3? still forming shows only when no
// closed one is running. Older ones never draw.
Seq p3Shown = na
if barstate.islast and p3Ok and p3Recs.size() > 0
    for i = p3Recs.size() - 1 to 0
        Seq rc = p3Recs.get(i)
        if na(p3Shown) and rc.live and not f_p3Forming(rc) and f_p3Visible(rc) and f_p3SpotOk(rc)
            p3Shown := rc
    for i = p3Recs.size() - 1 to 0
        Seq rc = p3Recs.get(i)
        if na(p3Shown) and f_p3Visible(rc) and (rc.live or rc.phase >= (rc.viaC3 ? 4 : 3)) and f_p3SpotOk(rc)
            p3Shown := rc
if barstate.islast
    [smHit, smWho, smO2] = f_kSmt(p3Shown)
    kSmtHit := smHit
    kSmtWho := smWho
 
if barstate.islast
    for b in p3Boxes
        box.delete(b)
    for l in p3Lines
        line.delete(l)
    for lb in p3Lbls
        label.delete(lb)
    p3Boxes.clear()
    p3Lines.clear()
    p3Lbls.clear()
    if p3Ok and not na(p3Shown)
        f_p3Draw(p3Shown)
    // The sequence's own names, drawn before the SMT names.
    int p3SeqN = p3Lbls.size()
    // The HTF candle SMTs: reference to taker, a dot on the reference, timeframe and asset past the newest swing's wick.
    // Names sharing a stretch of chart step a text line out, the lower timeframe nearest its line.
    if smtOn and p3SmtLn and p3Marks.size() > 0
        int nmk = p3Marks.size()
        for i = 0 to nmk - 1
            Div m = p3Marks.get(i)
            if m.takeAt > m.refAt
                bool bearM = m.dir == -1
                p3Lines.push(line.new(m.refAt, m.refPx, m.takeAt, m.takePx, xloc = xloc.bar_time, color = LILAC, width = 1, style = m.ssmt ? line.style_dashed : line.style_solid))
                if smtDot
                    p3Lbls.push(label.new(m.refAt, m.refPx, "•", xloc = xloc.bar_time, style = label.style_label_center, color = color.new(#FFFFFF, 100), textcolor = LILAC, size = SZ_BODY))
                if smtLblIn != "Off"
                    int rank = 0
                    for j = 0 to nmk - 1
                        Div o = p3Marks.get(j)
                        if j != i and o.dir == m.dir and o.refAt < m.takeAt and m.refAt < o.takeAt and (o.sec < m.sec or (o.sec == m.sec and j < i))
                            rank += 1
                    // A sequence tag already past this wick: the name steps out a line past it.
                    if p3SeqN > 0
                        for k = 0 to p3SeqN - 1
                            label q = p3Lbls.get(k)
                            if label.get_x(q) == m.takeAt and label.get_y(q) == m.takePx
                                rank += 1
                    string pad   = rank == 0 ? "" : rank == 1 ? "\n" : rank == 2 ? "\n\n" : "\n\n\n"
                    string tfTxt = f_p3TfLogo(m.sec) + (m.ssmt ? " SSMT" : " SMT")
                    string who   = str.upper(m.who)
                    string txt   = smtLblIn == "HTF" or m.who == "" ? tfTxt : smtLblIn == "Assets" ? who : tfTxt + " · " + who
                    // At the newest swing's extreme, past the wick: above a high, below a low. The middle of the line sat on the
                    // candles between the two swings.
                    int    xm    = m.takeAt
                    label  sl    = f_p3Lbl(xm, m.takePx, bearM ? txt + pad : pad + txt, bearM ? label.style_label_down : label.style_label_up, text.align_center)
                    label.set_size(sl, SZ_META)
                    label.set_textcolor(sl, LILAC)
    if smtOn and p3Ssmt and not p3SmtLn
        for m in p3Marks
            if m.ssmt and m.takeAt > m.refAt
                p3Lines.push(line.new(m.refAt, m.refPx, m.takeAt, m.takePx, xloc = xloc.bar_time, color = LILAC, width = 1, style = line.style_dashed))
                f_p3Lbl(m.takeAt, m.takePx, f_p3TfLogo(m.sec) + " SSMT", m.dir == -1 ? label.style_label_down : label.style_label_up, text.align_center)
 
// == HTF FVGS ==
// Read on the HTF candle timeframe when one of its candles closes: the closed candle against the one two
// before it. A gap starts at the middle candle's open and is removed by a close through its far side.
var array<Gap> hFvgs = array.new<Gap>()
var int hLastT = na
if hFvgOn and kSrc >= 0
    bool hNew = not na(kT1) and kT1 != hLastT
    hLastT := kT1
    if hNew and not na(kT2)
        bool hBull = not na(kL1) and not na(kH3) and kL1 > kH3
        bool hBear = not na(kH1) and not na(kL3) and kH1 < kL3
        if hBull or hBear
            bool dup = false
            for f in hFvgs
                if f.fromT == kT2
                    dup := true
            if not dup
                hFvgs.push(Gap.new(owner = 0, fromT = kT2, top = hBull ? kL1 : kL3, bot = hBull ? kH3 : kH1, bull = hBull, toT = na, first = false))
                if hFvgs.size() > 50
                    hFvgs.shift()
    if barstate.isconfirmed and hFvgs.size() > 0
        for i = hFvgs.size() - 1 to 0
            Gap f = hFvgs.get(i)
            if f.bull ? close < f.bot : close > f.top
                hFvgs.remove(i)
    if barstate.islast and hFvgs.size() > 0
        int    hEdge = kOn ? time + CHART_SEC * 1000 * math.max(1, kOffset - 7) : time + CHART_SEC * 1000 * 20
        string hCap  = f_kName(kTf) + " FVG"
        int    shown = 0
        for i = hFvgs.size() - 1 to 0
            Gap f = hFvgs.get(i)
            if shown < hFvgMax and hEdge > f.fromT
                shown += 1
                f_p3Box(f.fromT, f.top, hEdge, f.bot, color.new(f.bull ? C_UP : C_DN, 85), hCap)
                float mid = math.avg(f.top, f.bot)
                p3Lines.push(line.new(f.fromT, mid, hEdge, mid, xloc = xloc.bar_time, color = INK, width = 1, style = line.style_dotted))
 
// The checklist: the live sequence and what it has.
var table p3Tbl = p3On and p3List ? table.new(p3ListAt == "Bottom center" ? position.bottom_center : p3ListAt == "Bottom right" ? position.bottom_right : p3ListAt == "Middle right" ? position.middle_right : p3ListAt == "Top left" ? position.top_left : p3ListAt == "Bottom left" ? position.bottom_left : position.middle_left, 2, phone ? 5 : 11, frame_color = INK, frame_width = 1, border_width = 0) : na
 
//@function The phase of a sequence, one name for the checklist and the header strip: C2? / C3? / xC2?
//          while it forms, xC2 for a two-sided C3, else C and the phase.
//@param rc (Seq) The sequence.
//@returns (string) The phase name.
f_p3PhName(Seq rc) =>
    f_p3Forming(rc) ? (rc.viaC3 ? "C3?" : rc.both ? "xC2?" : "C2?") : rc.both and rc.phase == 3 ? "xC2" : "C" + str.tostring(rc.phase)
 
//@function One checklist row, all ink, monospace, left aligned.
//@returns (bool) Always true.
f_p3Row(int row, string name, string val) =>
    table.cell(p3Tbl, 0, row, name, text_color = INK, text_size = TBL_SZ, text_halign = text.align_left, text_font_family = font.family_monospace)
    table.cell(p3Tbl, 1, row, val, text_color = INK, text_size = TBL_SZ, text_halign = text.align_left, text_font_family = font.family_monospace)
    true
 
if barstate.islast and p3On and p3List
    Seq dr = p3Shown
    string phase = not p3Ok ? "no HTF" : not na(dr) ? (dr.side == 1 ? "↑ " : "↓ ") + f_p3PhName(dr) + (dr.live ? "" : " done") : p3Pending ? "xC2 both sides" : "none"
    float  eqNow = na
    string eqTip = ""
    if not na(dr) and dr.phase >= 3
        int w = dr.phase >= 4 ? 4 : 3
        [zt, zb] = f_p3Zone(dr, w)
        if not na(zt)
            eqNow := f_p3Eq(dr, zt, zb)
            eqTip := "C" + str.tostring(w) + (dr.side == 1 ? " wick holds above " : " wick holds below ") + str.tostring(eqNow, format.mintick)
    bool c2Ok = not na(dr) and not f_p3Forming(dr) and dr.phase >= 3
    string p3Stat = not p3Ok ? "NO HTF" : na(dr) ? "WAITING" : dr.live ? "● LIVE" : "DONE"
    table.cell(p3Tbl, 0, 0, "PO3 Fractalized", text_color = INK, text_size = TBL_SZ, text_halign = text.align_left, text_font_family = font.family_monospace)
    table.cell(p3Tbl, 1, 0, p3Stat, text_color = LIVE, text_size = TBL_SZ, text_halign = text.align_right, text_font_family = font.family_monospace)
    string p3Prof = p3Ok ? f_kName(p3Tf) : "--"
    string c2Name = not na(dr) and dr.viaC3 ? "C3 CLOSED" : "C2 CLOSED"
    string eqVal  = na(eqNow) ? "--" : str.tostring(eqNow, format.mintick)
    bool   spDead = not na(dr) and (dr.phase >= 4 ? dr.spent4 : dr.spent3)
    string spVal  = na(dr) or dr.phase < 3 or na(eqNow) ? "--" : spDead ? "spent" : "live"
    // Phone: the phase, the closure, the CISD and the EQ.
    if phone
        f_p3Row(1, "PHASE", phase)
        f_p3Row(2, c2Name, c2Ok ? "✓" : "×")
        f_p3Row(3, "CISD", not na(dr) and not na(dr.cxB) ? "✓" : "×")
        f_p3Row(4, "EQ", eqVal)
    else if spOn
        // Spacious: the header strip already names the instrument, timeframes and assets.
        f_p3Row(1, "PHASE", phase)
        f_p3Row(2, c2Name, c2Ok ? "✓" : "×")
        f_p3Row(3, "CISD", not na(dr) and not na(dr.cxB) ? "✓" : "×")
        f_p3Row(4, "SMT", not na(dr) and dr.smt ? "✓" : "×")
        f_p3Row(5, "PSP", not na(dr) and dr.psp ? "✓" : "×")
        f_p3Row(6, "T-SPOT", spVal)
        f_p3Row(7, "EQ", eqVal)
    else
        f_p3Row(1, "INSTRUMENT", syminfo.ticker)
        f_p3Row(2, "TIMEFRAME", f_tfName() + " → " + p3Prof)
        f_p3Row(3, "ASSETS", f_aList())
        f_p3Row(4, "PHASE", phase)
        f_p3Row(5, c2Name, c2Ok ? "✓" : "×")
        f_p3Row(6, "CISD", not na(dr) and not na(dr.cxB) ? "✓" : "×")
        f_p3Row(7, "SMT", not na(dr) and dr.smt ? "✓" : "×")
        f_p3Row(8, "PSP", not na(dr) and dr.psp ? "✓" : "×")
        f_p3Row(9, "T-SPOT", spVal)
        f_p3Row(10, "EQ", eqVal)
    if eqTip != ""
        table.cell_set_tooltip(p3Tbl, 1, phone ? 4 : spOn ? 7 : 10, eqTip)
 
// The header strip, top centre, in a plain frame: the timeframes, the phase in teal, the assets below.
var table hStripTbl = hStripOn and not phone and not hTitleOn ? table.new(position.top_center, 1, 3, frame_color = INK, frame_width = 1, border_width = 0) : na
if barstate.islast and hStripOn and not phone and not hTitleOn
    Seq  hs   = p3Shown
    string hTfs = (kAuto ? "⟳ AUTO    " : "") + f_tfName() + " ▸ " + (p3Ok ? f_kName(p3Tf) : "--")
    string hPh  = not p3Ok ? "No HTF" : na(hs) ? (p3Pending ? "xC2 both sides" : "No sequence") : (hs.side == 1 ? "▲ " : "▼ ") + f_p3PhName(hs) + " Phase" + (hs.live ? "" : " · done")
    table.cell(hStripTbl, 0, 0, hTfs, text_color = INK, text_size = SZ_BODY, text_font_family = font.family_monospace)
    table.cell(hStripTbl, 0, 1, hPh, text_color = LIVE, text_size = SZ_BODY, text_font_family = font.family_monospace)
    table.cell(hStripTbl, 0, 2, "₰ " + syminfo.ticker + " · " + f_aList(), text_color = INK, text_size = SZ_META, text_font_family = font.family_monospace)
 
//@function The candle of a chart-built book that a HTF candle holds: open at or after that candle's
//          open and before the next one's.
//@param cs (array<Candle>) The book.
//@param tms (array<int>) The HTF candles' open times, newest first.
//@param k (int) The HTF candle's offset.
//@returns (int) The book index, or -1.
f_p3IdxAt(array<Candle> cs, array<int> tms, int k) =>
    int op  = tms.get(k)
    int nx  = k == 0 ? na : tms.get(k - 1)
    int idx = -1
    if not na(op) and cs.size() > 0
        for i = 0 to cs.size() - 1
            int t = cs.get(i).t
            if t >= op and (na(nx) or t < nx)
                idx := i
    idx
 
//@function Per offset, whether a HTF candle is a PSP: it traded through the high or low of the candle
//          before it and closed the other way to a correlated asset.
//@param cs (array<Candle>) The lane's chart-built book.
//@param tms (array<int>) The lane's open times, newest first.
//@returns (array<bool>) One flag per open time, newest first.
f_p3LanePsp(array<Candle> cs, array<int> tms) =>
    array<bool> res = array.new<bool>(tms.size(), false)
    if p3On and p3Psp
        for k = 0 to tms.size() - 1
            int i = f_p3IdxAt(cs, tms, k)
            if i >= 1
                Candle cd = cs.get(i)
                Candle pv = cs.get(i - 1)
                res.set(k, (cd.h > pv.h or cd.l < pv.l) and f_p3Psp(cd))
    res
 
//@function The drawn sequence's tags and sweep offsets on the profile's HTF candles, each candle found by
//          the open times it holds.
//@param tms (array<int>) The HTF candles' open times, newest first.
//@returns ([array<string>, int, int, int, int]) Tags per offset, then the offsets of C1, C2, C3 and C4
//          (-1 when not shown).
f_p3Tags(array<int> tms) =>
    array<string> tags = array.new<string>(tms.size(), "")
    int off1 = -1
    int off2 = -1
    int off3 = -1
    int off4 = -1
    if not na(p3Shown)
        Seq rc = p3Shown
        for k = 0 to tms.size() - 1
            int op = tms.get(k)
            int nx = k == 0 ? na : tms.get(k - 1)
            if not na(op)
                bool has1 = not na(f_extT(rc.c1, rc.side)) and f_extT(rc.c1, rc.side) >= op and (na(nx) or f_extT(rc.c1, rc.side) < nx)
                bool has2 = rc.c2.t >= op and (na(nx) or rc.c2.t < nx)
                bool has3 = not na(rc.c3.t) and rc.c3.t >= op and (na(nx) or rc.c3.t < nx)
                bool has4 = not na(rc.c4.t) and rc.c4.t >= op and (na(nx) or rc.c4.t < nx)
                if has1
                    off1 := k
                if has2
                    off2 := k
                if has3
                    off3 := k
                if has4
                    off4 := k
                if p3TagsIn != "Off"
                    if has2
                        tags.set(k, f_p3C2Tag(rc))
                    else if has3
                        tags.set(k, "C3" + (rc.viaC3 and f_p3Forming(rc) ? "?" : ""))
                    else if has4 and p3TagsIn == "C1/C2/C3/C4"
                        tags.set(k, "C4")
        if off1 >= 0 and p3TagsIn != "Off"
            tags.set(off1, "C1")
    int sw1 = p3Sweep ? off1 : -1
    [tags, sw1, off2, off3, off4]
 
//@function Time left on the forming candle: HH:MM:SS under a day, then days and HH:MM (11d 14:35). --:-- with no live tick.
//@returns (string) The countdown.
f_kTimer(int closeT) =>
    string out = "--:--"
    if barstate.isrealtime and not na(closeT)
        int left = math.round((closeT - timenow) / 1000)
        if left > 0
            int d = math.floor(left / 86400)
            int r = left % 86400
            out := d > 0 ? str.tostring(d) + "d " + str.tostring(math.floor(r / 3600), "00") + ":" + str.tostring(math.floor((r % 3600) / 60), "00") : str.tostring(math.floor(r / 3600), "00") + ":" + str.tostring(math.floor((r % 3600) / 60), "00") + ":" + str.tostring(r % 60, "00")
    out
 
var array<box>   kBoxes = array.new<box>()
var array<line>  kWicks = array.new<line>()
var array<label> kLbls  = array.new<label>()
 
//@function Whether a block draws the previous candle's 25 / 50 / 75 lines: daily and higher only.
//@param tf (string) The block's timeframe.
//@returns (bool) True when the quarters draw.
f_kQOn(string tf) =>
    kPrevQ and timeframe.in_seconds(tf) >= 86400
 
//@function Draws one timeframe's candles, oldest on the left, with its name and countdown above.
//@param x0 (int) Bar index of the block's first candle.
//@param tf (string) The timeframe.
//@param o (array<float>) Opens, newest first; h, l and c likewise.
//@param closeT (int) Close time of the forming candle.
//@param psp (array<bool>) Per offset, whether the candle is a PSP.
//@param tags (array<string>) Per offset, the Po3 tag, empty for none.
//@param tagSide (int) -1 tags above the highs, 1 below the lows.
//@param off1 (int) Offset of C1 for its sweep line, -1 for none.
//@param off2 (int) Offset of C2.
//@param tms (array<int>) Open times, newest first.
//@param src (bool) Whether the fractal model runs on this block.
//@returns (int) Bar index just past the block.
f_kBlock(int x0, string tf, array<float> o, array<float> h, array<float> l, array<float> c, int closeT, array<bool> psp, array<string> tags, int tagSide, int off1, int off2, array<int> tms, bool src) =>
    // The block shows Candles, or enough to keep C1 on it.
    int   n    = math.min(math.max(kCount, off1 + 1), o.size())
    int   half = int((kWidth - 1) / 2)
    int   step = kWidth + 1
    float top  = na
    bool  qOn  = f_kQOn(tf)
    bool  topTag = false
    bool  botTag = false
    float hiV    = na
    float loV    = na
    int   hiK    = -1
    int   loK    = -1
    for i = 0 to n - 1
        int   k  = n - 1 - i
        float oo = o.get(k)
        float hh = h.get(k)
        float ll = l.get(k)
        float cc = c.get(k)
        if not (na(oo) or na(hh) or na(ll) or na(cc))
            bool  bull = cc >= oo
            int   x    = x0 + i * step + half
            float bt   = math.max(oo, cc)
            float bb   = math.min(oo, cc)
            if bt == bb
                bt += syminfo.mintick
            // A PSP candle fills in the T-Spot and FVG hues: violet bullish, dark grey bearish.
            color body = psp.get(k) ? color.new(bull ? C_UP : C_DN, 55) : bull ? K_BULL_BODY : K_BEAR_BODY
            kBoxes.push(box.new(x - half, bt, x + half, bb, xloc = xloc.bar_index, bgcolor = body, border_color = k == 0 ? LILAC : K_INK, border_width = 1))
            string tg = tags.get(k)
            if tg != ""
                // The C1-C4 names sit under each candle, whichever way the sequence runs.
                label tl = label.new(x, ll, tg, xloc = xloc.bar_index, style = label.style_label_up, color = color.new(#FFFFFF, 100), textcolor = INK, size = SZ_BODY)
                label.set_text_font_family(tl, font.family_monospace)
                kLbls.push(tl)
                botTag := true
            kWicks.push(line.new(x, hh, x, bt, xloc = xloc.bar_index, color = K_INK, width = 1))
            kWicks.push(line.new(x, bb, x, ll, xloc = xloc.bar_index, color = K_INK, width = 1))
            // The previous candle's midpoint is already the 50% line when the quarters are on.
            if kMid and not (qOn and k == 1)
                float md = math.avg(hh, ll)
                kWicks.push(line.new(x - half - 1, md, x + half + 1, md, xloc = xloc.bar_index, color = K_REF, style = line.style_dotted, width = 1))
            // A sweep: a closed candle wicks through the prior candle's extreme and closes back inside.
            if kSweep and k >= 1 and k + 1 < n
                float ph = h.get(k + 1)
                float pl = l.get(k + 1)
                int   xp = x - step
                if not na(ph) and hh > ph and cc < ph
                    kWicks.push(line.new(xp, ph, x + half + 1, ph, xloc = xloc.bar_index, color = INK, width = 1))
                if not na(pl) and ll < pl and cc > pl
                    kWicks.push(line.new(xp, pl, x + half + 1, pl, xloc = xloc.bar_index, color = INK, width = 1))
            top := na(top) ? hh : math.max(top, hh)
            if na(hiV) or hh > hiV
                hiV := hh
                hiK := k
            if na(loV) or ll < loV
                loV := ll
                loK := k
    // C1's extreme that C2 traded through. A closed C2 already has it from the sweep lines.
    if off1 >= 0 and off1 < n and off2 >= 0 and (not kSweep or off2 == 0)
        float lv = tagSide == -1 ? h.get(off1) : l.get(off1)
        if not na(lv)
            int xs = x0 + (n - 1 - off1) * step + half
            int xe = x0 + (n - 1 - off2) * step + 2 * half + 1
            kWicks.push(line.new(xs, lv, xe, lv, xloc = xloc.bar_index, color = INK, width = 1))
    // The HTF candle SMT: C1's extreme to C2's in the sequence hue.
    if kSmtHit and off1 >= 0 and off1 < n and off2 >= 0 and off2 < off1 and tagSide != 0
        float v1 = tagSide == -1 ? h.get(off1) : l.get(off1)
        float v2 = tagSide == -1 ? h.get(off2) : l.get(off2)
        if not (na(v1) or na(v2))
            kWicks.push(line.new(x0 + (n - 1 - off1) * step + half, v1, x0 + (n - 1 - off2) * step + half, v2, xloc = xloc.bar_index, color = LILAC, width = 1))
    // The chart's SMT lines on the block too: the candle holding the reference to the candle that took it,
    // at the same prices, when both are on the block and are different candles.
    if smtOn and p3SmtLn and p3Marks.size() > 0
        for m in p3Marks
            int rk = -1
            int ck = -1
            for k = 0 to n - 1
                int op = tms.get(k)
                if not na(op)
                    if rk < 0 and op <= m.refAt
                        rk := k
                    if ck < 0 and op <= m.takeAt
                        ck := k
            if ck >= 0 and rk > ck and rk < n
                kWicks.push(line.new(x0 + (n - 1 - rk) * step + half, m.refPx, x0 + (n - 1 - ck) * step + half, m.takePx, xloc = xloc.bar_index, color = LILAC, width = 1, style = m.ssmt ? line.style_dashed : line.style_solid))
    // C2's extreme across the block: solid while it holds, dotted to the candle that traded through it,
    // which is marked with a cross outside its wick.
    int xBrk = -1
    if off2 >= 0 and off2 < n and tagSide != 0
        float c2v = tagSide == -1 ? h.get(off2) : l.get(off2)
        if not na(c2v)
            int brk = -1
            if off2 > 0
                for k = off2 - 1 to 0
                    float ek = tagSide == -1 ? h.get(k) : l.get(k)
                    if brk < 0 and not na(ek) and (tagSide == -1 ? ek > c2v : ek < c2v)
                        brk := k
            int xs = x0 + (n - 1 - off2) * step + half
            int xe = brk >= 0 ? x0 + (n - 1 - brk) * step + half : x0 + n * step - 1
            kWicks.push(line.new(xs, c2v, xe, c2v, xloc = xloc.bar_index, color = INK, width = 1, style = brk >= 0 ? line.style_dotted : line.style_solid))
            if brk >= 0
                xBrk := brk
                string pad = tagSide == 1 and brk < tags.size() and tags.get(brk) != "" ? "\n" : ""
                label xl = label.new(xe, tagSide == -1 ? h.get(brk) : l.get(brk), tagSide == -1 ? "✕" + pad : pad + "✕", xloc = xloc.bar_index, style = tagSide == -1 ? label.style_label_down : label.style_label_up, color = color.new(#FFFFFF, 100), textcolor = INK, size = SZ_BODY)
                label.set_text_font_family(xl, font.family_monospace)
                kLbls.push(xl)
    // The previous candle's high and low, from that candle rightward and named past the block.
    if kPrevHL and n >= 2 and not na(h.get(1)) and not na(l.get(1))
        string nm  = f_kName(tf)
        bool   pre = nm == "1D" or nm == "1W" or nm == "1M"
        string hi  = pre ? "P" + str.substring(nm, 1) + "H" : nm + " H"
        string lo  = pre ? "P" + str.substring(nm, 1) + "L" : nm + " L"
        int    xR  = x0 + n * step - 1
        int    xP  = x0 + (n - 2) * step + half
        for [t, px] in array.from(h.get(1), l.get(1))
            kWicks.push(line.new(xP, px, xR + 1, px, xloc = xloc.bar_index, color = INK, width = 1))
            label pl = label.new(xR + 1, px, t == 0 ? hi : lo, xloc = xloc.bar_index, style = label.style_label_left, color = color.new(#FFFFFF, 100), textcolor = INK, size = SZ_META)
            label.set_text_font_family(pl, font.family_monospace)
            kLbls.push(pl)
    // Quarters of the previous candle's range on the daily and higher blocks, named at the right: D 25%, D 50%, D 75%.
    if qOn and n >= 2 and not na(h.get(1)) and not na(l.get(1))
        float  rLo = l.get(1)
        float  rSz = h.get(1) - rLo
        int    xR  = x0 + n * step - 1
        string nm  = f_kName(tf)
        string tag = nm == "1D" or nm == "1W" or nm == "1M" ? str.substring(nm, 1) : nm
        for q in array.from(0.25, 0.5, 0.75)
            float px  = rLo + rSz * q
            color col = INK
            kWicks.push(line.new(x0 + (n - 2) * step + half, px, xR + 1, px, xloc = xloc.bar_index, color = col, width = 1))
            label ql = label.new(xR + 1, px, tag + " " + str.tostring(int(q * 100)) + "%", xloc = xloc.bar_index, style = label.style_label_left, color = color.new(#FFFFFF, 100), textcolor = col, size = SZ_META)
            label.set_text_font_family(ql, font.family_monospace)
            kLbls.push(ql)
    // The New York open time of the candle that made the block's high and of the one that made its low,
    // left off where a Po3 tag already names that candle on that side, and stepped past the cross when
    // that candle also carries one on the same side.
    bool hiTxt = false
    bool loTxt = false
    if kHlTimes
        for [side, kk] in array.from(hiK, loK)
            bool up = side == 0
            if kk >= 0 and kk < tms.size() and not na(tms.get(kk)) and not (kk < tags.size() and tags.get(kk) != "" and not up)
                label tl = label.new(x0 + (n - 1 - kk) * step + half, up ? hiV : loV, CHART_SEC >= 86400 ? str.format_time(tms.get(kk), "dd MMM", "America/New_York") : str.format_time(tms.get(kk), "HH:mm", "America/New_York"), xloc = xloc.bar_index, style = up ? label.style_label_down : label.style_label_up, color = color.new(#FFFFFF, 100), textcolor = INK, size = SZ_META)
                if kk == xBrk and up == (tagSide == -1)
                    label.set_text(tl, up ? label.get_text(tl) + "\n\n" : "\n\n" + label.get_text(tl))
                label.set_text_font_family(tl, font.family_monospace)
                kLbls.push(tl)
                hiTxt := hiTxt or up
                loTxt := loTxt or not up
    if not na(top)
        // The name and countdown step a text line clear of a tag or a time on the same edge.
        // The timeframe's name sits above AND below the block; the countdown rides on the Name and countdown side.
        bool   atTop = kBadge == "Top"
        string tfNm  = (src ? " ◌ " : "") + f_kName(tf)
        string name  = tfNm + (kTimer ? " · " + f_kTimer(closeT) : "")
        bool   clash = atTop ? topTag or hiTxt : botTag or loTxt
        string txt   = atTop ? name + (clash ? "\n" : "") : (clash ? "\n" : "") + name
        int    xMid  = x0 + int((n * step - 1) / 2)
        label lb = label.new(xMid, atTop ? top : loV, txt, xloc = xloc.bar_index, style = atTop ? label.style_label_down : label.style_label_up, color = color.new(#FFFFFF, 100), textcolor = INK, size = SZ_HEAD, text_formatting = text.format_bold)
        label.set_text_font_family(lb, font.family_monospace)
        kLbls.push(lb)
        bool   clash2 = atTop ? botTag or loTxt : topTag or hiTxt
        string txt2   = atTop ? (clash2 ? "\n" : "") + tfNm : tfNm + (clash2 ? "\n" : "")
        label lb2 = label.new(xMid, atTop ? loV : top, txt2, xloc = xloc.bar_index, style = atTop ? label.style_label_up : label.style_label_down, color = color.new(#FFFFFF, 100), textcolor = INK, size = SZ_HEAD, text_formatting = text.format_bold)
        label.set_text_font_family(lb2, font.family_monospace)
        kLbls.push(lb2)
    x0 + n * step + (kPrevHL or qOn ? 7 : 3)
 
//@function The live T-Spot of the drawn sequence across its candle on the HTF block, to the block's right edge.
//@param x0 (int) Bar index of the block's first candle.
//@param n (int) Candles in the block.
//@param off3 (int) Offset of C3, -1 for none.
//@param off4 (int) Offset of C4, -1 for none.
//@returns (bool) Always true.
f_kSpot(int x0, int n, int off3, int off4) =>
    if p3Spot and p3SpotK and not na(p3Shown)
        Seq rc   = p3Shown
        int   w    = rc.phase >= 4 and off4 >= 0 ? 4 : 3
        int   off  = w == 4 ? off4 : off3
        bool  dead = w == 4 ? rc.spent4 : rc.spent3
        if off >= 0 and off < n and not (dead and p3SpotIn != "Open")
            [zt, zb] = f_p3Zone(rc, w)
            if not na(zt)
                int step = kWidth + 1
                int xs   = x0 + (n - 1 - off) * step - 1
                int xe   = x0 + n * step - 1
                color fc = f_p3SpotCol(rc.side)
                kBoxes.push(box.new(xs, zt, xe, zb, xloc = xloc.bar_index, bgcolor = fc, border_color = fc, border_width = 1))
                if p3SpotEq
                    float eq = f_p3Eq(rc, zt, zb)
                    kWicks.push(line.new(xs, eq, xe, eq, xloc = xloc.bar_index, color = rc.side == 1 ? C_UP : C_DN, width = 1))
    true
 
//@function Dashed lines from the chart candles that made the forming HTF candle's high and low across to
//          that candle on the block.
//@param x0 (int) Bar index of the block's first candle.
//@param n (int) Candles in the block.
//@returns (bool) Always true.
f_kOrigin(int x0, int n) =>
    if kOrigin and p3On and p3Cs.size() > 0 and n > 0
        Candle cd = p3Cs.last()
        int      xc = x0 + (n - 1) * (kWidth + 1) + int((kWidth - 1) / 2)
        for [i, b] in array.from(cd.hiB, cd.loB)
            float px = i == 0 ? cd.h : cd.l
            if not na(b) and b < bar_index
                kWicks.push(line.new(math.max(b, bar_index - 4900), px, xc, px, xloc = xloc.bar_index, color = K_REF, width = 1, style = line.style_dashed))
    true
 
//@function The forming HTF candle's open, dotted, and the previous candle's EQ, solid while closes hold the
//          side the candle opened on and dotted once one crosses, each from where it formed to past the
//          block, named there. The EQ is left off where the previous range's 50% line already names it.
//@param x0 (int) Bar index of the block's first candle.
//@param n (int) Candles in the block.
//@param tf (string) The block's timeframe.
//@returns (bool) Always true.
f_kOpenEq(int x0, int n, string tf) =>
    if kOpenEq and p3On and p3Cs.size() >= 2 and n >= 2
        Candle cd  = p3Cs.last()
        Candle pv  = p3Cs.get(p3Cs.size() - 2)
        int      xR  = x0 + n * (kWidth + 1)
        string   nm  = f_kName(tf)
        bool     qOn = f_kQOn(tf)
        if not na(cd.oB)
            kWicks.push(line.new(math.max(cd.oB, bar_index - 4900), cd.o, xR, cd.o, xloc = xloc.bar_index, color = OPENS, width = 1, style = line.style_dotted))
            label ol = label.new(xR, cd.o, nm + " open", xloc = xloc.bar_index, style = label.style_label_left, color = color.new(#FFFFFF, 100), textcolor = INK, size = SZ_META)
            label.set_text_font_family(ol, font.family_monospace)
            kLbls.push(ol)
        float eq = math.avg(pv.h, pv.l)
        if not qOn and not na(pv.oB) and math.abs(eq - cd.o) > syminfo.mintick
            kWicks.push(line.new(math.max(pv.oB, bar_index - 4900), eq, xR, eq, xloc = xloc.bar_index, color = INK, width = 1, style = p3EqBroken ? line.style_dotted : line.style_solid))
            label el = label.new(xR, eq, nm + " EQ", xloc = xloc.bar_index, style = label.style_label_left, color = color.new(#FFFFFF, 100), textcolor = INK, size = SZ_META)
            label.set_text_font_family(el, font.family_monospace)
            kLbls.push(el)
    true
 
//@function The sequence CISD: from the open where the opposing run began to the confirming candle, in the
//          sequence's colour, dotted once a close has gone back through it. Left off where a CISD line
//          already sits within four ticks.
//@param rc (Seq) The sequence.
//@returns (bool) Always true.
f_p3SeqCx(Seq rc) =>
    if p3SeqCx and not na(rc.cxStartT) and not na(rc.cxLvl) and not na(rc.cxT)
        bool taken = false
        for c in cxDone
            if not c.dead and math.abs(c.lvl - rc.cxLvl) <= syminfo.mintick * 4
                taken := true
        if not taken
            int   x2  = rc.cxT + CHART_SEC * 1000 * 3
            color col = rc.side == 1 ? C_UP : C_DN
            p3Lines.push(line.new(rc.cxStartT, rc.cxLvl, x2, rc.cxLvl, xloc = xloc.bar_time, color = col, width = 1, style = na(rc.cxBrokeT) ? line.style_solid : line.style_dotted))
            f_p3Lbl(x2, rc.cxLvl, "CISD", label.style_label_left, text.align_left)
    true
 
//@function A divider's top name, always the New York calendar day of the candle's open: a Sunday 18:00
//          open reads Sun. Weekly reads the open's date; monthly the month the candle covers. Below a day
//          only the first divider of each New York day carries it.
//@param t (int) The candle's open time.
//@param tPrev (int) The previous divider's open time, na for the first.
//@returns (string) The name, empty for none.
f_p3DivName(int t, int tPrev) =>
    string d = str.format_time(t, "EEE", "America/New_York")
    p3SrcSec >= 2419200 ? str.format_time(t + 43200000, "MMM", "America/New_York") : p3SrcSec >= 604800 ? str.format_time(t, "dd MMM", "America/New_York") : p3SrcSec >= 86400 or na(tPrev) ? d : d != str.format_time(tPrev, "EEE", "America/New_York") ? d : ""
 
//@function The dividers' names: the day above the top of each line, the New York open time below its
//          foot (a day or less), both in black. Fixed lane: each sits one blank text row past its end of
//          the line. A CISD name is centred on its level and a SMT name takes the first row off its line,
//          both inside the dividers' span, so neither reaches the divider row.
//@returns (bool) Always true.
f_p3DivNames() =>
    if p3Ok and p3DivOn and p3DivLbl and p3DivTs.size() > 0
        for [i, t0] in p3DivTs
            string nm = f_p3DivName(t0, i > 0 ? p3DivTs.get(i - 1) : na)
            if nm != ""
                label dl = label.new(t0, line.get_y1(p3Divs.get(i)), nm + "\n", xloc = xloc.bar_time, style = label.style_label_down, color = color.new(#FFFFFF, 100), textcolor = INK, size = SZ_META, textalign = text.align_center)
                label.set_text_font_family(dl, font.family_monospace)
                p3Lbls.push(dl)
            if p3SrcSec <= 86400 and not spOn
                label tl = label.new(t0, line.get_y2(p3Divs.get(i)), "\n" + str.format_time(t0, "HH:mm", "America/New_York"), xloc = xloc.bar_time, style = label.style_label_up, color = color.new(#FFFFFF, 100), textcolor = INK, size = SZ_META, textalign = text.align_center)
                label.set_text_font_family(tl, font.family_monospace)
                p3Lbls.push(tl)
    true
 
if barstate.islast
    if p3Ok and not na(p3Shown)
        f_p3SeqCx(p3Shown)
    f_p3DivNames()
 
if barstate.islast
    for b in kBoxes
        box.delete(b)
    for w in kWicks
        line.delete(w)
    for lb in kLbls
        label.delete(lb)
    kBoxes.clear()
    kWicks.clear()
    kLbls.clear()
    if kOn
        array<float> kOa = array.from(kO0, kO1, kO2, kO3, kO4, kO5, kO6, kO7, kO8, kO9, kO10, kO11, kO12, kO13, kO14)
        array<float> kHa = array.from(kH0, kH1, kH2, kH3, kH4, kH5, kH6, kH7, kH8, kH9, kH10, kH11, kH12, kH13, kH14)
        array<float> kLa = array.from(kL0, kL1, kL2, kL3, kL4, kL5, kL6, kL7, kL8, kL9, kL10, kL11, kL12, kL13, kL14)
        array<float> kCa = array.from(kC0, kC1, kC2, kC3, kC4, kC5, kC6, kC7, kC8, kC9, kC10, kC11, kC12, kC13, kC14)
        array<int> kTa = array.from(kT0, kT1, kT2, kT3, kT4, kT5, kT6, kT7, kT8, kT9, kT10, kT11, kT12, kT13, kT14)
        array<bool>  kPa = f_p3LanePsp(p3Cs, kTa)
        [tg, o1, o2, o3, o4] = f_p3Tags(kTa)
        f_kBlock(bar_index + kOffset, kTf, kOa, kHa, kLa, kCa, kTc, kPa, tg, na(p3Shown) ? 0 : p3Shown.side, o1, o2, kTa, p3Ok)
        int kN = math.min(math.max(kCount, o1 + 1), kOa.size())
        f_kSpot(bar_index + kOffset, kN, o3, o4)
        f_kOrigin(bar_index + kOffset, kN)
        f_kOpenEq(bar_index + kOffset, kN, kTf)
 
// == PDH / PDL ON THE CHART ==
// The previous day's high and low across the live chart, for the charts where the HTF block is not a day.
// Read off the chart's own bars, so each line starts on the bar that printed it. A day the chart did
// not see from its open is never adopted: its extremes are not the day's.
 
var bool  pdSeen   = false
var float pdDayHi  = na
var float pdDayLo  = na
var int   pdDayHiT = na
var int   pdDayLoT = na
var float pdH      = na
var float pdL      = na
var int   pdHT     = na
var int   pdLT     = na
var bool  pdHTaken = false
var bool  pdLTaken = false
 
int  pdDay    = time("D")
bool pdNewDay = timeframe.isintraday and not na(pdDay) and pdDay != pdDay[1]
if pdNewDay
    if pdSeen
        pdH  := pdDayHi
        pdHT := pdDayHiT
        pdL  := pdDayLo
        pdLT := pdDayLoT
    pdSeen   := true
    pdHTaken := false
    pdLTaken := false
    pdDayHi  := high
    pdDayHiT := time
    pdDayLo  := low
    pdDayLoT := time
else if timeframe.isintraday
    if na(pdDayHi) or high > pdDayHi
        pdDayHi  := high
        pdDayHiT := time
    if na(pdDayLo) or low < pdDayLo
        pdDayLo  := low
        pdDayLoT := time
if not na(pdH) and high > pdH
    pdHTaken := true
if not na(pdL) and low < pdL
    pdLTaken := true
 
bool kDayBlock = kOn and kPrevHL and f_kName(kTf) == "1D"
if barstate.islast and kChartPD and timeframe.isintraday and not kDayBlock
    int xR = time + timeframe.in_seconds() * 1000
    for [i, px] in array.from(pdH, pdL)
        if not na(px)
            bool taken = i == 0 ? pdHTaken : pdLTaken
            int  x1    = i == 0 ? pdHT : pdLT
            kWicks.push(line.new(x1, px, xR, px, xloc = xloc.bar_time, color = INK, width = 1, style = taken ? line.style_dotted : line.style_solid))
            label pl = label.new(xR, px, i == 0 ? "PDH" : "PDL", xloc = xloc.bar_time, style = label.style_label_left, color = color.new(#FFFFFF, 100), textcolor = INK, size = SZ_BODY)
            label.set_text_font_family(pl, font.family_monospace)
            kLbls.push(pl)
 
// == ALERTS ==
// Only for sequences the chart would draw: direction, SSMT filter, xC2 wait and T-Spot filter. A closure
// alerts once, the first confirmed bar it qualifies. A spent T-Spot alerts on the bar after its candle
// closed through the EQ, read from the candles themselves so nothing depends on a earlier tick.
var array<int> p3AlDone = array.new<int>()
bool p3AlC2Bull = false
bool p3AlC2Bear = false
bool p3AlC3Bull = false
bool p3AlC3Bear = false
bool p3AlX      = false
if p3Ok and barstate.isconfirmed and p3Recs.size() > 0
    bool htfNew = p3Cs.size() >= 2 and p3Cs.last().t == time(p3Tf) and time(p3Tf) != time(p3Tf)[1]
    for rc in p3Recs
        if rc.live and not f_p3Forming(rc) and rc.phase >= 3 and f_p3Visible(rc) and f_p3SpotOk(rc)
            int akey = rc.c2.t * rc.side
            if not p3AlDone.includes(akey)
                p3AlDone.push(akey)
                if p3AlDone.size() > 40
                    p3AlDone.shift()
                if rc.side == 1
                    p3AlC2Bull := p3AlC2Bull or not rc.viaC3
                    p3AlC3Bull := p3AlC3Bull or rc.viaC3
                else
                    p3AlC2Bear := p3AlC2Bear or not rc.viaC3
                    p3AlC3Bear := p3AlC3Bear or rc.viaC3
        if htfNew and f_p3Visible(rc) and f_p3SpotOk(rc)
            int lastT = p3Cs.get(p3Cs.size() - 2).t
            for w in array.from(3, 4)
                int wt = w == 3 ? rc.c3.t : rc.c4.t
                if not na(wt) and wt == lastT
                    [zt, zb] = f_p3Zone(rc, w)
                    float cl = p3Cs.get(p3Cs.size() - 2).c
                    if not na(zt) and (rc.side == 1 ? cl < zb : cl > zt)
                        p3AlX := true
alertcondition(p3AlC2Bull, "Bullish C2 closure", "Bullish C2 closure on {{ticker}}: C3 should wick into the EQ zone and hold")
alertcondition(p3AlC2Bear, "Bearish C2 closure", "Bearish C2 closure on {{ticker}}: C3 should wick into the EQ zone and hold")
alertcondition(p3AlC3Bull, "Bullish C3 closure", "Bullish C3 closure on {{ticker}}: C4 should wick into the EQ zone and hold")
alertcondition(p3AlC3Bear, "Bearish C3 closure", "Bearish C3 closure on {{ticker}}: C4 should wick into the EQ zone and hold")
alertcondition(p3AlX, "T-Spot spent", "T-Spot spent on {{ticker}}: the candle closed through the EQ")

← 返回列表