HDSXNTRADER

PO3 HDSXN

Nov 23rd, 2026
424
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 186.16 KB | Software | 1 0
  1. //@version=6
  2. indicator("PO3 Fractal Model by HDSXN", shorttitle = "PO3FM", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, calc_bars_count = 2000)
  3.  
  4. // Built from PO3 Fractal v4 (kept unchanged as the reference), aligned to the TTrades Fractal Model:
  5. // HTF closure (C2 / C3) + LTF CISD, C4 continuation, T-Spot, candle EQ, C1 sweep, SD projections, formation
  6. // liquidity, bias / Auto Bias, up to 3 time filters, history 0-40, early CISD, SMT, info table and alerts.
  7. // Full version. ON by default: the model, protected swings, SMT, PSP, chart CISD, HTF FVG and the setup table
  8. // (+ grade on the model CISD). OFF by default (can be turned on in the settings): extra HTF blocks, ADR / CDR,
  9. // sessions, BSL / SSL and IFVG. PDH / PDL / PWH / PWL are ON.
  10.  
  11. //#region [INPUTS]
  12. // Input sections in display order; Calculation comes last.
  13. // TradingView stores settings by position (in_0, in_1 ...): adding or removing an input shifts every later one.
  14.  
  15. grpAlerts = 'Alerts Settings'
  16. showAlerts = input.bool(true, 'Alerts?', group = grpAlerts, tooltip = "Master switch for every alert of this indicator.\n\nTo create one: click the three dots next to the indicator name (or right-click it on the chart) > Add alert > Create. Condition: Any alert() function call. Alerts keep the settings they were created with; after changing these, create the alert again.")
  17. modelAlerts = input.bool(true, 'Model Candles?', group = grpAlerts, tooltip = 'A full model: a C2 or C3 closure with its CISD, or its continuation. The alert says Candle 2, Candle 3 or Candle 4.')
  18. earlyCisdAlerts = input.bool(false, 'Early CISD?', group = grpAlerts, tooltip = 'A CISD before the HTF candle has closed. The alert says Potential Candle 2.')
  19. smtAlerts = input.bool(true, 'SMT Divergence?', group = grpAlerts, tooltip = 'A correlated pair disagrees while a model runs: after C2 closes, the pair goes past its own C2 extreme while price does not.')
  20. protAlerts = input.bool(true, 'Protected Swings?', group = grpAlerts, tooltip = 'A new protected swing (continuation dot) after the reversal CISD.')
  21.  
  22. grpWarn = 'Warnings and Error Messages'
  23. showWarn = input.bool(true, 'Show?', group = grpWarn, tooltip = 'Shows a short message on the chart when something cannot work: the chart timeframe does not fit the selected fractal, or a correlated pair has no data.')
  24.  
  25. grpModel = 'General Settings'
  26. showHistory = input.int(1, 'History', minval = 0, maxval = 40, group = grpModel, tooltip = 'How many earlier setups stay drawn next to the latest one. 0 = only the latest.')
  27. modelType = input.string('Automatic', 'Fractal', options = ['Automatic', 'Custom', '1s-1m', '15s-5m', '1m-15m', '3m-30m', '5m-1H', '15m-4H', '1H-1D', '4H-1W', '1D-1M'], group = grpModel, inline = 'fractal')
  28. showC2 = input.bool(true, 'C2', group = grpModel, inline = 'fractal')
  29. showC3 = input.bool(true, 'C3', group = grpModel, inline = 'fractal')
  30. showC4 = input.bool(true, 'C4', group = grpModel, inline = 'fractal', tooltip = "Fractal: chart timeframe - model HTF. Automatic picks it from the chart (1m - 15m, 5m - 1H, 15m - 4H, 30m - 4H, 1H - 1D, 4H - 1W ...).\n\nC2: C2 closure models (C2 takes C1's high / low and closes back inside). C3: C3 closure models (C2 took C1 without closing back inside, C3 closes beyond C2's body without taking C2's extreme). C4: the C4 continuation (its T-Spot). A model is only drawn once its CISD confirms.")
  31. customLTF = input.timeframe('60', 'Custom Fractal', group = grpModel, inline = 'custom')
  32. customHTF = input.timeframe('1D', '-', group = grpModel, inline = 'custom', tooltip = 'Only used when Fractal is Custom: the entry timeframe and the HTF the model runs on.')
  33. biasFilter = input.string('Neutral', 'Bias', options = ['Neutral', 'Bullish', 'Bearish', 'Auto Bias 1', 'Auto Bias 2'], group = grpModel, tooltip = 'Neutral: bullish and bearish setups. Bullish / Bearish: only setups of that side are shown.\n\nAuto Bias 1 / 2: follows the fractal model one / two steps higher (on 5m-1H: 15m-4H / 1H-1D). While that model runs (C3 and C4, until its C2 extreme is closed through) only setups in its direction are shown; with no higher model both sides show.')
  34.  
  35. grpCandles = 'HTF Candles'
  36. htfCandleCount = input.int(4, 'HTF Candles', minval = 1, maxval = 40, group = grpCandles, tooltip = '1 to 40 candles drawn. The model always keeps the last 5 HTF candles in memory, whatever is drawn.')
  37. htfSize = input.string('Small', 'Size', options = ['Small', 'Normal', 'Large'], group = grpCandles, inline = 'size')
  38. hideHtf = input.bool(false, 'Hide?', group = grpCandles, inline = 'size')
  39. hideSetups = input.bool(false, 'Hide Setups?', group = grpCandles, inline = 'size', tooltip = 'Hide?: hides the HTF candles on the right.\n\nHide Setups?: no models on the chart (C2 / C3 / C4, CISD, T-Spots, protected swings, chart SMT, projections, formation liquidity, early CISD), and no model alerts. The HTF candles and their lines stay.')
  40. showX1 = input.bool(false, 'HTF 1', group = grpCandles, inline = 'xhtf')
  41. x1Sel = input.string('Auto', '', options = ['Auto', '15m', '30m', '1H', '90m', '4H', '6H', '7H', 'D', 'W', 'M'], group = grpCandles, inline = 'xhtf')
  42. showX2 = input.bool(false, 'HTF 2', group = grpCandles, inline = 'xhtf')
  43. x2Sel = input.string('Auto', '', options = ['Auto', '15m', '30m', '1H', '90m', '4H', '6H', '7H', 'D', 'W', 'M'], group = grpCandles, inline = 'xhtf', tooltip = 'Extra HTF candles to the right of the model HTF candles, with its title (HTF Label / Remaining Time) above and / or below each block.\n\nAuto: HTF 1 = one step above the model HTF, HTF 2 = one step above HTF 1 (1m-15m: 1H / 4H, 5m-1H: 4H / D, 15m-4H: D / W, 1H-1D: W / M). 90m, 6H and 7H are never picked by Auto.\n\nNo model runs on them; they show Previous EQ, Candle 1 Sweep, SMT and PSP like the model block (HTF Open only on the model block), with the same settings. Up to 10 candles each (HTF Candles).')
  44. candleOffsetIn = input.int(0, 'Offset', minval = -100, maxval = 100, group = grpCandles, tooltip = 'Positive: moves the HTF candles to the right. Negative: to the left.')
  45. bullBody = input.color(color.rgb(255, 255, 255), 'Body', group = grpCandles, inline = 'body')
  46. bearBodyIn = input.color(#131722, '', group = grpCandles, inline = 'body')
  47. borderBullIn = input.color(#2a2e39, 'Border', group = grpCandles, inline = 'border')
  48. borderBearIn = input.color(#2a2e39, '', group = grpCandles, inline = 'border')
  49. wickBullIn = input.color(#2a2e39, 'Wick', group = grpCandles, inline = 'wick')
  50. wickBearIn = input.color(#2a2e39, '', group = grpCandles, inline = 'wick', tooltip = 'Body, Border, Wick: left bullish, right bearish.')
  51.  
  52. htfOpenColor = input.color(color.new(#787b86, 20), '', group = grpCandles, inline = 'htfopen')
  53. showHtfOpen = input.bool(true, 'HTF Open', group = grpCandles, inline = 'htfopen')
  54. htfOpenStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], group = grpCandles, inline = 'htfopen')
  55. htfOpenWidth = input.int(1, 'Width', minval = 1, group = grpCandles, inline = 'htfopen')
  56.  
  57. lineColor = input.color(color.new(#787b86, 75), '', group = grpCandles, inline = 'vline')
  58. showVlines = input.bool(true, 'Vertical Lines', group = grpCandles, inline = 'vline')
  59. lineStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], group = grpCandles, inline = 'vline')
  60. lineWidth = input.int(1, 'Width', minval = 1, group = grpCandles, inline = 'vline')
  61.  
  62. lhColor = input.color(color.new(#787B86, 40), '', group = grpCandles, inline = 'lh')
  63. showLH = input.bool(false, 'L/H Lines', group = grpCandles, inline = 'lh')
  64. lhStyle = input.string('Dotted', '', options = ['Solid', 'Dashed', 'Dotted'], group = grpCandles, inline = 'lh')
  65. lhWidth = input.int(1, 'Width', minval = 1, group = grpCandles, inline = 'lh')
  66.  
  67. prevEqColor = input.color(#787b86, '', group = grpCandles, inline = 'peq')
  68. showPrevEq = input.bool(true, 'Previous EQ', group = grpCandles, inline = 'peq')
  69. prevEqStyle = input.string('Dotted', '', options = ['Solid', 'Dashed', 'Dotted'], group = grpCandles, inline = 'peq')
  70. prevEqWidth = input.int(1, 'Width', minval = 1, group = grpCandles, inline = 'peq')
  71.  
  72. drawType = input.string('Both', 'Drawings Type', options = ['On Chart', 'HTF Candle', 'Both'], group = grpCandles, tooltip = "Where HTF Open and Previous EQ are drawn.\n\nOn Chart: from the open of the current HTF candle to the last bar.\nHTF Candle: on the HTF candles on the right.\nBoth: one line from the chart to the HTF candles.\n\nL/H Lines (the high and low of each HTF candle, over its own period) and vertical lines are drawn on the chart when turned on, whatever this setting.")
  73.  
  74. grpTime = 'HTF Candles Time Labels'
  75. showHtfStamps = input.bool(false, 'Enable Time Labels?', group = grpTime, tooltip = 'Open time under each HTF candle: the day name for daily, the date for weekly (NOV 2), the month for monthly.')
  76. timeFormat = input.string('24h', 'Time Format', options = ['24h', '12h'], group = grpTime)
  77. useCustomTz = input.bool(false, 'Custom Timezone? UTC', group = grpTime, inline = 'tz')
  78. tzHour = input.int(1, '', minval = -12, maxval = 14, group = grpTime, inline = 'tz')
  79. tzMin = input.int(0, ':', minval = 0, maxval = 59, group = grpTime, inline = 'tz', tooltip = 'Off: New York time. On: this UTC offset, e.g. 3 : 0 for Turkey.')
  80. showHtfName = input.bool(true, 'HTF Label', group = grpTime, inline = 'hname')
  81. showHtfTimer = input.bool(false, 'Remaining Time', group = grpTime, inline = 'hname')
  82. htfNamePos = input.string('Both', '', options = ['Both', 'Top', 'Bottom'], group = grpTime, inline = 'hname', tooltip = 'Over and / or under each block of HTF candles: its timeframe and the time left until the forming candle closes, e.g. 1H (12:40).')
  83. htfInfoColor = #787b86 // HTF time labels and time left (mid gray)
  84. htfNameColorL = #2a2e39 // HTF block timeframe name (dark, bold)
  85.  
  86. grpVisuals = 'Model Style'
  87. showEarlyCisd = input.bool(false, 'Show Early C2 CISD', group = grpVisuals, inline = 'early')
  88. earlyCisdStyle = input.string('Dotted', '', options = ['Solid', 'Dashed', 'Dotted'], group = grpVisuals, inline = 'early', tooltip = 'Early CISD: price closes through the CISD level while C2 is still forming, before the C2 candle closes. Drawn in the Bullish / Bearish CISD colors. Its alert is Early CISD? in Alerts Settings.')
  89.  
  90. cisdBullColor = input.color(#2962ff, '', group = grpVisuals, inline = 'bullcisd')
  91. showBullCisd = input.bool(true, 'Bullish CISD', group = grpVisuals, inline = 'bullcisd')
  92. cisdBullStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], group = grpVisuals, inline = 'bullcisd')
  93. cisdBullWidth = input.int(2, 'Width', minval = 1, group = grpVisuals, inline = 'bullcisd')
  94.  
  95. cisdBearColor = input.color(#f23645, '', group = grpVisuals, inline = 'bearcisd')
  96. showBearCisd = input.bool(true, 'Bearish CISD', group = grpVisuals, inline = 'bearcisd')
  97. cisdBearStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], group = grpVisuals, inline = 'bearcisd')
  98. cisdBearWidth = input.int(2, 'Width', minval = 1, group = grpVisuals, inline = 'bearcisd')
  99.  
  100. eqColor = input.color(#787b86, '', group = grpVisuals, inline = 'eq')
  101. showEQ = input.bool(true, 'Candle Equilibrium', group = grpVisuals, inline = 'eq')
  102. eqStyle = input.string('Dotted', '', options = ['Solid', 'Dashed', 'Dotted'], group = grpVisuals, inline = 'eq')
  103. eqWidth = input.int(1, 'Width', minval = 1, group = grpVisuals, inline = 'eq', tooltip = 'Line inside the T-Spot box: the middle of the previous HTF candle.')
  104.  
  105. sweepColorIn = input.color(#000000, '', group = grpVisuals, inline = 'sweep')
  106. showSweep = input.bool(true, 'Candle 1 Sweep', group = grpVisuals, inline = 'sweep')
  107. sweepStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], group = grpVisuals, inline = 'sweep')
  108. sweepWidth = input.int(1, 'Width', minval = 1, group = grpVisuals, inline = 'sweep')
  109. sweepDisplay = input.string('Both', 'C1 Sweep Display', options = ['Both', 'Chart', 'HTF Candles'], group = grpVisuals, tooltip = "Chart: line from the C1 high / low that C2 took, to where C2 closed.\nHTF Candles: the same on the HTF candles, plus a live line while the forming candle has taken the previous one and is back inside its range.\nBoth: both.")
  110.  
  111. showLabels = input.bool(true, 'Show Labels?', group = grpVisuals, inline = 'lbl')
  112. labelSize = input.string('Small', '', options = ['Tiny', 'Small', 'Normal', 'Large', 'Huge'], group = grpVisuals, inline = 'lbl')
  113. c2c3c4ColorL = #2a2e39 // C2 / C3 / C4 label text
  114.  
  115. showTSpot = input.bool(true, 'T-Spot', group = grpVisuals, inline = 'tspot')
  116. tSpotBullColor = input.color(color.new(#4caf50, 88), 'Bullish', group = grpVisuals, inline = 'tspot')
  117. tSpotBearColor = input.color(color.new(#787b86, 90), 'Bearish', group = grpVisuals, inline = 'tspot')
  118.  
  119. grpProt = 'Protected Swings'
  120. showIcCisd = input.bool(true, 'Enable Protected Swings?', group = grpProt, inline = 'proton', tooltip = "Continuations after the CISD. A swing is protected when it traded into a fair value gap in the setup's direction or took an earlier untaken swing, and price then closes through the opposite candles that led into it: a dot on the swing, plus a line (Style / Width) at the level that was closed through. A dot turns gray once price trades back through the swing and stays until the setup leaves the history.")
  121. protStyle = input.string('Solid', 'Style', options = ['Solid', 'Dashed', 'Dotted'], group = grpProt, inline = 'protsty')
  122. protWidth = input.int(1, 'Width', minval = 1, group = grpProt, inline = 'protsty')
  123. protBullColor = input.color(#2962ff, 'Bullish', group = grpProt, inline = 'protclr')
  124. protBearColor = input.color(#f23645, 'Bearish', group = grpProt, inline = 'protclr')
  125.  
  126. grpSmt = 'Asset Correlation'
  127. show_smt = input.bool(true, 'Enable SMT?', group = grpSmt, inline = 'smt', tooltip = 'SMT = this symbol and a correlated one disagree at the same level: one takes the previous high (or low), the other does not. Its alert is SMT Divergence? in Alerts Settings.')
  128. smtDisplay = input.string('Both', 'SMT Display', options = ['Both', 'Chart', 'HTF Candles'], group = grpSmt, tooltip = 'Chart: only for setups. The reversal SMT from the C1 to the C2 high / low, and the continuation SMT: after C2 a pair goes beyond the high / low of its own C2 candle while we do not; the line runs from our C2 extreme and its end follows our further highs / lows.\nHTF Candles: between the HTF candles on the right, the forming candle included.')
  129. smtLabels = input.bool(true, 'Labels?', group = grpSmt, inline = 'smtlbl')
  130. smtLblSize = input.string('Tiny', '', options = ['Tiny', 'Small', 'Normal', 'Large', 'Huge'], group = grpSmt, inline = 'smtlbl', tooltip = 'On the chart the label names the pair that made the SMT. The HTF candles show the line only.')
  131. pairMode = input.string('Automatic', 'Correlated Pairs', options = ['Automatic', 'Custom'], group = grpSmt, inline = 'pairs')
  132. useSecondPair = input.bool(true, 'Enable Second Pair?', group = grpSmt, inline = 'pairs', tooltip = "Automatic:\nFutures: NQ - ES + YM, ES - NQ + YM, YM / RTY - ES + NQ, GC - XAUEUR + XAUGBP, SI - XAGEUR + XAGGBP, CL - RB + HO, HO - CL + RB, RB - CL + HO\nCFD (same broker): US100 - US500 + US30, US500 - US100 + US30, US30 - US500 + US100, XAUUSD - XAUEUR + XAUGBP, XAGUSD - XAGEUR + XAGGBP, EURUSD - GBPUSD\n\nCustom: the two symbols below.")
  133. pair1In = input.symbol('CME_MINI:ES1!', '1.', group = grpSmt, inline = 'p1')
  134. pair1Inv = input.bool(false, 'Inverse?', group = grpSmt, inline = 'p1', tooltip = 'Inverse: the pair moves opposite to this symbol (e.g. DXY against EURUSD). Its highs are compared with your lows.')
  135. pair2In = input.symbol('CME_MINI:NQ1!', '2.', group = grpSmt, inline = 'p2')
  136. pair2Inv = input.bool(false, 'Inverse?', group = grpSmt, inline = 'p2')
  137. smtBullColor = input.color(#ff9800, '', group = grpSmt, inline = 'smtln')
  138. smtBearColor = input.color(#ff9800, '', group = grpSmt, inline = 'smtln')
  139. smtStyle = input.string('Solid', 'SMT Line', options = ['Solid', 'Dashed', 'Dotted'], group = grpSmt, inline = 'smtln')
  140. smtWidth = input.int(1, 'Width', minval = 1, group = grpSmt, inline = 'smtln', tooltip = 'Left color: bullish SMT (at lows). Right color: bearish SMT (at highs). Used for the lines and the pair names, on the chart and on the HTF candles.')
  141. showPsp = input.bool(true, 'Enable PSP?', group = grpSmt, inline = 'psp')
  142. pspMode = input.string('Both', '', options = ['Candle 1', 'Candle 2', 'Both'], group = grpSmt, inline = 'psp', tooltip = 'PSP (Precision Swing Point): the C1 or C2 candle closes a different color than the same HTF candle on a correlated pair (one bullish, one bearish). The C2 label on the swing then reads C2+PSP (a C3 model also shows C2 / C2+PSP on its C2 extreme, and C3 on C3). Dojis are ignored.')
  143.  
  144. grpStdDev = 'Standard Deviation Projections'
  145. showStdDev = input.bool(true, 'Enable Projections?', group = grpStdDev)
  146. stdLabels = input.bool(true, 'Labels?', group = grpStdDev, inline = 'sdl')
  147. stdLblSize = input.string('Small', '', options = ['Tiny', 'Small', 'Normal', 'Large'], group = grpStdDev, inline = 'sdl')
  148. stdDevCalc = input.string('Body to Wick', 'Type', options = ['Wick to Wick', 'Body to Wick'], group = grpStdDev, inline = 'sdt')
  149. stdDevInput = input.string('-1, -2, -2.5, -4, -4.5', '', group = grpStdDev, inline = 'sdt', tooltip = "Levels as multiples of the C2 leg, which always ends on the wick of the C2 extreme (the low of a bullish C2, the high of a bearish one). Body to Wick: the leg starts at the CISD level (the open, so the body, of the candle the CISD comes from). Wick to Wick: it starts at that candle's wick (its high in a bullish setup, its low in a bearish one). Negative = beyond the start of the leg, in the setup's direction.")
  150. stdDevColor = input.color(color.new(#787B86, 0), '', group = grpStdDev, inline = 'sdc')
  151. stdStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], group = grpStdDev, inline = 'sdc')
  152. stdWidth = input.int(1, 'Width', minval = 1, group = grpStdDev, inline = 'sdc')
  153.  
  154. grpFl = 'Formation Liquidity'
  155. showFl = input.bool(true, 'Enable Formation Liquidity?', group = grpFl, tooltip = 'Targets of the model: the high (bullish) or low (bearish) of the C1 candle and of the candle before it. A line starts where that high / low printed and stops at the bar that takes it.')
  156. flColor = input.color(#9598a1, '', group = grpFl, inline = 'fl')
  157. flStyle = input.string('Dotted', '', options = ['Solid', 'Dashed', 'Dotted'], group = grpFl, inline = 'fl')
  158. flWidth = input.int(1, 'Width', minval = 1, group = grpFl, inline = 'fl')
  159.  
  160. grpTimeF = 'Time Filter'
  161. useTimeFilter = input.bool(false, 'Enable Time Filter?', group = grpTimeF, tooltip = 'New setups only when the HTF candle that makes the closure (C2, or C3 for a C3 model) OPENS inside one of the checked windows. On 1H with 08:00-11:30 the first closure is the one at 09:00: to include the 08:00 closure, start at 07:00. With no window checked, nothing is filtered.')
  162. tfApplyBelow = input.timeframe('60', 'Apply below', group = grpTimeF, tooltip = 'Only charts below this timeframe are filtered.')
  163. tfUseTz = input.bool(false, 'Custom Timezone? UTC', group = grpTimeF, inline = 'tftz')
  164. tfTzHour = input.int(1, '', minval = -12, maxval = 14, group = grpTimeF, inline = 'tftz')
  165. tfTzMin = input.int(0, ':', minval = 0, maxval = 59, group = grpTimeF, inline = 'tftz', tooltip = 'Off: the windows are New York time.')
  166. f1On = input.bool(false, 'Filter 1', group = grpTimeF, inline = 'f1')
  167. f1Sess = input.session('0200-0500', '', group = grpTimeF, inline = 'f1')
  168. f2On = input.bool(false, 'Filter 2', group = grpTimeF, inline = 'f2')
  169. f2Sess = input.session('0800-1100', '', group = grpTimeF, inline = 'f2')
  170. f3On = input.bool(false, 'Filter 3', group = grpTimeF, inline = 'f3')
  171. f3Sess = input.session('1330-1615', '', group = grpTimeF, inline = 'f3')
  172.  
  173.  
  174. // [ADR] average daily range + current daily range, shown in the Info Table
  175. grpAdr = 'ADR / CDR'
  176. adrShow = input.bool(false, 'Show in Info Table', group = grpAdr, inline = 'adrtbl')
  177. adrLen = input.int(14, 'Length', minval = 1, maxval = 100, group = grpAdr, inline = 'adrtbl', tooltip = 'ADR = average high-low of this many completed days (today excluded). CDR = today\'s high-low so far, with its share of ADR. A day starts 18:00 New York (forex 17:00), on every broker. Forex in pips, the rest in price points.')
  178. adrLinesShow = input.bool(false, 'ADR+ / ADR- Lines', group = grpAdr, inline = 'adrln', tooltip = 'ADR+ = today\'s low + ADR, ADR- = today\'s high - ADR: how far the day can still reach if it makes a full average range. Drawn for the current day only.')
  179. adrLineColor = input.color(#b2b5be, '', group = grpAdr, inline = 'adrln')
  180. adrLineStyle = input.string('Dashed', '', options = ['Solid', 'Dashed', 'Dotted'], group = grpAdr, inline = 'adrln')
  181.  
  182. grpInfo = 'Info Table'
  183. tbl_show = input.bool(true, 'Show Info?', group = grpInfo, inline = 'info')
  184. tbl_style = input.string('Text', '', options = ['Table', 'Text'], group = grpInfo, inline = 'info')
  185. tbl_text_size = input.string('Tiny', '', options = ['Tiny', 'Small', 'Normal', 'Large'], group = grpInfo, inline = 'info')
  186. tbl_border = input.bool(false, 'Border?', group = grpInfo, inline = 'info', tooltip = 'Table: with a background. Text: text only. Border?: a frame around it.\n\nRows: symbol (timeframe), model, time to close, bias, time filter (only when it is on), SMT pairs, ADR + CDR %, date.')
  187. tbl_pos_vert = input.string('Bottom', 'Table Location', options = ['Top', 'Middle', 'Bottom'], group = grpInfo, inline = 'tblpos')
  188. tbl_pos_horiz = input.string('Right', '', options = ['Left', 'Center', 'Right'], group = grpInfo, inline = 'tblpos')
  189. tbl_asset = input.bool(true, 'Asset', group = grpInfo, inline = 'r1')
  190. tbl_ctf = input.bool(true, 'Chart Timeframe', group = grpInfo, inline = 'r1')
  191. tbl_fractal = input.bool(true, 'Fractal', group = grpInfo, inline = 'r2')
  192. tbl_ttc = input.bool(true, 'Time to Close', group = grpInfo, inline = 'r2')
  193. tbl_bias = input.bool(true, 'Bias', group = grpInfo, inline = 'r3')
  194. tbl_tfilter = input.bool(true, 'Time Filter', group = grpInfo, inline = 'r3')
  195. tbl_smt = input.bool(true, 'SMT Ticker(s)', group = grpInfo, inline = 'r4')
  196. tbl_date = input.bool(false, 'Date', group = grpInfo, inline = 'r4')
  197. tbl_bg_colorIn = input.color(#ffffff, 'Colors', group = grpInfo, inline = 'tblclr')
  198. tbl_text_color = input.color(#787b86, '', group = grpInfo, inline = 'tblclr')
  199.  
  200. //#endregion
  201.  
  202. //#region [CONSTANTS AND STATE]
  203.  
  204. noColor = color.new(#000000, 100)
  205.  
  206. // Dark chart background: colors still at their default (light-theme) value switch to a light equivalent
  207. isDarkChart = color.r(chart.bg_color) + color.g(chart.bg_color) + color.b(chart.bg_color) < 382
  208. themed(color c, color lightDef, color darkAlt) =>
  209. isDarkChart and c == lightDef ? darkAlt : c
  210. bearBody = themed(bearBodyIn, #131722, #5d606b)
  211. borderBull = themed(borderBullIn, #2a2e39, #b2b5be)
  212. borderBear = themed(borderBearIn, #2a2e39, #b2b5be)
  213. wickBull = themed(wickBullIn, #2a2e39, #b2b5be)
  214. wickBear = themed(wickBearIn, #2a2e39, #b2b5be)
  215. sweepColor = themed(sweepColorIn, #000000, #b2b5be)
  216. tbl_bg_color = themed(tbl_bg_colorIn, #ffffff, #1e222d)
  217. htfNameColor = isDarkChart ? #d1d4dc : htfNameColorL
  218. c2c3c4Color = isDarkChart ? #d1d4dc : c2c3c4ColorL
  219. validColor = #787b86 // C2 / C3 label once the model stayed valid through C4
  220. tblHeadColor = tbl_text_color == #787b86 ? (isDarkChart ? #d1d4dc : #2a2e39) : tbl_text_color
  221. takenColor = #b2b5be // protected swing dot after it is taken
  222. icBackfillMaxBars = 300
  223. icCisdDotSize = 'Small'
  224.  
  225. // HTF candle size: half body width and the distance between candle centers, in bars
  226. htfHalf = htfSize == 'Large' ? 4 : htfSize == 'Normal' ? 3 : 2
  227. candleSpacing = htfHalf * 2 + 1
  228. // the model reads up to 5 HTF candles (C3 model: the candle before its C1 for formation liquidity): at least 5 are kept, only 'HTF Candles' of them are drawn
  229. htfKeep = math.max(htfCandleCount, 5)
  230.  
  231. // where things are drawn
  232. dtChart = drawType != 'HTF Candle'
  233. dtHtf = drawType != 'On Chart'
  234. sweepOnChart = showSweep and sweepDisplay != 'HTF Candles'
  235. sweepOnHtf = showSweep and sweepDisplay != 'Chart'
  236. smtOnChart = show_smt and smtDisplay != 'HTF Candles'
  237. smtOnHtf = show_smt and smtDisplay != 'Chart'
  238.  
  239. // The single 'Calculated bars' setting is TradingView's own (calc_bars_count above, default 2000): the script
  240. // only sees that many bars. The first fifth (at most 500) only warm up the HTF candles; the model runs on the rest.
  241. var int firstBar = bar_index
  242. calcOn = bar_index - firstBar >= math.min(500, (last_bar_index - firstBar + 1) / 5)
  243.  
  244. type HtfCandle
  245. float o
  246. float h
  247. float l
  248. float c
  249. int hBar
  250. int lBar
  251. box body
  252. line wickUp
  253. line wickDown
  254. line eqLine
  255. int midX
  256. line sweepLine = na
  257. bool triggerBuy = false
  258. bool triggerSell = false
  259. int openTime = na
  260. label timeLbl = na
  261. // [HTF SMT] each pair's extremes over this HTF candle (p = pair 1, q = pair 2) + the lines drawn for it
  262. float pH = na
  263. float pL = na
  264. float qH = na
  265. float qL = na
  266. float pO = na
  267. float pC = na
  268. float qO = na
  269. float qC = na
  270. label pspLbl = na
  271. line smtHLine = na
  272. line smtLLine = na
  273. // [LIVE SWEEP] lines on this candle's high / low while the next (forming) candle trades through them
  274. line liveHiLn = na
  275. line liveLoLn = na
  276. // [C1 SWEEP] segunda linha: o mesmo candle pode ser C1 de um C2 de alta e de um de baixa (C2 outside)
  277. line sweepLineHi = na
  278.  
  279. type PeriodState
  280. float prevHigh = na
  281. float prevLow = na
  282. bool prevC2Buy = false
  283. bool prevC2Sell = false
  284.  
  285. type StdDevData
  286. array<label> labels
  287. array<line> lines
  288.  
  289. type ICCisd
  290. float extremePrice
  291. bool taken = false
  292. label dotLbl = na
  293. bool isBull = false
  294. line ln = na
  295. bool frozen = false
  296. int swBar = na
  297. int liveHtf = na // open time of the HTF candle after C4 (C5); the dot freezes when it closes
  298.  
  299. type C2Setup
  300. bool isBull
  301. float extreme
  302. int phase = 1
  303. bool dead = false
  304. label c2Lbl
  305. label swLbl = na // C3 model: the 'C2' / 'C2+PSP' label on the C2 extreme (the swing)
  306. string swTag = 'C2'
  307. int c2BarIndex = na
  308. line c1SweepLn = na
  309. box c3Box = na
  310. line c3Dash = na
  311. label c3Lbl = na
  312. float cisdLevel = na
  313. int cisdIndex = na
  314. bool cisdConfirmed = false
  315. line cisdLine = na
  316. label cisdLbl = na // 'CISD+ B': the setup grade at the end of the CISD line
  317. int cisdEndIndex = na
  318. StdDevData stdDevData = na
  319. box c4Box = na
  320. line c4Dash = na
  321. label c4Lbl = na
  322. float c4Top = na
  323. float c4Bottom = na
  324. bool c4Invalid = false
  325. bool justConfirmed = false
  326. array<ICCisd> icList = na
  327. // [SMT] continuation SMT (SMT section): pairs' extreme around our C2 extreme (ref) and since then
  328. // (run), our own extreme since then (own*), and the line whose end slides with it
  329. bool csInit = false
  330. int csStart = na // first bar after the C2 candle (C3 model: C3's open)
  331. float csRun1 = na
  332. float csRun2 = na
  333. bool csDiv = false
  334. float csOwnPx = na
  335. int csOwnBar = na
  336. line csLn = na
  337. label csLb = na
  338. float c2P1 = na // each pair's own C2 candle low (bullish) / high (bearish)
  339. float c2P2 = na
  340. bool icPending = false
  341. float icLevel = na
  342. int icStartIndex = na
  343. float icExtreme = na
  344. int icExtremeIndex = na
  345. float c3Extreme = na
  346. float c3Hi = na // C3's range (C4 protected swings inside it need not beat the last dot)
  347. float c3Lo = na
  348. bool icStopped = false
  349. // [SMT] chart SMT lines of this setup (reversal at C2, continuations after the CISD)
  350. array<line> smtLns = na
  351. array<label> smtLbls = na
  352. // [REVEAL] nothing is drawn until the CISD confirms; what to draw then
  353. bool revealed = false
  354. bool c3Model = false
  355. string tag = 'C2'
  356. float c1Px = na
  357. int c1Bar = na
  358. int sweepEnd = na
  359. bool smtHit = false
  360. string smtTxt = ''
  361. int c3Start = na
  362. float c3Top = na
  363. float c3Bot = na
  364. float c3Mid = na
  365. int c4Start = na
  366. // [LABEL] where the model label prints when it is not the swing (C3 model: C3's extreme)
  367. int lblBar = na
  368. float lblPx = na
  369. // [C3 LINE] C3 model: dotted line at C3's extreme, from its bar to the end of C4
  370. int c3LnBar = na
  371. line c3Ln = na
  372. float c4Mid = na
  373. // [FORMATION LIQUIDITY] target-side extremes of C1 (1) and the candle before it (0)
  374. float fl1Px = na
  375. int fl1Bar = na
  376. float fl0Px = na
  377. int fl0Bar = na
  378.  
  379. type SetupRecord
  380. C2Setup setup
  381. int creationBar
  382.  
  383. type EarlyCisdRecord
  384. line ln
  385. int barIndex
  386.  
  387. var array<HtfCandle> htfCandles = array.new<HtfCandle>()
  388. var array<int> htfOpenBars = array.new<int>() // open bars of the last HTF candles, newest first
  389. var array<line> vLines = array.new<line>()
  390. var PeriodState state = PeriodState.new()
  391. var C2Setup buySetup = na
  392. var C2Setup sellSetup = na
  393. var array<SetupRecord> setupRecords = array.new<SetupRecord>()
  394. // Persistent protected-swing dots: independent of any setup's lifespan
  395. var array<ICCisd> icDots = array.new<ICCisd>()
  396. var array<EarlyCisdRecord> bullEarlyCisdRecords = array.new<EarlyCisdRecord>()
  397. var array<EarlyCisdRecord> bearEarlyCisdRecords = array.new<EarlyCisdRecord>()
  398. var int htfOpenBar = na
  399. var line htfOpenLn = na
  400. var bool cisdBullFiredThisBar = false
  401. var bool cisdBearFiredThisBar = false
  402.  
  403. allowBuy = biasFilter != 'Bearish'
  404. allowSell = biasFilter != 'Bullish'
  405.  
  406. // [SMT] correlated pairs. Futures -> related continuous contracts; CFDs -> related CFDs at the same broker
  407. // (same session and price feed, so swings line up bar for bar).
  408. smt_ticker = str.upper(syminfo.ticker)
  409.  
  410. // Futures: [pair 1, pair 2]
  411. f_fut_pairs(string t) =>
  412. string f1 = ''
  413. string f2 = ''
  414. if str.startswith(t, 'MES')
  415. f1 := 'MNQ1!'
  416. f2 := 'MYM1!'
  417. else if str.startswith(t, 'MNQ')
  418. f1 := 'MES1!'
  419. f2 := 'MYM1!'
  420. else if str.startswith(t, 'MYM')
  421. f1 := 'MES1!'
  422. f2 := 'MNQ1!'
  423. else if str.startswith(t, 'M2K')
  424. f1 := 'MES1!'
  425. f2 := 'MNQ1!'
  426. else if str.startswith(t, 'MGC')
  427. f1 := 'OANDA:XAUEUR'
  428. f2 := 'OANDA:XAUGBP'
  429. else if str.startswith(t, 'SIL')
  430. f1 := 'OANDA:XAGEUR'
  431. f2 := 'OANDA:XAGGBP'
  432. else if str.startswith(t, 'ES')
  433. f1 := 'NQ1!'
  434. f2 := 'YM1!'
  435. else if str.startswith(t, 'NQ')
  436. f1 := 'ES1!'
  437. f2 := 'YM1!'
  438. else if str.startswith(t, 'YM') or str.startswith(t, 'RTY')
  439. f1 := 'ES1!'
  440. f2 := 'NQ1!'
  441. else if str.startswith(t, 'GC')
  442. // a metal pairs with the same metal in euro and pound
  443. f1 := 'OANDA:XAUEUR'
  444. f2 := 'OANDA:XAUGBP'
  445. else if str.startswith(t, 'SI')
  446. f1 := 'OANDA:XAGEUR'
  447. f2 := 'OANDA:XAGGBP'
  448. else if str.startswith(t, 'CL') or str.startswith(t, 'MCL')
  449. f1 := 'RB1!'
  450. f2 := 'HO1!'
  451. else if str.startswith(t, 'HO')
  452. f1 := 'CL1!'
  453. f2 := 'RB1!'
  454. else if str.startswith(t, 'RB')
  455. f1 := 'CL1!'
  456. f2 := 'HO1!'
  457. else if str.startswith(t, 'BTC')
  458. f1 := 'ETH1!'
  459. else if str.startswith(t, 'ETH')
  460. f1 := 'BTC1!'
  461. [f1, f2]
  462.  
  463. // Automatic pairs: [pair 1, pair 1 fallback, pair 2, pair 2 fallback]. Brokers name the same CFD
  464. // differently (US500 / SPX500), so the fallback name is requested too and whichever has data is used.
  465. f_smt_pairs(string t) =>
  466. [a1, b1, a2, b2] = switch t
  467. 'US100' => ['US500', 'SPX500', 'US30', '']
  468. 'NAS100' => ['SPX500', 'US500', 'US30', '']
  469. 'USTEC' => ['US500', 'SPX500', 'US30', '']
  470. 'US500' => ['US100', 'NAS100', 'US30', '']
  471. 'SPX500' => ['US100', 'NAS100', 'US30', '']
  472. 'US30' => ['US500', 'SPX500', 'US100', 'NAS100']
  473. 'XAUUSD' => ['XAUEUR', 'OANDA:XAUEUR', 'XAUGBP', 'OANDA:XAUGBP']
  474. 'GOLD' => ['XAUEUR', 'OANDA:XAUEUR', 'XAUGBP', 'OANDA:XAUGBP']
  475. 'XAGUSD' => ['XAGEUR', 'OANDA:XAGEUR', 'XAGGBP', 'OANDA:XAGGBP']
  476. 'SILVER' => ['XAGEUR', 'OANDA:XAGEUR', 'XAGGBP', 'OANDA:XAGGBP']
  477. 'EURUSD' => ['GBPUSD', '', '', '']
  478. 'GBPUSD' => ['EURUSD', '', '', '']
  479. 'AUDUSD' => ['NZDUSD', '', '', '']
  480. 'NZDUSD' => ['AUDUSD', '', '', '']
  481. 'USDJPY' => ['USDCHF', '', 'USDCAD', '']
  482. 'USDCHF' => ['USDJPY', '', 'USDCAD', '']
  483. 'USDCAD' => ['USDCHF', '', 'USDJPY', '']
  484. // FXCM energy CFDs, like CL1! <-> RB1! + HO1!
  485. 'USOIL' => ['GASOLINEF', '', 'HEATINGOILF', '']
  486. 'GASOLINEF' => ['USOIL', '', 'HEATINGOILF', '']
  487. 'HEATINGOILF' => ['USOIL', '', 'GASOLINEF', '']
  488. // Crypto: BTC <-> ETH on the same exchange
  489. 'BTCUSDT' => ['ETHUSDT', '', '', '']
  490. 'ETHUSDT' => ['BTCUSDT', '', '', '']
  491. 'BTCUSDT.P' => ['ETHUSDT.P', '', '', '']
  492. 'ETHUSDT.P' => ['BTCUSDT.P', '', '', '']
  493. 'BTCUSD' => ['ETHUSD', '', '', '']
  494. 'ETHUSD' => ['BTCUSD', '', '', '']
  495. => ['', '', '', '']
  496. string pre = syminfo.prefix + ':'
  497. // a name with its own exchange ('OANDA:XAUEUR') is used as it is
  498. string p1a = a1 != '' ? (str.contains(a1, ':') ? a1 : pre + a1) : ''
  499. string p1b = b1 != '' ? (str.contains(b1, ':') ? b1 : pre + b1) : ''
  500. string p2a = a2 != '' ? (str.contains(a2, ':') ? a2 : pre + a2) : ''
  501. string p2b = b2 != '' ? (str.contains(b2, ':') ? b2 : pre + b2) : ''
  502. if p1a == '' and syminfo.type == 'futures'
  503. [f1, f2] = f_fut_pairs(t)
  504. // a dated contract (NQZ2026) pairs with the same contract of the other future (ESZ2026);
  505. // the continuous chart (NQ1!) keeps the continuous pairs
  506. string sfx = str.match(t, '[FGHJKMNQUVXZ][0-9]{4}$')
  507. if sfx != ''
  508. f1 := str.endswith(f1, '1!') ? str.replace(f1, '1!', sfx) : f1
  509. f2 := str.endswith(f2, '1!') ? str.replace(f2, '1!', sfx) : f2
  510. p1a := f1
  511. p2a := f2
  512. [p1a, p1b, p2a, p2b]
  513.  
  514. [smtA1, smtB1, smtA2, smtB2] = f_smt_pairs(smt_ticker)
  515. bool smtCustom = pairMode == 'Custom'
  516. string pair1A = smtCustom ? (pair1In == ticker.standard(syminfo.tickerid) ? '' : pair1In) : smtA1
  517. string pair1B = smtCustom ? '' : smtB1
  518. string pair2A = not useSecondPair ? '' : smtCustom ? (pair2In == ticker.standard(syminfo.tickerid) ? '' : pair2In) : smtA2
  519. string pair2B = not useSecondPair or smtCustom ? '' : smtB2
  520. bool pair1InvOn = smtCustom and pair1Inv
  521. bool pair2InvOn = smtCustom and pair2Inv
  522.  
  523. //#endregion
  524.  
  525. //#region [FUNCTIONS]
  526.  
  527. customTfLabel(string tf) =>
  528. float mins = str.tonumber(tf)
  529. string result = tf
  530. if not na(mins)
  531. if mins >= 60 and mins % 60 == 0
  532. result := str.tostring(int(mins / 60)) + 'H'
  533. else
  534. result := str.tostring(int(mins)) + 'm'
  535. result
  536.  
  537. tfLabel(string tf) =>
  538. switch tf
  539. '1S' => '1s'
  540. '15S' => '15s'
  541. '1D' => '1D'
  542. 'D' => '1D'
  543. '2D' => '2D'
  544. '3D' => '3D'
  545. '1W' => '1W'
  546. 'W' => '1W'
  547. '2W' => '2W'
  548. '3W' => '3W'
  549. '1M' => '1M'
  550. '2M' => '2M'
  551. '3M' => '3M'
  552. '6M' => '6M'
  553. '9M' => '9M'
  554. '12M' => '12M'
  555. => customTfLabel(tf)
  556.  
  557. curTfCode() =>
  558. timeframe.isdaily ? '1D' : timeframe.isweekly ? '1W' : timeframe.ismonthly ? '1M' : timeframe.period
  559.  
  560. tablePosition(string vert, string horz) =>
  561. switch vert + '-' + horz
  562. 'Top-Left' => position.top_left
  563. 'Top-Center' => position.top_center
  564. 'Top-Right' => position.top_right
  565. 'Middle-Left' => position.middle_left
  566. 'Middle-Center' => position.middle_center
  567. 'Middle-Right' => position.middle_right
  568. 'Bottom-Left' => position.bottom_left
  569. 'Bottom-Center' => position.bottom_center
  570. 'Bottom-Right' => position.bottom_right
  571. => position.top_right
  572.  
  573. lineStyleFromStr(string s) =>
  574. switch s
  575. 'Solid' => line.style_solid
  576. 'Dashed' => line.style_dashed
  577. 'Dotted' => line.style_dotted
  578. => line.style_dashed
  579.  
  580. textSize(string s) =>
  581. switch s
  582. 'Tiny' => size.tiny
  583. 'Small' => size.small
  584. 'Normal' => size.normal
  585. 'Large' => size.large
  586. => size.huge
  587.  
  588. directionalLabel(int xBar, float yPrice, string txt, bool bullish, color txtColor = na) =>
  589. color useColor = na(txtColor) ? c2c3c4Color : txtColor
  590. label.new(xBar, yPrice, text = txt, style = bullish ? label.style_label_up : label.style_label_down, color = na, textcolor = useColor, size = textSize(labelSize))
  591.  
  592. // One step smaller than a size setting (used for the HTF time stamps)
  593. smallerSize(string s) =>
  594. switch s
  595. 'Huge' => size.large
  596. 'Large' => size.normal
  597. 'Normal' => size.small
  598. => size.tiny
  599.  
  600. pad2(int v) =>
  601. v < 10 ? '0' + str.tostring(v) : str.tostring(v)
  602.  
  603. // 01:00:00 style countdown for the info table (hours always shown)
  604. formatHms(int ms) =>
  605. totalSec = int(math.max(ms, 0) / 1000)
  606. dd = int(totalSec / 86400)
  607. hh = int((totalSec % 86400) / 3600)
  608. mm = int((totalSec % 3600) / 60)
  609. ss = int(totalSec % 60)
  610. (dd > 0 ? str.tostring(dd) + 'd ' : '') + pad2(hh) + ':' + pad2(mm) + ':' + pad2(ss)
  611.  
  612. biggerSize(string s) =>
  613. switch s
  614. 'Tiny' => size.small
  615. 'Small' => size.normal
  616. 'Normal' => size.large
  617. => size.huge
  618.  
  619. // HTF block timer: 14:39 under an hour, 3:14:39 under a day, 2d 03:14 above
  620. formatRemaining(int ms) =>
  621. totalSec = int(math.max(ms, 0) / 1000)
  622. dd = int(totalSec / 86400)
  623. hh = int((totalSec % 86400) / 3600)
  624. mm = int((totalSec % 3600) / 60)
  625. ss = int(totalSec % 60)
  626. dd > 0 ? str.tostring(dd) + 'd ' + pad2(hh) + ':' + pad2(mm) : hh > 0 ? str.tostring(hh) + ':' + pad2(mm) + ':' + pad2(ss) : pad2(mm) + ':' + pad2(ss)
  627.  
  628. // UTC offset as a Pine timezone string, e.g. GMT+0300
  629. gmtString(int h, int m) =>
  630. 'GMT' + (h < 0 ? '-' : '+') + pad2(math.abs(h)) + pad2(m)
  631.  
  632. stampTz = useCustomTz ? gmtString(tzHour, tzMin) : 'America/New_York'
  633. filterTz = tfUseTz ? gmtString(tfTzHour, tfTzMin) : 'America/New_York'
  634.  
  635. // Symbol without its exchange prefix (CBOT_MINI:YM1! -> YM1!)
  636. statusSym(string sym) =>
  637. str.contains(sym, ':') ? array.get(str.split(sym, ':'), 1) : sym
  638.  
  639. // Model HTF for the Automatic fractal; '' = this chart timeframe has no model
  640. autoHTF() =>
  641. switch timeframe.period
  642. '1S' => '1'
  643. '15S' => '5'
  644. '1' => '15'
  645. '2' => '30'
  646. '3' => '30'
  647. '5' => '60'
  648. '15' => '240'
  649. '30' => '240'
  650. '60' => '1D'
  651. '120' => '2D'
  652. '180' => '3D'
  653. '240' => '1W'
  654. '480' => '2W'
  655. '720' => '3W'
  656. '1D' => '1M'
  657. 'D' => '1M'
  658. '2D' => '2M'
  659. '1W' => '3M'
  660. 'W' => '3M'
  661. '2W' => '6M'
  662. '3W' => '9M'
  663. '1M' => '12M'
  664. 'M' => '12M'
  665. => ''
  666.  
  667. ltfCode() =>
  668. switch modelType
  669. '1s-1m' => '1S'
  670. '15s-5m' => '15S'
  671. '1m-15m' => '1'
  672. '3m-30m' => '3'
  673. '5m-1H' => '5'
  674. '15m-4H' => '15'
  675. '1H-1D' => '60'
  676. '4H-1W' => '240'
  677. '1D-1M' => '1D'
  678. 'Custom' => customLTF
  679. => curTfCode()
  680.  
  681. // The label only carries PSP (C2 / C2+PSP); SMT shows as its own line and pair name
  682. c2TagText(bool psp) =>
  683. 'C2' + (psp ? '+PSP' : '')
  684.  
  685. // SMT color by direction: bearish at highs, bullish at lows
  686. smtColorFor(bool isHigh) =>
  687. isHigh ? smtBearColor : smtBullColor
  688.  
  689. // [HTF SMT] Creates / updates / removes one divergence segment.
  690. smtHtfSeg(line ln, bool active, int x1, float y1, int x2, float y2, bool isHigh) =>
  691. line l = ln
  692. if active
  693. if na(l)
  694. l := line.new(x1, y1, x2, y2, color = smtColorFor(isHigh), style = lineStyleFromStr(smtStyle), width = smtWidth)
  695. else
  696. line.set_xy1(l, x1, y1)
  697. line.set_xy2(l, x2, y2)
  698. line.set_color(l, smtColorFor(isHigh))
  699. line.set_style(l, lineStyleFromStr(smtStyle))
  700. line.set_width(l, smtWidth)
  701. else if not na(l)
  702. line.delete(l)
  703. l := na
  704. l
  705.  
  706. // [LIVE SWEEP] Creates / updates / removes one live sweep line.
  707. liveSweepLine(line ln, bool on, int x1, int x2, float y) =>
  708. line l = ln
  709. if on
  710. if na(l)
  711. l := line.new(x1, y, x2, y, color = sweepColor, style = lineStyleFromStr(sweepStyle), width = sweepWidth)
  712. line.set_xy1(l, x1, y)
  713. line.set_xy2(l, x2, y)
  714. line.set_color(l, sweepColor)
  715. line.set_style(l, lineStyleFromStr(sweepStyle))
  716. line.set_width(l, sweepWidth)
  717. else if not na(l)
  718. line.delete(l)
  719. l := na
  720. l
  721.  
  722. // [LIVE SWEEP] The forming candle (index 0) taking the previous candle's high or low and trading back inside its range draws the sweep
  723. // line right away, before it closes. Older candles never keep a live line.
  724. // Must be called AFTER the block's candles have been drawn (it needs each candle's midX).
  725. updateLiveSweeps(array<HtfCandle> cs) =>
  726. int n = cs.size()
  727. if n > 2
  728. for i = 2 to n - 1
  729. HtfCandle old = cs.get(i)
  730. old.liveHiLn := liveSweepLine(old.liveHiLn, false, 0, 0, na)
  731. old.liveLoLn := liveSweepLine(old.liveLoLn, false, 0, 0, na)
  732. if n > 0
  733. HtfCandle cur = cs.get(0)
  734. cur.liveHiLn := liveSweepLine(cur.liveHiLn, false, 0, 0, na)
  735. cur.liveLoLn := liveSweepLine(cur.liveLoLn, false, 0, 0, na)
  736. if n > 1
  737. HtfCandle cur = cs.get(0)
  738. HtfCandle prv = cs.get(1)
  739. // only while price is back inside the previous candle's range (swept and reclaimed)
  740. bool liveBear = sweepOnHtf and allowSell and cur.h > prv.h and cur.c < prv.h
  741. bool liveBull = sweepOnHtf and allowBuy and cur.l < prv.l and cur.c > prv.l
  742. prv.liveHiLn := liveSweepLine(prv.liveHiLn, liveBear, prv.midX, cur.midX + htfHalf * 2 + 2, prv.h)
  743. prv.liveLoLn := liveSweepLine(prv.liveLoLn, liveBull, prv.midX, cur.midX + htfHalf * 2 + 2, prv.l)
  744.  
  745. method delete(HtfCandle c) =>
  746. box.delete(c.body)
  747. line.delete(c.wickUp)
  748. line.delete(c.wickDown)
  749. line.delete(c.eqLine)
  750. line.delete(c.sweepLine)
  751. line.delete(c.sweepLineHi)
  752. label.delete(c.timeLbl)
  753. line.delete(c.smtHLine)
  754. line.delete(c.smtLLine)
  755. line.delete(c.liveHiLn)
  756. line.delete(c.liveLoLn)
  757. label.delete(c.pspLbl)
  758.  
  759. // A candle kept only for the model (beyond the drawn count): nothing of it shows
  760. method hide(HtfCandle c) =>
  761. box.set_bgcolor(c.body, noColor)
  762. box.set_border_color(c.body, noColor)
  763. line.set_color(c.wickUp, noColor)
  764. line.set_color(c.wickDown, noColor)
  765. line.set_color(c.eqLine, noColor)
  766. line.delete(c.sweepLine)
  767. c.sweepLine := na
  768. line.delete(c.sweepLineHi)
  769. c.sweepLineHi := na
  770. line.delete(c.smtHLine)
  771. c.smtHLine := na
  772. line.delete(c.smtLLine)
  773. c.smtLLine := na
  774. line.delete(c.liveHiLn)
  775. c.liveHiLn := na
  776. line.delete(c.liveLoLn)
  777. c.liveLoLn := na
  778. label.delete(c.timeLbl)
  779. c.timeLbl := na
  780. label.delete(c.pspLbl)
  781. c.pspLbl := na
  782. c
  783.  
  784. method update(HtfCandle c, float curH, float curL, float curC, int curBar) =>
  785. if curH > c.h
  786. c.h := curH
  787. c.hBar := curBar
  788. if curL < c.l
  789. c.l := curL
  790. c.lBar := curBar
  791. c.c := curC
  792. c
  793.  
  794.  
  795. // Time label text under an HTF candle: month, week's date (NOV 2), day name (daily) or the open time
  796. htfStampText(int t, string tf) =>
  797. tf == '12M' ? str.format_time(t + 12 * 60 * 60 * 1000, 'yyyy', stampTz) : str.endswith(tf, 'M') ? str.upper(str.format_time(t + 12 * 60 * 60 * 1000, 'MMM', stampTz)) : str.endswith(tf, 'W') ? str.upper(str.format_time(t + 12 * 60 * 60 * 1000, 'MMM d', stampTz)) : timeframe.in_seconds(tf) >= 86400 ?str.upper(str.format_time(t + 12 * 60 * 60 * 1000, 'EEE', stampTz)) : str.format_time(t, timeFormat == '12h' ? 'h:mma' : 'HH:mm', stampTz)
  798.  
  799. // Draws one HTF candle centered on bar midX
  800. method draw(HtfCandle c, int midX, string tf) =>
  801. bool isBull = c.c >= c.o
  802. float eqPx = (c.h + c.l) / 2
  803. box.set_left(c.body, midX - htfHalf)
  804. box.set_right(c.body, midX + htfHalf)
  805. box.set_top(c.body, math.max(c.o, c.c))
  806. box.set_bottom(c.body, math.min(c.o, c.c))
  807. box.set_bgcolor(c.body, isBull ? bullBody : bearBody)
  808. box.set_border_color(c.body, isBull ? borderBull : borderBear)
  809. line.set_x1(c.wickUp, midX)
  810. line.set_x2(c.wickUp, midX)
  811. line.set_y1(c.wickUp, c.h)
  812. line.set_y2(c.wickUp, math.max(c.o, c.c))
  813. line.set_color(c.wickUp, isBull ? wickBull : wickBear)
  814. line.set_x1(c.wickDown, midX)
  815. line.set_x2(c.wickDown, midX)
  816. line.set_y1(c.wickDown, c.l)
  817. line.set_y2(c.wickDown, math.min(c.o, c.c))
  818. line.set_color(c.wickDown, isBull ? wickBull : wickBear)
  819. // Previous EQ on the HTF candles: from this candle's middle to the next candle
  820. line.set_x1(c.eqLine, midX)
  821. line.set_x2(c.eqLine, midX)
  822. line.set_y1(c.eqLine, eqPx)
  823. line.set_y2(c.eqLine, eqPx)
  824. line.set_color(c.eqLine, showPrevEq and dtHtf ? prevEqColor : noColor)
  825. line.set_style(c.eqLine, lineStyleFromStr(prevEqStyle))
  826. line.set_width(c.eqLine, prevEqWidth)
  827. c.midX := midX
  828.  
  829. string timeText = htfStampText(c.openTime, tf)
  830.  
  831. if showHtfStamps
  832. if na(c.timeLbl)
  833. c.timeLbl := label.new(midX, c.l, timeText, style = label.style_label_up, color = na, textcolor = htfInfoColor, size = smallerSize(labelSize))
  834. else
  835. label.set_xy(c.timeLbl, midX, c.l)
  836. label.set_text(c.timeLbl, timeText)
  837. label.set_textcolor(c.timeLbl, htfInfoColor)
  838. label.set_size(c.timeLbl, smallerSize(labelSize))
  839. else if not na(c.timeLbl)
  840. label.delete(c.timeLbl)
  841. c.timeLbl := na
  842. c
  843.  
  844. newHtfCandle() =>
  845. HtfCandle.new(open, high, low, close, bar_index, bar_index,
  846. box.new(bar_index, high, bar_index, low, border_color = noColor, border_width = 1, bgcolor = noColor),
  847. line.new(bar_index, high, bar_index, high, color = noColor),
  848. line.new(bar_index, low, bar_index, low, color = noColor),
  849. line.new(bar_index, high, bar_index, high, color = noColor),
  850. na, openTime = time)
  851.  
  852. // Close time of the forming HTF candle. time_close() came back stale for 30m / 1H on lower charts,
  853. // so intraday timeframes use their open time + length; daily and above keep time_close().
  854. htfCloseTime(string tf) =>
  855. int sec = timeframe.in_seconds(tf)
  856. sec < 86400 ? time(tf) + sec * 1000 : time_close(tf)
  857.  
  858.  
  859. drawEarlyCisd(bool isBull, float level, int idx, int confirmBar) =>
  860. array<EarlyCisdRecord> target = isBull ? bullEarlyCisdRecords : bearEarlyCisdRecords
  861. color clr = isBull ? cisdBullColor : cisdBearColor
  862. if showEarlyCisd and calcOn and not hideSetups
  863. // line only, ending one candle after the candle that closed through the level
  864. ln = line.new(idx, level, confirmBar + 1, level, color = clr, style = lineStyleFromStr(earlyCisdStyle))
  865. target.push(EarlyCisdRecord.new(ln, confirmBar))
  866. if showAlerts and earlyCisdAlerts and calcOn and not hideSetups
  867. alert((isBull ? 'Bullish' : 'Bearish') + ' Potential Candle 2 on ' + syminfo.ticker, alert.freq_once_per_bar_close)
  868.  
  869. pruneEarlyCisd(array<EarlyCisdRecord> recs, int thresholdBar) =>
  870. if not na(thresholdBar)
  871. while recs.size() > 0 and recs.first().barIndex < thresholdBar
  872. line.delete(recs.shift().ln)
  873.  
  874. consumeLastEarlyCisd(array<EarlyCisdRecord> recs) =>
  875. if recs.size() > 0
  876. line.delete(recs.pop().ln)
  877.  
  878. parseFloats(string src) =>
  879. var out = array.new<float>()
  880. array.clear(out)
  881. for part in str.split(str.replace_all(src, ' ', ''), ',')
  882. v = str.tonumber(part)
  883. if not na(v)
  884. out.push(v)
  885. out
  886.  
  887.  
  888. // SD projections: a short tick and a label on its left per level, at the swing bar
  889. createStdDevProjections(C2Setup s) =>
  890. if showStdDev
  891. devs = parseFloats(stdDevInput)
  892. if devs.size() > 0
  893. level0 = s.cisdLevel
  894. level1 = s.extreme
  895. // Wick to Wick: the leg starts at the wick of the candle the CISD level comes from
  896. if stdDevCalc == 'Wick to Wick' and not na(s.cisdIndex)
  897. int jb = bar_index - s.cisdIndex
  898. if jb >= 0 and jb <= 1499
  899. level0 := s.isBull ? high[jb] : low[jb]
  900. int leftBar = s.c2BarIndex
  901. float priceRange = s.isBull ? level0 - level1 : level1 - level0
  902. lbs = array.new<label>()
  903. lns = array.new<line>()
  904. for dev in devs
  905. devPrice = s.isBull ? level0 - priceRange * dev : level0 + priceRange * dev
  906. lns.push(line.new(leftBar, devPrice, leftBar + 3, devPrice, color = stdDevColor, style = lineStyleFromStr(stdStyle), width = stdWidth))
  907. if stdLabels
  908. lbs.push(label.new(leftBar, devPrice, str.tostring(dev), style = label.style_label_right, color = na, textcolor = stdDevColor, size = textSize(stdLblSize)))
  909. s.stdDevData := StdDevData.new(lbs, lns)
  910.  
  911. confirmCisd(C2Setup s, int confirmBar, bool live = true) =>
  912. s.cisdConfirmed := true
  913. if live
  914. s.justConfirmed := true
  915. s.cisdEndIndex := confirmBar
  916. showLine = s.isBull ? showBullCisd : showBearCisd
  917. clr = s.isBull ? cisdBullColor : cisdBearColor
  918. lnStyle = s.isBull ? cisdBullStyle : cisdBearStyle
  919. lnWidth = s.isBull ? cisdBullWidth : cisdBearWidth
  920. if showLine
  921. // line only, ending one candle after the candle that closed through the level
  922. s.cisdLine := line.new(s.cisdIndex, s.cisdLevel, confirmBar + 1, s.cisdLevel, color = clr, style = lineStyleFromStr(lnStyle), width = lnWidth)
  923. createStdDevProjections(s)
  924.  
  925. icClearPending(C2Setup s) =>
  926. s.icPending := false
  927. s.icLevel := na
  928. s.icStartIndex := na
  929. s.icExtreme := na
  930. s.icExtremeIndex := na
  931. s
  932.  
  933. // Walks back from the extreme bar through consecutive opposing candles.
  934. // bias: 1 = bullish candles (used for bearish setups), -1 = bearish candles (used for bullish setups)
  935. icFindCisdLevel(int extremeBarIdx, int bias) =>
  936. int offset = bar_index - extremeBarIdx
  937. float cisdPrice = na
  938. int cisdIdx = na
  939. bool foundFirst = false
  940. for i = offset to math.min(offset + 500, bar_index, 1499)
  941. float cOpen = open[i]
  942. float cClose = close[i]
  943. int att = cClose > cOpen ? 1 : cClose < cOpen ? -1 : 0
  944. if att == 0
  945. continue
  946. if not foundFirst
  947. if att == bias
  948. foundFirst := true
  949. cisdPrice := cOpen
  950. cisdIdx := bar_index - i
  951. else
  952. if att != bias
  953. break
  954. cisdPrice := cOpen
  955. cisdIdx := bar_index - i
  956. [cisdPrice, cisdIdx]
  957.  
  958. // Re-anchor the IC level on the opposing run that leads into the current extreme
  959. icRetrace(C2Setup s) =>
  960. [lvl, lvlIdx] = icFindCisdLevel(s.icExtremeIndex, s.isBull ? -1 : 1)
  961. if not na(lvl)
  962. s.icLevel := lvl
  963. s.icStartIndex := lvlIdx
  964. s
  965.  
  966. // Greys out any protected swing once price has wicked beyond its extreme on bar m
  967. icMarkTaken(C2Setup s, int m) =>
  968. if not na(s) and not na(s.icList) and s.icList.size() > 0
  969. int off = bar_index - m
  970. if off >= 0
  971. for ic in s.icList
  972. if not ic.taken and not ic.frozen and not na(ic.extremePrice)
  973. bool sweep = s.isBull ? low[off] < ic.extremePrice : high[off] > ic.extremePrice
  974. if sweep
  975. ic.taken := true
  976. label.set_textcolor(ic.dotLbl, takenColor)
  977. s
  978.  
  979. // The C4 label and the protected swing dots: when a dot sits where the C4 label prints (a few bars, about
  980. // the same price) the label moves to the right of that dot so both stay readable
  981. float lblDodgeTol = ta.atr(14)
  982. c4LabelDodge(C2Setup s) =>
  983. if not na(s) and not na(s.c4Lbl) and not na(s.icList) and s.icList.size() > 0
  984. int x = label.get_x(s.c4Lbl)
  985. float y = label.get_y(s.c4Lbl)
  986. int nx = x
  987. for ic in s.icList
  988. if not na(ic.dotLbl)
  989. int dx = label.get_x(ic.dotLbl)
  990. if dx >= nx - 1 and dx <= nx + 4 and math.abs(ic.extremePrice - y) <= nz(lblDodgeTol)
  991. nx := dx + 2
  992. if nx != x
  993. label.set_x(s.c4Lbl, nx)
  994.  
  995. registerIcCisd(C2Setup s, float swPx, int swIdx, int brokeBar) =>
  996. color clr = s.isBull ? protBullColor : protBearColor
  997. label dotLbl = label.new(swIdx, swPx, '●', style = s.isBull ? label.style_label_up : label.style_label_down, color = na, textcolor = clr, size = textSize(icCisdDotSize))
  998. // the level price closed through to confirm the swing; like the CISD line it ends one candle after that close
  999. line lvlLn = not na(s.icLevel) and not na(s.icStartIndex) ? line.new(s.icStartIndex, s.icLevel, brokeBar + 1, s.icLevel, color = clr, style = lineStyleFromStr(protStyle), width = protWidth) : na
  1000. ic = ICCisd.new(swPx, dotLbl = dotLbl, isBull = s.isBull, ln = lvlLn, swBar = swIdx)
  1001. if na(s.icList)
  1002. s.icList := array.new<ICCisd>()
  1003. s.icList.push(ic)
  1004. // global list: survives setup eviction
  1005. icDots.push(ic)
  1006. c4LabelDodge(s)
  1007.  
  1008. // Greys a dot when price wicks beyond its extreme. A grey dot stays on the chart until its
  1009. // setup leaves the history; it needs no more watching, so it leaves this list.
  1010. icMarkTakenAll(int htfOpenT) =>
  1011. if icDots.size() > 0
  1012. for i = icDots.size() - 1 to 0
  1013. ic = icDots.get(i)
  1014. if not ic.frozen and not na(ic.liveHtf) and htfOpenT != ic.liveHtf
  1015. ic.frozen := true
  1016. if not ic.taken and not ic.frozen and not na(ic.extremePrice)
  1017. bool sweep = ic.isBull ? low < ic.extremePrice : high > ic.extremePrice
  1018. if sweep
  1019. ic.taken := true
  1020. label.set_textcolor(ic.dotLbl, takenColor)
  1021. if ic.taken or ic.frozen
  1022. icDots.remove(i)
  1023.  
  1024. // [POI] A continuation only counts when its swing reached a point of interest formed since the C2 extreme
  1025. // (not only since the last protected swing): a same-direction fair value gap (bullish gap: low of a candle above
  1026. // the high two candles back), or an earlier swing low / high that was still untaken (the swing sweeps it).
  1027. // The swing has to go into the gap: only touching its edge is not enough.
  1028. icPoiStart(C2Setup s, int swIdx) =>
  1029. math.max(na(s.c2BarIndex) ? swIdx - 150 : s.c2BarIndex, swIdx - 150)
  1030.  
  1031. icInFvg(C2Setup s, float swPx, int swIdx) =>
  1032. bool hit = false
  1033. int first = math.max(icPoiStart(s, swIdx) + 2, bar_index - 1497)
  1034. if first < swIdx
  1035. for b = swIdx - 1 to first
  1036. int off = bar_index - b
  1037. if s.isBull ? (low[off] > high[off + 2] and swPx < low[off]) : (high[off] < low[off + 2] and swPx > high[off])
  1038. hit := true
  1039. break
  1040. hit
  1041.  
  1042. icSweepsSwing(C2Setup s, float swPx, int swIdx) =>
  1043. bool hit = false
  1044. int first = math.max(icPoiStart(s, swIdx), 1, bar_index - 1497)
  1045. // extreme of the candles between a candidate swing and our swing: an untaken swing is never beyond it
  1046. float run = na
  1047. if swIdx - 2 >= first
  1048. for p = swIdx - 2 to first
  1049. int off = bar_index - p
  1050. float nx = s.isBull ? low[off - 1] : high[off - 1]
  1051. run := na(run) ? nx : s.isBull ? math.min(run, nx) : math.max(run, nx)
  1052. if s.isBull
  1053. if low[off] <= low[off + 1] and low[off] <= low[off - 1] and swPx < low[off] and run >= low[off]
  1054. hit := true
  1055. break
  1056. else
  1057. if high[off] >= high[off + 1] and high[off] >= high[off - 1] and swPx > high[off] and run <= high[off]
  1058. hit := true
  1059. break
  1060. hit
  1061.  
  1062. // One step of the IC state machine for bar m (m == bar_index live, m < bar_index when replaying).
  1063. icStep(C2Setup s, int m, bool live) =>
  1064. int off = bar_index - m
  1065. float o_m = open[off]
  1066. float c_m = close[off]
  1067. float h_m = high[off]
  1068. float l_m = low[off]
  1069. bool oppBar = s.isBull ? c_m < o_m : c_m > o_m
  1070.  
  1071. // a swing that is not confirmed within one HTF candle's worth of bars is dropped
  1072. int htfLen = htfOpenBars.size() > 1 ? htfOpenBars.get(0) - htfOpenBars.get(1) : na
  1073. if s.icPending and not na(htfLen) and not na(s.icExtremeIndex) and m - s.icExtremeIndex > htfLen
  1074. icClearPending(s)
  1075.  
  1076. if s.icPending
  1077. // New extreme: dot moves and the level re-anchors on the opposing run into it
  1078. bool newExt = s.isBull ? l_m < s.icExtreme : h_m > s.icExtreme
  1079. if newExt
  1080. s.icExtreme := s.isBull ? l_m : h_m
  1081. s.icExtremeIndex := m
  1082. icRetrace(s)
  1083. // Body break through the current level; it may be the extreme bar itself (the swing candle closes back
  1084. // over the series it ran into)
  1085. if m >= s.icExtremeIndex and not na(s.icLevel)
  1086. bool broke = s.isBull ? c_m > s.icLevel : c_m < s.icLevel
  1087. if broke
  1088. // the swing is the run's extreme
  1089. float swPx = s.icExtreme
  1090. int swIdx = s.icExtremeIndex
  1091. // in C4 a new protected swing has to go beyond the setup's last one from C3 on
  1092. bool c4Ok = true
  1093. if not na(s.c4Start) and swIdx >= s.c4Start and not na(s.icList) and s.icList.size() > 0
  1094. ICCisd lastIc = s.icList.last()
  1095. if lastIc.swBar >= nz(s.c3Start, 0)
  1096. c4Ok := s.isBull ? swPx < lastIc.extremePrice : swPx > lastIc.extremePrice
  1097. // ... unless it is the swing that made C4's own low / high so far (its wick)
  1098. if not c4Ok
  1099. bool isExt = true
  1100. for kb = math.min(math.max(s.c4Start, bar_index - 1499), swIdx) to swIdx
  1101. int o2 = bar_index - kb
  1102. if s.isBull ? low[o2] < swPx : high[o2] > swPx
  1103. isExt := false
  1104. break
  1105. c4Ok := isExt
  1106. // ... or it is still inside C3's range; beyond it no dot
  1107. if not c4Ok
  1108. c4Ok := swPx > s.c3Lo and swPx < s.c3Hi
  1109. if c4Ok and (icInFvg(s, swPx, swIdx) or icSweepsSwing(s, swPx, swIdx))
  1110. registerIcCisd(s, swPx, swIdx, m)
  1111. if live and showAlerts and protAlerts
  1112. alert((s.isBull ? 'Bullish' : 'Bearish') + ' Protected Swing on ' + syminfo.ticker, alert.freq_once_per_bar_close)
  1113. icClearPending(s)
  1114. else if oppBar
  1115. s.icPending := true
  1116. s.icLevel := o_m
  1117. s.icStartIndex := m
  1118. s.icExtreme := s.isBull ? l_m : h_m
  1119. s.icExtremeIndex := m
  1120. s
  1121.  
  1122. // Replays the same step function over bars that already happened (CISD confirmed inside C2,
  1123. // before the setup object existed). Covers cisdEndIndex + 1 .. lastBar.
  1124. method replayIc(C2Setup s, int lastBar) =>
  1125. if showIcCisd and s.cisdConfirmed and not na(s.cisdEndIndex)
  1126. int firstBar = math.max(s.cisdEndIndex + 1, bar_index - icBackfillMaxBars)
  1127. if lastBar >= firstBar
  1128. for m = firstBar to lastBar
  1129. icMarkTaken(s, m)
  1130. icStep(s, m, false)
  1131. s
  1132.  
  1133. // Wick beyond the C3 extreme during C4 stops IC detection.
  1134. icCheckC4Wick(C2Setup s) =>
  1135. if not s.icStopped and s.phase == 2 and not na(s.c3Extreme)
  1136. if s.isBull ? low < s.c3Extreme : high > s.c3Extreme
  1137. s.icStopped := true
  1138. s
  1139.  
  1140. icHardStop(C2Setup s) =>
  1141. s.dead or s.phase == 0 or s.c4Invalid or s.icStopped
  1142.  
  1143. method updateIc(C2Setup s) =>
  1144. if not na(s)
  1145. icCheckC4Wick(s)
  1146. // always keep existing dots up to date, even if detection has stopped
  1147. icMarkTaken(s, bar_index)
  1148. if icHardStop(s) or not showIcCisd or not s.cisdConfirmed or na(s.cisdEndIndex)
  1149. icClearPending(s)
  1150. else
  1151. // Only ever arm / move / break on a closed candle, and only after the CISD confirm bar
  1152. if barstate.isconfirmed and bar_index > s.cisdEndIndex
  1153. icStep(s, bar_index, true)
  1154. s
  1155.  
  1156. deleteSetupVisuals(C2Setup s) =>
  1157. if not na(s)
  1158. label.delete(s.c2Lbl)
  1159. label.delete(s.swLbl)
  1160. line.delete(s.cisdLine)
  1161. label.delete(s.cisdLbl)
  1162. line.delete(s.c1SweepLn)
  1163. line.delete(s.c3Ln)
  1164. if not na(s.smtLns)
  1165. for ln in s.smtLns
  1166. line.delete(ln)
  1167. for lb in s.smtLbls
  1168. label.delete(lb)
  1169. box.delete(s.c3Box)
  1170. line.delete(s.c3Dash)
  1171. label.delete(s.c3Lbl)
  1172. box.delete(s.c4Box)
  1173. line.delete(s.c4Dash)
  1174. label.delete(s.c4Lbl)
  1175. if not na(s.stdDevData)
  1176. for lb in s.stdDevData.labels
  1177. label.delete(lb)
  1178. for ln in s.stdDevData.lines
  1179. line.delete(ln)
  1180. // its protected swings go with it (icMarkTakenAll() drops them from its list)
  1181. if not na(s.icList)
  1182. for ic in s.icList
  1183. label.delete(ic.dotLbl)
  1184. line.delete(ic.ln)
  1185. ic.dotLbl := na
  1186. ic.ln := na
  1187. ic.taken := true
  1188.  
  1189. registerRecord(C2Setup s) =>
  1190. setupRecords.push(SetupRecord.new(s, bar_index))
  1191. while setupRecords.size() > showHistory + 1
  1192. evicted = setupRecords.shift()
  1193. // stop the evicted setup from ever drawing again (buySetup/sellSetup may still point to it)
  1194. evicted.setup.dead := true
  1195. evicted.setup.phase := 0
  1196. evicted.setup.icStopped := true
  1197. deleteSetupVisuals(evicted.setup)
  1198. earliestVisibleBar = setupRecords.size() > 0 ? setupRecords.first().creationBar : na
  1199. pruneEarlyCisd(bullEarlyCisdRecords, earliestVisibleBar)
  1200. pruneEarlyCisd(bearEarlyCisdRecords, earliestVisibleBar)
  1201.  
  1202. autoTf = switch modelType
  1203. '1s-1m' => '1'
  1204. '15s-5m' => '5'
  1205. '1m-15m' => '15'
  1206. '3m-30m' => '30'
  1207. '5m-1H' => '60'
  1208. '15m-4H' => '240'
  1209. '1H-1D' => '1D'
  1210. '4H-1W' => '1W'
  1211. '1D-1M' => '1M'
  1212. 'Custom' => customHTF
  1213. => autoHTF() == '' ? '1M' : autoHTF()
  1214.  
  1215. // The chart must be the fractal's entry timeframe or lower, and below the model HTF
  1216. validTf = (modelType == 'Automatic' ? autoHTF() != '' : timeframe.in_seconds() <= timeframe.in_seconds(ltfCode())) and timeframe.in_seconds(autoTf) > timeframe.in_seconds()
  1217. // HTF candles stay visible on a chart above the fractal's entry timeframe (no model there), as long as the HTF is above the chart
  1218. htfTfOk = timeframe.in_seconds(autoTf) > timeframe.in_seconds() and (modelType != 'Automatic' or autoHTF() != '')
  1219.  
  1220. // [AUTO BIAS] the fractal model 1 / 2 steps above (on 5m-1H: Auto Bias 1 = 15m-4H, Auto Bias 2 = 1H-1D;
  1221. // a bearish 1H-1D model -> only bearish setups that day).
  1222. // The ladder of model HTFs: 15m, 1H, 4H, 1D, 1W, 1M, 3M, 12M; each with its entry timeframe.
  1223. abNextHtf(simple string tf) =>
  1224. int s = timeframe.in_seconds(tf)
  1225. s < timeframe.in_seconds('15') ? '15' : s < timeframe.in_seconds('60') ? '60' : s < timeframe.in_seconds('240') ? '240' : s < timeframe.in_seconds('1D') ? '1D' : s < timeframe.in_seconds('1W') ? '1W' : s < timeframe.in_seconds('1M') ? '1M' : s < timeframe.in_seconds('3M') ? '3M' : '12M'
  1226. abLtfOf(simple string htf) =>
  1227. switch htf
  1228. '15' => '1'
  1229. '60' => '5'
  1230. '240' => '15'
  1231. '1D' => '60'
  1232. '1W' => '240'
  1233. '1M' => '1D'
  1234. '3M' => '1W'
  1235. => '1M'
  1236.  
  1237. // Direction of the higher model, run on its own entry timeframe: C2 closure (takes C1's high / low, closes back
  1238. // inside) + CISD (close through the open of the run into the C2 extreme). It holds through C3 and C4 and ends
  1239. // when C4 closes or a close goes beyond the C2 extreme (XC2). A newer model replaces an older one.
  1240. // +1 bullish, -1 bearish, 0 none.
  1241. abDir(simple string htf) =>
  1242. // reads open / close up to ~1500 bars back below; one fixed deep read sizes this context's buffers up front
  1243. float bufWarm = close[1499] + open[1499]
  1244. var float c1H = na
  1245. var float c1L = na
  1246. var float cH = na
  1247. var float cL = na
  1248. var int cHb = na
  1249. var int cLb = na
  1250. var int dir = 0
  1251. var int want = 0 // C2 closed, CISD not yet confirmed: +1 / -1
  1252. var float ext = na
  1253. var float lvl = na
  1254. var int left = 0
  1255. if timeframe.change(htf)
  1256. if left > 0
  1257. left -= 1
  1258. if left == 0
  1259. dir := 0
  1260. want := 0
  1261. float cc = close[1]
  1262. bool bear = not na(c1H) and cH > c1H and cc < c1H
  1263. bool bull = not na(c1L) and cL < c1L and cc > c1L
  1264. if bear or bull
  1265. bool isBear = bear and (not bull or cHb > cLb)
  1266. int eb = isBear ? cHb : cLb
  1267. ext := isBear ? cH : cL
  1268. // CISD level: open of the run of opposite candles that led into the extreme
  1269. int bias = isBear ? 1 : -1
  1270. float lv = na
  1271. bool found = false
  1272. int off0 = bar_index - eb
  1273. for i = off0 to math.min(off0 + 300, bar_index, 1499)
  1274. int att = close[i] > open[i] ? 1 : close[i] < open[i] ? -1 : 0
  1275. if att == 0
  1276. continue
  1277. if not found
  1278. if att == bias
  1279. found := true
  1280. lv := open[i]
  1281. else
  1282. if att != bias
  1283. break
  1284. lv := open[i]
  1285. lvl := lv
  1286. left := 2
  1287. dir := 0
  1288. want := isBear ? -1 : 1
  1289. // the CISD may already have closed through inside C2, after the extreme
  1290. if not na(lvl) and off0 > 1
  1291. for i = 1 to off0 - 1
  1292. if (isBear and close[i] < lvl) or (not isBear and close[i] > lvl)
  1293. dir := want
  1294. want := 0
  1295. break
  1296. c1H := cH
  1297. c1L := cL
  1298. cH := high
  1299. cL := low
  1300. cHb := bar_index
  1301. cLb := bar_index
  1302. else
  1303. if na(cH) or high > cH
  1304. cH := high
  1305. cHb := bar_index
  1306. if na(cL) or low < cL
  1307. cL := low
  1308. cLb := bar_index
  1309. if left > 0
  1310. if want != 0 and not na(lvl) and (want < 0 ? close < lvl : close > lvl)
  1311. dir := want
  1312. want := 0
  1313. if not na(ext) and (dir < 0 or want < 0 ? close > ext : dir > 0 or want > 0 ? close < ext : false)
  1314. dir := 0
  1315. want := 0
  1316. left := 0
  1317. bar_index < 0 and not na(bufWarm) ? 0 : dir
  1318.  
  1319. int abSteps = biasFilter == 'Auto Bias 1' ? 1 : biasFilter == 'Auto Bias 2' ? 2 : 0
  1320. string abHtf = abSteps == 2 ? abNextHtf(abNextHtf(autoTf)) : abNextHtf(autoTf)
  1321. string abLtf = abLtfOf(abHtf)
  1322. int abBias = 0
  1323. if abSteps > 0
  1324. abBias := request.security(syminfo.tickerid, abLtf, abDir(abHtf)[1], lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true, calc_bars_count = 5000)
  1325. // the bias the setups follow: Bullish / Bearish / Neutral
  1326. string biasNow = abSteps == 0 ? biasFilter : abBias > 0 ? 'Bullish' : abBias < 0 ? 'Bearish' : 'Neutral'
  1327.  
  1328. // [TIME FILTER] new setups only inside the checked windows, on charts below 'Apply below'
  1329. inWindow(string sess) =>
  1330. not na(time(timeframe.period, sess, filterTz))
  1331.  
  1332. timeFilterActive = useTimeFilter and (f1On or f2On or f3On) and timeframe.in_seconds() < timeframe.in_seconds(tfApplyBelow)
  1333. inTimeFilter = not timeFilterActive or (f1On and inWindow(f1Sess)) or (f2On and inWindow(f2Sess)) or (f3On and inWindow(f3Sess))
  1334.  
  1335. // Symbol kind. Used for the ADR / CDR unit (forex in pips, the rest in price points)
  1336. // and for the trading day.
  1337. adrTicker = str.upper(syminfo.ticker)
  1338. adrIsMetal = str.startswith(adrTicker, 'XAU') or str.startswith(adrTicker, 'XAG') or str.startswith(adrTicker, 'XPT') or str.startswith(adrTicker, 'XPD')
  1339. adrHasDigit = str.contains(adrTicker, '0') or str.contains(adrTicker, '1') or str.contains(adrTicker, '2') or str.contains(adrTicker, '3') or str.contains(adrTicker, '4') or str.contains(adrTicker, '5') or str.contains(adrTicker, '6') or str.contains(adrTicker, '7') or str.contains(adrTicker, '8') or str.contains(adrTicker, '9')
  1340. adrIsFx = not adrIsMetal and (syminfo.type == 'forex' or (syminfo.type == 'cfd' and str.length(adrTicker) == 6 and not adrHasDigit))
  1341. adrPip = str.contains(adrTicker, 'JPY') ? 0.01 : 0.0001
  1342.  
  1343.  
  1344. // [NY DAY] Trading day in New York time, the same on every broker: forex starts 17:00, indices,
  1345. // metals and the rest 18:00. Crypto trades 24/7 and keeps the symbol's own daily candle.
  1346. dayIsCrypto = syminfo.type == 'crypto'
  1347. dayStartH = adrIsFx ? 17 : 18
  1348.  
  1349. nyNewDay(simple int h, simple bool crypto) =>
  1350. int off = (24 - h) * 3600000
  1351. crypto ? timeframe.change('1D') : not na(time[1]) and dayofmonth(time + off, 'America/New_York') != dayofmonth(time[1] + off, 'America/New_York')
  1352.  
  1353. // [ADR] ADR / CDR table and ADR+ / ADR- lines on the NY trading day (see [NY DAY]).
  1354. // Built from 1H bars so it does not depend on chart history: ADR = average high-low of the last
  1355. // len completed days (today excluded), plus today's high / low so far.
  1356. adrReq(simple int len, simple int h, simple bool crypto) =>
  1357. var float dH = na
  1358. var float dL = na
  1359. var float[] ranges = array.new_float()
  1360. if nyNewDay(h, crypto)
  1361. if not na(dH)
  1362. ranges.push(dH - dL)
  1363. if ranges.size() > len
  1364. ranges.shift()
  1365. dH := high
  1366. dL := low
  1367. else
  1368. dH := na(dH) ? high : math.max(dH, high)
  1369. dL := na(dL) ? low : math.min(dL, low)
  1370. float adr = ranges.size() == len ? ranges.avg() : na
  1371. [adr, dH, dL]
  1372.  
  1373.  
  1374. // [1H REQUEST] ADR always comes from 1H; on a 5m chart the same request also gives the model HTF candle.
  1375. h60Req(simple int len, simple int h, simple bool crypto) =>
  1376. [adr, dH, dL] = adrReq(len, h, crypto)
  1377. [adr, dH, dL, open, high, low, close, high[1], low[1]]
  1378.  
  1379. [adrVal, adrDayH, adrDayL, h60O, h60H, h60L, h60C, h60H1, h60L1] = request.security(syminfo.tickerid, '60', h60Req(adrLen, dayStartH, dayIsCrypto), lookahead = barmerge.lookahead_on, calc_bars_count = 5000)
  1380.  
  1381. // Model HTF candle: forming candle [0] and the previous one's high / low.
  1382. float currentO = h60O
  1383. float currentH = h60H
  1384. float currentL = h60L
  1385. // close comes from the chart bar: D / W / M futures bars close at the settlement price, the model uses the last trade
  1386. float currentC = close
  1387. float prevH1 = h60H1
  1388. float prevL1 = h60L1
  1389. if autoTf != '60'
  1390. [mO, mH, mL, mC, mH1, mL1] = request.security(syminfo.tickerid, autoTf, [open[0], high[0], low[0], close[0], high[1], low[1]], lookahead = barmerge.lookahead_on, calc_bars_count = 5000)
  1391. currentO := mO
  1392. currentH := mH
  1393. currentL := mL
  1394. prevH1 := mH1
  1395. prevL1 := mL1
  1396.  
  1397.  
  1398. // [SMT / PSP] One request per pair, at the chart timeframe: the pair's bar high / low, plus its last two
  1399. // completed model HTF candles ([1] = C2, [2] = C1 on the first bar of a new HTF candle), built from the
  1400. // same bars. Used for SMT on the chart, SMT on the HTF candles, and PSP.
  1401. type PairBars
  1402. float h
  1403. float l
  1404. float o
  1405. float c
  1406. float h1
  1407. float l1
  1408. float h2
  1409. float l2
  1410. float o1
  1411. float c1
  1412. float o2
  1413. float c2
  1414. float o3
  1415. float c3
  1416.  
  1417. smtPairReq(simple string htf) =>
  1418. var float cH = na
  1419. var float cL = na
  1420. var float cO = na
  1421. var float pH1 = na
  1422. var float pL1 = na
  1423. var float pO1 = na
  1424. var float pC1 = na
  1425. var float pH2 = na
  1426. var float pL2 = na
  1427. var float pO2 = na
  1428. var float pC2 = na
  1429. var float pO3 = na
  1430. var float pC3 = na
  1431. if timeframe.change(htf)
  1432. pO3 := pO2
  1433. pC3 := pC2
  1434. pH2 := pH1
  1435. pL2 := pL1
  1436. pO2 := pO1
  1437. pC2 := pC1
  1438. pH1 := cH
  1439. pL1 := cL
  1440. pO1 := cO
  1441. pC1 := close[1]
  1442. cH := high
  1443. cL := low
  1444. cO := open
  1445. else
  1446. cH := na(cH) ? high : math.max(cH, high)
  1447. cL := na(cL) ? low : math.min(cL, low)
  1448. cO := na(cO) ? open : cO
  1449. PairBars.new(high, low, open, close, pH1, pL1, pH2, pL2, pO1, pC1, pO2, pC2, pO3, pC3)
  1450.  
  1451. // Inverse pair: flip it so its highs line up with our lows
  1452. pairInvert(PairBars p, bool inv) =>
  1453. inv and not na(p) ? PairBars.new(-p.l, -p.h, -p.o, -p.c, -p.l1, -p.h1, -p.l2, -p.h2, -p.o1, -p.c1, -p.o2, -p.c2, -p.o3, -p.c3) : p
  1454.  
  1455. bool needPairs = show_smt or showPsp
  1456. PairBars pb1a = na
  1457. if needPairs and pair1A != ''
  1458. pb1a := request.security(pair1A, timeframe.period, smtPairReq(autoTf), ignore_invalid_symbol = true, calc_bars_count = 5000)
  1459. PairBars pb1b = na
  1460. if needPairs and pair1B != ''
  1461. pb1b := request.security(pair1B, timeframe.period, smtPairReq(autoTf), ignore_invalid_symbol = true, calc_bars_count = 5000)
  1462. PairBars pb2a = na
  1463. if needPairs and pair2A != ''
  1464. pb2a := request.security(pair2A, timeframe.period, smtPairReq(autoTf), ignore_invalid_symbol = true, calc_bars_count = 5000)
  1465. PairBars pb2b = na
  1466. if needPairs and pair2B != ''
  1467. pb2b := request.security(pair2B, timeframe.period, smtPairReq(autoTf), ignore_invalid_symbol = true, calc_bars_count = 5000)
  1468.  
  1469. // The fallback name is used only when the first choice never had data
  1470. var bool seen1a = false
  1471. var bool seen1b = false
  1472. var bool seen2a = false
  1473. var bool seen2b = false
  1474. seen1a := seen1a or (not na(pb1a) and not na(pb1a.h))
  1475. seen1b := seen1b or (not na(pb1b) and not na(pb1b.h))
  1476. seen2a := seen2a or (not na(pb2a) and not na(pb2a.h))
  1477. seen2b := seen2b or (not na(pb2b) and not na(pb2b.h))
  1478. bool use1b = not seen1a and seen1b
  1479. bool use2b = not seen2a and seen2b
  1480.  
  1481. PairBars pair1 = pairInvert(use1b ? pb1b : pb1a, pair1InvOn)
  1482. PairBars pair2 = pairInvert(use2b ? pb2b : pb2a, pair2InvOn)
  1483. string pair1Name = pair1A == '' ? '' : use1b ? pair1B : pair1A
  1484. string pair2Name = pair2A == '' ? '' : use2b ? pair2B : pair2A
  1485. bool pair1Seen = seen1a or seen1b
  1486. bool pair2Seen = seen2a or seen2b
  1487.  
  1488. // [EXTRA HTF] HTF 1 / HTF 2: higher timeframe candle blocks right of the model block.
  1489. // No model runs on them. Each block is requested on its own timeframe (a 1m chart's 2000 bars cannot
  1490. // build daily candles), and each pair the same way, so SMT / PSP reach the older candles too.
  1491. xSelTf(simple string s) =>
  1492. switch s
  1493. '15m' => '15'
  1494. '30m' => '30'
  1495. '1H' => '60'
  1496. '90m' => '90'
  1497. '4H' => '240'
  1498. '6H' => '360'
  1499. '7H' => '420'
  1500. 'D' => '1D'
  1501. 'W' => '1W'
  1502. 'M' => '1M'
  1503. => ''
  1504.  
  1505. string x1Auto = abNextHtf(autoTf)
  1506. string x1Tf = x1Sel == 'Auto' ? x1Auto : xSelTf(x1Sel)
  1507. string x2Base = showX1 ? x1Tf : x1Auto
  1508. string x2Tf = x2Sel == 'Auto' ? abNextHtf(x2Base) : xSelTf(x2Sel)
  1509. bool x1On = showX1 and validTf and not hideHtf and timeframe.in_seconds(x1Tf) > timeframe.in_seconds() and (x1Sel != 'Auto' or timeframe.in_seconds(x1Tf) > timeframe.in_seconds(autoTf))
  1510. bool x2On = showX2 and validTf and not hideHtf and timeframe.in_seconds(x2Tf) > timeframe.in_seconds() and (x2Sel != 'Auto' or timeframe.in_seconds(x2Tf) > timeframe.in_seconds(x2Base))
  1511. int nX = math.min(htfCandleCount, 10)
  1512.  
  1513. type XData
  1514. array<float> o
  1515. array<float> h
  1516. array<float> l
  1517. array<float> c
  1518. array<int> t
  1519.  
  1520. // The last n candles, newest first. Only filled on the last bar (the blocks are drawn there).
  1521. xReq(simple int n) =>
  1522. array<float> ao = array.new<float>()
  1523. array<float> ah = array.new<float>()
  1524. array<float> al = array.new<float>()
  1525. array<float> ac = array.new<float>()
  1526. array<int> at = array.new<int>()
  1527. if barstate.islast
  1528. for k = 0 to n - 1
  1529. if na(time[k])
  1530. break
  1531. ao.push(open[k])
  1532. ah.push(high[k])
  1533. al.push(low[k])
  1534. ac.push(close[k])
  1535. at.push(time[k])
  1536. [ao, ah, al, ac, at]
  1537.  
  1538. xFetch(string sym, string tf) =>
  1539. [o, h, l, c, t] = request.security(sym, tf, xReq(nX), lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true, calc_bars_count = 100)
  1540. XData.new(o, h, l, c, t)
  1541.  
  1542. XData x1D = na
  1543. XData x1P = na
  1544. XData x1Q = na
  1545. XData x2D = na
  1546. XData x2P = na
  1547. XData x2Q = na
  1548. if x1On
  1549. x1D := xFetch(syminfo.tickerid, x1Tf)
  1550. if needPairs and pair1Name != ''
  1551. x1P := xFetch(pair1Name, x1Tf)
  1552. if needPairs and pair2Name != ''
  1553. x1Q := xFetch(pair2Name, x1Tf)
  1554. if x2On
  1555. x2D := xFetch(syminfo.tickerid, x2Tf)
  1556. if needPairs and pair1Name != ''
  1557. x2P := xFetch(pair1Name, x2Tf)
  1558. if needPairs and pair2Name != ''
  1559. x2Q := xFetch(pair2Name, x2Tf)
  1560.  
  1561. // Chart symbol swept C1 (that is what makes it a C2). SMT = a pair did NOT sweep its own C1.
  1562. pairSmtBuy(PairBars p) =>
  1563. not na(p) and p.l1 >= p.l2
  1564. pairSmtSell(PairBars p) =>
  1565. not na(p) and p.h1 <= p.h2
  1566. smtBuyHit = show_smt and (pairSmtBuy(pair1) or pairSmtBuy(pair2))
  1567. smtSellHit = show_smt and (pairSmtSell(pair1) or pairSmtSell(pair2))
  1568.  
  1569. // PSP: own candle and the pair's same candle close in different colors (dojis ignored)
  1570. pspDiff(float o, float c, float po, float pc) =>
  1571. (c - o) * (pc - po) < 0
  1572. pairPsp(PairBars p, HtfCandle own1, HtfCandle own2) =>
  1573. bool chk1 = pspMode != 'Candle 2'
  1574. bool chk2 = pspMode != 'Candle 1'
  1575. not na(p) and ((chk2 and pspDiff(own2.o, own2.c, p.o1, p.c1)) or (chk1 and pspDiff(own1.o, own1.c, p.o2, p.c2)))
  1576. // C3 model (when C4 opens): PSP on its C1 (pair 3 back) and C2 (pair 2 back), not on C3
  1577. pairPsp3(PairBars p, HtfCandle own1, HtfCandle own2) =>
  1578. bool chk1 = pspMode != 'Candle 2'
  1579. bool chk2 = pspMode != 'Candle 1'
  1580. not na(p) and ((chk2 and pspDiff(own2.o, own2.c, p.o2, p.c2)) or (chk1 and pspDiff(own1.o, own1.c, p.o3, p.c3)))
  1581.  
  1582. // SMT label text: the pair(s) that diverged
  1583. smtNames(bool d1, bool d2) =>
  1584. string s = ''
  1585. if smtLabels
  1586. if d1
  1587. s := statusSym(pair1Name)
  1588. if d2
  1589. s := s == '' ? statusSym(pair2Name) : s + '/' + statusSym(pair2Name)
  1590. s
  1591.  
  1592. c2Buy = currentL < prevL1 and currentC > prevL1
  1593. c2Sell = currentH > prevH1 and currentC < prevH1
  1594. int htfOpenT = time(autoTf)
  1595. periodChanged = htfOpenT != htfOpenT[1]
  1596.  
  1597.  
  1598. // T-Spot geometry at the current bar: between the previous HTF candle's EQ and this candle's open
  1599. // EQ rule: a C2 that closed against the setup (bullish setup, bearish C2; doji
  1600. // too) uses its close -> wick extreme; otherwise, and always for C3, the full range.
  1601. phaseGeom(bool isBull, bool c2Ref) =>
  1602. float mid = (state.prevHigh + state.prevLow) / 2
  1603. if c2Ref and htfCandles.size() > 1
  1604. HtfCandle c = htfCandles.get(1)
  1605. if isBull ? c.c <= c.o : c.c >= c.o
  1606. mid := isBull ? (c.c + c.l) / 2 : (c.c + c.h) / 2
  1607. [math.max(open, mid), math.min(open, mid), mid]
  1608.  
  1609. // T-Spot box + EQ of one stage, drawn from bar x0 to the current bar. The C3 box has no
  1610. // label; 'C4' sits at the start of the C4 box, on the C3 EQ line.
  1611. drawPhaseAt(bool isBull, int stage, int x0, float top, float bot, float mid, bool withLbl = true) =>
  1612. color bxCol = isBull ? tSpotBullColor : tSpotBearColor
  1613. box bx = showTSpot ? box.new(x0, top, bar_index + 1, bot, border_color = na, bgcolor = bxCol) : na
  1614. line dash = showEQ ? line.new(x0, mid, bar_index + 1, mid, color = eqColor, width = eqWidth, style = lineStyleFromStr(eqStyle)) : na
  1615. label lbl = na
  1616. if stage == 4 and withLbl and showLabels and validTf
  1617. lbl := label.new(x0, mid, 'C4', style = isBull ? label.style_label_upper_left : label.style_label_lower_left, color = na, textcolor = c2c3c4Color, size = textSize(labelSize))
  1618. [bx, dash, lbl]
  1619.  
  1620. // [SMT] one chart SMT line (+ pair name label at its middle) owned by a setup
  1621. smtDrawOn(C2Setup s, int x1, float y1, int x2, float y2, bool isHigh, string txt) =>
  1622. if na(s.smtLns)
  1623. s.smtLns := array.new<line>()
  1624. s.smtLbls := array.new<label>()
  1625. s.smtLns.push(line.new(x1, y1, x2, y2, color = smtColorFor(isHigh), style = lineStyleFromStr(smtStyle), width = smtWidth))
  1626. if txt != ''
  1627. s.smtLbls.push(label.new(int(math.round((x1 + x2) / 2.0)), (y1 + y2) / 2, txt, style = isHigh ? label.style_label_down : label.style_label_up, color = na, textcolor = smtColorFor(isHigh), size = textSize(smtLblSize)))
  1628.  
  1629. modelText() =>
  1630. tfLabel(ltfCode()) + '-' + tfLabel(autoTf)
  1631.  
  1632. // C4 failed: label turns XC4, label, EQ and box in red
  1633. c4Fail(C2Setup s) =>
  1634. if not na(s.c4Lbl)
  1635. label.set_text(s.c4Lbl, 'XC4')
  1636. label.set_textcolor(s.c4Lbl, cisdBearColor)
  1637. line.set_color(s.c4Dash, cisdBearColor)
  1638. box.set_bgcolor(s.c4Box, color.new(cisdBearColor, 85))
  1639.  
  1640. // [REVEAL] A model is only drawn once its LTF CISD confirms. Everything that already happened is drawn then.
  1641. method reveal(C2Setup s) =>
  1642. if not s.revealed
  1643. s.revealed := true
  1644. if showLabels and validTf
  1645. s.c2Lbl := directionalLabel(nz(s.lblBar, s.c2BarIndex), nz(s.lblPx, s.extreme), s.tag, s.isBull)
  1646. if s.c3Model and not na(s.c2BarIndex)
  1647. s.swLbl := directionalLabel(s.c2BarIndex, s.extreme, s.swTag, s.isBull)
  1648. // [C1 SWEEP] on the chart: from the C1 high / low that was taken to the end of C2
  1649. if sweepOnChart and validTf and not na(s.c1Bar) and not na(s.c1Px)
  1650. s.c1SweepLn := line.new(s.c1Bar, s.c1Px, s.sweepEnd, s.c1Px, color = sweepColor, style = lineStyleFromStr(sweepStyle), width = sweepWidth)
  1651. if s.c3Model and showLabels and validTf and not na(s.c3LnBar) and not na(s.lblPx)
  1652. s.c3Ln := line.new(s.c3LnBar, s.lblPx, bar_index, s.lblPx, color = sweepColor, style = line.style_dotted)
  1653. // [REVERSAL SMT] C2 took C1's high / low but a pair did not: line from the C1 extreme to the C2 extreme
  1654. if smtOnChart and s.smtHit and validTf and not na(s.c1Bar) and not na(s.c1Px)
  1655. smtDrawOn(s, s.c1Bar, s.c1Px, s.c2BarIndex, s.extreme, not s.isBull, s.smtTxt)
  1656. if not na(s.c3Start)
  1657. [bx, dash, _] = drawPhaseAt(s.isBull, 3, s.c3Start, s.c3Top, s.c3Bot, s.c3Mid)
  1658. s.c3Box := bx
  1659. s.c3Dash := dash
  1660. if s.phase == 2
  1661. box.set_right(s.c3Box, s.c4Start)
  1662. line.set_x2(s.c3Dash, s.c4Start)
  1663. if s.phase == 2 and showC4 and not na(s.c4Start)
  1664. [bx4, dash4, lbl4] = drawPhaseAt(s.isBull, 4, s.c4Start, s.c4Top, s.c4Bottom, s.c4Mid)
  1665. s.c4Box := bx4
  1666. s.c4Dash := dash4
  1667. s.c4Lbl := lbl4
  1668. c4LabelDodge(s)
  1669. if s.c4Invalid
  1670. c4Fail(s)
  1671. registerRecord(s)
  1672. if showAlerts and modelAlerts
  1673. alert((s.isBull ? 'Bullish ' : 'Bearish ') + (s.c3Model ? 'Candle 3' : 'Candle 2') + ' (' + s.tag + ') on ' + syminfo.ticker + ', ' + modelText(), alert.freq_once_per_bar_close)
  1674. s
  1675.  
  1676. // A new model. C2 model: created when C3 opens. C3 model (C3 closure): created when C4 opens, so it
  1677. // starts in C4. Nothing is drawn until the CISD confirms (see reveal).
  1678. newSetup(bool isBull, bool c3Model, float extreme, int extremeBar, string tag, float c1Px, int c1Bar, int sweepEnd, float cisdLevel, int cisdIndex, bool cisdAlreadyConfirmed, int cisdConfirmBar, bool smtHit, string smtTxt, float fl1Px, int fl1Bar, float fl0Px, int fl0Bar) =>
  1679. C2Setup s = C2Setup.new(isBull = isBull, extreme = extreme, phase = 1, dead = false, c2Lbl = na)
  1680. s.c3Model := c3Model
  1681. s.c2BarIndex := extremeBar
  1682. s.tag := tag
  1683. s.c1Px := c1Px
  1684. s.c1Bar := c1Bar
  1685. s.sweepEnd := sweepEnd
  1686. s.smtHit := smtHit
  1687. s.smtTxt := smtTxt
  1688. s.fl1Px := fl1Px
  1689. s.fl1Bar := fl1Bar
  1690. s.fl0Px := fl0Px
  1691. s.fl0Bar := fl0Bar
  1692. s.cisdLevel := cisdLevel
  1693. s.cisdIndex := cisdIndex
  1694. [top, bot, mid] = phaseGeom(isBull, not c3Model)
  1695. if c3Model
  1696. if htfCandles.size() > 1
  1697. s.c3Extreme := isBull ? htfCandles.get(1).l : htfCandles.get(1).h
  1698. s.c3Hi := htfCandles.get(1).h
  1699. s.c3Lo := htfCandles.get(1).l
  1700. // the 'C3' label sits at C3's low / high, in the middle of the C3 period
  1701. s.lblPx := s.c3Extreme
  1702. s.lblBar := na(sweepEnd) ? na : int(math.round((sweepEnd + bar_index - 1) / 2.0))
  1703. s.c3LnBar := isBull ? htfCandles.get(1).lBar : htfCandles.get(1).hBar
  1704. // C3 T-Spot, drawn back over the C3 period: between C3's open and C2's EQ (a C2 that closed against the
  1705. // setup uses close <-> wick extreme), as a C2 model's C3 box would have been
  1706. if htfCandles.size() > 2 and htfOpenBars.size() > 1
  1707. HtfCandle c3bK2 = htfCandles.get(2)
  1708. HtfCandle c3bK3 = htfCandles.get(1)
  1709. float c3bMid = (c3bK2.h + c3bK2.l) / 2
  1710. if isBull ? c3bK2.c <= c3bK2.o : c3bK2.c >= c3bK2.o
  1711. c3bMid := isBull ? (c3bK2.c + c3bK2.l) / 2 : (c3bK2.c + c3bK2.h) / 2
  1712. s.c3Start := htfOpenBars.get(1)
  1713. s.c3Top := math.max(c3bK3.o, c3bMid)
  1714. s.c3Bot := math.min(c3bK3.o, c3bMid)
  1715. s.c3Mid := c3bMid
  1716. s.phase := 2
  1717. s.c4Start := bar_index
  1718. s.c4Top := top
  1719. s.c4Bottom := bot
  1720. s.c4Mid := mid
  1721. else
  1722. // The C3 T-Spot is trimmed to EQ <-> CISD when the CISD level lies inside it (the EQ edge stays, the open
  1723. // edge moves to the CISD); a CISD outside leaves EQ <-> open.
  1724. // EQ on the wrong side of C3's open (bearish: below it) with the CISD between them: the box and EQ go
  1725. // above the open instead, open <-> (C2 extreme + open) / 2. A CISD outside keeps EQ <-> open.
  1726. bool cisdIn = not na(cisdLevel) and cisdLevel > bot and cisdLevel < top
  1727. bool wrongSide = isBull ? mid > open : mid < open
  1728. if cisdIn and wrongSide
  1729. mid := ((isBull ? state.prevLow : state.prevHigh) + open) / 2
  1730. top := math.max(open, mid)
  1731. bot := math.min(open, mid)
  1732. else if cisdIn
  1733. if top == mid
  1734. bot := cisdLevel
  1735. else
  1736. top := cisdLevel
  1737. s.c3Start := bar_index
  1738. s.c3Top := top
  1739. s.c3Bot := bot
  1740. s.c3Mid := mid
  1741. if cisdAlreadyConfirmed and not na(cisdLevel) and not na(cisdIndex) and not na(cisdConfirmBar)
  1742. s.reveal()
  1743. confirmCisd(s, cisdConfirmBar, false)
  1744. s.replayIc(bar_index - 1)
  1745. s
  1746.  
  1747. method advanceToC4(C2Setup s) =>
  1748. if htfCandles.size() > 1
  1749. c3 = htfCandles.get(1)
  1750. s.c3Extreme := s.isBull ? c3.l : c3.h
  1751. s.c3Hi := c3.h
  1752. s.c3Lo := c3.l
  1753. box.set_right(s.c3Box, bar_index)
  1754. line.set_x2(s.c3Dash, bar_index)
  1755. [top, bot, mid] = phaseGeom(s.isBull, false)
  1756. s.c4Start := bar_index
  1757. s.c4Top := top
  1758. s.c4Bottom := bot
  1759. s.c4Mid := mid
  1760. s.phase := 2
  1761. s.c4Invalid := false
  1762. if s.revealed and showC4
  1763. [bx, dash, lbl] = drawPhaseAt(s.isBull, 4, bar_index, top, bot, mid)
  1764. s.c4Box := bx
  1765. s.c4Dash := dash
  1766. s.c4Lbl := lbl
  1767. c4LabelDodge(s)
  1768. if s.revealed and showAlerts and modelAlerts and showC4
  1769. alert((s.isBull ? 'Bullish' : 'Bearish') + ' Candle 4 on ' + syminfo.ticker + ', ' + modelText(), alert.freq_once_per_bar_close)
  1770. s
  1771.  
  1772. // a finished setup's dots can still grey during the next HTF candle (C5), then keep their color.
  1773. icFreeze(C2Setup s) =>
  1774. if not na(s) and not na(s.icList)
  1775. for ic in s.icList
  1776. ic.liveHtf := htfOpenT
  1777.  
  1778. method finish(C2Setup s) =>
  1779. icFreeze(s)
  1780. // the model stayed valid through C4: gray label
  1781. label.set_textcolor(s.c2Lbl, validColor)
  1782. label.set_textcolor(s.swLbl, validColor)
  1783. if not na(s.c4Box) and not s.c4Invalid
  1784. box.set_right(s.c4Box, bar_index)
  1785. if not na(s.c4Dash) and not s.c4Invalid
  1786. line.set_x2(s.c4Dash, bar_index)
  1787. s.phase := 0
  1788. s
  1789.  
  1790. method deleteStdDev(C2Setup s) =>
  1791. if not na(s.stdDevData)
  1792. for lb in s.stdDevData.labels
  1793. label.delete(lb)
  1794. for ln in s.stdDevData.lines
  1795. line.delete(ln)
  1796. s.stdDevData := na
  1797. s
  1798.  
  1799. method extendAndCheck(C2Setup s) =>
  1800. if not na(s) and not s.dead and s.phase != 0
  1801. // T-Spot box and EQ grow with price, one bar past the current bar, so a new box shows
  1802. // on its first bar (the C4 EQ stops at an XC4)
  1803. if s.phase == 1
  1804. box.set_right(s.c3Box, bar_index + 1)
  1805. if not na(s.c3Dash)
  1806. line.set_x2(s.c3Dash, bar_index + 1)
  1807. else if not s.c4Invalid
  1808. box.set_right(s.c4Box, bar_index + 1)
  1809. line.set_x2(s.c4Dash, bar_index + 1)
  1810. if s.phase == 2 and not na(s.c3Ln)
  1811. line.set_x2(s.c3Ln, bar_index + 1)
  1812.  
  1813. // XC2: price touches or trades through the swing (the C2 extreme), wick is enough.
  1814. c2Breach = s.isBull ? low <= s.extreme : high >= s.extreme
  1815. if c2Breach
  1816. // red: fails in the first candle after the closure (C3; for a C3 model, C4); orange: in the second (C4)
  1817. if not na(s.c2Lbl)
  1818. label.set_text(s.c2Lbl, 'X' + s.tag)
  1819. label.set_textcolor(s.c2Lbl, s.phase == 2 and not s.c3Model ? color.orange : cisdBearColor)
  1820. if not na(s.swLbl)
  1821. label.set_text(s.swLbl, 'X' + s.swTag)
  1822. label.set_textcolor(s.swLbl, cisdBearColor)
  1823. box.delete(s.c3Box)
  1824. s.c3Box := na
  1825. line.delete(s.c3Dash)
  1826. s.c3Dash := na
  1827. box.delete(s.c4Box)
  1828. s.c4Box := na
  1829. line.delete(s.c4Dash)
  1830. s.c4Dash := na
  1831. label.delete(s.c4Lbl)
  1832. s.c4Lbl := na
  1833. line.delete(s.c1SweepLn)
  1834. s.c1SweepLn := na
  1835. line.delete(s.c3Ln)
  1836. s.c3Ln := na
  1837. // its SMT lines go too
  1838. if not na(s.smtLns)
  1839. for ln in s.smtLns
  1840. line.delete(ln)
  1841. for lb in s.smtLbls
  1842. label.delete(lb)
  1843. s.smtLns.clear()
  1844. s.smtLbls.clear()
  1845. s.csLn := na
  1846. s.csLb := na
  1847. s.deleteStdDev()
  1848. s.dead := true
  1849. s.phase := 0
  1850. s
  1851.  
  1852. // XC4: the C4 continuation is stopped the moment price trades through C3's opposite extreme (bearish: a high
  1853. // above C3's high, bullish: a low below C3's low), intrabar, without waiting for the close. The label turns
  1854. // XC4 and the label, EQ and box turn red and stop there.
  1855. // (Protected swings still stop on their own rule: a wick beyond C3's extreme during C4.)
  1856. method checkC4Invalid(C2Setup s) =>
  1857. if not na(s) and not s.dead and s.phase == 2 and not s.c4Invalid and not na(s.c3Extreme)
  1858. invalid = s.isBull ? low < s.c3Extreme : high > s.c3Extreme
  1859. if invalid
  1860. s.c4Invalid := true
  1861. c4Fail(s)
  1862. line.set_x2(s.c4Dash, bar_index)
  1863. box.set_right(s.c4Box, bar_index)
  1864. s
  1865.  
  1866. method checkCisdConfirm(C2Setup s) =>
  1867. if not na(s) and not s.dead and not s.cisdConfirmed and s.phase != 0 and not na(s.cisdLevel) and not na(s.cisdIndex)
  1868. confirmed = s.isBull ? close > s.cisdLevel : close < s.cisdLevel
  1869. if confirmed
  1870. s.reveal()
  1871. confirmCisd(s, bar_index)
  1872. s
  1873.  
  1874. // New model on a trigger, otherwise C3 -> C4 -> finished on each new HTF candle
  1875. processSetup(C2Setup existing, bool trigger, bool isBull, bool c3Model, float extreme, int extremeBar, string tag, float c1Px, int c1Bar, int sweepEnd, float cisdLevel, int cisdIndex, bool cisdDone, int cisdBar, bool smtHit, string smtTxt, float fl1Px, int fl1Bar, float fl0Px, int fl0Bar) =>
  1876. C2Setup result = existing
  1877. if trigger
  1878. result := newSetup(isBull, c3Model, extreme, extremeBar, tag, c1Px, c1Bar, sweepEnd, cisdLevel, cisdIndex, cisdDone, cisdBar, smtHit, smtTxt, fl1Px, fl1Bar, fl0Px, fl0Bar)
  1879. else if periodChanged and not na(existing) and not existing.dead
  1880. result := existing.phase == 1 ? existing.advanceToC4() : existing.phase == 2 ? existing.finish() : existing
  1881. result
  1882.  
  1883. markTrigger(bool trigger, bool allow, int idx, bool isBuy) =>
  1884. if trigger and allow and htfCandles.size() > idx
  1885. c = htfCandles.get(idx)
  1886. if isBuy
  1887. c.triggerBuy := true
  1888. else
  1889. c.triggerSell := true
  1890.  
  1891. //#endregion
  1892.  
  1893. //#region [LOGIC]
  1894.  
  1895. var float h0 = high
  1896. var float l0 = low
  1897. var float h1 = high
  1898. var float l1 = low
  1899.  
  1900. if periodChanged
  1901. h1 := h0[1]
  1902. l1 := l0[1]
  1903. h0 := high
  1904. l0 := low
  1905.  
  1906. if high >= h0
  1907. h0 := high
  1908. if low <= l0
  1909. l0 := low
  1910.  
  1911. bool up = close > open
  1912. bool dw = close < open
  1913. bool eq = close == open
  1914.  
  1915. var float bullLevelFixed = na
  1916. var int bullIndexFixed = na
  1917. var float bearLevelFixed = na
  1918. var int bearIndexFixed = na
  1919.  
  1920. // CISD level of the newest low / high that took the previous HTF candle's low / high: the open of the run
  1921. // of opposite candles that led into it. Searched up to 300 bars back (a long one-way run is still found);
  1922. // when no run is found the level is cleared, so an older swing's level can never confirm this one.
  1923. if low == l0 and low < l1
  1924. bool bullFound = false
  1925. if (dw[0] or eq[0]) and (up[1] or eq[1]) and not (eq[0] and eq[1])
  1926. bullLevelFixed := open
  1927. bullIndexFixed := bar_index
  1928. bullFound := true
  1929. else
  1930. for i = 2 to 300
  1931. if low[i] < low
  1932. break
  1933. if (up[i] or eq[i]) and dw[i - 1]
  1934. b = i - 1
  1935. bullLevelFixed := open[b]
  1936. bullIndexFixed := bar_index - b
  1937. for j = b to 0
  1938. if open[j] > bullLevelFixed and dw[j]
  1939. bullLevelFixed := open[j]
  1940. bullIndexFixed := bar_index - j
  1941. // the level stays at the run's open even when the extreme candle opened beyond it
  1942. bullFound := true
  1943. break
  1944. if not bullFound
  1945. bullLevelFixed := na
  1946. bullIndexFixed := na
  1947.  
  1948. if high == h0 and high > h1
  1949. bool bearFound = false
  1950. if (up[0] or eq[0]) and (dw[1] or eq[1]) and not (eq[0] and eq[1])
  1951. bearLevelFixed := open
  1952. bearIndexFixed := bar_index
  1953. bearFound := true
  1954. else
  1955. for i = 2 to 300
  1956. if high[i] > high
  1957. break
  1958. if (dw[i] or eq[i]) and up[i - 1]
  1959. yb = i - 1
  1960. bearLevelFixed := open[yb]
  1961. bearIndexFixed := bar_index - yb
  1962. for j = yb to 0
  1963. if open[j] < bearLevelFixed and up[j]
  1964. bearLevelFixed := open[j]
  1965. bearIndexFixed := bar_index - j
  1966. bearFound := true
  1967. break
  1968. if not bearFound
  1969. bearLevelFixed := na
  1970. bearIndexFixed := na
  1971.  
  1972. var bool bullReclaimed = false
  1973. var int bullReclaimBar = na
  1974. var bool bearReclaimed = false
  1975. var int bearReclaimBar = na
  1976.  
  1977. bullEarlyCisdFiredThisBar = false
  1978. bearEarlyCisdFiredThisBar = false
  1979. cisdBullFiredThisBar := false
  1980. cisdBearFiredThisBar := false
  1981.  
  1982. bullPeriodSweep = l0 < l1
  1983. bearPeriodSweep = h0 > h1
  1984.  
  1985. newBullLevel = not na(bullIndexFixed) and (na(bullIndexFixed[1]) or bullIndexFixed != bullIndexFixed[1])
  1986. if newBullLevel or na(bullLevelFixed)
  1987. bullReclaimed := false
  1988. bullReclaimBar := na
  1989. if not na(bullLevelFixed) and not bullReclaimed and close > bullLevelFixed
  1990. bullReclaimed := true
  1991. bullReclaimBar := bar_index
  1992. if bullPeriodSweep
  1993. drawEarlyCisd(true, bullLevelFixed, bullIndexFixed, bar_index)
  1994. bullEarlyCisdFiredThisBar := true
  1995.  
  1996. newBearLevel = not na(bearIndexFixed) and (na(bearIndexFixed[1]) or bearIndexFixed != bearIndexFixed[1])
  1997. if newBearLevel or na(bearLevelFixed)
  1998. bearReclaimed := false
  1999. bearReclaimBar := na
  2000. if not na(bearLevelFixed) and not bearReclaimed and close < bearLevelFixed
  2001. bearReclaimed := true
  2002. bearReclaimBar := bar_index
  2003. if bearPeriodSweep
  2004. drawEarlyCisd(false, bearLevelFixed, bearIndexFixed, bar_index)
  2005. bearEarlyCisdFiredThisBar := true
  2006.  
  2007.  
  2008. candleOffset = candleOffsetIn + 10
  2009.  
  2010. if periodChanged
  2011. if htfCandles.size() > 0
  2012. newest = htfCandles.first()
  2013. state.prevHigh := newest.h
  2014. state.prevLow := newest.l
  2015. htfCandles.unshift(newHtfCandle())
  2016. while htfCandles.size() > htfKeep
  2017. htfCandles.pop().delete()
  2018. htfOpenBar := bar_index
  2019. htfOpenBars.unshift(bar_index)
  2020. if htfOpenBars.size() > 5
  2021. htfOpenBars.pop()
  2022. else if htfCandles.size() > 0
  2023. htfCandles.set(0, htfCandles.first().update(high, low, close, bar_index))
  2024.  
  2025. // [HTF SMT / PSP] fold this bar's pair high / low / open / close into the forming HTF candle
  2026. if (show_smt or showPsp) and htfCandles.size() > 0
  2027. HtfCandle htfNow = htfCandles.first()
  2028. if not na(pair1) and not na(pair1.h)
  2029. htfNow.pH := na(htfNow.pH) ? pair1.h : math.max(htfNow.pH, pair1.h)
  2030. htfNow.pL := na(htfNow.pL) ? pair1.l : math.min(htfNow.pL, pair1.l)
  2031. htfNow.pO := na(htfNow.pO) ? pair1.o : htfNow.pO
  2032. htfNow.pC := pair1.c
  2033. if not na(pair2) and not na(pair2.h)
  2034. htfNow.qH := na(htfNow.qH) ? pair2.h : math.max(htfNow.qH, pair2.h)
  2035. htfNow.qL := na(htfNow.qL) ? pair2.l : math.min(htfNow.qL, pair2.l)
  2036. htfNow.qO := na(htfNow.qO) ? pair2.o : htfNow.qO
  2037. htfNow.qC := pair2.c
  2038.  
  2039. if periodChanged
  2040. state.prevC2Buy := c2Buy[1]
  2041. state.prevC2Sell := c2Sell[1]
  2042.  
  2043. c2BuyTrigger = periodChanged and state.prevC2Buy
  2044. c2SellTrigger = periodChanged and state.prevC2Sell
  2045.  
  2046. // [PSP] the new candle was just added: get(1) = C2, get(2) = C1
  2047. bool pspHit = false
  2048. if showPsp and periodChanged and htfCandles.size() > 2
  2049. HtfCandle own2 = htfCandles.get(1)
  2050. HtfCandle own1 = htfCandles.get(2)
  2051. pspHit := pairPsp(pair1, own1, own2) or pairPsp(pair2, own1, own2)
  2052.  
  2053. // [TIME FILTER] as in the TTrades model, the window is judged on the OPEN of the HTF candle that makes the
  2054. // closure (C2 for a C2 model, C3 for a C3 model): with 08:00-11:30 on 1H the first closure is the one at 09:00;
  2055. // to include the 08:00 closure, start the window at 07:00.
  2056. var bool tfAtCurOpen = true
  2057. var bool tfAtPrevOpen = true
  2058. if periodChanged
  2059. tfAtPrevOpen := tfAtCurOpen
  2060. tfAtCurOpen := inTimeFilter
  2061. bool setupOk = calcOn and validTf and tfAtPrevOpen and not hideSetups
  2062. bool buyOk = allowBuy and setupOk and biasNow != 'Bearish'
  2063. bool sellOk = allowSell and setupOk and biasNow != 'Bullish'
  2064.  
  2065. // [C3 CLOSURE] when C4 opens: C2 (get(2)) took C1's low (get(3)) without closing back inside (so no C2
  2066. // model), then C3 (get(1)) stayed above C2's low and closed above C2's body. Bearish: the mirror.
  2067. bool c3BuyTrigger = false
  2068. bool c3SellTrigger = false
  2069. if periodChanged and htfCandles.size() > 3
  2070. HtfCandle k3 = htfCandles.get(1)
  2071. HtfCandle k2 = htfCandles.get(2)
  2072. HtfCandle k1 = htfCandles.get(3)
  2073. c3BuyTrigger := k2.l < k1.l and k2.c <= k1.l and k3.l >= k2.l and k3.c > math.max(k2.o, k2.c)
  2074. c3SellTrigger := k2.h > k1.h and k2.c >= k1.h and k3.h <= k2.h and k3.c < math.min(k2.o, k2.c)
  2075.  
  2076. // the C2 / C3 checkboxes choose the model types (C4 = the C4 continuation)
  2077. bool c2BuyGo = c2BuyTrigger and buyOk and showC2
  2078. bool c2SellGo = c2SellTrigger and sellOk and showC2
  2079. bool c3BuyGo = c3BuyTrigger and buyOk and showC3 and not c2BuyGo
  2080. bool c3SellGo = c3SellTrigger and sellOk and showC3 and not c2SellGo
  2081.  
  2082. if (c2BuyGo or c3BuyGo) and bullReclaimed[1]
  2083. consumeLastEarlyCisd(bullEarlyCisdRecords)
  2084. if (c2SellGo or c3SellGo) and bearReclaimed[1]
  2085. consumeLastEarlyCisd(bearEarlyCisdRecords)
  2086.  
  2087. htfAt(int idx) =>
  2088. htfCandles.size() > idx ? htfCandles.get(idx) : na
  2089. openBarAt(int idx) =>
  2090. htfOpenBars.size() > idx ? htfOpenBars.get(idx) : na
  2091. // [FORMATION LIQUIDITY] target side of one HTF candle (bullish: its high)
  2092. flPick(int idx, bool isBull) =>
  2093. HtfCandle c = htfAt(idx)
  2094. [na(c) ? na : isBull ? c.h : c.l, na(c) ? na : isBull ? c.hBar : c.lBar]
  2095.  
  2096. // C3 model: 'C3' at C3's extreme, and 'C2' / 'C2+PSP' on the C2 extreme (the swing). PSP is checked on that
  2097. // swing's C1 (get(3)) and C2 (get(2)) against the pair's same candles.
  2098. bool psp3Hit = false
  2099. if showPsp and (c3BuyGo or c3SellGo) and htfCandles.size() > 3
  2100. psp3Hit := pairPsp3(pair1, htfCandles.get(3), htfCandles.get(2)) or pairPsp3(pair2, htfCandles.get(3), htfCandles.get(2))
  2101. string c3Tag = 'C3'
  2102. string c3SwTag = 'C2' + (psp3Hit ? '+PSP' : '')
  2103.  
  2104. // C2 model: C2 = get(1), C1 = get(2). C3 model: C2 = get(2), C1 = get(3).
  2105. int bI1 = c3BuyGo ? 3 : 2
  2106. HtfCandle bK1 = htfAt(bI1)
  2107. HtfCandle bK2 = htfAt(bI1 - 1)
  2108. [bF1p, bF1b] = flPick(bI1, true)
  2109. [bF0p, bF0b] = flPick(bI1 + 1, true)
  2110. buySetup := processSetup(buySetup, c2BuyGo or c3BuyGo, true, c3BuyGo, na(bK2) ? na : bK2.l, na(bK2) ? na : bK2.lBar, c3BuyGo ? c3Tag : c2TagText(pspHit), na(bK1) ? na : bK1.l, na(bK1) ? na : bK1.lBar, c3BuyGo ? openBarAt(1) : bar_index, bullLevelFixed[1], bullIndexFixed[1], bullReclaimed[1], bullReclaimBar[1], c2BuyGo and smtBuyHit, smtNames(pairSmtBuy(pair1), pairSmtBuy(pair2)), bF1p, bF1b, bF0p, bF0b)
  2111. if c3BuyGo and not na(buySetup)
  2112. buySetup.swTag := c3SwTag
  2113. // the model may already have been drawn inside newSetup (CISD confirmed during C3)
  2114. label.set_text(buySetup.swLbl, c3SwTag)
  2115. if (c2BuyGo or c3BuyGo) and not na(buySetup) and not na(bK2)
  2116. buySetup.c2P1 := bK2.pL
  2117. buySetup.c2P2 := bK2.qL
  2118. buySetup.csStart := c3BuyGo ? openBarAt(1) : bar_index
  2119.  
  2120. int sI1 = c3SellGo ? 3 : 2
  2121. HtfCandle sK1 = htfAt(sI1)
  2122. HtfCandle sK2 = htfAt(sI1 - 1)
  2123. [sF1p, sF1b] = flPick(sI1, false)
  2124. [sF0p, sF0b] = flPick(sI1 + 1, false)
  2125. sellSetup := processSetup(sellSetup, c2SellGo or c3SellGo, false, c3SellGo, na(sK2) ? na : sK2.h, na(sK2) ? na : sK2.hBar, c3SellGo ? c3Tag : c2TagText(pspHit), na(sK1) ? na : sK1.h, na(sK1) ? na : sK1.hBar, c3SellGo ? openBarAt(1) : bar_index, bearLevelFixed[1], bearIndexFixed[1], bearReclaimed[1], bearReclaimBar[1], c2SellGo and smtSellHit, smtNames(pairSmtSell(pair1), pairSmtSell(pair2)), sF1p, sF1b, sF0p, sF0b)
  2126. if c3SellGo and not na(sellSetup)
  2127. sellSetup.swTag := c3SwTag
  2128. // the model may already have been drawn inside newSetup (CISD confirmed during C3)
  2129. label.set_text(sellSetup.swLbl, c3SwTag)
  2130. if (c2SellGo or c3SellGo) and not na(sellSetup) and not na(sK2)
  2131. sellSetup.c2P1 := sK2.pH
  2132. sellSetup.c2P2 := sK2.qH
  2133. sellSetup.csStart := c3SellGo ? openBarAt(1) : bar_index
  2134.  
  2135. markTrigger(c2BuyGo or c3BuyGo, true, bI1, true)
  2136. markTrigger(c2SellGo or c3SellGo, true, sI1, false)
  2137.  
  2138. buySetup := buySetup.extendAndCheck()
  2139. sellSetup := sellSetup.extendAndCheck()
  2140.  
  2141. buySetup := buySetup.checkC4Invalid()
  2142. sellSetup := sellSetup.checkC4Invalid()
  2143.  
  2144. buySetup := buySetup.checkCisdConfirm()
  2145. sellSetup := sellSetup.checkCisdConfirm()
  2146.  
  2147. // check every persistent dot against the current bar BEFORE new dots can form on it
  2148. icMarkTakenAll(htfOpenT)
  2149.  
  2150. buySetup := buySetup.updateIc()
  2151. sellSetup := sellSetup.updateIc()
  2152.  
  2153. if not na(buySetup) and buySetup.justConfirmed
  2154. cisdBullFiredThisBar := true
  2155. buySetup.justConfirmed := false
  2156.  
  2157. if not na(sellSetup) and sellSetup.justConfirmed
  2158. cisdBearFiredThisBar := true
  2159. sellSetup.justConfirmed := false
  2160.  
  2161. // Separate alert conditions: in TradingView's "Add Alert" dialog pick one of these
  2162. // instead of "Any alert() function call" to set the CISD alerts up on their own.
  2163. alertcondition(bullEarlyCisdFiredThisBar and showAlerts and earlyCisdAlerts and not hideSetups, title = 'Bullish Early CISD', message = 'Bullish Early CISD on {{ticker}} ({{interval}})')
  2164. alertcondition(bearEarlyCisdFiredThisBar and showAlerts and earlyCisdAlerts and not hideSetups, title = 'Bearish Early CISD', message = 'Bearish Early CISD on {{ticker}} ({{interval}})')
  2165. alertcondition(cisdBullFiredThisBar and showAlerts and modelAlerts and not hideSetups, title = 'Bullish CISD Confirmed', message = 'Bullish CISD Confirmed on {{ticker}} ({{interval}})')
  2166. alertcondition(cisdBearFiredThisBar and showAlerts and modelAlerts and not hideSetups, title = 'Bearish CISD Confirmed', message = 'Bearish CISD Confirmed on {{ticker}} ({{interval}})')
  2167.  
  2168. // [LIVE C2] The C2 setup while the C2 candle is still forming, updated on every tick: the forming HTF candle has
  2169. // taken the previous candle's low (high) and price is back inside its range. Drawn on the last bar only:
  2170. // the sweep line from the C1 low (high) that was taken, the 'C2' label on the current extreme and the CISD
  2171. // line (dotted until a close goes through it, then in the live style), all in the Live C2 color. It goes away when the condition stops
  2172. // holding, and when the HTF candle closes the regular model (C3 open + CISD) takes over.
  2173. liveC2On = input.bool(true, 'Live C2', group = grpVisuals, inline = 'livec2')
  2174. liveC2Col = input.color(#9c27b0, '', group = grpVisuals, inline = 'livec2')
  2175. liveC2Sty = input.string('Dashed', '', options = ['Solid', 'Dashed', 'Dotted'], group = grpVisuals, inline = 'livec2', tooltip = 'Shows the C2 setup in real time, while the C2 candle is still forming, updated on every tick: the CISD line in this color (dotted until a candle closes through it, then in this style), a tiny C2 on the extreme, and the sweep line minimal: light gray, dotted. When the HTF candle closes, the regular model takes over (C2 label, sweep line in its own color / style). Off: nothing is drawn while the candle forms; the CISD and the sweep line only appear when C2 closes. Same filters as the model (bias, C2 checkbox, time filter, chart timeframe).')
  2176. var line lvBullSw = na
  2177. var line lvBullCisd = na
  2178. var label lvBullLbl = na
  2179. var line lvBearSw = na
  2180. var line lvBearCisd = na
  2181. var label lvBearLbl = na
  2182. // live C2 side for the setup table: 1 bullish, -1 bearish, 0 none
  2183. var int lvSide = 0
  2184. if barstate.islast
  2185. lvSide := 0
  2186. line.delete(lvBullSw)
  2187. line.delete(lvBullCisd)
  2188. label.delete(lvBullLbl)
  2189. line.delete(lvBearSw)
  2190. line.delete(lvBearCisd)
  2191. label.delete(lvBearLbl)
  2192. lvBullSw := na
  2193. lvBullCisd := na
  2194. lvBullLbl := na
  2195. lvBearSw := na
  2196. lvBearCisd := na
  2197. lvBearLbl := na
  2198. if liveC2On and showC2 and validTf and calcOn and not hideSetups and tfAtCurOpen and htfCandles.size() > 1
  2199. HtfCandle lvC0 = htfCandles.get(0)
  2200. HtfCandle lvC1 = htfCandles.get(1)
  2201. bool lvBull = allowBuy and biasNow != 'Bearish' and lvC0.l < lvC1.l and close > lvC1.l
  2202. bool lvBear = allowSell and biasNow != 'Bullish' and lvC0.h > lvC1.h and close < lvC1.h
  2203. if lvBull
  2204. lvSide := 1
  2205. if showSweep
  2206. lvBullSw := line.new(lvC1.lBar, lvC1.l, bar_index, lvC1.l, color = #b2b5be, style = line.style_dotted)
  2207. if showLabels
  2208. lvBullLbl := label.new(lvC0.lBar, lvC0.l, 'C2', style = label.style_label_up, color = na, textcolor = liveC2Col, size = size.tiny)
  2209. if showBullCisd and not na(bullLevelFixed) and not na(bullIndexFixed)
  2210. lvBullCisd := line.new(bullIndexFixed, bullLevelFixed, bar_index + 1, bullLevelFixed, color = liveC2Col, style = bullReclaimed ? lineStyleFromStr(liveC2Sty) : line.style_dotted)
  2211. if lvBear
  2212. lvSide := -1
  2213. if showSweep
  2214. lvBearSw := line.new(lvC1.hBar, lvC1.h, bar_index, lvC1.h, color = #b2b5be, style = line.style_dotted)
  2215. if showLabels
  2216. lvBearLbl := label.new(lvC0.hBar, lvC0.h, 'C2', style = label.style_label_down, color = na, textcolor = liveC2Col, size = size.tiny)
  2217. if showBearCisd and not na(bearLevelFixed) and not na(bearIndexFixed)
  2218. lvBearCisd := line.new(bearIndexFixed, bearLevelFixed, bar_index + 1, bearLevelFixed, color = liveC2Col, style = bearReclaimed ? lineStyleFromStr(liveC2Sty) : line.style_dotted)
  2219.  
  2220. // HTF Start Line (PO3 / Bandz style): one line at each HTF open, all with the same height = high / low
  2221. // since the oldest HTF candle that has a line, plus a margin, with the NY open time on top.
  2222. // Redrawn on the last bar, anchored by time.
  2223. vlLbl = input.bool(false, 'Start Line: time', group = grpCandles, inline = 'vline2', tooltip = 'New York time of each HTF candle open, on top of the vertical line.')
  2224. vlLblCol = input.color(color.rgb(110, 108, 105), '', group = grpCandles, inline = 'vline2')
  2225. vlPad = input.int(15, 'Margin %', minval = 0, maxval = 100, group = grpCandles, inline = 'vline2', tooltip = 'The lines run the full height of the chart. This only sets how far above the high of the HTF candles the time label sits, in % of their range.')
  2226. var array<int> vlT = array.new<int>()
  2227. var array<label> vlLb = array.new<label>()
  2228. if showVlines and periodChanged and calcOn
  2229. vlT.unshift(time)
  2230. while vlT.size() > htfCandleCount
  2231. vlT.pop()
  2232. if barstate.islast
  2233. while vLines.size() > 0
  2234. line.delete(vLines.pop())
  2235. while vlLb.size() > 0
  2236. label.delete(vlLb.pop())
  2237. if showVlines and vlT.size() > 0 and htfCandles.size() > 0
  2238. float vlHi = high
  2239. float vlLo = low
  2240. for i = 0 to math.min(vlT.size(), htfCandles.size()) - 1
  2241. vlHi := math.max(vlHi, htfCandles.get(i).h)
  2242. vlLo := math.min(vlLo, htfCandles.get(i).l)
  2243. float vlRng = math.max(vlHi - vlLo, syminfo.mintick * 10)
  2244. float vlTop = vlHi + vlRng * vlPad / 100.0
  2245. float vlBot = vlLo - vlRng * vlPad / 100.0
  2246. for vt in vlT
  2247. vLines.push(line.new(vt, vlBot, vt, vlTop, xloc = xloc.bar_time, extend = extend.both, color = lineColor, style = lineStyleFromStr(lineStyle), width = lineWidth))
  2248. if vlLbl
  2249. vlLb.push(label.new(vt, vlTop, str.format_time(vt, 'HH:mm', 'America/New_York'), xloc = xloc.bar_time, color = color.new(color.white, 100), style = label.style_label_down, textcolor = vlLblCol, size = size.tiny))
  2250.  
  2251.  
  2252. //#endregion
  2253.  
  2254.  
  2255. // [FORMATION LIQUIDITY] the target side of the C1 candle and of the candle before it (bullish:
  2256. // their highs, bearish: their lows). A line starts where that high / low printed and ends at the bar
  2257. // that trades through it; an untaken one runs to the last bar. Levels already taken before the swing
  2258. // are not targets.
  2259. var array<line> flLines = array.new<line>()
  2260. // Loops read these up to ~1500 bars back; reserving the history up front keeps a realtime bar
  2261. // from asking for more than the buffer chosen on historical bars (runtime error on candle close).
  2262. max_bars_back(high, 1500)
  2263. max_bars_back(low, 1500)
  2264. max_bars_back(open, 1500)
  2265. max_bars_back(close, 1500)
  2266. // Drawings anchored far back (ADR lines from the day's first bar: ~1400 bars on 1m) need the bar's
  2267. // time: without this, every new realtime bar asks one bar further than the buffer chosen on history.
  2268. max_bars_back(time, 5000)
  2269. // A drawing's left end is never moved further back than the time buffer allows
  2270. xAnchor(int x) =>
  2271. na(x) ? na : math.max(x, bar_index - 4900)
  2272.  
  2273. flLine(float px, int b, bool isBull, int swingBar) =>
  2274. if not na(px) and not na(b) and b < bar_index
  2275. // untaken: runs to the last bar
  2276. int endB = bar_index
  2277. int maxBack = math.min(bar_index - b, 1500)
  2278. for off = maxBack - 1 to 0
  2279. if isBull ? high[off] > px : low[off] < px
  2280. endB := bar_index - off
  2281. break
  2282. if endB > nz(swingBar, b)
  2283. flLines.push(line.new(xAnchor(b), px, endB, px, color = flColor, style = lineStyleFromStr(flStyle), width = flWidth))
  2284.  
  2285. flDraw(C2Setup s) =>
  2286. if not na(s) and s.revealed and not s.dead
  2287. flLine(s.fl1Px, s.fl1Bar, s.isBull, s.c2BarIndex)
  2288. flLine(s.fl0Px, s.fl0Bar, s.isBull, s.c2BarIndex)
  2289.  
  2290. if barstate.islast
  2291. for ln in flLines
  2292. line.delete(ln)
  2293. flLines.clear()
  2294. if showFl and validTf
  2295. flDraw(buySetup)
  2296. flDraw(sellSetup)
  2297.  
  2298. // [L/H LINES] each HTF candle's high and low on the chart, over that candle's own period
  2299. var array<line> lhHi = array.new<line>()
  2300. var array<line> lhLo = array.new<line>()
  2301. if showLH and calcOn and htfCandles.size() > 0
  2302. HtfCandle cNow = htfCandles.first()
  2303. if periodChanged or lhHi.size() == 0
  2304. lhHi.unshift(line.new(bar_index, cNow.h, bar_index, cNow.h, color = lhColor, style = lineStyleFromStr(lhStyle), width = lhWidth))
  2305. lhLo.unshift(line.new(bar_index, cNow.l, bar_index, cNow.l, color = lhColor, style = lineStyleFromStr(lhStyle), width = lhWidth))
  2306. while lhHi.size() > htfCandleCount
  2307. line.delete(lhHi.pop())
  2308. line.delete(lhLo.pop())
  2309. else
  2310. line.set_xy1(lhHi.first(), xAnchor(line.get_x1(lhHi.first())), cNow.h)
  2311. line.set_xy2(lhHi.first(), bar_index, cNow.h)
  2312. line.set_xy1(lhLo.first(), xAnchor(line.get_x1(lhLo.first())), cNow.l)
  2313. line.set_xy2(lhLo.first(), bar_index, cNow.l)
  2314.  
  2315. //#region [PLOT]
  2316.  
  2317. // One horizontal line, created / moved / removed
  2318. hzLine(line ln, bool on, int x1, float y, int x2, color c, string st, int w) =>
  2319. line l = ln
  2320. if on and not na(x1) and not na(y) and not na(x2)
  2321. if na(l)
  2322. l := line.new(xAnchor(x1), y, x2, y, color = c, style = lineStyleFromStr(st), width = w)
  2323. else
  2324. line.set_xy1(l, xAnchor(x1), y)
  2325. line.set_xy2(l, x2, y)
  2326. line.set_color(l, c)
  2327. line.set_style(l, lineStyleFromStr(st))
  2328. line.set_width(l, w)
  2329. else if not na(l)
  2330. line.delete(l)
  2331. l := na
  2332. l
  2333.  
  2334. var line prevEqLn = na
  2335.  
  2336. // [HTF SMT ON CHART] the SMTs drawn between the HTF candles, repeated on the chart at the exact bars that made
  2337. // those HTF highs / lows (with the pair name). Redrawn with the HTF candles.
  2338. smtHtfChart = input.bool(true, 'HTF SMT on Chart', group = grpSmt, tooltip = 'The same SMT lines shown between the HTF candles on the right, also drawn on the chart: from the bar that made the older HTF high / low to the bar that made the newer one, with the pair name.')
  2339. var array<line> smtChLns = array.new<line>()
  2340. var array<label> smtChLbs = array.new<label>()
  2341.  
  2342. // [EXTRA HTF] drawings of the HTF 1 / HTF 2 blocks (and the timeframe titles), redrawn on the last bar.
  2343. // Pooled: each redraw moves the drawings of the previous one (in the order they are drawn) instead of
  2344. // deleting and creating them; xUsed counts the boxes / lines / labels used so far, the rest is deleted after.
  2345. var array<box> xBoxes = array.new<box>()
  2346. var array<line> xLines = array.new<line>()
  2347. var array<label> xLabels = array.new<label>()
  2348. var array<int> xUsed = array.from(0, 0, 0)
  2349.  
  2350. xLine(int x1, float y1, int x2, float y2, color c, string st, int w) =>
  2351. int i = xUsed.get(1)
  2352. if i < xLines.size()
  2353. line l = xLines.get(i)
  2354. line.set_xy1(l, x1, y1)
  2355. line.set_xy2(l, x2, y2)
  2356. line.set_color(l, c)
  2357. line.set_style(l, lineStyleFromStr(st))
  2358. line.set_width(l, w)
  2359. else
  2360. xLines.push(line.new(x1, y1, x2, y2, color = c, style = lineStyleFromStr(st), width = w))
  2361. xUsed.set(1, i + 1)
  2362.  
  2363. xBox(int left, float top, int right, float bot, color border, color bg) =>
  2364. int i = xUsed.get(0)
  2365. if i < xBoxes.size()
  2366. box b = xBoxes.get(i)
  2367. box.set_lefttop(b, left, top)
  2368. box.set_rightbottom(b, right, bot)
  2369. box.set_border_color(b, border)
  2370. box.set_bgcolor(b, bg)
  2371. else
  2372. xBoxes.push(box.new(left, top, right, bot, border_color = border, border_width = 1, bgcolor = bg))
  2373. xUsed.set(0, i + 1)
  2374.  
  2375. xLabel(int x, float y, string txt, string st, color tc, bool bold = false, bool big = false) =>
  2376. int i = xUsed.get(2)
  2377. if i < xLabels.size()
  2378. label b = xLabels.get(i)
  2379. label.set_xy(b, x, y)
  2380. label.set_text(b, txt)
  2381. label.set_style(b, st)
  2382. label.set_textcolor(b, tc)
  2383. label.set_size(b, big ? textSize(labelSize) : smallerSize(labelSize))
  2384. label.set_text_formatting(b, bold ? text.format_bold : text.format_none)
  2385. else
  2386. xLabels.push(label.new(x, y, txt, style = st, color = na, textcolor = tc, size = big ? textSize(labelSize) : smallerSize(labelSize), text_formatting = bold ? text.format_bold : text.format_none))
  2387. xUsed.set(2, i + 1)
  2388.  
  2389. // Block title: the timeframe (bold, dark) and, under it, the time left in brackets (gray), over the block's highest
  2390. // high, under its lowest low (mirrored: time first), or both (a line lower when the time labels sit below).
  2391. // Two labels so each line keeps its own color; blank lines stack them. One size above the time labels.
  2392. xTitle(int x, float top, float bot, string tf) =>
  2393. string nm = showHtfName ? tfLabel(tf) : ''
  2394. string tm = showHtfTimer ? '(' + formatRemaining(htfCloseTime(tf) - (barstate.isrealtime ? timenow : time_close)) + ')' : ''
  2395. bool both = nm != '' and tm != ''
  2396. if nm != '' or tm != ''
  2397. if htfNamePos != 'Bottom'
  2398. if nm != ''
  2399. xLabel(x, top, both ? nm + '\n ' : nm, label.style_label_down, htfNameColor, true, true)
  2400. if tm != ''
  2401. xLabel(x, top, tm, label.style_label_down, htfInfoColor, false, true)
  2402. if htfNamePos != 'Top'
  2403. string pre = showHtfStamps ? ' \n' : ''
  2404. if tm != ''
  2405. xLabel(x, bot, pre + tm, label.style_label_up, htfInfoColor, false, true)
  2406. if nm != ''
  2407. xLabel(x, bot, pre + (both ? ' \n' : '') + nm, label.style_label_up, htfNameColor, true, true)
  2408.  
  2409. // A pair's candle with the same open time (else the same position), flipped for an inverse pair
  2410. xPair(XData p, bool inv, int i, int t) =>
  2411. float h = na
  2412. float l = na
  2413. float o = na
  2414. float c = na
  2415. if not na(p) and not na(p.t) and p.t.size() > 0
  2416. int j = p.t.indexof(t)
  2417. if j < 0 and i < p.t.size()
  2418. j := i
  2419. if j >= 0
  2420. h := inv ? -p.l.get(j) : p.h.get(j)
  2421. l := inv ? -p.h.get(j) : p.l.get(j)
  2422. o := inv ? -p.o.get(j) : p.o.get(j)
  2423. c := inv ? -p.c.get(j) : p.c.get(j)
  2424. [h, l, o, c]
  2425.  
  2426. // One block starting at bar 'left'; returns its right edge. Same look and rules as the model block:
  2427. // sweep = a candle takes the previous high / low and closes back inside (the forming one while it is back
  2428. // inside), SMT between consecutive candles, PSP on the two candles of a closed sweep.
  2429. xBlock(XData d, XData p, XData q, bool pInv, bool qInv, int left, string tf) =>
  2430. int n = na(d) or na(d.o) ? 0 : d.o.size()
  2431. int right = left
  2432. if n > 0
  2433. array<int> mids = array.new<int>(n, 0)
  2434. array<float> cs = d.c.copy()
  2435. cs.set(0, close) // like the model block: the chart's last trade, not a futures settlement
  2436. array<float> ph = array.new<float>(n, na)
  2437. array<float> pl = array.new<float>(n, na)
  2438. array<float> po = array.new<float>(n, na)
  2439. array<float> pc = array.new<float>(n, na)
  2440. array<float> qh = array.new<float>(n, na)
  2441. array<float> ql = array.new<float>(n, na)
  2442. array<float> qo = array.new<float>(n, na)
  2443. array<float> qc = array.new<float>(n, na)
  2444. float top = na
  2445. float bot = na
  2446. for i = n - 1 to 0
  2447. int mid = left + candleSpacing * (n - 1 - i) + htfHalf
  2448. float o = d.o.get(i)
  2449. float h = d.h.get(i)
  2450. float l = d.l.get(i)
  2451. float c = cs.get(i)
  2452. bool bull = c >= o
  2453. mids.set(i, mid)
  2454. xLine(mid, h, mid, math.max(o, c), bull ? wickBull : wickBear, 'Solid', 1)
  2455. xLine(mid, l, mid, math.min(o, c), bull ? wickBull : wickBear, 'Solid', 1)
  2456. xBox(mid - htfHalf, math.max(o, c), mid + htfHalf, math.min(o, c), bull ? borderBull : borderBear, bull ? bullBody : bearBody)
  2457. top := na(top) ? h : math.max(top, h)
  2458. bot := na(bot) ? l : math.min(bot, l)
  2459. if showHtfStamps
  2460. xLabel(mid, l, htfStampText(d.t.get(i), tf), label.style_label_up, htfInfoColor)
  2461. [a1, b1, c1, d1] = xPair(p, pInv, i, d.t.get(i))
  2462. ph.set(i, a1)
  2463. pl.set(i, b1)
  2464. po.set(i, c1)
  2465. pc.set(i, d1)
  2466. [a2, b2, c2, d2] = xPair(q, qInv, i, d.t.get(i))
  2467. qh.set(i, a2)
  2468. ql.set(i, b2)
  2469. qo.set(i, c2)
  2470. qc.set(i, d2)
  2471. right := mids.get(0) + htfHalf
  2472.  
  2473. // no HTF Open here: only the model HTF's open is drawn
  2474. if showPrevEq and n > 1
  2475. for i = n - 1 to 1
  2476. float eqPx = (d.h.get(i) + d.l.get(i)) / 2
  2477. xLine(mids.get(i), eqPx, mids.get(i - 1), eqPx, prevEqColor, prevEqStyle, prevEqWidth)
  2478.  
  2479. // sweeps: older candle i, newer i - 1 (i - 1 = 0 is the forming candle: live sweep)
  2480. array<bool> pspLo = array.new<bool>(n, false)
  2481. array<bool> pspHi = array.new<bool>(n, false)
  2482. if n > 1
  2483. for i = n - 1 to 1
  2484. float oldH = d.h.get(i)
  2485. float oldL = d.l.get(i)
  2486. float newC = cs.get(i - 1)
  2487. bool bullS = allowBuy and d.l.get(i - 1) < oldL and newC > oldL
  2488. bool bearS = allowSell and d.h.get(i - 1) > oldH and newC < oldH
  2489. int endX = mids.get(i - 1) + htfHalf * 2 + 2
  2490. if sweepOnHtf and bullS
  2491. xLine(mids.get(i), oldL, endX, oldL, sweepColor, sweepStyle, sweepWidth)
  2492. if sweepOnHtf and bearS
  2493. xLine(mids.get(i), oldH, endX, oldH, sweepColor, sweepStyle, sweepWidth)
  2494. // PSP once the sweeping candle has closed: C1 = i, C2 = i - 1
  2495. if showPsp and i >= 2 and (bullS or bearS)
  2496. for j = i - 1 to i
  2497. bool chk = j == i ? pspMode != 'Candle 2' : pspMode != 'Candle 1'
  2498. if chk and (pspDiff(d.o.get(j), cs.get(j), po.get(j), pc.get(j)) or pspDiff(d.o.get(j), cs.get(j), qo.get(j), qc.get(j)))
  2499. if bullS
  2500. pspLo.set(j, true)
  2501. else
  2502. pspHi.set(j, true)
  2503. for j = 0 to n - 1
  2504. if pspLo.get(j) or pspHi.get(j)
  2505. bool below = pspLo.get(j)
  2506. xLabel(mids.get(j), below ? d.l.get(j) : d.h.get(j), below and showHtfStamps ? ' \nPSP' : 'PSP', below ? label.style_label_up : label.style_label_down, c2c3c4Color)
  2507.  
  2508. // SMT between consecutive candles, per pair; hidden once a newer candle trades beyond it
  2509. if smtOnHtf
  2510. float newerH = na
  2511. float newerL = na
  2512. for i = 0 to n - 1
  2513. float ch = d.h.get(i)
  2514. float cl = d.l.get(i)
  2515. bool bear = false
  2516. bool bull = false
  2517. if i < n - 1
  2518. float oh = d.h.get(i + 1)
  2519. float ol = d.l.get(i + 1)
  2520. if not na(ph.get(i)) and not na(ph.get(i + 1))
  2521. bear := (ch > oh and ph.get(i) < ph.get(i + 1)) or (ch < oh and ph.get(i) > ph.get(i + 1))
  2522. bull := (cl < ol and pl.get(i) > pl.get(i + 1)) or (cl > ol and pl.get(i) < pl.get(i + 1))
  2523. if not na(qh.get(i)) and not na(qh.get(i + 1))
  2524. bear := bear or (ch > oh and qh.get(i) < qh.get(i + 1)) or (ch < oh and qh.get(i) > qh.get(i + 1))
  2525. bull := bull or (cl < ol and ql.get(i) > ql.get(i + 1)) or (cl > ol and ql.get(i) < ql.get(i + 1))
  2526. if not na(newerH) and newerH > ch
  2527. bear := false
  2528. if not na(newerL) and newerL < cl
  2529. bull := false
  2530. if bear
  2531. xLine(mids.get(i + 1), oh, mids.get(i), ch, smtColorFor(true), smtStyle, smtWidth)
  2532. if bull
  2533. xLine(mids.get(i + 1), ol, mids.get(i), cl, smtColorFor(false), smtStyle, smtWidth)
  2534. newerH := na(newerH) ? ch : math.max(newerH, ch)
  2535. newerL := na(newerL) ? cl : math.min(newerL, cl)
  2536.  
  2537. xTitle(int(math.round((left + right) / 2.0)), top, bot, tf)
  2538. right
  2539.  
  2540. if barstate.islast
  2541. xUsed.fill(0)
  2542.  
  2543. if (barstate.islast or barstate.isrealtime) and htfTfOk and htfCandles.size() > 0 and not hideHtf
  2544. n = math.min(htfCandles.size(), htfCandleCount)
  2545. // candles kept only for the model stay hidden
  2546. if htfCandles.size() > n
  2547. for i = n to htfCandles.size() - 1
  2548. htfCandles.get(i).hide()
  2549. for i = n - 1 to 0
  2550. htfCandles.get(i).draw(bar_index + candleOffset + candleSpacing * (n - 1 - i) + htfHalf, autoTf)
  2551. HtfCandle cur0 = htfCandles.first()
  2552. int blockLeft = htfCandles.get(n - 1).midX - htfHalf
  2553. int blockRight = cur0.midX + htfHalf
  2554.  
  2555. // HTF Open (current HTF candle) by Drawings Type
  2556. int lx1 = dtChart ? htfOpenBar : blockLeft
  2557. int lx2 = dtHtf ? blockRight : bar_index
  2558. htfOpenLn := hzLine(htfOpenLn, showHtfOpen, lx1, cur0.o, lx2, htfOpenColor, htfOpenStyle, htfOpenWidth)
  2559. // Previous EQ on the chart: the middle of the last closed HTF candle, from the current candle's open
  2560. float prevEqPx = n > 1 ? (htfCandles.get(1).h + htfCandles.get(1).l) / 2 : na
  2561. prevEqLn := hzLine(prevEqLn, showPrevEq and dtChart, htfOpenBar, prevEqPx, bar_index, prevEqColor, prevEqStyle, prevEqWidth)
  2562.  
  2563.  
  2564. // Previous EQ and Candle 1 Sweep on the HTF candles
  2565. for i = n - 1 to 0
  2566. HtfCandle c = htfCandles.get(i)
  2567. if i > 0
  2568. line.set_x2(c.eqLine, htfCandles.get(i - 1).midX)
  2569. // uma linha por lado: low (C2 de alta) e high (C2 de baixa) podem existir no mesmo candle
  2570. int sweepEndX = i > 0 ? htfCandles.get(i - 1).midX + htfHalf * 2 + 2 : c.midX
  2571. c.sweepLine := liveSweepLine(c.sweepLine, sweepOnHtf and i > 0 and c.triggerBuy, c.midX, sweepEndX, c.l)
  2572. c.sweepLineHi := liveSweepLine(c.sweepLineHi, sweepOnHtf and i > 0 and c.triggerSell, c.midX, sweepEndX, c.h)
  2573.  
  2574. // [HTF SMT] divergence between consecutive HTF candles (i = newer, i + 1 = older), per pair. Strict: one
  2575. // makes the higher high, the other a lower high (equal is not SMT). Hidden once a newer HTF candle trades
  2576. // beyond it.
  2577. bool htfSmtOn = smtOnHtf and (pair1Name != '' or pair2Name != '')
  2578. while smtChLns.size() > 0
  2579. line.delete(smtChLns.pop())
  2580. while smtChLbs.size() > 0
  2581. label.delete(smtChLbs.pop())
  2582. float newerH = na
  2583. float newerL = na
  2584. for i = 0 to n - 1
  2585. HtfCandle cur = htfCandles.get(i)
  2586. HtfCandle prev = i < n - 1 ? htfCandles.get(i + 1) : na
  2587. bool bear1 = false
  2588. bool bull1 = false
  2589. bool bear2 = false
  2590. bool bull2 = false
  2591. if htfSmtOn and not na(prev)
  2592. if not na(cur.pH) and not na(prev.pH)
  2593. bear1 := (cur.h > prev.h and cur.pH < prev.pH) or (cur.h < prev.h and cur.pH > prev.pH)
  2594. bull1 := (cur.l < prev.l and cur.pL > prev.pL) or (cur.l > prev.l and cur.pL < prev.pL)
  2595. if not na(cur.qH) and not na(prev.qH)
  2596. bear2 := (cur.h > prev.h and cur.qH < prev.qH) or (cur.h < prev.h and cur.qH > prev.qH)
  2597. bull2 := (cur.l < prev.l and cur.qL > prev.qL) or (cur.l > prev.l and cur.qL < prev.qL)
  2598. if not na(newerH) and newerH > cur.h
  2599. bear1 := false
  2600. bear2 := false
  2601. if not na(newerL) and newerL < cur.l
  2602. bull1 := false
  2603. bull2 := false
  2604. newerH := na(newerH) ? cur.h : math.max(newerH, cur.h)
  2605. newerL := na(newerL) ? cur.l : math.min(newerL, cur.l)
  2606. int x1 = na(prev) ? cur.midX : prev.midX
  2607. float yH = na(prev) ? cur.h : prev.h
  2608. float yL = na(prev) ? cur.l : prev.l
  2609. cur.smtHLine := smtHtfSeg(cur.smtHLine, bear1 or bear2, x1, yH, cur.midX, cur.h, true)
  2610. cur.smtLLine := smtHtfSeg(cur.smtLLine, bull1 or bull2, x1, yL, cur.midX, cur.l, false)
  2611. // the same SMT on the chart, between the bars that made those highs / lows
  2612. if smtHtfChart and validTf and not na(prev)
  2613. if (bear1 or bear2) and not na(prev.hBar) and not na(cur.hBar) and cur.hBar > prev.hBar
  2614. smtChLns.push(line.new(xAnchor(prev.hBar), prev.h, cur.hBar, cur.h, color = smtColorFor(true), style = lineStyleFromStr(smtStyle), width = smtWidth))
  2615. string tH = smtNames(bear1, bear2)
  2616. if tH != ''
  2617. smtChLbs.push(label.new(int(math.round((prev.hBar + cur.hBar) / 2.0)), (prev.h + cur.h) / 2, tH, style = label.style_label_down, color = na, textcolor = smtColorFor(true), size = textSize(smtLblSize)))
  2618. if (bull1 or bull2) and not na(prev.lBar) and not na(cur.lBar) and cur.lBar > prev.lBar
  2619. smtChLns.push(line.new(xAnchor(prev.lBar), prev.l, cur.lBar, cur.l, color = smtColorFor(false), style = lineStyleFromStr(smtStyle), width = smtWidth))
  2620. string tL = smtNames(bull1, bull2)
  2621. if tL != ''
  2622. smtChLbs.push(label.new(int(math.round((prev.lBar + cur.lBar) / 2.0)), (prev.l + cur.l) / 2, tL, style = label.style_label_up, color = na, textcolor = smtColorFor(false), size = textSize(smtLblSize)))
  2623.  
  2624. // [PSP] on the C1 / C2 HTF candles of setups: the candle closes a different color than a pair's same candle
  2625. for i = 0 to n - 1
  2626. HtfCandle c = htfCandles.get(i)
  2627. bool pspBull = false
  2628. bool pspBear = false
  2629. bool pspD1 = pspDiff(c.o, c.c, c.pO, c.pC)
  2630. bool pspD2 = pspDiff(c.o, c.c, c.qO, c.qC)
  2631. if showPsp
  2632. // C1 carries the setup's trigger flag, C2 is the next (newer) candle
  2633. for side = 0 to 1
  2634. bool isBullSide = side == 0
  2635. // this candle as C1 (its own flag) or as C2 (the older candle's flag)
  2636. bool asC1 = i > 0 and (isBullSide ? c.triggerBuy : c.triggerSell) and pspMode != 'Candle 2'
  2637. bool asC2 = i < n - 1 and (isBullSide ? htfCandles.get(i + 1).triggerBuy : htfCandles.get(i + 1).triggerSell) and pspMode != 'Candle 1'
  2638. if (asC1 or asC2) and (pspD1 or pspD2)
  2639. if isBullSide
  2640. pspBull := true
  2641. else
  2642. pspBear := true
  2643. if pspBull or pspBear
  2644. bool below = pspBull
  2645. float y = below ? c.l : c.h
  2646. // below the candle the time stamp sits first, so PSP goes on the next line
  2647. string txt = below and showHtfStamps ? ' \nPSP' : 'PSP'
  2648. string tip = 'PSP: ' + (pspD1 ? statusSym(pair1Name) : '') + (pspD1 and pspD2 ? ' + ' : '') + (pspD2 ? statusSym(pair2Name) : '')
  2649. if na(c.pspLbl)
  2650. c.pspLbl := label.new(c.midX, y, txt, style = below ? label.style_label_up : label.style_label_down, color = na, textcolor = c2c3c4Color, size = smallerSize(labelSize), tooltip = tip)
  2651. else
  2652. label.set_xy(c.pspLbl, c.midX, y)
  2653. label.set_text(c.pspLbl, txt)
  2654. label.set_tooltip(c.pspLbl, tip)
  2655. label.set_style(c.pspLbl, below ? label.style_label_up : label.style_label_down)
  2656. label.set_textcolor(c.pspLbl, c2c3c4Color)
  2657. else if not na(c.pspLbl)
  2658. label.delete(c.pspLbl)
  2659. c.pspLbl := na
  2660.  
  2661. if n > 1
  2662. updateLiveSweeps(htfCandles)
  2663.  
  2664. // block title (HTF Label + Remaining Time), then [EXTRA HTF] HTF 1 / HTF 2 to the right
  2665. float mTop = na
  2666. float mBot = na
  2667. for i = 0 to n - 1
  2668. mTop := na(mTop) ? htfCandles.get(i).h : math.max(mTop, htfCandles.get(i).h)
  2669. mBot := na(mBot) ? htfCandles.get(i).l : math.min(mBot, htfCandles.get(i).l)
  2670. xTitle(int(math.round((blockLeft + blockRight) / 2.0)), mTop, mBot, autoTf)
  2671. if x1On or x2On
  2672. // a block that would end past the 500-bar drawing limit right of the last bar is left out
  2673. int xLeft = blockRight + candleSpacing + 3
  2674. if x1On and xLeft + nX * candleSpacing + 12 <= bar_index + 495
  2675. xLeft := xBlock(x1D, x1P, x1Q, pair1InvOn, pair2InvOn, xLeft, x1Tf) + candleSpacing + 3
  2676. if x2On and xLeft + nX * candleSpacing + 12 <= bar_index + 495
  2677. xBlock(x2D, x2P, x2Q, pair1InvOn, pair2InvOn, xLeft, x2Tf)
  2678.  
  2679. // [EXTRA HTF] pooled drawings this redraw did not use
  2680. if barstate.islast
  2681. while xBoxes.size() > xUsed.get(0)
  2682. box.delete(xBoxes.pop())
  2683. while xLines.size() > xUsed.get(1)
  2684. line.delete(xLines.pop())
  2685. while xLabels.size() > xUsed.get(2)
  2686. label.delete(xLabels.pop())
  2687.  
  2688. // NY trading day start (see [NY DAY]), used by the ADR
  2689. bool newKlDay = nyNewDay(dayStartH, dayIsCrypto)
  2690.  
  2691. var int adrDayStartBar = na
  2692. if newKlDay
  2693. adrDayStartBar := bar_index
  2694.  
  2695. fmtPts(float v) =>
  2696. adrIsFx ? str.tostring(v / adrPip, '#.0') + ' pips' : str.tostring(v, format.mintick) + ' pts'
  2697.  
  2698. // [INFO TABLE] one centered column, a few short rows
  2699. tbl_sz = textSize(tbl_text_size)
  2700. tbl_dim_color = color.new(tbl_text_color, 45)
  2701. tblBg = tbl_style == 'Text' ? noColor : tbl_bg_color
  2702. tblFrame = tbl_border ? color.new(tbl_text_color, 75) : noColor
  2703.  
  2704. var table infoTbl = na
  2705. if barstate.islast
  2706. // layout: ES1! (1H) / 1H-1D Model / 01:00:00 / Bias: Neutral / SMT(Auto): NQ1!, YM1! (+ ADR, date)
  2707. array<string> rows = array.new<string>()
  2708. array<color> clrs = array.new<color>()
  2709. array<string> szs = array.new<string>()
  2710. string head = tbl_asset ? syminfo.ticker : ''
  2711. if tbl_ctf
  2712. head := head == '' ? tfLabel(curTfCode()) : head + ' (' + tfLabel(curTfCode()) + ')'
  2713. if head != ''
  2714. rows.push(head)
  2715. clrs.push(tblHeadColor)
  2716. szs.push(tbl_sz)
  2717. // chart timeframe does not fit the fractal: the warning shows here, whatever the row checkboxes
  2718. if tbl_fractal or not validTf
  2719. rows.push(validTf ? tfLabel(ltfCode()) + '-' + tfLabel(autoTf) + ' Model' : '⚠ ' + (modelType == 'Automatic' ? 'No model' : modelType) + ' on the ' + tfLabel(curTfCode()) + ' chart')
  2720. clrs.push(validTf ? tbl_text_color : cisdBearColor)
  2721. szs.push(tbl_sz)
  2722. if tbl_ttc and validTf
  2723. rows.push(formatHms(htfCloseTime(autoTf) - (barstate.isrealtime ? timenow : time_close)))
  2724. clrs.push(tblHeadColor)
  2725. szs.push(biggerSize(tbl_text_size))
  2726. if tbl_bias
  2727. bool bullish = biasNow == 'Bullish'
  2728. bool bearish = biasNow == 'Bearish'
  2729. rows.push('Bias: ' + biasNow + (abSteps > 0 ? ' (AB' + str.tostring(abSteps) + ' ' + tfLabel(abLtf) + '-' + tfLabel(abHtf) + ')' : ''))
  2730. clrs.push(bullish ? cisdBullColor : bearish ? cisdBearColor : tbl_text_color)
  2731. szs.push(tbl_sz)
  2732. if tbl_tfilter and useTimeFilter
  2733. string fWin = ''
  2734. if f1On
  2735. fWin := f1Sess
  2736. if f2On
  2737. fWin := (fWin == '' ? '' : fWin + ', ') + f2Sess
  2738. if f3On
  2739. fWin := (fWin == '' ? '' : fWin + ', ') + f3Sess
  2740. rows.push('Filter: ' + (not timeFilterActive ? 'not used' : fWin + (inTimeFilter ? ' (open)' : ' (closed)')))
  2741. clrs.push(timeFilterActive and inTimeFilter ? tbl_text_color : tbl_dim_color)
  2742. szs.push(tbl_sz)
  2743. if tbl_smt
  2744. string smtTxt = ''
  2745. if pair1Name != ''
  2746. smtTxt := statusSym(pair1Name) + (pair1Seen ? '' : ' (no data)')
  2747. if pair2Name != ''
  2748. smtTxt := (smtTxt == '' ? '' : smtTxt + ', ') + statusSym(pair2Name) + (pair2Seen ? '' : ' (no data)')
  2749. bool smtOff = not show_smt and not showPsp
  2750. rows.push('SMT(' + (smtCustom ? 'Custom' : 'Auto') + '): ' + (smtOff ? 'Off' : smtTxt == '' ? 'n/a' : smtTxt))
  2751. clrs.push(smtOff or smtTxt == '' ? tbl_dim_color : tbl_text_color)
  2752. szs.push(tbl_sz)
  2753. // ADR 655.3 pts · 62% (the % is today's range, CDR, as a share of ADR)
  2754. if adrShow and not na(adrVal) and adrVal > 0 and not na(adrDayH) and not na(adrDayL)
  2755. rows.push('ADR ' + fmtPts(adrVal) + ' · ' + str.tostring((adrDayH - adrDayL) / adrVal * 100, '0') + '%')
  2756. clrs.push(tbl_text_color)
  2757. szs.push(tbl_sz)
  2758. if tbl_date
  2759. rows.push(str.format_time(time_close, 'MMM dd yyyy', syminfo.timezone))
  2760. clrs.push(tbl_text_color)
  2761. szs.push(tbl_sz)
  2762.  
  2763. if not na(infoTbl)
  2764. table.delete(infoTbl)
  2765. infoTbl := na
  2766. if tbl_show and rows.size() > 0
  2767. infoTbl := table.new(tablePosition(tbl_pos_vert, tbl_pos_horiz), 1, rows.size(), bgcolor = tblBg, border_color = noColor, border_width = 0, frame_color = tblFrame, frame_width = tbl_border ? 1 : 0)
  2768. for r = 0 to rows.size() - 1
  2769. table.cell(infoTbl, 0, r, rows.get(r), text_color = clrs.get(r), bgcolor = tblBg, text_size = szs.get(r), text_halign = text.align_center, text_font_family = font.family_monospace, text_formatting = r == 0 and head != '' ? text.format_bold : text.format_none)
  2770.  
  2771. var line adrUpLn = na
  2772. var line adrDnLn = na
  2773. var label adrUpLbl = na
  2774. var label adrDnLbl = na
  2775. if barstate.islast
  2776. bool adrLnOk = adrLinesShow and not na(adrVal) and adrVal > 0 and not na(adrDayStartBar) and not na(adrDayH) and not na(adrDayL)
  2777. if adrLnOk
  2778. float upPx = adrDayL + adrVal
  2779. float dnPx = adrDayH - adrVal
  2780. int x2 = bar_index + candleOffset - 3
  2781. if na(adrUpLn)
  2782. adrUpLn := line.new(xAnchor(adrDayStartBar), upPx, x2, upPx, color = adrLineColor, style = lineStyleFromStr(adrLineStyle))
  2783. adrDnLn := line.new(xAnchor(adrDayStartBar), dnPx, x2, dnPx, color = adrLineColor, style = lineStyleFromStr(adrLineStyle))
  2784. adrUpLbl := label.new(x2, upPx, 'ADR+', style = label.style_label_left, color = na, textcolor = adrLineColor, size = size.small)
  2785. adrDnLbl := label.new(x2, dnPx, 'ADR-', style = label.style_label_left, color = na, textcolor = adrLineColor, size = size.small)
  2786. else
  2787. line.set_xy1(adrUpLn, xAnchor(adrDayStartBar), upPx)
  2788. line.set_xy2(adrUpLn, x2, upPx)
  2789. line.set_xy1(adrDnLn, xAnchor(adrDayStartBar), dnPx)
  2790. line.set_xy2(adrDnLn, x2, dnPx)
  2791. label.set_xy(adrUpLbl, x2, upPx)
  2792. label.set_xy(adrDnLbl, x2, dnPx)
  2793. else if not na(adrUpLn)
  2794. line.delete(adrUpLn)
  2795. line.delete(adrDnLn)
  2796. label.delete(adrUpLbl)
  2797. label.delete(adrDnLbl)
  2798. adrUpLn := na
  2799. adrDnLn := na
  2800. adrUpLbl := na
  2801. adrDnLbl := na
  2802.  
  2803.  
  2804. // [WARNINGS] short message at the top of the chart
  2805. var table warnTbl = na
  2806. if barstate.islast
  2807. string msg = ''
  2808. if not validTf
  2809. msg := 'Fractal ' + modelType + ' does not work on the ' + tfLabel(curTfCode()) + ' chart.'
  2810. if (show_smt or showPsp) and pair1Name == '' and pair2Name == ''
  2811. msg := (msg == '' ? '' : msg + '\n') + 'No correlated pair for ' + syminfo.ticker + '. Set one in Asset Correlation > Custom.'
  2812. if (show_smt or showPsp) and pair1Name != '' and not pair1Seen
  2813. msg := (msg == '' ? '' : msg + '\n') + 'No data for ' + statusSym(pair1Name) + '.'
  2814. if (show_smt or showPsp) and pair2Name != '' and not pair2Seen
  2815. msg := (msg == '' ? '' : msg + '\n') + 'No data for ' + statusSym(pair2Name) + '.'
  2816. if not na(warnTbl)
  2817. table.delete(warnTbl)
  2818. warnTbl := na
  2819. if showWarn and msg != ''
  2820. warnTbl := table.new(position.top_center, 1, 1, bgcolor = color.new(color.red, 85), frame_color = color.new(color.red, 50), frame_width = 1)
  2821. table.cell(warnTbl, 0, 0, msg, text_color = color.red, text_size = size.small)
  2822.  
  2823. // ============================================================
  2824. // [SMT] ON CHART: continuation SMT inside a live setup
  2825. // ============================================================
  2826. // SMT on the chart belongs to a setup: the reversal SMT is drawn at C2 (newSetup). The
  2827. // continuation SMT: after the C2 candle a pair goes beyond its own C2 candle's extreme while we stay
  2828. // inside ours (bullish: a pair makes a lower low, we a higher low). The line joins our C2 extreme and our
  2829. // bar at that moment; from then the end slides to our further extremes (still not beyond C2).
  2830. // One line per setup, live until the setup ends.
  2831. smt_on = smtOnChart and calcOn and (pair1Name != '' or pair2Name != '')
  2832.  
  2833. float p1BarH = na(pair1) ? na : pair1.h
  2834. float p1BarL = na(pair1) ? na : pair1.l
  2835. float p2BarH = na(pair2) ? na : pair2.h
  2836. float p2BarL = na(pair2) ? na : pair2.l
  2837. // The pairs' bar highs / lows of the last bars, kept in arrays: a function that only runs on some bars
  2838. // cannot read a series' history (it would see the values of its earlier calls).
  2839. SMT_BUF = 1500
  2840. var array<float> pBuf1H = array.new<float>()
  2841. var array<float> pBuf1L = array.new<float>()
  2842. var array<float> pBuf2H = array.new<float>()
  2843. var array<float> pBuf2L = array.new<float>()
  2844. pBuf1H.push(p1BarH)
  2845. pBuf1L.push(p1BarL)
  2846. pBuf2H.push(p2BarH)
  2847. pBuf2L.push(p2BarL)
  2848. if pBuf1H.size() > SMT_BUF
  2849. pBuf1H.shift()
  2850. pBuf1L.shift()
  2851. pBuf2H.shift()
  2852. pBuf2L.shift()
  2853.  
  2854. f_smt_draw(C2Setup s, int x1, float y1, int x2, float y2, bool isHigh, string txt) =>
  2855. smtDrawOn(s, x1, y1, x2, y2, isHigh, txt)
  2856. if showAlerts and smtAlerts
  2857. alert((isHigh ? 'Bearish' : 'Bullish') + ' SMT Divergence on ' + syminfo.ticker, alert.freq_once_per_bar_close)
  2858.  
  2859. // beyond = further in the setup's direction of the extreme (bearish: higher, bullish: lower)
  2860. f_beyond(bool isHigh, float a, float b) =>
  2861. not na(a) and not na(b) and (isHigh ? a > b : a < b)
  2862.  
  2863. // one bar of the continuation SMT check: the pairs' run since C2, and from the first bar where a pair
  2864. // is beyond its C2-time extreme while we are not, our extreme (the line's end)
  2865. f_csStep(C2Setup s, bool isHigh, float own, int ownBar, float v1, float v2) =>
  2866. if na(s.csRun1) or f_beyond(isHigh, v1, s.csRun1)
  2867. s.csRun1 := v1
  2868. if na(s.csRun2) or f_beyond(isHigh, v2, s.csRun2)
  2869. s.csRun2 := v2
  2870. bool ok = not na(own) and not f_beyond(isHigh, own, s.extreme) and own != s.extreme
  2871. if not s.csDiv
  2872. if ok and (f_beyond(isHigh, s.csRun1, s.c2P1) or f_beyond(isHigh, s.csRun2, s.c2P2))
  2873. s.csDiv := true
  2874. s.csOwnPx := own
  2875. s.csOwnBar := ownBar
  2876. else if ok and f_beyond(isHigh, own, s.csOwnPx)
  2877. s.csOwnPx := own
  2878. s.csOwnBar := ownBar
  2879. s
  2880.  
  2881. f_smtCont(C2Setup s) =>
  2882. if smt_on and not na(s) and not s.dead and s.phase != 0 and not na(s.c2BarIndex) and not na(s.extreme)
  2883. bool isHigh = not s.isBull
  2884. int start = s.csStart
  2885. if not na(start) and bar_index >= start
  2886. if not s.csInit
  2887. // first bar of the check: replay the bars since the C2 candle closed (C3 model: since C3 opened)
  2888. int n = pBuf1H.size()
  2889. for x = math.max(start, bar_index - n + 1) to bar_index
  2890. int off = bar_index - x
  2891. float v1 = (isHigh ? pBuf1H : pBuf1L).get(n - 1 - off)
  2892. float v2 = (isHigh ? pBuf2H : pBuf2L).get(n - 1 - off)
  2893. f_csStep(s, isHigh, isHigh ? high[off] : low[off], x, v1, v2)
  2894. s.csInit := true
  2895. else
  2896. f_csStep(s, isHigh, isHigh ? high : low, bar_index, isHigh ? p1BarH : p1BarL, isHigh ? p2BarH : p2BarL)
  2897. bool d1 = s.csDiv and f_beyond(isHigh, s.csRun1, s.c2P1)
  2898. bool d2 = s.csDiv and f_beyond(isHigh, s.csRun2, s.c2P2)
  2899. if s.revealed and (d1 or d2)
  2900. string txt = smtNames(d1, d2)
  2901. if na(s.csLn)
  2902. f_smt_draw(s, s.c2BarIndex, s.extreme, s.csOwnBar, s.csOwnPx, isHigh, txt)
  2903. s.csLn := s.smtLns.last()
  2904. s.csLb := txt != '' and s.smtLbls.size() > 0 ? s.smtLbls.last() : na
  2905. else if line.get_x2(s.csLn) != s.csOwnBar or line.get_y2(s.csLn) != s.csOwnPx
  2906. line.set_xy2(s.csLn, s.csOwnBar, s.csOwnPx)
  2907. if not na(s.csLb)
  2908. label.set_xy(s.csLb, int(math.round((s.c2BarIndex + s.csOwnBar) / 2.0)), (s.extreme + s.csOwnPx) / 2)
  2909. label.set_text(s.csLb, txt)
  2910. s
  2911.  
  2912. f_smtCont(buySetup)
  2913. f_smtCont(sellSetup)
  2914.  
  2915. //#endregion
  2916.  
  2917. // ══════════════════════════════════════════════════════════════════════════
  2918. // ══ MÓDULOS PO3 sobre a base Fractal ═════════════════════════════════════
  2919. // 1) Session Liquidity (Ásia, Londres, NY AM, NY PM) PO3 / CISD Model+
  2920. // 2) PDH / PDL / PWH / PWL PO3
  2921. // 3) Liquidez BSL / SSL desenhada + sweeps PO3 / CISD Model+ / IFVG Ultimate
  2922. // 4) HTF FVG em até 3 timeframes PO3 / CISD Model+
  2923. // 5) Tabela de setup (checklist + nota) CISD Model+
  2924. // 6) CISD do gráfico (confirmado, potencial, stop, nota) CISD Model+
  2925. // 7) Plot do IFVG IFVG Ultimate Pro+
  2926. // Todos os inputs destes módulos ficam depois dos inputs da base.
  2927. // ══════════════════════════════════════════════════════════════════════════
  2928. NYTZ = 'America/New_York'
  2929. // lado permitido pelo Bias da base (Neutral / Bullish / Bearish / Auto Bias)
  2930. mBias(bool bu) => bu ? allowBuy and biasNow != 'Bearish' : allowSell and biasNow != 'Bullish'
  2931. mAtr = nz(lblDodgeTol)
  2932.  
  2933. // ── 1) Session Liquidity ──────────────────────────────────────────────────
  2934. // Máxima / mínima de cada sessão (horário de NY) vira nível no fim da sessão. Tocado = varrido:
  2935. // com "Preserve" a linha fica pontilhada e para na vela do sweep; sem ele, some. Varrido há mais
  2936. // de 24h sai. No máximo 24 níveis.
  2937. G_SS = 'Session Liquidity'
  2938. ssShow = input.bool(false, 'Show Session Liquidity', inline = 'SS0', group = G_SS)
  2939. ssKeep = input.bool(true, 'Preserve After Sweep', inline = 'SS0', group = G_SS)
  2940. ssCol = input.color(#787b86, '', inline = 'SS1', group = G_SS)
  2941. ssSty = input.string('Dotted', 'Style', options = ['Solid', 'Dashed', 'Dotted'], inline = 'SS1', group = G_SS)
  2942. ssAsiaOn = input.bool(true, 'Asia', inline = 'SS2', group = G_SS)
  2943. ssAsia = input.session('2100-0100', '', inline = 'SS2', group = G_SS)
  2944. ssLonOn = input.bool(true, 'London', inline = 'SS3', group = G_SS)
  2945. ssLon = input.session('0300-0600', '', inline = 'SS3', group = G_SS)
  2946. ssAmOn = input.bool(true, 'NY AM', inline = 'SS4', group = G_SS)
  2947. ssAm = input.session('0930-1200', '', inline = 'SS4', group = G_SS)
  2948. ssPmOn = input.bool(true, 'NY PM', inline = 'SS5', group = G_SS)
  2949. ssPm = input.session('1400-1700', '', inline = 'SS5', group = G_SS)
  2950. type SessLvl
  2951. string name
  2952. float price
  2953. int bar
  2954. bool hi
  2955. line ln
  2956. label lb
  2957. bool swept = false
  2958. int sweptTime = na
  2959. var ssLv = array.new<SessLvl>()
  2960. ss_nm = array.from('ASIA', 'LON', 'NYAM', 'NYPM')
  2961. ss_on = array.from(ssAsiaOn, ssLonOn, ssAmOn, ssPmOn)
  2962. ss_in = array.from(not na(time(timeframe.period, ssAsia, NYTZ)), not na(time(timeframe.period, ssLon, NYTZ)), not na(time(timeframe.period, ssAm, NYTZ)), not na(time(timeframe.period, ssPm, NYTZ)))
  2963. var ss_was = array.new_bool(4, false)
  2964. var ss_h = array.new_float(4, na)
  2965. var ss_l = array.new_float(4, na)
  2966. var ss_hb = array.new_int(4, na)
  2967. var ss_lb = array.new_int(4, na)
  2968. ssPush(string nm, float px, int bar, bool isHigh) =>
  2969. if ssShow and not na(px)
  2970. ln = line.new(bar, px, bar_index, px, color = ssCol, style = lineStyleFromStr(ssSty))
  2971. lb = label.new(bar_index, px, nm, style = label.style_label_left, color = noColor, textcolor = ssCol, size = size.tiny)
  2972. ssLv.push(SessLvl.new(nm, px, bar, isHigh, ln, lb))
  2973. while ssLv.size() > 24
  2974. old = ssLv.shift()
  2975. old.ln.delete()
  2976. old.lb.delete()
  2977. true
  2978. for k = 0 to 3
  2979. bool inz = ss_in.get(k)
  2980. bool was = ss_was.get(k)
  2981. if ss_on.get(k)
  2982. if inz and not was
  2983. ss_h.set(k, high)
  2984. ss_l.set(k, low)
  2985. ss_hb.set(k, bar_index)
  2986. ss_lb.set(k, bar_index)
  2987. if inz and was
  2988. if high > nz(ss_h.get(k), high)
  2989. ss_h.set(k, high)
  2990. ss_hb.set(k, bar_index)
  2991. if low < nz(ss_l.get(k), low)
  2992. ss_l.set(k, low)
  2993. ss_lb.set(k, bar_index)
  2994. if not inz and was
  2995. string tag = str.tostring(month(time, NYTZ)) + '/' + str.tostring(dayofmonth(time, NYTZ)) + ' ' + ss_nm.get(k)
  2996. ssPush(tag + '.H', ss_h.get(k), nz(ss_hb.get(k), bar_index), true)
  2997. ssPush(tag + '.L', ss_l.get(k), nz(ss_lb.get(k), bar_index), false)
  2998. ss_was.set(k, inz)
  2999. // última sessão varrida de cada lado (item "Session Sweep" da tabela)
  3000. var ssSwHi = -10000
  3001. var ssSwLo = -10000
  3002. if ssLv.size() > 0
  3003. for i = ssLv.size() - 1 to 0
  3004. s = ssLv.get(i)
  3005. if not s.swept and (s.hi ? high > s.price : low < s.price)
  3006. s.swept := true
  3007. s.sweptTime := time
  3008. if s.hi
  3009. ssSwHi := bar_index
  3010. else
  3011. ssSwLo := bar_index
  3012. if ssKeep
  3013. s.ln.set_style(line.style_dotted)
  3014. s.ln.set_x2(bar_index)
  3015. s.lb.set_x(bar_index)
  3016. s.lb.set_style(s.hi ? label.style_label_down : label.style_label_up)
  3017. if not ssKeep
  3018. s.ln.delete()
  3019. s.lb.delete()
  3020. bool ssOld = s.swept and (not ssKeep or time - s.sweptTime > 86400000)
  3021. if ssOld
  3022. s.ln.delete()
  3023. s.lb.delete()
  3024. ssLv.remove(i)
  3025. if not ssOld and not s.swept and barstate.islast
  3026. s.ln.set_x2(bar_index)
  3027. s.lb.set_x(bar_index)
  3028.  
  3029. // ── 2) PDH / PDL / PWH / PWL ──────────────────────────────────────────────
  3030. // Máxima e mínima do dia e da semana anteriores, do horário em que foram feitas até a barra atual
  3031. // (ou até o primeiro toque, com "Cut on touch"). Desenho só na última barra.
  3032. G_PD = 'PDH / PDL / PWH / PWL'
  3033. pdCol = input.color(#787b86, '', inline = 'pd0', group = G_PD)
  3034. pdSty = input.string('Dotted', 'Style', options = ['Solid', 'Dashed', 'Dotted'], inline = 'pd0', group = G_PD)
  3035. pdCut = input.bool(true, 'Cut on touch', inline = 'pd0', group = G_PD)
  3036. pd_on = array.from(input.bool(true, 'PDH', inline = 'pd1', group = G_PD), input.bool(true, 'PDL', inline = 'pd1', group = G_PD), input.bool(true, 'PWH', inline = 'pd1', group = G_PD), input.bool(true, 'PWL', inline = 'pd1', group = G_PD))
  3037. type PdLvl
  3038. float px
  3039. int t
  3040. int hit
  3041. float cur
  3042. int ct
  3043. line ln
  3044. label lb
  3045. var pdL = array.from(PdLvl.new(), PdLvl.new(), PdLvl.new(), PdLvl.new())
  3046. pd_nd = timeframe.change('1D')
  3047. [pwH, pwL, pwT] = request.security(syminfo.tickerid, 'W', [high[1], low[1], time[1]], lookahead = barmerge.lookahead_on, calc_bars_count = 10)
  3048. pd_nw = pwT != nz(pwT[1])
  3049. for i = 0 to 3
  3050. v = pdL.get(i)
  3051. bool hi = i % 2 == 0
  3052. float x = hi ? high : low
  3053. if i < 2 ? pd_nd : pd_nw
  3054. float w = i < 2 ? v.cur : hi ? pwH : pwL
  3055. v.t := nz(v.ct, time)
  3056. v.px := w
  3057. v.cur := x
  3058. v.ct := time
  3059. v.hit := na
  3060. else if na(v.cur) or (hi ? x > v.cur : x < v.cur)
  3061. v.cur := x
  3062. v.ct := time
  3063. if na(v.hit) and (hi ? high >= v.px : low <= v.px)
  3064. v.hit := time
  3065. if barstate.islast
  3066. v.ln.delete()
  3067. v.lb.delete()
  3068. if pd_on.get(i) and not na(v.px)
  3069. bool cut = pdCut and not na(v.hit)
  3070. int x2 = cut ? v.hit : time
  3071. v.ln := line.new(v.t, v.px, x2, v.px, xloc = xloc.bar_time, color = pdCol, style = lineStyleFromStr(pdSty))
  3072. v.lb := label.new(x2, v.px, (i < 2 ? 'PD' : 'PW') + (hi ? 'H' : 'L'), xloc = xloc.bar_time, textcolor = pdCol, style = cut ? (hi ? label.style_label_down : label.style_label_up) : label.style_label_left, color = noColor, size = size.tiny)
  3073.  
  3074. // ── 3) Liquidez BSL / SSL + sweeps ────────────────────────────────────────
  3075. // Pools = swings (máx / mín de 3 velas) do timeframe da liquidez ainda não tomados. As N mais novas
  3076. // de cada lado são desenhadas; quando o preço toma uma, a linha fica do swing até o toque com o
  3077. // texto do sweep. O sweep também alimenta a tabela e a origem do CISD do gráfico.
  3078. G_LQ = 'Liquidity'
  3079. lqOn = input.bool(false, 'Show BSL / SSL', inline = 'lq0', group = G_LQ)
  3080. lqCol = input.color(#787b86, '', inline = 'lq0', group = G_LQ)
  3081. lqN = input.int(3, 'per side', minval = 1, maxval = 10, inline = 'lq0', group = G_LQ)
  3082. lqTxt = input.string('$$$', 'Sweep text', group = G_LQ, tooltip = 'Texto do rótulo da pool já varrida. Vazio = BSL / SSL.')
  3083. type SwPt
  3084. float y
  3085. int t
  3086. bool taken = false
  3087. line ln = na
  3088. label lb = na
  3089. var lqHi = array.new<SwPt>()
  3090. var lqLo = array.new<SwPt>()
  3091. var lqSwL = array.new<line>()
  3092. var lqSwB = array.new<label>()
  3093. lqSecs = timeframe.in_seconds()
  3094. lqTf = lqSecs <= 60 ? '15' : lqSecs <= 180 ? '30' : lqSecs <= 300 ? '60' : lqSecs <= 1800 ? '240' : autoTf
  3095. var float lqCurH = high
  3096. var int lqCurHt = time
  3097. var float lqCurL = low
  3098. var int lqCurLt = time
  3099. var lqHs = array.new<float>()
  3100. var lqLs = array.new<float>()
  3101. var lqHts = array.new<int>()
  3102. var lqLts = array.new<int>()
  3103. lqChg = timeframe.change(lqTf)
  3104. if lqChg
  3105. lqHs.push(lqCurH)
  3106. lqLs.push(lqCurL)
  3107. lqHts.push(lqCurHt)
  3108. lqLts.push(lqCurLt)
  3109. if lqHs.size() > 5
  3110. lqHs.shift()
  3111. lqLs.shift()
  3112. lqHts.shift()
  3113. lqLts.shift()
  3114. lqCurH := high
  3115. lqCurHt := time
  3116. lqCurL := low
  3117. lqCurLt := time
  3118. if not lqChg
  3119. if high > lqCurH
  3120. lqCurH := high
  3121. lqCurHt := time
  3122. if low < lqCurL
  3123. lqCurL := low
  3124. lqCurLt := time
  3125. LqDrop(SwPt pt) =>
  3126. pt.ln.delete()
  3127. pt.lb.delete()
  3128. pt.ln := na
  3129. pt.lb := na
  3130. true
  3131. LqAdd(array<SwPt> pts, float y, int t) =>
  3132. pts.push(SwPt.new(y, t))
  3133. if pts.size() > 40
  3134. LqDrop(pts.shift())
  3135. true
  3136. // marca as pools que o preço passou; devolve se alguma foi tomada nesta barra
  3137. LqSweep(array<SwPt> pts, bool isHigh) =>
  3138. found = false
  3139. if pts.size() > 0
  3140. for i = pts.size() - 1 to 0
  3141. pt = pts.get(i)
  3142. if not pt.taken and (isHigh ? high > pt.y : low < pt.y)
  3143. pt.taken := true
  3144. found := true
  3145. if not na(pt.ln)
  3146. pt.ln.set_x2(time)
  3147. pt.lb.set_x(bar_index)
  3148. pt.lb.set_style(isHigh ? label.style_label_down : label.style_label_up)
  3149. if lqTxt != ''
  3150. pt.lb.set_text(lqTxt)
  3151. lqSwL.push(pt.ln)
  3152. lqSwB.push(pt.lb)
  3153. pt.ln := na
  3154. pt.lb := na
  3155. if lqSwL.size() > 20
  3156. lqSwL.shift().delete()
  3157. lqSwB.shift().delete()
  3158. found
  3159. if lqChg and lqHs.size() >= 3
  3160. lqK = lqHs.size()
  3161. float lqMidH = lqHs.get(lqK - 2)
  3162. if lqMidH >= lqHs.get(lqK - 3) and lqMidH >= lqHs.get(lqK - 1)
  3163. LqAdd(lqHi, lqMidH, lqHts.get(lqK - 2))
  3164. float lqMidL = lqLs.get(lqK - 2)
  3165. if lqMidL <= lqLs.get(lqK - 3) and lqMidL <= lqLs.get(lqK - 1)
  3166. LqAdd(lqLo, lqMidL, lqLts.get(lqK - 2))
  3167. bool lqHiFound = LqSweep(lqHi, true)
  3168. bool lqLoFound = LqSweep(lqLo, false)
  3169. var lqSwHiBar = -10000
  3170. var lqSwLoBar = -10000
  3171. if lqHiFound
  3172. lqSwHiBar := bar_index
  3173. if lqLoFound
  3174. lqSwLoBar := bar_index
  3175. for lqSide in array.from(true, false)
  3176. lqPts = lqSide ? lqHi : lqLo
  3177. lqCnt = 0
  3178. if lqPts.size() > 0
  3179. for i = lqPts.size() - 1 to 0
  3180. pt = lqPts.get(i)
  3181. bool lqDr = lqOn and calcOn and not pt.taken and lqCnt < lqN
  3182. if lqDr
  3183. lqCnt += 1
  3184. if na(pt.ln)
  3185. pt.ln := line.new(pt.t, pt.y, time, pt.y, xloc = xloc.bar_time, color = lqCol, style = line.style_dotted)
  3186. pt.lb := label.new(bar_index, pt.y, lqSide ? 'BSL' : 'SSL', style = label.style_label_left, color = noColor, textcolor = lqCol, size = size.tiny)
  3187. if barstate.islast
  3188. pt.ln.set_x2(time)
  3189. pt.lb.set_x(bar_index)
  3190. if not lqDr and not pt.taken and not na(pt.ln)
  3191. LqDrop(pt)
  3192. alertcondition(lqHiFound, 'Buyside liquidity swept', '{{ticker}} {{interval}}: buyside liquidity swept')
  3193. alertcondition(lqLoFound, 'Sellside liquidity swept', '{{ticker}} {{interval}}: sellside liquidity swept')
  3194.  
  3195. // ── 4) HTF FVG ────────────────────────────────────────────────────────────
  3196. // FVG de 3 velas em até 3 timeframes maiores, lido sem repaint (lookahead_on com [1] / [3]). A zona
  3197. // nasce no fechamento da vela HTF que completa o gap e morre quando o CORPO de uma vela desse
  3198. // timeframe fecha além da borda de trás. Posição 0 = HTF do modelo; 1 e 2 = extras.
  3199. G_FV = 'HTF FVG'
  3200. fvOn = input.bool(true, 'Show HTF FVG', inline = 'fv0', group = G_FV)
  3201. fvBullCol = input.color(color.new(color.blue, 88), '', inline = 'fv0', group = G_FV)
  3202. fvBearCol = input.color(color.new(color.red, 88), '', inline = 'fv0', group = G_FV)
  3203. fvMax = input.int(2, 'Max per side', minval = 1, maxval = 10, inline = 'fv0', group = G_FV, tooltip = 'Quantos FVGs de alta e de baixa ficam no gráfico por timeframe. Os mais antigos saem.')
  3204. fvMode = input.string('Auto', 'Extra TFs', options = ['Off', 'Auto', 'Manual'], inline = 'fv1', group = G_FV, tooltip = 'FVGs de timeframes acima do HTF do modelo.\nAuto: 1m = 1H e D; 3m / 5m = 4H e D; 15m = D e W; 30m / 1H = W; acima = M.\nManual: os dois timeframes abaixo.\nO número é quantos timeframes extras entram (1 ou 2).')
  3205. fvNx = input.int(1, '', minval = 1, maxval = 2, inline = 'fv1', group = G_FV)
  3206. fvM1 = input.timeframe('240', 'Manual', inline = 'fv2', group = G_FV)
  3207. fvM2 = input.timeframe('1D', '', inline = 'fv2', group = G_FV)
  3208. fvTf1 = fvMode == 'Manual' ? fvM1 : lqSecs <= 60 ? '60' : lqSecs <= 300 ? '240' : lqSecs <= 900 ? '1D' : lqSecs <= 3600 ? '1W' : '1M'
  3209. fvTf2 = fvMode == 'Manual' ? fvM2 : lqSecs <= 300 ? '1D' : lqSecs <= 3600 ? '1W' : '1M'
  3210. fvS0 = timeframe.in_seconds(autoTf)
  3211. fvS1 = timeframe.in_seconds(fvTf1)
  3212. fvS2 = timeframe.in_seconds(fvTf2)
  3213. fv_on = array.from(fvOn and validTf, fvOn and fvMode != 'Off' and fvS1 > lqSecs and fvS1 != fvS0, fvOn and fvMode != 'Off' and fvNx >= 2 and fvS2 > lqSecs and fvS2 != fvS0 and fvS2 != fvS1)
  3214. [fa_o, fa_h, fa_l, fa_c, fa_h3, fa_l3, fa_t3, fa_t1] = request.security(syminfo.tickerid, autoTf, [open[1], high[1], low[1], close[1], high[3], low[3], time[3], time[1]], lookahead = barmerge.lookahead_on)
  3215. [fb_o, fb_h, fb_l, fb_c, fb_h3, fb_l3, fb_t3, fb_t1] = request.security(syminfo.tickerid, fvTf1, [open[1], high[1], low[1], close[1], high[3], low[3], time[3], time[1]], lookahead = barmerge.lookahead_on)
  3216. [fc_o, fc_h, fc_l, fc_c, fc_h3, fc_l3, fc_t3, fc_t1] = request.security(syminfo.tickerid, fvTf2, [open[1], high[1], low[1], close[1], high[3], low[3], time[3], time[1]], lookahead = barmerge.lookahead_on)
  3217. fv_nw = array.from(not na(fa_t1) and fa_t1 != nz(fa_t1[1]), not na(fb_t1) and fb_t1 != nz(fb_t1[1]), not na(fc_t1) and fc_t1 != nz(fc_t1[1]))
  3218. fv_os = array.from(fa_o, fb_o, fc_o)
  3219. fv_hs = array.from(fa_h, fb_h, fc_h)
  3220. fv_ls = array.from(fa_l, fb_l, fc_l)
  3221. fv_cs = array.from(fa_c, fb_c, fc_c)
  3222. fv_h3s = array.from(fa_h3, fb_h3, fc_h3)
  3223. fv_l3s = array.from(fa_l3, fb_l3, fc_l3)
  3224. fv_t3s = array.from(fa_t3, fb_t3, fc_t3)
  3225. fv_nms = array.from(tfLabel(autoTf) + ' FVG', tfLabel(fvTf1) + ' FVG', tfLabel(fvTf2) + ' FVG')
  3226. type Fz
  3227. box bx
  3228. line ce
  3229. label lb
  3230. float top
  3231. float bot
  3232. bool bull
  3233. int k
  3234. var fzs = array.new<Fz>()
  3235. FzDel(Fz f) =>
  3236. f.bx.delete()
  3237. f.ce.delete()
  3238. f.lb.delete()
  3239. true
  3240. fvRight = time + lqSecs * 5000
  3241. // barra em que o preço negociou dentro de um FVG de HTF ainda válido (item "HTF PDA Delivery")
  3242. var fvDelL = -10000
  3243. var fvDelS = -10000
  3244. for k = 0 to 2
  3245. if fv_on.get(k) and fv_nw.get(k) and not na(fv_h3s.get(k)) and not na(fv_t3s.get(k))
  3246. bool fvBu = fv_ls.get(k) > fv_h3s.get(k)
  3247. if fvBu or fv_hs.get(k) < fv_l3s.get(k)
  3248. float fvTop = fvBu ? fv_ls.get(k) : fv_l3s.get(k)
  3249. float fvBot = fvBu ? fv_h3s.get(k) : fv_hs.get(k)
  3250. float fvMid = (fvTop + fvBot) / 2
  3251. fvC = fvBu ? fvBullCol : fvBearCol
  3252. fvBx = box.new(fv_t3s.get(k), fvTop, fvRight, fvBot, xloc = xloc.bar_time, border_color = noColor, bgcolor = fvC)
  3253. fvCe = line.new(fv_t3s.get(k), fvMid, fvRight, fvMid, xloc = xloc.bar_time, color = color.new(fvC, 40), style = line.style_dotted)
  3254. fvLb = label.new(fvRight, fvMid, fv_nms.get(k), xloc = xloc.bar_time, style = label.style_label_left, color = noColor, textcolor = color.new(fvC, 0), size = size.tiny)
  3255. fzs.push(Fz.new(fvBx, fvCe, fvLb, fvTop, fvBot, fvBu, k))
  3256. // só os "Max per side" mais novos deste timeframe e lado ficam
  3257. fvCnt = 0
  3258. for i = fzs.size() - 1 to 0
  3259. f = fzs.get(i)
  3260. if f.k == k and f.bull == fvBu
  3261. fvCnt += 1
  3262. if fvCnt > fvMax
  3263. FzDel(f)
  3264. fzs.remove(i)
  3265. if fzs.size() > 0
  3266. for i = fzs.size() - 1 to 0
  3267. f = fzs.get(i)
  3268. float fvLo = math.min(fv_os.get(f.k), fv_cs.get(f.k))
  3269. float fvHiB = math.max(fv_os.get(f.k), fv_cs.get(f.k))
  3270. bool fvDead = not fv_on.get(f.k) or (fv_nw.get(f.k) and (f.bull ? fvLo < f.bot : fvHiB > f.top))
  3271. if fvDead
  3272. FzDel(f)
  3273. fzs.remove(i)
  3274. if not fvDead
  3275. if low <= f.top and high >= f.bot
  3276. if f.bull
  3277. fvDelL := bar_index
  3278. else
  3279. fvDelS := bar_index
  3280. if barstate.islast
  3281. f.bx.set_right(fvRight)
  3282. f.ce.set_x2(fvRight)
  3283. f.lb.set_x(fvRight)
  3284.  
  3285. // ── 5) Tabela de setup (checklist + nota) ─────────────────────────────────
  3286. // Os 6 itens do CISD Model+ avaliados com as peças deste indicador, na janela de 15 velas antes do
  3287. // C2: sweep de liquidez (pivôs do gráfico ou BSL / SSL), entrega em HTF FVG, volume acima da média,
  3288. // sweep de sessão, alvo livre a pelo menos 1R e SMT. Nota pelos itens que faltam: 0 = A+, 1 = A, 2 = B+, 3 = B, mais = C (Session Sweep não conta com Session Liquidity desligado).
  3289. G_CK = 'Setup Table'
  3290. ckShow = input.bool(true, 'Show Setup Table', inline = 'ck0', group = G_CK)
  3291. ckPos = input.string('Top Right', '', options = ['Top Left', 'Top Right', 'Middle Right', 'Bottom Left', 'Bottom Right'], inline = 'ck0', group = G_CK)
  3292. ckCisdLbl = input.bool(true, 'Grade on the model CISD', group = G_CK, tooltip = 'Escreve CISD+ / CISD- e a nota do setup no fim da linha do CISD do C2 / C3, como no CISD do gráfico.')
  3293. CK_WIN = 15
  3294. ck_volS = ta.sma(volume, 20)
  3295. var ckVolBar = -10000
  3296. if not na(ck_volS) and volume > ck_volS * 1.2
  3297. ckVolBar := bar_index
  3298. // liquidez do timeframe do gráfico (pivôs de 2 velas), só para o checklist
  3299. var ckPh = array.new_float()
  3300. var ckPl = array.new_float()
  3301. float ckNewH = ta.pivothigh(high, 2, 2)
  3302. float ckNewL = ta.pivotlow(low, 2, 2)
  3303. if not na(ckNewH)
  3304. ckPh.push(ckNewH)
  3305. if ckPh.size() > 2
  3306. ckPh.shift()
  3307. if not na(ckNewL)
  3308. ckPl.push(ckNewL)
  3309. if ckPl.size() > 2
  3310. ckPl.shift()
  3311. var ckSwHi = -10000
  3312. var ckSwLo = -10000
  3313. if ckPh.size() > 0
  3314. for i = ckPh.size() - 1 to 0
  3315. if high > ckPh.get(i) and close < ckPh.get(i)
  3316. ckPh.remove(i)
  3317. ckSwHi := bar_index
  3318. if ckPl.size() > 0
  3319. for i = ckPl.size() - 1 to 0
  3320. if low < ckPl.get(i) and close > ckPl.get(i)
  3321. ckPl.remove(i)
  3322. ckSwLo := bar_index
  3323. // SMT ativo num setup do lado
  3324. var ckSmtBull = -10000
  3325. var ckSmtBear = -10000
  3326. if not na(buySetup) and not buySetup.dead and (buySetup.smtHit or buySetup.csDiv)
  3327. ckSmtBull := bar_index
  3328. if not na(sellSetup) and not sellSetup.dead and (sellSetup.smtHit or sellSetup.csDiv)
  3329. ckSmtBear := bar_index
  3330. // alvo mais próximo ainda não tomado: sessões, BSL / SSL e PD / PW
  3331. ckTarget(bool above) =>
  3332. float best = na
  3333. for s in ssLv
  3334. if not s.swept and (above ? s.price > close : s.price < close)
  3335. best := na(best) ? s.price : above ? math.min(best, s.price) : math.max(best, s.price)
  3336. for pt in (above ? lqHi : lqLo)
  3337. if not pt.taken and (above ? pt.y > close : pt.y < close)
  3338. best := na(best) ? pt.y : above ? math.min(best, pt.y) : math.max(best, pt.y)
  3339. for k = (above ? 0 : 1) to 3 by 2
  3340. v = pdL.get(k)
  3341. if na(v.hit) and not na(v.px) and (above ? v.px > close : v.px < close)
  3342. best := na(best) ? v.px : above ? math.min(best, v.px) : math.max(best, v.px)
  3343. best
  3344. // os 6 itens de um setup (bu = alta, stop, entrada) na janela que começa na barra w
  3345. ckEval(bool bu, float stop, float entry, int w, bool sm) =>
  3346. float tg = ckTarget(bu)
  3347. float d = math.abs(entry - stop)
  3348. array.from(math.max(bu ? ckSwLo : ckSwHi, bu ? lqSwLoBar : lqSwHiBar) >= w, (bu ? fvDelL : fvDelS) >= w, ckVolBar >= w, (bu ? ssSwLo : ssSwHi) >= w, not na(tg) and not na(entry) and (bu ? tg > entry : tg < entry) and d > 0 and math.abs(tg - entry) / d >= 1.0, sm)
  3349. // nota pelos itens que faltam: 0 = A+ (4), 1 = A (3), 2 = B+ (2), 3 = B (1), 4 ou mais = C (0).
  3350. // Com Session Liquidity desligado o item Session Sweep nunca passa, então ele não conta.
  3351. ckGrade(array<bool> a) =>
  3352. miss = ssShow ? 0 : -1
  3353. for b in a
  3354. miss += b ? 0 : 1
  3355. 4 - math.min(miss, 4)
  3356. ck_gr = str.split('C,B,B+,A,A+', ',')
  3357. ckGradeTxt(int g) => ck_gr.get(g)
  3358. ck_names = array.from('Liquidity Sweep', 'HTF PDA Delivery', 'Volume', 'Session Sweep', 'Clear Targets', 'SMT')
  3359. // último setup revelado (CISD confirmado): avaliado uma vez, na barra em que aparece
  3360. var ckRes = array.new_bool(6, false)
  3361. var ckG = 0
  3362. var C2Setup ckSet = na
  3363. var int ckKeyB = na
  3364. var int ckKeyS = na
  3365. // live C2 (candle still forming): checked again on every tick of the last bar, same call as the closed setup
  3366. var ckLvR = array.new_bool(6, false)
  3367. var ckLvG = 0
  3368. bool ckLvOk = false
  3369. for ckSide in array.from(true, false)
  3370. C2Setup s = ckSide ? buySetup : sellSetup
  3371. int ckKey = ckSide ? ckKeyB : ckKeyS
  3372. bool ckNew = not na(s) and s.revealed and not na(s.c2BarIndex) and (na(ckKey) or s.c2BarIndex != ckKey)
  3373. bool ckLive = not ckNew and barstate.islast and lvSide == (ckSide ? 1 : -1)
  3374. if ckNew or ckLive
  3375. float e = na
  3376. float l = ckSide ? bullLevelFixed : bearLevelFixed
  3377. int b = na
  3378. bool m = false
  3379. if ckNew
  3380. e := s.extreme
  3381. l := s.cisdLevel
  3382. b := s.c2BarIndex
  3383. m := s.smtHit or s.csDiv
  3384. else
  3385. HtfCandle c0 = htfCandles.get(0)
  3386. HtfCandle c1 = htfCandles.get(1)
  3387. e := ckSide ? c0.l : c0.h
  3388. b := ckSide ? c0.lBar : c0.hBar
  3389. m := show_smt and (ckSide ? c0.pL >= c1.pL or c0.qL >= c1.qL : c0.pH <= c1.pH or c0.qH <= c1.qH)
  3390. array<bool> r = ckEval(ckSide, e, l, b - CK_WIN, m)
  3391. int g = ckGrade(r)
  3392. if ckLive
  3393. ckLvR := r
  3394. ckLvG := g
  3395. ckLvOk := true
  3396. else
  3397. ckRes := r
  3398. ckG := g
  3399. ckSet := s
  3400. // nota do setup no fim da linha do CISD do C2 / C3, como no CISD do gráfico
  3401. if ckCisdLbl and not na(s.cisdLine) and na(s.cisdLbl)
  3402. string ckTt = s.tag + (ckSide ? ' bull' : ' bear') + '\nGrade: ' + ckGradeTxt(g)
  3403. for [i, nm] in ck_names
  3404. ckTt += '\n' + (r.get(i) ? '✅ ' : '❌ ') + nm
  3405. s.cisdLbl := label.new(line.get_x2(s.cisdLine), s.cisdLevel, (ckSide ? 'CISD+ ' : 'CISD- ') + ckGradeTxt(g), style = label.style_label_left, color = noColor, textcolor = ckSide ? cisdBullColor : cisdBearColor, size = size.tiny, tooltip = ckTt)
  3406. if ckSide
  3407. ckKeyB := b
  3408. else
  3409. ckKeyS := b
  3410. var table ckTbl = na
  3411. if barstate.islast
  3412. if not na(ckTbl)
  3413. table.delete(ckTbl)
  3414. ckTbl := na
  3415. if ckShow
  3416. ckTbl := table.new(str.lower(str.replace(ckPos, ' ', '_')), 2, 10, bgcolor = tblBg, border_width = 1, border_color = color.new(tbl_text_color, 80))
  3417. // a live C2 takes the table while it lasts; the hourglass = its CISD is not confirmed yet
  3418. bool ckLv = ckLvOk
  3419. bool ckBu = ckLv ? lvSide > 0 : not na(ckSet) and ckSet.isBull
  3420. array<bool> ckSr = ckLv ? ckLvR : ckRes
  3421. int ckSg = ckLv ? ckLvG : ckG
  3422. string ckSt = ckLv ? 'Live C2' + (ckBu ? ' bull' : ' bear') + ((ckBu ? bullReclaimed : bearReclaimed) ? '' : ' ⏳') : na(ckSet) ? '-' : (ckSet.dead ? 'X' : '') + ckSet.tag + (ckBu ? ' bull' : ' bear')
  3423. bool ckNone = na(ckSet) and not ckLv
  3424. color ckHead = tblHeadColor
  3425. table.cell(ckTbl, 0, 0, 'Bias', text_color = ckHead, text_size = size.tiny)
  3426. table.cell(ckTbl, 1, 0, biasNow, text_color = biasNow == 'Bullish' ? cisdBullColor : biasNow == 'Bearish' ? cisdBearColor : ckHead, text_size = size.tiny)
  3427. table.cell(ckTbl, 0, 1, 'Setup', text_color = ckHead, text_size = size.tiny)
  3428. table.cell(ckTbl, 1, 1, ckSt, text_color = ckNone ? ckHead : ckLv ? liveC2Col : ckBu ? cisdBullColor : cisdBearColor, text_size = size.tiny)
  3429. table.cell(ckTbl, 0, 2, 'Setup Grade', text_color = ckHead, text_size = size.tiny)
  3430. table.cell(ckTbl, 1, 2, ckNone ? '-' : ckGradeTxt(ckSg), text_color = ckNone ? ckHead : ckSg >= 3 ? #00C853 : ckSg >= 1 ? #FFB300 : #FF7043, text_size = size.tiny)
  3431. for [i, nm] in ck_names
  3432. table.cell(ckTbl, 0, i + 3, nm, text_color = tbl_text_color, text_size = size.tiny)
  3433. table.cell(ckTbl, 1, i + 3, ckNone or (i == 3 and not ssShow) ? '-' : ckSr.get(i) ? '✅' : '❌', text_color = tbl_text_color, text_size = size.tiny)
  3434.  
  3435. // ── 6) CISD do gráfico (CISD Model+ | Triton) ─────────────────────────────
  3436. // Motor de CISD do Triton no timeframe do gráfico: perna atual, extremo da perna e nível = abertura
  3437. // mais extrema da sequência contrária; o fechamento além do nível vira o lado. Só nasce depois de um
  3438. // sweep de liquidez ou de uma entrega em FVG do gráfico (janela de 15 velas), respeita o Bias, leva
  3439. // a nota do checklist no rótulo e SOME POR COMPLETO (linha, rótulo, linha do SL e rótulo do SL) quando
  3440. // o preço viola o stop (extremo da perna).
  3441. // Não repete: no mesmo nível de um CISD do modelo ou de um protected swing, não é desenhado.
  3442. G_TC = 'Chart CISD (Triton)'
  3443. tcOn = input.bool(true, 'Chart CISD', inline = 'tc0', group = G_TC)
  3444. tcPot = input.bool(true, 'Potential', inline = 'tc0', group = G_TC, tooltip = 'Mostra o nível tracejado ANTES da confirmação: onde o preço precisa fechar para o CISD valer.')
  3445. tcWick = input.bool(true, 'Stop on wick', inline = 'tc0', group = G_TC, tooltip = 'O CISD do gráfico que foi estopado / violado é sempre apagado do gráfico (linha, rótulo, SL).\n\nLigado: apaga assim que o preço toca o stop (extremo da perna), mesmo só com o pavio.\nDesligado: só apaga quando uma vela FECHA além do stop.')
  3446. tcMax = input.int(3, 'Setups per side', minval = 1, maxval = 30, inline = 'tc1', group = G_TC)
  3447. tcMinG = input.string('C', 'Min grade', options = ['C', 'B', 'B+', 'A', 'A+'], inline = 'tc1', group = G_TC)
  3448. tcFvg = input.bool(true, 'Accept chart FVG delivery', group = G_TC, tooltip = 'Além do sweep de liquidez, vale como origem o preço ter negociado dentro de um FVG do timeframe do gráfico.')
  3449. tcProx = input.bool(true, 'Ignore close CISDs', group = G_TC, tooltip = 'Não cria um CISD a menos de 0,75 ATR de outro do mesmo lado ainda válido.')
  3450. tcSl = input.bool(true, 'Show stop', inline = 'tc2', group = G_TC)
  3451. tcRisk = input.float(0, 'Risk $ (0 = off)', minval = 0, inline = 'tc2', group = G_TC, tooltip = 'Com um valor acima de 0, o tooltip do rótulo mostra quantos contratos cabem nesse risco até o stop.')
  3452. type TcC
  3453. bool bu
  3454. float lv
  3455. float sl
  3456. bool dead = false
  3457. line ln = na
  3458. label lb = na
  3459. line sln = na
  3460. label slb = na
  3461. // apaga tudo o que pertence a um CISD do gráfico (linha, rótulo, linha do SL, rótulo do SL)
  3462. TcDel(TcC c) =>
  3463. line.delete(c.ln)
  3464. label.delete(c.lb)
  3465. line.delete(c.sln)
  3466. label.delete(c.slb)
  3467. c.ln := na
  3468. c.lb := na
  3469. c.sln := na
  3470. c.slb := na
  3471. true
  3472. // abertura mais extrema da perna ATUAL (a vela de agora e as anteriores do mesmo lado) e a barra dela
  3473. tcLegCur(int bias) =>
  3474. sh = 0
  3475. float ext = open
  3476. if (close > open ? 1 : close < open ? -1 : 0) == bias
  3477. for i = 1 to 500
  3478. ct = close[i] > open[i] ? 1 : close[i] < open[i] ? -1 : 0
  3479. if ct == 0
  3480. continue
  3481. if ct != bias
  3482. break
  3483. if bias == 1 ? open[i] < ext : open[i] > ext
  3484. ext := open[i]
  3485. sh := i
  3486. [ext, bar_index - sh]
  3487. // o mesmo para a perna ANTERIOR do lado pedido (a vela de agora é contrária ou doji)
  3488. tcLegPrev(int bias) =>
  3489. fnd = false
  3490. sh = 1
  3491. float ext = na
  3492. for j = 1 to 500
  3493. ct = close[j] > open[j] ? 1 : close[j] < open[j] ? -1 : 0
  3494. if ct == 0
  3495. continue
  3496. if fnd and ct != bias
  3497. break
  3498. if ct == bias and (not fnd or (bias == 1 ? open[j] < ext : open[j] > ext))
  3499. ext := open[j]
  3500. sh := j
  3501. fnd := true
  3502. [ext, bar_index - sh]
  3503. var tcBias = 0
  3504. var float tcLvl = na
  3505. var int tcLvlB = na
  3506. var float tcPiv = na
  3507. var int tcPivB = na
  3508. var tcArr = array.new<TcC>()
  3509. tcEv = array.new_bool(2, false)
  3510. tcMinR = ck_gr.indexof(tcMinG)
  3511. // FVG do timeframe do gráfico (só para a origem do CISD, sem desenho)
  3512. var float tcFbT = na
  3513. var float tcFbB = na
  3514. var float tcFsT = na
  3515. var float tcFsB = na
  3516. var tcFvL = -10000
  3517. var tcFvS = -10000
  3518. if low > high[2] and close[1] > high[2]
  3519. tcFbT := low
  3520. tcFbB := high[2]
  3521. if high < low[2] and close[1] < low[2]
  3522. tcFsT := low[2]
  3523. tcFsB := high
  3524. if not na(tcFbB) and low <= tcFbT and low >= tcFbB
  3525. tcFvL := bar_index
  3526. if not na(tcFsT) and high >= tcFsB and high <= tcFsT
  3527. tcFvS := bar_index
  3528. tcW = bar_index - CK_WIN
  3529. bool tcOkL = math.max(ckSwLo, lqSwLoBar) >= tcW or (tcFvg and tcFvL >= tcW)
  3530. bool tcOkS = math.max(ckSwHi, lqSwHiBar) >= tcW or (tcFvg and tcFvS >= tcW)
  3531. // níveis de CISD que o modelo já mostra (CISD do setup e protected swings): não repetir
  3532. tcPx = array.new_float()
  3533. for tcSide in array.from(true, false)
  3534. C2Setup s = tcSide ? buySetup : sellSetup
  3535. if not na(s)
  3536. if s.revealed and not s.dead and not na(s.cisdLevel)
  3537. tcPx.push(s.cisdLevel)
  3538. if not na(s.icList)
  3539. for ic in s.icList
  3540. if not ic.taken and not na(ic.ln)
  3541. tcPx.push(ic.ln.get_y1())
  3542. TcDup(float lv) =>
  3543. r = false
  3544. float tol = math.max(mAtr * 0.15, syminfo.mintick)
  3545. for p in tcPx
  3546. if math.abs(p - lv) <= tol
  3547. r := true
  3548. r
  3549. tcCt = close > open ? 1 : close < open ? -1 : 0
  3550. // tcNb: lado novo nesta barra (semente ou virada); 0 = nada muda
  3551. tcNb = 0
  3552. if tcBias == 0
  3553. if bar_index > 10
  3554. tcNb := tcCt
  3555. if tcNb == 0
  3556. for k = 1 to 50
  3557. tcNb := close[k] > open[k] ? 1 : close[k] < open[k] ? -1 : 0
  3558. if tcNb != 0
  3559. break
  3560. else
  3561. // extremo novo da perna: o nível do CISD é recalculado
  3562. if tcBias == 1 ? high > tcPiv : low < tcPiv
  3563. tcPiv := tcBias == 1 ? high : low
  3564. tcPivB := bar_index
  3565. if tcCt == tcBias
  3566. [tcP1, tcB1] = tcLegCur(tcBias)
  3567. tcLvl := tcP1
  3568. tcLvlB := tcB1
  3569. else
  3570. [tcP2, tcB2] = tcLegPrev(tcBias)
  3571. tcLvl := tcP2
  3572. tcLvlB := tcB2
  3573. // fechamento além do nível = CISD (vira o lado)
  3574. if tcBias == 1 ? close < tcLvl : close > tcLvl
  3575. tcNb := -tcBias
  3576. tcBu = tcNb == 1
  3577. if tcOn and calcOn and (tcBu ? tcOkL : tcOkS) and mBias(tcBu)
  3578. tcBlk = TcDup(tcLvl)
  3579. if tcProx
  3580. for c in tcArr
  3581. if c.bu == tcBu and not c.dead and math.abs(c.lv - tcLvl) < mAtr * 0.75
  3582. tcBlk := true
  3583. if not tcBlk
  3584. bool tcSm = (tcBu ? ckSmtBull : ckSmtBear) >= tcW
  3585. array<bool> tcCk = ckEval(tcBu, tcPiv, tcLvl, tcW, tcSm)
  3586. tcG = ckGrade(tcCk)
  3587. if tcG >= tcMinR
  3588. tcCol = tcBu ? cisdBullColor : cisdBearColor
  3589. tcGt = ckGradeTxt(tcG)
  3590. string tcTt = (tcBu ? 'CISD+ ' : 'CISD- ') + tfLabel(curTfCode()) + '\nGrade: ' + tcGt + '\nEntry: ' + str.tostring(tcLvl, format.mintick) + '\nStop: ' + str.tostring(tcPiv, format.mintick)
  3591. float tcD = math.abs(tcLvl - tcPiv)
  3592. if tcRisk > 0 and tcD > 0
  3593. tcTt += '\nContracts: ' + str.tostring(math.floor(tcRisk / (tcD * syminfo.pointvalue)))
  3594. for [i, nm] in ck_names
  3595. tcTt += '\n' + (tcCk.get(i) ? '✅ ' : '❌ ') + nm
  3596. tcC = TcC.new(tcBu, tcLvl, tcPiv)
  3597. tcC.ln := line.new(tcLvlB, tcLvl, bar_index + 3, tcLvl, color = tcCol)
  3598. tcC.lb := label.new(bar_index + 3, tcLvl, 'CISD' + (tcBu ? '+ ' : '- ') + tcGt, style = label.style_label_left, color = noColor, textcolor = tcCol, size = size.tiny, tooltip = tcTt)
  3599. if tcSl
  3600. tcC.sln := line.new(tcPivB, tcPiv, bar_index + 3, tcPiv, color = htfInfoColor, style = line.style_dotted)
  3601. tcC.slb := label.new(bar_index + 3, tcPiv, 'SL', style = label.style_label_left, color = noColor, textcolor = htfInfoColor, size = size.tiny)
  3602. tcArr.push(tcC)
  3603. tcEv.set(tcBu ? 0 : 1, true)
  3604. // só os "Setups per side" mais novos deste lado ficam
  3605. tcCnt = 0
  3606. for i = tcArr.size() - 1 to 0
  3607. tcO = tcArr.get(i)
  3608. if tcO.bu == tcBu
  3609. tcCnt += 1
  3610. if tcCnt > tcMax
  3611. TcDel(tcO)
  3612. tcArr.remove(i)
  3613. if tcNb != 0
  3614. tcBias := tcNb
  3615. [tcP3, tcB3] = tcLegCur(tcNb)
  3616. tcLvl := tcP3
  3617. tcLvlB := tcB3
  3618. tcPiv := tcNb == 1 ? high : low
  3619. tcPivB := bar_index
  3620. // invalidação: o CISD do gráfico estopado / violado é apagado por completo (linha, rótulo, SL e rótulo do SL).
  3621. // Pavio (Stop on wick ligado) ou fechamento além do stop; sai também o que passou a repetir um CISD do modelo.
  3622. if tcArr.size() > 0
  3623. for i = tcArr.size() - 1 to 0
  3624. tcO = tcArr.get(i)
  3625. bool tcViol = tcO.bu ? (tcWick ? low < tcO.sl : close < tcO.sl) : (tcWick ? high > tcO.sl : close > tcO.sl)
  3626. if tcViol or TcDup(tcO.lv)
  3627. TcDel(tcO)
  3628. tcArr.remove(i)
  3629. // CISD potencial: o nível que ainda não foi fechado, refeito na última barra
  3630. var line tcPl = na
  3631. var label tcPlb = na
  3632. if barstate.islast
  3633. tcPl.delete()
  3634. tcPlb.delete()
  3635. tcPl := na
  3636. tcPlb := na
  3637. tcPbu = tcBias == -1
  3638. if tcOn and tcPot and tcBias != 0 and not na(tcLvl) and (tcPbu ? close < tcLvl and tcOkL : close > tcLvl and tcOkS) and mBias(tcPbu) and not TcDup(tcLvl)
  3639. tcPc = color.new(tcPbu ? cisdBullColor : cisdBearColor, 25)
  3640. tcPl := line.new(tcLvlB, tcLvl, bar_index + 5, tcLvl, color = tcPc, style = line.style_dashed)
  3641. tcPlb := label.new(bar_index + 5, tcLvl, tcPbu ? 'Potential CISD+' : 'Potential CISD-', style = label.style_label_left, color = noColor, textcolor = tcPc, size = size.tiny, tooltip = (tcPbu ? 'Close above ' : 'Close below ') + str.tostring(tcLvl, format.mintick) + ' confirms\nStop: ' + str.tostring(tcPiv, format.mintick))
  3642. alertcondition(tcEv.get(0), 'Chart CISD Bull', '{{ticker}} {{interval}}: CISD bull')
  3643. alertcondition(tcEv.get(1), 'Chart CISD Bear', '{{ticker}} {{interval}}: CISD bear')
  3644.  
  3645. // ── 7) Plot do IFVG (IFVG Ultimate Pro+) ──────────────────────────────────
  3646. // A caixa do FVG invertido, a linha de entrada e o rótulo "IFVG+" / "IFVG-" (com ● quando a vela da
  3647. // inversão teve volume acima da média). Mesma detecção do IFVG Ultimate, modo "Single": a cada swing,
  3648. // o melhor FVG contra o lado é o candidato; se um fechamento atravessa o FVG inteiro em até 15 velas,
  3649. // ele vira IFVG. Não nasce se o fechamento já passou da origem do swing. Stop = extremo desde o FVG:
  3650. // tocado, o setup some (ou fica cinza). Respeita o Bias.
  3651. G_IF = 'IFVG'
  3652. ifOn = input.bool(false, 'Show IFVG', inline = 'if0', group = G_IF)
  3653. ifCBu = input.color(color.blue, '', inline = 'if0', group = G_IF)
  3654. ifCBe = input.color(color.red, '', inline = 'if0', group = G_IF)
  3655. ifCBx = input.color(color.new(color.gray, 75), 'Box', inline = 'if0', group = G_IF)
  3656. ifMax = input.int(2, 'Setups shown', minval = 1, maxval = 50, inline = 'if1', group = G_IF)
  3657. ifHide = input.bool(true, 'Hide stopped', inline = 'if1', group = G_IF)
  3658. ifMin = input.float(0.0, 'Min FVG (ATR)', minval = 0.0, step = 0.1, group = G_IF, tooltip = 'Altura mínima do FVG para ele virar candidato a IFVG, em múltiplos do ATR(14). 0 = todos.')
  3659. type IfC
  3660. int b1
  3661. int b3
  3662. float top
  3663. float bot
  3664. float sp
  3665. bool done = false
  3666. type IfS
  3667. bool bu
  3668. float sl
  3669. float be
  3670. box bx
  3671. line ln
  3672. label lb
  3673. bool res = false
  3674. var ifCL = array.new<IfC>()
  3675. var ifCH = array.new<IfC>()
  3676. var ifSet = array.new<IfS>()
  3677. ifEv = array.new_bool(2, false)
  3678. ifPL = ta.lowestbars(3) == -1
  3679. ifPH = ta.highestbars(3) == -1
  3680. ifC1 = close[1]
  3681. ifVol = volume[1] > ck_volS[1]
  3682. // Candidatos de um lado: isLow = swing que nasce num fundo (FVGs de alta, que viram IFVG de baixa).
  3683. IfTrack(bool isLow, array<IfC> arr, bool pivO, bool pivP) =>
  3684. var float oP = na
  3685. var int oB = na
  3686. var bool frz = false
  3687. var float frzP = na
  3688. var int frzB = na
  3689. var IfC live = na
  3690. float pSrc = isLow ? high[1] : low[1]
  3691. float top = isLow ? low[1] : low[3]
  3692. float bot = isLow ? high[3] : high[1]
  3693. bool fvg = (isLow ? low[1] > high[3] : high[1] < low[3]) and top - bot >= ifMin * mAtr
  3694. if pivO
  3695. oP := isLow ? low[1] : high[1]
  3696. oB := bar_index - 1
  3697. frz := false
  3698. live := na
  3699. if not na(oB)
  3700. if frz and (isLow ? pSrc > frzP : pSrc < frzP)
  3701. frz := false
  3702. if (not frz or bar_index == frzB + 1) and bar_index - 3 >= oB - 1 and fvg
  3703. if not na(live)
  3704. if not live.done and arr.indexof(live) < 0
  3705. live := na
  3706. bool mk = na(live)
  3707. if not mk
  3708. if not live.done and (isLow ? top > live.top : bot < live.bot)
  3709. k = arr.indexof(live)
  3710. if k >= 0
  3711. arr.remove(k)
  3712. mk := true
  3713. if mk
  3714. live := IfC.new(bar_index - 1, bar_index - 3, top, bot, oP)
  3715. arr.push(live)
  3716. if arr.size() > 50
  3717. arr.shift()
  3718. if not frz and pivP
  3719. frz := true
  3720. frzP := pSrc
  3721. frzB := bar_index
  3722. true
  3723. // Inversão: o fechamento da vela anterior atravessou o FVG inteiro. srcBear = FVGs de baixa (IFVG de alta).
  3724. IfCheck(array<IfC> arr, bool srcBear) =>
  3725. if arr.size() > 0
  3726. for i = arr.size() - 1 to 0
  3727. e = arr.get(i)
  3728. if not e.done
  3729. bool trg = srcBear ? ifC1 > e.top : ifC1 < e.bot
  3730. if trg
  3731. e.done := true
  3732. if ifOn and calcOn and mBias(srcBear) and not (srcBear ? ifC1 >= e.sp : ifC1 <= e.sp)
  3733. float sl = srcBear ? low : high
  3734. for j = 0 to bar_index - e.b1
  3735. sl := srcBear ? math.min(sl, low[j]) : math.max(sl, high[j])
  3736. col = srcBear ? ifCBu : ifCBe
  3737. bx = box.new(e.b3, e.top, bar_index, e.bot, border_color = noColor, bgcolor = ifCBx)
  3738. ln = line.new(bar_index - 1, ifC1, bar_index + 8, ifC1, color = col)
  3739. lb = label.new(bar_index + 8, ifC1, (srcBear ? 'IFVG+' : 'IFVG-') + (ifVol ? ' ●' : ''), style = label.style_label_left, color = noColor, textcolor = col, size = size.tiny)
  3740. ifSet.push(IfS.new(srcBear, sl, e.sp, bx, ln, lb))
  3741. ifEv.set(srcBear ? 0 : 1, true)
  3742. while ifSet.size() > ifMax
  3743. o = ifSet.shift()
  3744. o.bx.delete()
  3745. o.ln.delete()
  3746. o.lb.delete()
  3747. if not trg and bar_index - e.b1 > 15
  3748. arr.remove(i)
  3749. true
  3750. IfTrack(true, ifCL, ifPL, ifPH)
  3751. IfTrack(false, ifCH, ifPH, ifPL)
  3752. IfCheck(ifCL, false)
  3753. IfCheck(ifCH, true)
  3754. // stop tocado = setup perdido; origem do swing alcançada = resolvido (fica no gráfico)
  3755. if ifSet.size() > 0
  3756. for i = ifSet.size() - 1 to 0
  3757. ifS = ifSet.get(i)
  3758. if not ifS.res
  3759. bool ifStop = ifS.bu ? low < ifS.sl : high > ifS.sl
  3760. if ifStop or (ifS.bu ? high >= ifS.be : low <= ifS.be)
  3761. ifS.res := true
  3762. if ifStop and not ifHide
  3763. ifS.ln.set_color(color.gray)
  3764. ifS.lb.set_textcolor(color.gray)
  3765. if ifStop and ifHide
  3766. ifS.bx.delete()
  3767. ifS.ln.delete()
  3768. ifS.lb.delete()
  3769. ifSet.remove(i)
  3770. alertcondition(ifEv.get(0), 'IFVG Bull', '{{ticker}} {{interval}}: IFVG bull')
  3771. alertcondition(ifEv.get(1), 'IFVG Bear', '{{ticker}} {{interval}}: IFVG bear')
  3772.  
Advertisement
Add Comment
Please, Sign In to add comment