TDT Time Dilation | Sattam

S4tt4m · study · 1376 行 · 点赞 85 · TradingView 原页

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

Pine Script

// This Pine Script(TM) code is subject to the terms of the Mozilla Public License 2.0
// TDT Time Dilation | Sattam
// Candle counting from highs and lows with the strict counting rule, counts out
// of consolidations, time-level strips, reversal time lines, TDT sequences,
// market phases, entry windows and multi-timeframe time alignment.
//@version=6
indicator("TDT Time Dilation | Sattam", shorttitle = "TDT", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_bars_back = 500)
 
// =============================================================================
// CONSTANTS
// =============================================================================
const string P_TPL = "Gann box template (0-4-7-13-17-21-31) · قالب صندوق جان"
const string P_BAS = "Basic 1-3-7-13-17-21-31 (time expanded) · الأساسية (تمدد الزمن)"
const string P_REV = "Reversal 1-3-7-13-21-31 · الانعكاس"
const string P_2ND = "2nd 1-5-9-17-25-37 (time contracted) · الثانية (انكماش الزمن)"
const string P_PER = "Perfect 1-3-6-9-15-24-39 · المثالية"
 
const string M_AUTO = "Auto (TDT pairing) · تلقائي (أزواج TDT)"
const string M_MAN  = "Manual · يدوي"
const string S_CALL = "Callout · صندوق"
const string W_LAT  = "Latest count · العدّ الأحدث"
const string W_BOTH = "Both counts · العدّان"
const string Z_TINY = "Tiny · صغير جداً"
const string Z_SML  = "Small · صغير"
const string Z_NRM  = "Normal · عادي"
const string D_TR   = "Top right · أعلى اليمين"
const string D_BR   = "Bottom right · أسفل اليمين"
const string D_TL   = "Top left · أعلى اليسار"
const string D_BL   = "Bottom left · أسفل اليسار"
const string T_OFF  = "Off · بدون فلتر"
const string T_H1   = "HTF 1 trend · اتجاه الفريم الأعلى 1"
const string T_H2   = "HTF 2 trend · اتجاه الفريم الأعلى 2"
const string S_TEXT = "Plain text · نص فقط"
 
const string G_CNT = "Counting · العدّ"
const string G_CON = "Consolidation (time distortion) · التجميع (تشويه الزمن)"
const string G_LVL = "Gann box template levels · مستويات قالب صندوق جان"
const string G_STR = "Strip style · شكل الشريط"
const string G_TML = "Time lines · خطوط الزمن"
const string G_FRC = "Fractals and key levels · الفراكتل والمستويات المهمة"
const string G_SWG = "TDT types (count numbers) · أنواع TDT (أرقام العدّ)"
const string G_MTF = "Time alignment (multi-timeframe) · توافق الزمن (عدة فريمات)"
const string G_WIN = "Entry windows · نوافذ الدخول"
const string G_DSH = "Dashboard · اللوحة"
const string G_ALR = "Alerts · التنبيهات"
const string G_EXT = "Extras · إضافات"
 
const string X_ALL  = "All · الكل"
const string X_NONE = "None · لا شيء"
const string X_SKIP = "Skip consolidation candles in counts · طرح شموع التجميع من العدّ"
const string X_HTF3 = "Third higher timeframe (framework) · فريم أعلى ثالث (الإطار)"
const string X_LINE = "HTF count lines and tags on this chart · خطوط ووسوم عدّ الفريم الأعلى"
const string X_TWO  = "Second count per side · عدّ ثانٍ لكل اتجاه"
const string X_SESS = "Session of the previous day high / low · جلسة قمة وقاع اليوم السابق"
 
// =============================================================================
// INPUTS
// =============================================================================
int    fracLen  = input.int(2, "Fractal strength (bars each side) · قوة الفراكتل (شموع كل جهة)", minval = 1, maxval = 10, group = G_CNT, tooltip = "Bill Williams fractal = 2. [HH] = top fractal above the previous top fractal. [LL] = bottom fractal below the previous bottom fractal. Every [LL] starts a bullish count, every [HH] starts a bearish count.\n\nفراكتل بيل ويليامز = 2. [HH] قمة أعلى من القمة السابقة، و[LL] قاع أدنى من القاع السابق. كل [LL] يبدأ عدّاً صاعداً، وكل [HH] يبدأ عدّاً هابطاً.")
float  dojiPct  = input.float(10.0, "Doji body max (% of range) · أقصى جسم للدوجي (% من المدى)", minval = 0.0, maxval = 50.0, step = 1.0, group = G_CNT, tooltip = "Doji candles (wicks with almost no body) are counted for both bullish and bearish counts.\n\nشمعة الدوجي (فتائل بلا جسم تقريباً) تُعدّ في العدّ الصاعد والهابط معاً.")
int    cycleEnd = input.int(21, "Cycle ends at · نهاية الدورة عند", minval = 7, maxval = 200, group = G_CNT, tooltip = "21 is the last number where the cycle ends most of the time. A new [HH] / [LL] that is not beyond the current extreme only restarts the count after this number.\n\n21 آخر رقم تنتهي عنده الدورة غالباً. القمة أو القاع الجديد الذي لا يتجاوز الطرف الحالي لا يعيد العدّ إلا بعد هذا الرقم.")
string preset   = input.string(P_TPL, "Time levels · مستويات الزمن", options = [P_TPL, P_BAS, P_REV, P_2ND, P_PER], group = G_CNT, tooltip = "Gann box template uses the seven level slots below. The other choices are the TDT sequences.\n\nقالب صندوق جان يستخدم الخانات السبع أدناه، والخيارات الأخرى هي متتاليات TDT.")
bool   showBull = input.bool(true, "Bullish count (from lows) · العدّ الصاعد (من القيعان)", group = G_CNT)
bool   showBear = input.bool(true, "Bearish count (from highs) · العدّ الهابط (من القمم)", group = G_CNT)
int    histN    = input.int(3, "Strips kept per side · عدد الأشرطة لكل اتجاه", minval = 1, maxval = 20, group = G_CNT)
int    calcDepth = input.int(5000, "Calculation depth (bars) · عمق الحساب (شموع)", minval = 300, maxval = 50000, group = G_CNT, tooltip = "Counting starts this many bars before the last bar, so the counts are the same however much history is loaded. Higher timeframes use the same number of their own bars.\n\nيبدأ العدّ قبل آخر شمعة بهذا العدد من الشموع، فتبقى الأعداد ثابتة مهما كان التاريخ المحمّل. الفريمات الأعلى تستخدم نفس العدد من شموعها.")
bool   revOn    = input.bool(true, "Count again from reversals · العدّ من جديد من الانعكاسات", group = G_CNT, inline = "rvr", tooltip = "Count from 1 and wait for a significant number like 7, then count again from the new reversal. A swing on one of these numbers starts a count in the other direction, even when it is not a [HH] / [LL].\n\nعُدّ من 1 حتى رقم مهم مثل 7، ثم عُدّ من جديد من الانعكاس. القمة أو القاع الواضح على أحد هذه الأرقام يبدأ عدّاً في الاتجاه المعاكس حتى لو لم يكن [HH] / [LL].")
string revAt    = input.string("7,13,21", "", group = G_CNT, inline = "rvr")
 
bool   useCons  = input.bool(true, "Count expansions out of consolidations · عدّ التوسع عند الخروج من التجميع", group = G_CON, tooltip = "The count starts at the candle that leaves the consolidation. Candles inside the consolidation are not counted, even the one that made the high or low.\n\nالعدّ يبدأ من الشمعة التي تخرج من التجميع. شموع التجميع لا تُعدّ، حتى التي صنعت القمة أو القاع.")
int    consLen  = input.int(10, "Consolidation length (candles) · طول التجميع (شموع)", minval = 5, maxval = 50, group = G_CON, tooltip = "Most consolidations take 10 or 20 candles. 7 and 13 are rare and mean the market changes gears.\n\nأغلب التجميعات 10 أو 20 شمعة. 7 و13 نادرة وتعني أن السوق يغيّر سرعته.")
float  consMult = input.float(2.0, "Max range (x ATR) · أقصى مدى (× ATR)", minval = 0.5, step = 0.1, group = G_CON, tooltip = "A consolidation is this many candles whose total range is not larger than this many ATR(14).\n\nالتجميع هو هذا العدد من الشموع ومداها الكلي لا يتجاوز هذا العدد من ATR(14).")
bool   showCons = input.bool(true, "Show consolidation boxes · إظهار صناديق التجميع", group = G_CON, inline = "cb")
color  consCol  = input.color(color.new(#9E9E9E, 82), "", group = G_CON, inline = "cb")
 
bool  t1On = input.bool(true, "", group = G_LVL, inline = "r1")
int   t1V  = input.int(0, "", minval = 0, maxval = 400, group = G_LVL, inline = "r1")
color t1C  = input.color(#000000, "", group = G_LVL, inline = "r1")
bool  t2On = input.bool(false, "", group = G_LVL, inline = "r1")
int   t2V  = input.int(4, "", minval = 0, maxval = 400, group = G_LVL, inline = "r1")
color t2C  = input.color(#FFEB3B, "", group = G_LVL, inline = "r1")
bool  t3On = input.bool(true, "", group = G_LVL, inline = "r2")
int   t3V  = input.int(7, "", minval = 0, maxval = 400, group = G_LVL, inline = "r2")
color t3C  = input.color(#FFEB3B, "", group = G_LVL, inline = "r2")
bool  t4On = input.bool(true, "", group = G_LVL, inline = "r2")
int   t4V  = input.int(13, "", minval = 0, maxval = 400, group = G_LVL, inline = "r2")
color t4C  = input.color(#000000, "", group = G_LVL, inline = "r2")
bool  t5On = input.bool(false, "", group = G_LVL, inline = "r3")
int   t5V  = input.int(17, "", minval = 0, maxval = 400, group = G_LVL, inline = "r3")
color t5C  = input.color(#3F51D8, "", group = G_LVL, inline = "r3")
bool  t6On = input.bool(true, "", group = G_LVL, inline = "r3")
int   t6V  = input.int(21, "", minval = 0, maxval = 400, group = G_LVL, inline = "r3")
color t6C  = input.color(#C62833, "", group = G_LVL, inline = "r3")
bool  t7On = input.bool(true, "", group = G_LVL, inline = "r4")
int   t7V  = input.int(31, "", minval = 0, maxval = 400, group = G_LVL, inline = "r4")
color t7C  = input.color(#2F35D6, "", group = G_LVL, inline = "r4")
 
float  stripH   = input.float(0.25, "Strip height (x ATR) · ارتفاع الشريط (× ATR)", minval = 0.05, step = 0.05, group = G_STR)
float  stripGap = input.float(0.15, "Gap from extreme (x ATR) · المسافة عن الطرف (× ATR)", minval = 0.0, step = 0.05, group = G_STR)
int    fillTr   = input.int(10, "Fill transparency · شفافية التعبئة", minval = 0, maxval = 100, group = G_STR)
color  pal1     = input.color(#B4585E, "Fill · التعبئة", group = G_STR, inline = "p1")
color  pal2     = input.color(#4F4285, "", group = G_STR, inline = "p1")
color  pal3     = input.color(#2B3A9C, "", group = G_STR, inline = "p1")
color  pal4     = input.color(#1C1F4F, "", group = G_STR, inline = "p1")
color  pal5     = input.color(#2D2342, "", group = G_STR, inline = "p1")
color  pal6     = input.color(#3D4463, "", group = G_STR, inline = "p1")
string lblSizeS = input.string(Z_SML, "Number size · حجم الأرقام", options = [Z_TINY, Z_SML, Z_NRM], group = G_STR)
 
bool   showRev  = input.bool(true, "Reversal time lines · خطوط زمن الانعكاس", group = G_TML, inline = "rv")
string revStr   = input.string("13,21", "", group = G_TML, inline = "rv")
color  revCol   = input.color(#F2E14C, "", group = G_TML, inline = "rv")
bool   showFtz  = input.bool(false, "Fib time zone · مناطق فيبو الزمنية", group = G_TML, inline = "fz")
string ftzStr   = input.string("0,1,3,5,7,13,17,21", "", group = G_TML, inline = "fz")
bool   ftzOne   = input.bool(false, "Use one color · لون واحد", group = G_TML, inline = "fz1")
color  ftzCol   = input.color(#4A57F5, "", group = G_TML, inline = "fz1")
bool   show90   = input.bool(false, "90th candle (long-term cycle change) · الشمعة 90 (تغيّر الدورة الطويلة)", group = G_TML, inline = "c90")
color  c90Col   = input.color(#FF5252, "", group = G_TML, inline = "c90")
 
bool   showFr   = input.bool(true, "Show [HH] / [LL] · إظهار [HH] / [LL]", group = G_FRC)
color  hhCol    = input.color(#B22833, "Higher High · قمة أعلى", group = G_FRC)
color  llCol    = input.color(#1E9E3E, "Lower Low · قاع أدنى", group = G_FRC)
bool   showKL   = input.bool(true, "HTF key levels · مستويات الفريم الأعلى المهمة", group = G_FRC, inline = "kl")
string klTF     = input.timeframe("D", "", group = G_FRC, inline = "kl", tooltip = "Previous candle high and low of this timeframe.\n\nقمة وقاع الشمعة السابقة في هذا الفريم.")
color  klCol    = input.color(#F2E14C, "", group = G_FRC, inline = "kl")
color  sweepCol = input.color(#FF9800, "Key level sweep · اختراق المستوى المهم", group = G_FRC, tooltip = "A [HH] / [LL] that took the HTF key level is a counting start at the key level.\n\n[HH] / [LL] الذي اخترق مستوى الفريم الأعلى هو بداية عدّ عند المستوى المهم.")
bool   klFilter = input.bool(false, "Count only from key level sweeps · العدّ فقط من اختراق المستوى المهم", group = G_FRC)
bool   showStr  = input.bool(true, "Structure shift line (dotted) · خط تحوّل الهيكل (منقّط)", group = G_FRC, inline = "st")
color  strCol   = input.color(#E0E0E0, "", group = G_FRC, inline = "st")
 
bool   showSw   = input.bool(true, "Count numbers on turning points · أرقام العدّ على نقاط الانعكاس", group = G_SWG, tooltip = "Writes 1 on the first counted candle and the running count on every swing that lands on one of the numbers below.\n\nيكتب 1 على أول شمعة معدودة، ورقم العدّ على كل قمة أو قاع يقع على أحد الأرقام أدناه.")
string swStyle  = input.string(S_CALL, "Style · الشكل", options = [S_CALL, S_TEXT], group = G_SWG)
string swWhich  = input.string(W_LAT, "Counts numbered · الأعداد المرقّمة", options = [W_LAT, W_BOTH], group = G_SWG, tooltip = "Latest count numbers only the count that started most recently, so one count is read at a time.\n\nالعدّ الأحدث يرقّم فقط العدّ الذي بدأ آخراً، ليُقرأ عدّ واحد في كل مرة.")
string swTrend  = input.string(T_OFF, "Numbers with the trend · الأرقام مع الاتجاه", options = [T_OFF, T_H1, T_H2], group = G_SWG, tooltip = "Show count numbers only for the count in the trend direction. The trend is the direction of the most recent count on the chosen higher timeframe: a count from a low means up, so only the bullish count is numbered; a count from a high means down. Off numbers as set above.\n\nأظهر أرقام العدّ فقط للعدّ الذي في اتجاه الترند. الترند هو اتجاه آخر عدّ في الفريم الأعلى المختار: عدّ من قاع يعني صاعداً فيُرقَّم العدّ الصاعد فقط، وعدّ من قمة يعني هابطاً. «بدون فلتر» يرقّم حسب الإعداد السابق.")
bool   sw7   = input.bool(true, "Reversal 7 · انعكاس 7", group = G_SWG, tooltip = "Reversal points of the method: 7, 13 and 21, then 31 where the cycle closes.\n\nنقاط الانعكاس في المنهج: 7 و13 و21، ثم 31 حيث تُغلق الدورة.")
bool   sw13  = input.bool(true, "Reversal 13 · انعكاس 13", group = G_SWG)
bool   sw21  = input.bool(true, "Reversal 21 · انعكاس 21", group = G_SWG)
bool   sw31  = input.bool(true, "Reversal 31 · انعكاس 31", group = G_SWG)
bool   sw3   = input.bool(false, "Number 3 · الرقم 3", group = G_SWG, tooltip = "Other numbers of the sequences, off by default: 3, delayed or hastened 4/5, 9/11, 17, 25, and 20 of the 20/21 turning point.\n\nأرقام أخرى من المتتاليات، معطّلة افتراضياً: 3، والمؤخَّرة والمعجَّلة 4/5 و9/11 و17 و25، و20 من نقطة الانعكاس 20/21.")
bool   sw4   = input.bool(false, "Number 4 · الرقم 4", group = G_SWG)
bool   sw5   = input.bool(false, "Number 5 · الرقم 5", group = G_SWG)
bool   sw9   = input.bool(false, "Number 9 · الرقم 9", group = G_SWG)
bool   sw11  = input.bool(false, "Number 11 · الرقم 11", group = G_SWG)
bool   sw17  = input.bool(false, "Number 17 · الرقم 17", group = G_SWG)
bool   sw20  = input.bool(false, "Number 20 · الرقم 20", group = G_SWG)
bool   sw25  = input.bool(false, "Number 25 · الرقم 25", group = G_SWG)
color  swBull   = input.color(#2962FF, "Bullish count · العدّ الصاعد", group = G_SWG)
color  swBear   = input.color(#E53935, "Bearish count · العدّ الهابط", group = G_SWG)
 
string htfMode  = input.string(M_AUTO, "Higher timeframes · الفريمات الأعلى", options = [M_AUTO, M_MAN], group = G_MTF, tooltip = "Auto uses the TDT pairing: H1 counts for 5m and 1m, H4 for 15m and 5m, D1 for H1 and 15m, W1 for D1 and H4, M1 for W1 and D1.\n\nالتلقائي يستخدم أزواج TDT: H1 لـ5m و1m، وH4 لـ15m و5m، وD1 لـH1 و15m، وW1 لـD1 وH4، وM1 لـW1 وD1.")
bool   useH1    = input.bool(true, "HTF 1 · الفريم الأعلى 1", group = G_MTF, inline = "h1")
string h1In     = input.timeframe("60", "", group = G_MTF, inline = "h1")
bool   useH2    = input.bool(true, "HTF 2 · الفريم الأعلى 2", group = G_MTF, inline = "h2")
string h2In     = input.timeframe("240", "", group = G_MTF, inline = "h2")
bool   showCall = input.bool(true, "Alignment callouts · فقاعات التوافق", group = G_MTF, inline = "cl")
color  callCol  = input.color(#2A98A6, "", group = G_MTF, inline = "cl")
string keyStr   = input.string("7,13,20,21", "Key numbers · الأرقام المفتاحية", group = G_MTF)
int    tol      = input.int(0, "Tolerance (bars) · السماحية (شموع)", minval = 0, maxval = 4, group = G_MTF, tooltip = "Delayed or hastened counts still align (20/21, 12/13).\n\nالعدّ المؤخَّر أو المعجَّل يتوافق أيضاً (20/21، 12/13).")
 
bool   showWinBg = input.bool(false, "Shade bars inside an entry window · تظليل الشموع داخل نافذة الدخول", group = G_WIN, inline = "wb")
color  winCol    = input.color(color.new(#2A98A6, 88), "", group = G_WIN, inline = "wb")
 
bool   showDash = input.bool(true, "Show dashboard · إظهار اللوحة", group = G_DSH)
string dashPosS = input.string(D_TR, "Position · الموضع", options = [D_TR, D_BR, D_TL, D_BL], group = G_DSH)
string dashSzS  = input.string(Z_SML, "Size · الحجم", options = [Z_TINY, Z_SML, Z_NRM], group = G_DSH)
bool   showGuide = input.bool(true, "Guide rows · أسطر الإرشاد", group = G_DSH, tooltip = "HTF setup (scalp inside the 7th-9th HTF candle retracement, continuation after the 13th HTF candle), entry modes (entry / confirmation / bias timeframes) and a stop loss guide.\n\nإعداد الفريم الأعلى (سكالب داخل تصحيح الشمعة 7-9، واستمرار بعد الشمعة 13)، وأنماط الدخول (فريم الدخول والتأكيد والاتجاه)، ودليل وقف الخسارة.")
 
string alertStr = input.string("7,13,21", "Alert on count numbers · التنبيه عند أرقام العدّ", group = G_ALR)
 
string extras   = input.string(X_ALL, "Extras · إضافات", options = [X_ALL, X_NONE, X_SKIP, X_HTF3, X_LINE, X_TWO, X_SESS], group = G_EXT, tooltip = "Skip: candles inside consolidations are left out of the running counts (the time is distorted, so those candles do not exist). Third HTF: month, week and day frame the 4H / 1H counts. HTF lines: a vertical line and a 'Daily : 13' tag where a higher timeframe count lands on a key number. Second count: the previous count of each side keeps running until its cycle ends. Session: which session (Asia, London, New York) made the previous day high and low.\n\nالطرح: شموع التجميع تُطرح من الأعداد. الفريم الثالث: الشهري والأسبوعي واليومي إطار لعدّ 4H و1H. خطوط الفريم الأعلى: خط عمودي ووسم مثل «Daily : 13» حين يقع عدّ فريم أعلى على رقم مفتاحي. العدّ الثاني: العدّ السابق لكل اتجاه يستمر حتى نهاية دورته. الجلسة: أي جلسة (آسيا، لندن، نيويورك) صنعت قمة وقاع اليوم السابق.")
bool   useH3    = input.bool(true, "HTF 3 · الفريم الأعلى 3", group = G_EXT, inline = "h3")
string h3In     = input.timeframe("D", "", group = G_EXT, inline = "h3", tooltip = "Used in Manual mode. Auto uses month, week and day for 1H / 4H charts.\n\nيُستخدم في الوضع اليدوي. التلقائي يستخدم الشهري والأسبوعي واليومي لشارت 1H و4H.")
color  htfLnCol = input.color(#E53935, "HTF count lines · خطوط عدّ الفريم الأعلى", group = G_EXT)
color  swAlt    = input.color(#00C853, "Second count numbers · أرقام العدّ الثاني", group = G_EXT)
color  sessCol  = input.color(#B0BEC5, "Previous day session tags · وسوم جلسة اليوم السابق", group = G_EXT)
 
bool xSkip = extras == X_ALL or extras == X_SKIP
bool xHtf3 = extras == X_ALL or extras == X_HTF3
bool xLine = extras == X_ALL or extras == X_LINE
bool xTwo  = extras == X_ALL or extras == X_TWO
bool xSess = extras == X_ALL or extras == X_SESS
 
// Verification hook: the test copy replaces this line to draw only inside a date window
bool drawOK = true
 
// =============================================================================
// TYPES
// =============================================================================
type Strip
    int   dir
    int   ext
    float extP
    int   zero
    float a
    bool  kl
    bool  exp
    float sLvl
    int   sIdx
    bool  conf = false
    float lblY
    array<box>   bxs
    array<line>  lns
    array<label> lbs
    line  sLine
    bool  rev = false
 
// =============================================================================
// HELPERS
// =============================================================================
f_size(string s) =>
    s == Z_TINY ? size.tiny : s == Z_NRM ? size.normal : size.small
 
f_fg(color c) =>
    color.r(c) == 0 and color.g(c) == 0 and color.b(c) == 0 ? chart.fg_color : c
 
// Numbers typed by the user. Kept within 0..400 so no drawing lands more than
// 500 bars in the future (a Pine runtime error).
f_parse(string s) =>
    array<int> out = array.new<int>()
    for part in str.split(s, ",")
        float v = str.tonumber(str.trim(part))
        if not na(v) and v >= 0 and v <= 400
            out.push(int(v))
    out
 
f_has(array<int> arr, int n) =>
    not na(n) and arr.includes(n)
 
f_near(array<int> arr, int n, int t) =>
    bool hit = false
    if not na(n)
        for v in arr
            if math.abs(n - v) <= t
                hit := true
    hit
 
f_tfLabel(string tf) =>
    int s = timeframe.in_seconds(tf)
    string r = ""
    if s < 60
        r := str.tostring(s) + "s"
    else if s < 3600
        r := str.tostring(s / 60.0, "#.#") + "m"
    else if s < 86400
        r := str.tostring(s / 3600.0, "#.#") + "h"
    else if s < 604800
        r := str.tostring(s / 86400.0, "#.#") + "D"
    else if s < 2419200
        r := str.tostring(s / 604800.0, "#.#") + "W"
    else
        r := str.tostring(s / 2592000.0, "#.#") + "M"
    r
 
// TDT timeframe pairing: which higher timeframes frame
// the counts of the chart timeframe. Slot 3 is the month / week / day framework
// for 1H / 4H charts. "" = none.
f_autoTF(int which) =>
    int s = timeframe.in_seconds(timeframe.period)
    string a = s <= 300 ? "60" : s <= 1800 ? "240" : s <= 14400 ? "D" : s <= 86400 ? "W" : "M"
    string b = s <= 60 ? "" : s <= 300 ? "240" : s <= 1800 ? "D" : s <= 14400 ? "W" : s <= 86400 ? "M" : ""
    string c = s <= 300 ? "D" : s <= 1800 ? "W" : s <= 14400 ? "M" : ""
    which == 1 ? a : which == 2 ? b : c
 
// Timeframe names for the tags (Daily : 13, H4 : 7)
f_tfName(string tf) =>
    int s = timeframe.in_seconds(tf)
    s >= 2419200 ? "Monthly" : s >= 604800 ? "Weekly" : s >= 86400 ? "Daily" : s >= 3600 ? "H" + str.tostring(s / 3600.0, "#.#") : "M" + str.tostring(s / 60.0, "#.#")
 
// Session of a bar time, New York hours
f_session(int t) =>
    int h = hour(t, "America/New_York")
    h >= 19 or h < 2 ? "Asia" : h < 8 ? "London" : h < 17 ? "New York" : "NY close"
 
f_style() =>
    int s = timeframe.in_seconds(timeframe.period)
    s <= 60 ? "Scalps" : s <= 300 ? "Scalps / Daytrades" : s <= 1800 ? "Daytrades / Short term" : s <= 3600 ? "Short term" : s <= 14400 ? "Swing" : s <= 86400 ? "Swing / Position" : "Position"
 
// Strict counting rule. Candle "1" is the extreme candle when it closes with the
// count or is a doji; otherwise it is the first candle after it that does
// ("Bearish closed candles are ignored in bullish countings" and the mirror).
// The extreme sits at offset `off`. na when no candle up to this bar qualifies yet.
f_one(int dir, int off, float dj) =>
    int one = na
    for i = off to 0
        if na(one)
            float rng   = high[i] - low[i]
            bool  doji  = rng <= 0 or math.abs(close[i] - open[i]) <= rng * dj / 100.0
            bool  inDir = dir == 1 ? close[i] > open[i] : close[i] < open[i]
            if inDir or doji
                one := bar_index - i
    one
 
// True when this bar closes with the count or is a doji (counted candle)
f_with(int dir, float dj) =>
    float rng = high - low
    rng <= 0 or math.abs(close - open) <= rng * dj / 100.0 or (dir == 1 ? close > open : close < open)
 
// A count keeps running from its extreme until price makes a new extreme beyond
// it or the count (n) passes the end of the cycle.
f_restart(float newP, float extP, int n, int dir, int mx) =>
    na(n) or (dir == -1 ? newP > extP : newP < extP) or n > mx
 
// Candles of finished consolidations inside [a, b]. Intervals are in time order,
// so the walk goes back from the newest and stops at the first one before a.
f_ovl(array<int> cs, array<int> ce, int a, int b) =>
    int n  = 0
    int sz = cs.size()
    if b >= a and sz > 0
        for i = sz - 1 to 0
            int en = ce.get(i)
            if en < a
                break
            int lo = math.max(a, cs.get(i))
            int hi = math.min(b, en)
            if hi >= lo
                n += hi - lo + 1
    n
 
// Distorted candles to leave out of a count that started after zero bar z and is
// read at bar `at` (finished consolidations plus the one in progress)
f_skip(bool on, array<int> cs, array<int> ce, bool inC, int cSt, int z, int at) =>
    int n = 0
    if on and not na(z)
        n := f_ovl(cs, ce, z + 1, at)
        if inC and at >= cSt
            n += math.max(0, at - math.max(cSt, z + 1) + 1)
    n
 
// Count number at bar `at` for zero bar z
f_num0(bool on, array<int> cs, array<int> ce, bool inC, int cSt, int z, int at) =>
    na(z) ? int(na) : at - z - f_skip(on, cs, ce, inC, cSt, z, at)
 
// The swing at offset `off` is the clear extreme of the running leg: no high
// (dir -1) or low (dir 1) between the leg start z and the swing goes beyond it.
f_clear(int dir, int off, int z, float p) =>
    bool ok = true
    if not na(z)
        int last = math.min(bar_index - z - 1, off + 300)
        if last >= off + 1
            for i = off + 1 to last
                if dir == -1 ? high[i] > p : low[i] < p
                    ok := false
                    break
    ok
 
// Counting engine, shared by the chart and the higher timeframes.
// Keeps the zero bar (candle before "1") of the bullish and bearish counts, the
// previous count of each side (second count) and the events of this bar. Only
// confirmed bars inside the calculation depth change the state, so the result
// does not depend on how much history is loaded. With skOn, candles inside
// consolidations are left out of every count (time distortion).
f_core(int R, float dj, int mx, bool cOn, int cLen, float cMul, float kHi, float kLo, bool kOn, bool rOn, string rStr, bool skOn, int depth) =>
    bool  ok  = barstate.isconfirmed and last_bar_index - bar_index < depth
    float hp  = ta.pivothigh(high, R, R)
    float lp  = ta.pivotlow(low, R, R)
    float at  = ta.atr(14)
    float rHi = ta.highest(high, cLen)
    float rLo = ta.lowest(low, cLen)
    var array<int> rv = f_parse(rStr)
    var array<int> cs = array.new<int>()
    var array<int> ce = array.new<int>()
    var float pH  = na
    var float pL  = na
    var int   bZ  = na
    var int   sZ  = na
    var int   bZ2 = na
    var int   sZ2 = na
    var float bP  = na
    var float sP  = na
    var bool  inC = false
    var float cHi = na
    var float cLo = na
    var int   cSt = na
    var int   brk = na
    var int   oSt = na
    var int   oEn = na
    var int   pend = 0
    // A count whose candle 1 has not closed yet (strict rule): price, extreme bar,
    // reversal and key level flags wait here until the first counted candle
    var bool  wS  = false
    var float wSP = na
    var int   wSX = na
    var bool  wSR = false
    var bool  wSK = false
    var bool  wB  = false
    var float wBP = na
    var int   wBX = na
    var bool  wBR = false
    var bool  wBK = false
    bool hh   = false
    bool ll   = false
    bool newB = false
    bool newS = false
    bool expB = false
    bool expS = false
    bool revB = false
    bool revS = false
    bool klB  = false
    bool klS  = false
    bool swH  = false
    bool swL  = false
    int  bXi  = na
    int  sXi  = na
    int  cLn  = na
    int  bEx  = na
    int  sEx  = na
    int  b2Ex = na
    int  s2Ex = na
    if ok
        // Consolidation: time is distorted, its candles are not counted.
        // It ends on any close beyond the box; the expansion count starts at the
        // first candle beyond the box that closes in the breakout direction.
        if cOn
            if inC
                if close > cHi or close < cLo
                    int d = close > cHi ? 1 : -1
                    inC  := false
                    cLn  := bar_index - cSt
                    brk  := bar_index
                    oSt  := cSt
                    oEn  := bar_index - 1
                    pend := d
                    cs.push(oSt)
                    ce.push(oEn)
                    if cs.size() > 60
                        cs.shift()
                        ce.shift()
            else if not na(at) and rHi - rLo <= cMul * at and (na(brk) or bar_index - cLen + 1 > brk)
                inC := true
                cHi := rHi
                cLo := rLo
                cSt := bar_index - cLen + 1
            if pend == 1
                if close > cHi and close > open
                    expB := true
                    pend := 0
                else if close <= cHi
                    pend := 0
            else if pend == -1
                if close < cLo and close < open
                    expS := true
                    pend := 0
                else if close >= cLo
                    pend := 0
        hh  := not na(hp) and not na(pH) and hp > pH
        ll  := not na(lp) and not na(pL) and lp < pL
        swH := hh and not na(kHi[R]) and high[R] > kHi[R]
        swL := ll and not na(kLo[R]) and low[R] < kLo[R]
        int  ex     = bar_index - R
        bool inside = (inC and ex >= cSt) or (not na(oEn) and ex >= oSt and ex <= oEn)
        // Counts on the swing bar, before this bar changes them
        bEx  := f_num0(skOn, cs, ce, inC, cSt, bZ, ex)
        sEx  := f_num0(skOn, cs, ce, inC, cSt, sZ, ex)
        b2Ex := f_num0(skOn, cs, ce, inC, cSt, bZ2, ex)
        s2Ex := f_num0(skOn, cs, ce, inC, cSt, sZ2, ex)
        int bNow = f_num0(skOn, cs, ce, inC, cSt, bZ, bar_index)
        int sNow = f_num0(skOn, cs, ce, inC, cSt, sZ, bar_index)
        // A waiting count starts on its first counted candle
        if wS and f_with(-1, dj)
            sZ2  := sZ
            sZ   := bar_index - 1
            sP   := wSP
            sXi  := wSX
            revS := wSR
            klS  := wSK
            newS := true
            wS   := false
        if wB and f_with(1, dj)
            bZ2  := bZ
            bZ   := bar_index - 1
            bP   := wBP
            bXi  := wBX
            revB := wBR
            klB  := wBK
            newB := true
            wB   := false
        // A swing on a significant number of the running count is a
        // reversal, and the count starts again from it in the other direction.
        // Only the clear extreme of the running leg counts as that reversal.
        bool topRev = rOn and not na(hp) and not na(bEx) and rv.includes(bEx) and f_clear(-1, R, bZ, hp)
        bool botRev = rOn and not na(lp) and not na(sEx) and rv.includes(sEx) and f_clear(1, R, sZ, lp)
        if not inside and ((hh and (not kOn or swH) and f_restart(hp, sP, sNow, -1, mx)) or topRev)
            int one = f_one(-1, R, dj)
            bool rv1 = topRev and not hh
            if na(one)
                wS  := true
                wSP := hp
                wSX := ex
                wSR := rv1
                wSK := swH
            else
                sZ2  := sZ
                sZ   := one - 1
                sP   := hp
                sXi  := ex
                revS := rv1
                klS  := swH
                newS := true
                wS   := false
        if not inside and ((ll and (not kOn or swL) and f_restart(lp, bP, bNow, 1, mx)) or botRev)
            int one = f_one(1, R, dj)
            bool rv1 = botRev and not ll
            if na(one)
                wB  := true
                wBP := lp
                wBX := ex
                wBR := rv1
                wBK := swL
            else
                bZ2  := bZ
                bZ   := one - 1
                bP   := lp
                bXi  := ex
                revB := rv1
                klB  := swL
                newB := true
                wB   := false
        // The candle that leaves the consolidation is candle 1 of the expansion count
        if expB
            if not newB
                bZ2 := bZ
            bZ   := bar_index - 1
            bP   := cLo
            bXi  := bar_index
            newB := true
            revB := false
            klB  := false
            wB   := false
        if expS
            if not newS
                sZ2 := sZ
            sZ   := bar_index - 1
            sP   := cHi
            sXi  := bar_index
            newS := true
            revS := false
            klS  := false
            wS   := false
        if not na(hp)
            pH := hp
        if not na(lp)
            pL := lp
    // Running counts on this bar; a second count lives until its cycle ends
    int bN  = f_num0(skOn, cs, ce, inC, cSt, bZ, bar_index)
    int sN  = f_num0(skOn, cs, ce, inC, cSt, sZ, bar_index)
    int bN2 = f_num0(skOn, cs, ce, inC, cSt, bZ2, bar_index)
    int sN2 = f_num0(skOn, cs, ce, inC, cSt, sZ2, bar_index)
    bN2 := not na(bN2) and bN2 <= mx ? bN2 : na
    sN2 := not na(sN2) and sN2 <= mx ? sN2 : na
    [bZ, sZ, bP, sP, newB, newS, expB, expS, hh, ll, hp, lp, swH, swL, cHi, cLo, cSt, cLn, inC, revB, revS, bN, sN, bN2, sN2, bEx, sEx, b2Ex, s2Ex, bXi, sXi, klB, klS]
 
// Higher timeframe: confirmed counts (previous HTF bar, +1 for the bar in
// progress), confirmed zero bars and the index of the HTF bar in progress.
f_htf(int R, float dj, int mx, bool cOn, int cLen, float cMul, bool rOn, string rStr, bool skOn, int depth) =>
    [bZ, sZ, bP, sP, nB, nS, eB, eS, hh, ll, hp, lp, swH, swL, cHi, cLo, cSt, cLn, inC, rB, rS, bN, sN, bN2, sN2, bEx, sEx, b2Ex, s2Ex, bXi, sXi, klB, klS] = f_core(R, dj, mx, cOn, cLen, cMul, float(na), float(na), false, rOn, rStr, skOn, depth)
    [bZ[1], sZ[1], bar_index, bN[1], sN[1]]
 
f_levels() =>
    array<int>   v = array.new<int>()
    array<color> c = array.new<color>()
    if preset == P_TPL
        if t1On
            v.push(t1V)
            c.push(f_fg(t1C))
        if t2On
            v.push(t2V)
            c.push(f_fg(t2C))
        if t3On
            v.push(t3V)
            c.push(f_fg(t3C))
        if t4On
            v.push(t4V)
            c.push(f_fg(t4C))
        if t5On
            v.push(t5V)
            c.push(f_fg(t5C))
        if t6On
            v.push(t6V)
            c.push(f_fg(t6C))
        if t7On
            v.push(t7V)
            c.push(f_fg(t7C))
        int n = v.size()
        if n > 1
            for i = 0 to n - 2
                for j = 0 to n - 2 - i
                    if v.get(j) > v.get(j + 1)
                        int tv = v.get(j)
                        v.set(j, v.get(j + 1))
                        v.set(j + 1, tv)
                        color tc = c.get(j)
                        c.set(j, c.get(j + 1))
                        c.set(j + 1, tc)
    else
        array<int> seq = preset == P_BAS ? array.from(0, 1, 3, 7, 13, 17, 21, 31) : preset == P_REV ? array.from(0, 1, 3, 7, 13, 21, 31) : preset == P_2ND ? array.from(0, 1, 5, 9, 17, 25, 37) : array.from(0, 1, 3, 6, 9, 15, 24, 39)
        array<int> hot = preset == P_BAS ? array.from(21) : preset == P_REV ? array.from(7, 13, 21) : array.new<int>()
        for x in seq
            v.push(x)
            c.push(hot.includes(x) ? f_fg(t6C) : chart.fg_color)
    [v, c]
 
f_ftzColor(int n) =>
    color c = #4A57F5
    if n == 0
        c := chart.fg_color
    else if n == 5 or n == 7
        c := #F7EB4C
    else if n == 13
        c := #F23A6A
    ftzOne ? ftzCol : c
 
// Market phases by candle count: retracements take 3-4 candles, expansions 4-7,
// reversals 7, 13 or 21. Consolidations (10 / 20) are read from the box itself.
f_phase(int n) =>
    string p = ""
    if n == 3
        p := "Retracement (3-4)"
    else if n == 4
        p := "Retracement ends / expansion (4)"
    else if n == 7
        p := "Expansion ends / reversal (7)"
    else if n == 13
        p := "Reversal (13)"
    else if n == 21
        p := "Reversal, cycle ends (21)"
    p
 
method clear(Strip s) =>
    for b in s.bxs
        b.delete()
    for l in s.lns
        l.delete()
    for t in s.lbs
        t.delete()
    s.sLine.delete()
 
method draw(Strip s, array<int> lv, array<color> lc, array<color> pal, string lsz) =>
    float a     = s.a
    float inner = s.dir == 1 ? s.extP - stripGap * a : s.extP + (stripGap + 0.45) * a
    float outer = s.dir == 1 ? inner - stripH * a : inner + stripH * a
    float top   = math.max(inner, outer)
    float bot   = math.min(inner, outer)
    s.lblY := bot
    int n = lv.size()
    if n > 0
        for k = 0 to n - 1
            int   x  = s.zero + lv.get(k)
            color cl = lc.get(k)
            if k > 0
                s.bxs.push(box.new(s.zero + lv.get(k - 1), top, x, bot, border_color = color(na), border_width = 0, bgcolor = color.new(pal.get((k - 1) % pal.size()), fillTr)))
            s.lns.push(line.new(x, top, x, bot, color = cl, width = 2))
            // "0" is hidden next to a "1" and on the extreme bar, where [HH] / [LL] sits
            bool hideLbl = lv.get(k) == 0 and ((k + 1 < n and lv.get(k + 1) == 1) or s.zero == s.ext)
            label lb = na
            if not hideLbl
                lb := label.new(x, bot, str.tostring(lv.get(k)), color = color(na), style = label.style_label_up, textcolor = cl, size = lsz)
            s.lbs.push(lb)
 
// With skipped consolidation candles, the levels still ahead move right so each
// level, and its reversal time line, sits on the candle where the count reaches it
method shift(Strip s, array<int> lv, int nNow, array<int> nums, array<line> vl) =>
    int n = lv.size()
    if n > 0 and not na(nNow) and s.lns.size() >= n
        for k = 0 to n - 1
            int L = lv.get(k)
            if L >= nNow
                int x = bar_index + L - nNow
                s.lns.get(k).set_x1(x)
                s.lns.get(k).set_x2(x)
                label lb = s.lbs.get(k)
                if not na(lb)
                    lb.set_x(x)
                if k > 0
                    s.bxs.get(k - 1).set_right(x)
                if k < n - 1
                    s.bxs.get(k).set_left(x)
    int m   = showRev ? nums.size() : 0
    int i90 = m
    if not na(nNow) and vl.size() >= m
        if m > 0
            for [i, v] in nums
                if v >= nNow
                    int x = bar_index + v - nNow
                    vl.get(i).set_x1(x)
                    vl.get(i).set_x2(x)
        if show90 and vl.size() > i90 and 90 >= nNow
            int x = bar_index + 90 - nNow
            vl.get(i90).set_x1(x)
            vl.get(i90).set_x2(x)
 
f_vlines(Strip s, array<int> nums, array<line> store, array<label> tstore) =>
    if showRev
        for v in nums
            store.push(line.new(s.zero + v, s.extP, s.zero + v, s.extP + s.a, extend = extend.both, color = revCol, width = 1))
    if show90
        store.push(line.new(s.zero + 90, s.extP, s.zero + 90, s.extP + s.a, extend = extend.both, color = c90Col, width = 1, style = line.style_dashed))
        tstore.push(label.new(s.zero + 90, s.lblY, "90", color = color(na), style = label.style_label_up, textcolor = c90Col, size = size.small))
 
f_clearL(array<line> ls, array<label> ts) =>
    for l in ls
        l.delete()
    for t in ts
        t.delete()
    ls.clear()
    ts.clear()
 
// Count number on a turning point, drawn as a small callout
f_num(int x, float y, string txt, color col, bool isTop) =>
    bool   call = swStyle == S_CALL
    string st   = isTop ? label.style_label_down : label.style_label_up
    label.new(x, y, txt, color = call ? color.new(#FFFFFF, 0) : color(na), style = call ? st : label.style_none, textcolor = col, size = size.small)
 
f_callText(array<string> names, array<int> nums) =>
    array<int> uniq = array.new<int>()
    for v in nums
        if not uniq.includes(v)
            uniq.push(v)
    string out = ""
    for u in uniq
        string g = ""
        for [i, v] in nums
            if v == u
                g := g == "" ? names.get(i) : g + " / " + names.get(i)
        string seg = uniq.size() == 1 ? g + "\n" + str.tostring(u) : g + "  " + str.tostring(u)
        out := out == "" ? seg : out + "\n" + seg
    out
 
// =============================================================================
// STATE
// =============================================================================
var array<int>    revNums  = f_parse(revStr)
var array<int>    ftzNums  = f_parse(ftzStr)
var array<int>    keyNums  = f_parse(keyStr)
var array<int>    alrNums  = f_parse(alertStr)
// Numbers written on turning points: the reversal points 7, 13, 21 and 31, plus
// any other sequence number switched on in the settings
f_swSet() =>
    array<int> a = array.new<int>()
    if sw7
        a.push(7)
    if sw13
        a.push(13)
    if sw21
        a.push(21)
    if sw31
        a.push(31)
    if sw3
        a.push(3)
    if sw4
        a.push(4)
    if sw5
        a.push(5)
    if sw9
        a.push(9)
    if sw11
        a.push(11)
    if sw17
        a.push(17)
    if sw20
        a.push(20)
    if sw25
        a.push(25)
    a
var array<int>    swNums   = f_swSet()
var array<color>  pal      = array.from(pal1, pal2, pal3, pal4, pal5, pal6)
var array<Strip>  bullHist = array.new<Strip>()
var array<Strip>  bearHist = array.new<Strip>()
var Strip         bullS    = na
var Strip         bearS    = na
var array<line>   vBull    = array.new<line>()
var array<label>  tBull    = array.new<label>()
var array<line>   vBear    = array.new<line>()
var array<label>  tBear    = array.new<label>()
var array<line>   ftzL     = array.new<line>()
var array<label>  ftzT     = array.new<label>()
var array<label>  swLbls   = array.new<label>()
var array<label>  callLbls = array.new<label>()
var array<box>    consBxs  = array.new<box>()
var box           consCur  = na
 
// Last swing high / low: the structure level (dotted line) of the next count
var float lastPH  = na
var int   lastPHi = na
var float lastPL  = na
var int   lastPLi = na
 
var array<int>   lv = array.new<int>()
var array<color> lc = array.new<color>()
if barstate.isfirst
    [v0, c0] = f_levels()
    lv := v0
    lc := c0
 
string lsz   = f_size(lblSizeS)
float  atr   = ta.atr(14)
bool   conf  = barstate.isconfirmed
int    chSec = timeframe.in_seconds(timeframe.period)
string chLbl = f_tfLabel(timeframe.period)
 
// =============================================================================
// COUNTING ENGINE ON THE CHART
// =============================================================================
bool klOn = timeframe.in_seconds(klTF) > chSec
[kH, kL] = request.security(syminfo.tickerid, klTF, [high[1], low[1]], lookahead = barmerge.lookahead_on)
 
[bZ, sZ, bP, sP, newBull, newBear, expB, expS, isHH, isLL, ph, pl, sweptH, sweptL, cHi, cLo, cSt, cLn, inCons, revB, revS, bN, sN, bN2, sN2, bEx, sEx, b2Ex, s2Ex, bXi, sXi, klB, klS] = f_core(fracLen, dojiPct, cycleEnd, useCons, consLen, consMult, klOn ? kH : na, klOn ? kL : na, klFilter and klOn, revOn, revAt, xSkip, calcDepth)
 
int   E  = bar_index - fracLen
float aE = nz(atr[fracLen], nz(atr, high - low))
 
plotshape(showFr and isHH, "[HH]", shape.square, location.abovebar, sweptH ? sweepCol : hhCol, offset = -fracLen, text = "[HH]", textcolor = sweptH ? sweepCol : hhCol, size = size.tiny)
plotshape(showFr and isLL, "[LL]", shape.square, location.belowbar, sweptL ? sweepCol : llCol, offset = -fracLen, text = "[LL]", textcolor = sweptL ? sweepCol : llCol, size = size.tiny)
 
var line  klHi  = na
var line  klLo  = na
var label klHiT = na
var label klLoT = na
if showKL and klOn
    bool newKL = kH != kH[1] or kL != kL[1] or na(klHi)
    if newKL and not na(kH)
        klHi.delete()
        klLo.delete()
        klHiT.delete()
        klLoT.delete()
        klHi  := line.new(bar_index, kH, bar_index + 5, kH, color = klCol, width = 1)
        klLo  := line.new(bar_index, kL, bar_index + 5, kL, color = klCol, width = 1)
        klHiT := label.new(bar_index + 5, kH, "KEY LEVEL", color = color(na), style = label.style_label_left, textcolor = klCol, size = size.small)
        klLoT := label.new(bar_index + 5, kL, "KEY LEVEL", color = color(na), style = label.style_label_left, textcolor = klCol, size = size.small)
    else if not na(klHi)
        klHi.set_x2(bar_index + 5)
        klLo.set_x2(bar_index + 5)
        klHiT.set_x(bar_index + 5)
        klLoT.set_x(bar_index + 5)
 
// Consolidation boxes (time distortion)
if showCons and useCons and conf and drawOK
    if inCons and na(consCur)
        consCur := box.new(cSt, cHi, bar_index, cLo, border_color = color.new(consCol, 40), bgcolor = consCol, text_color = color.new(chart.fg_color, 30), text_size = size.small, text_halign = text.align_left, text_valign = text.align_top)
    else if inCons
        consCur.set_right(bar_index)
    if not na(cLn) and not na(consCur)
        consCur.set_right(bar_index - 1)
        bool gear = cLn == 7 or cLn == 13
        consCur.set_text(str.tostring(cLn) + (gear ? "  gear change" : ""))
        consBxs.push(consCur)
        consCur := na
        if consBxs.size() > 30
            consBxs.shift().delete()
 
// Higher timeframes (needed by the count numbers below)
bool   autoTF = htfMode == M_AUTO
string h1TF   = autoTF ? f_autoTF(1) : h1In
string h2TF   = autoTF ? f_autoTF(2) : h2In
string h3TF   = autoTF ? f_autoTF(3) : h3In
bool   h1Ok   = (autoTF or useH1) and h1TF != "" and timeframe.in_seconds(h1TF) > chSec
bool   h2Ok   = (autoTF or useH2) and h2TF != "" and timeframe.in_seconds(h2TF) > chSec and h2TF != h1TF
bool   h3Ok   = xHtf3 and (autoTF or useH3) and h3TF != "" and timeframe.in_seconds(h3TF) > chSec and h3TF != h1TF and h3TF != h2TF
[h1B, h1S, h1I, h1Bn, h1Sn] = request.security(syminfo.tickerid, h1TF, f_htf(fracLen, dojiPct, cycleEnd, useCons, consLen, consMult, revOn, revAt, xSkip, calcDepth), lookahead = barmerge.lookahead_on)
[h2B, h2S, h2I, h2Bn, h2Sn] = request.security(syminfo.tickerid, h2TF, f_htf(fracLen, dojiPct, cycleEnd, useCons, consLen, consMult, revOn, revAt, xSkip, calcDepth), lookahead = barmerge.lookahead_on)
[h3B, h3S, h3I, h3Bn, h3Sn] = request.security(syminfo.tickerid, h3TF, f_htf(fracLen, dojiPct, cycleEnd, useCons, consLen, consMult, revOn, revAt, xSkip, calcDepth), lookahead = barmerge.lookahead_on)
// Count of the HTF candle in progress = confirmed count of the previous one + 1
int  h1Bull = h1Ok and not na(h1Bn) ? h1Bn + 1 : na
int  h1Bear = h1Ok and not na(h1Sn) ? h1Sn + 1 : na
int  h2Bull = h2Ok and not na(h2Bn) ? h2Bn + 1 : na
int  h2Bear = h2Ok and not na(h2Sn) ? h2Sn + 1 : na
int  h3Bull = h3Ok and not na(h3Bn) ? h3Bn + 1 : na
int  h3Bear = h3Ok and not na(h3Sn) ? h3Sn + 1 : na
bool newH1  = h1Ok and h1I != h1I[1]
bool newH2  = h2Ok and h2I != h2I[1]
bool newH3  = h3Ok and h3I != h3I[1]
string h1Lbl = h1Ok ? f_tfLabel(h1TF) : "-"
string h2Lbl = h2Ok ? f_tfLabel(h2TF) : "-"
string h3Lbl = h3Ok ? f_tfLabel(h3TF) : "-"
 
// Count numbers with the trend: the direction of the most recent count on the
// chosen higher timeframe (the bias comes from the higher timeframes)
int trDir = 0
if swTrend == T_H1 and h1Ok and not (na(h1B) and na(h1S))
    trDir := na(h1S) or (not na(h1B) and h1B >= h1S) ? 1 : -1
else if swTrend == T_H2 and h2Ok and not (na(h2B) and na(h2S))
    trDir := na(h2S) or (not na(h2B) and h2B >= h2S) ? 1 : -1
bool bullLblOk = trDir != -1
bool bearLblOk = trDir != 1
 
// =============================================================================
// TDT TYPES: count numbers on turning points (counts running before this swing)
// =============================================================================
f_swing(int x, float y, int n, color col, bool isTop) =>
    swLbls.push(f_num(x, y, str.tostring(n), col, isTop))
    if swLbls.size() > 200
        swLbls.shift().delete()
 
// Writes the numbers of up to four counts on one swing, stacked; returns how many
f_swingSet(float y0, bool isTop, int n1, color c1, int n2, color c2, int n3, color c3, int n4, color c4) =>
    float y    = y0
    float step = (isTop ? 0.6 : -0.6) * aE
    int   used = 0
    if not na(n1) and f_has(swNums, n1)
        f_swing(E, y, n1, c1, isTop)
        y += step
        used += 1
    if not na(n2) and f_has(swNums, n2)
        f_swing(E, y, n2, c2, isTop)
        y += step
        used += 1
    if not na(n3) and f_has(swNums, n3)
        f_swing(E, y, n3, c3, isTop)
        y += step
        used += 1
    if not na(n4) and f_has(swNums, n4)
        f_swing(E, y, n4, c4, isTop)
        used += 1
    used
 
int topUsed = 0
int botUsed = 0
if showSw and conf and drawOK
    int  ob     = bZ[1]
    int  os     = sZ[1]
    bool both   = swWhich == W_BOTH
    bool bullOn = both or na(os) or (not na(ob) and ob >= os)
    bool bearOn = both or not bullOn
    if trDir != 0
        bullOn := trDir == 1
        bearOn := trDir == -1
    int  nb  = bullOn ? bEx : na
    int  ns  = bearOn ? sEx : na
    int  nb2 = xTwo and bullOn and not na(b2Ex) and b2Ex <= cycleEnd ? b2Ex : na
    int  ns2 = xTwo and bearOn and not na(s2Ex) and s2Ex <= cycleEnd ? s2Ex : na
    if not na(ph)
        topUsed := f_swingSet(ph + 0.9 * aE, true, nb, swBull, ns, swBear, nb2, swAlt, ns2, swAlt)
    if not na(pl)
        botUsed := f_swingSet(pl - 0.9 * aE, false, ns, swBear, nb, swBull, ns2, swAlt, nb2, swAlt)
 
// =============================================================================
// NEW COUNTS
// =============================================================================
if newBear
    if not na(bearS) and not bearS.conf
        bearS.sLine.delete()
    int   ext  = sXi
    float lvl  = expS ? na : lastPL
    Strip s = Strip.new(-1, ext, sP, sZ, aE, klS, expS, lvl, lastPLi, false, na, array.new<box>(), array.new<line>(), array.new<label>(), na, revS)
    bool show = showBear and drawOK
    if show
        s.draw(lv, lc, pal, lsz)
        if showSw
            float y1 = sP + (0.9 + 0.6 * (sXi == E ? topUsed : 0)) * aE
            if bearLblOk
                s.lbs.push(f_num(sZ + 1, y1, "1", swBear, true))
    if not na(lvl)
        if close < lvl
            s.conf := true
        else if showStr and show
            s.sLine := line.new(lastPLi, lvl, bar_index, lvl, color = strCol, style = line.style_dotted, width = 1)
    // Only drawn strips are kept; a hidden count has nothing to clean up
    if show
        bearHist.push(s)
        if bearHist.size() > histN
            bearHist.shift().clear()
    bearS := s
    f_clearL(vBear, tBear)
    if show and (showRev or show90)
        f_vlines(s, revNums, vBear, tBear)
 
if newBull
    if not na(bullS) and not bullS.conf
        bullS.sLine.delete()
    int   ext  = bXi
    float lvl  = expB ? na : lastPH
    Strip s = Strip.new(1, ext, bP, bZ, aE, klB, expB, lvl, lastPHi, false, na, array.new<box>(), array.new<line>(), array.new<label>(), na, revB)
    bool show = showBull and drawOK
    if show
        s.draw(lv, lc, pal, lsz)
        if showSw
            // Below the strip numbers so the box does not cover them
            float y1 = math.min(s.lblY - 0.75 * aE, bP - (0.9 + 0.6 * (bXi == E ? botUsed : 0)) * aE)
            if bullLblOk
                s.lbs.push(f_num(bZ + 1, y1, "1", swBull, false))
    if not na(lvl)
        if close > lvl
            s.conf := true
        else if showStr and show
            s.sLine := line.new(lastPHi, lvl, bar_index, lvl, color = strCol, style = line.style_dotted, width = 1)
    // Only drawn strips are kept; a hidden count has nothing to clean up
    if show
        bullHist.push(s)
        if bullHist.size() > histN
            bullHist.shift().clear()
    bullS := s
    f_clearL(vBull, tBull)
    if show and (showRev or show90)
        f_vlines(s, revNums, vBull, tBull)
 
if xSkip and conf and drawOK
    if not na(bullS) and bullS.zero == bZ
        bullS.shift(lv, bN, revNums, vBull)
    if not na(bearS) and bearS.zero == sZ
        bearS.shift(lv, sN, revNums, vBear)
 
// Fib time zone on the most recent count
bool ftzBull = newBull and showBull and drawOK
bool ftzBear = newBear and showBear and drawOK
if showFtz and (ftzBull or ftzBear)
    Strip f = ftzBull and (not ftzBear or bullS.zero >= bearS.zero) ? bullS : bearS
    f_clearL(ftzL, ftzT)
    // Labels sit on the far side of the strip: below a bullish count, above a bearish one
    float fy = f.dir == 1 ? f.extP - 1.6 * f.a : f.extP + 1.6 * f.a
    for v in ftzNums
        color fc = f_ftzColor(v)
        ftzL.push(line.new(f.zero + v, f.extP, f.zero + v, f.extP + f.a, extend = extend.both, color = fc, width = v == 0 ? 2 : 1))
        ftzT.push(label.new(f.zero + v, fy, str.tostring(v), color = color(na), style = label.style_label_left, textcolor = fc, size = size.small))
 
if conf
    if not na(ph)
        lastPH  := ph
        lastPHi := E
    if not na(pl)
        lastPL  := pl
        lastPLi := E
 
// Structure shift: the dotted level breaks on a close (tracked even when the
// dotted line itself is hidden)
if conf and not na(bearS) and not bearS.conf and not na(bearS.sLvl)
    bearS.sLine.set_x2(bar_index)
    if close < bearS.sLvl
        bearS.conf := true
if conf and not na(bullS) and not bullS.conf and not na(bullS.sLvl)
    bullS.sLine.set_x2(bar_index)
    if close > bullS.sLvl
        bullS.conf := true
 
// =============================================================================
// COUNTS
// =============================================================================
int bullN  = bN
int bearN  = sN
int bullN2 = xTwo ? bN2 : na
int bearN2 = xTwo ? sN2 : na
 
 
// =============================================================================
// HTF COUNT LINES: a vertical line and a tag ("Daily : 13") where a
// higher timeframe count lands on a key number
// =============================================================================
var array<line>  htfLines = array.new<line>()
var array<label> htfTags  = array.new<label>()
f_htfMark(bool isNew, int nb, int ns, string tf, int slot) =>
    bool hb = isNew and f_has(keyNums, nb)
    bool hs = isNew and f_has(keyNums, ns)
    if hb or hs
        string nums = hb and hs ? str.tostring(nb) + " / " + str.tostring(ns) : hb ? str.tostring(nb) : str.tostring(ns)
        htfLines.push(line.new(bar_index, low, bar_index, high, extend = extend.both, color = htfLnCol, style = line.style_dashed, width = 1))
        htfTags.push(label.new(bar_index, low - (1.2 + 0.8 * slot) * nz(atr, high - low), f_tfName(tf) + " : " + nums, color = color.white, style = label.style_label_up, textcolor = htfLnCol, size = size.small))
        if htfLines.size() > 60
            htfLines.shift().delete()
            htfTags.shift().delete()
    hb or hs
 
bool htfMarked = false
if xLine and conf and drawOK
    bool m1 = f_htfMark(newH1, h1Bull, h1Bear, h1TF, 0)
    bool m2 = f_htfMark(newH2, h2Bull, h2Bear, h2TF, m1 ? 1 : 0)
    bool m3 = f_htfMark(newH3, h3Bull, h3Bear, h3TF, (m1 ? 1 : 0) + (m2 ? 1 : 0))
    htfMarked := m1 or m2 or m3
 
// =============================================================================
// PREVIOUS DAY HIGH / LOW SESSION: which session made yesterday's high and low
// =============================================================================
var float dHi = na
var float dLo = na
var int   dHiB = na
var int   dLoB = na
var int   dHiT = na
var int   dLoT = na
var string pdSess = "-"
var array<label> sessTags = array.new<label>()
bool intraday = chSec < 86400
// Only markets that trade through Asia, London and New York: a single exchange
// session (stocks, cash indices) has no Asia candles, so the split says nothing
var bool seesAsia = false
if intraday and not seesAsia and f_session(time) == "Asia"
    seesAsia := true
bool sessOk = intraday and seesAsia
bool newDay   = timeframe.change("D")
if sessOk and newDay
    if not na(dHi)
        string sH = f_session(dHiT)
        string sL = f_session(dLoT)
        pdSess := "H " + sH + "  |  L " + sL
        if xSess and drawOK
            sessTags.push(label.new(dHiB, dHi, "PDH " + sH, color = color(na), style = label.style_label_down, textcolor = sessCol, size = size.tiny))
            sessTags.push(label.new(dLoB, dLo, "PDL " + sL, color = color(na), style = label.style_label_up, textcolor = sessCol, size = size.tiny))
            if sessTags.size() > 20
                sessTags.shift().delete()
                sessTags.shift().delete()
    dHi  := high
    dLo  := low
    dHiB := bar_index
    dLoB := bar_index
    dHiT := time
    dLoT := time
else if sessOk
    if na(dHi) or high > dHi
        dHi  := high
        dHiB := bar_index
        dHiT := time
    if na(dLo) or low < dLo
        dLo  := low
        dLoB := bar_index
        dLoT := time
 
// =============================================================================
// TIME ALIGNMENT CALLOUTS
// A bullish count (from a low) on a key number looks for a top, a bearish one
// (from a high) for a bottom.
// =============================================================================
// Flags only (no allocation): trig = a higher timeframe candle opens on a key
// number, align = the chart count is on a key number while a higher timeframe is too
f_side(int cN, int b1, int b2, int b3, bool n1, bool n2, bool n3) =>
    bool chartHit = f_has(keyNums, cN)
    bool in1      = f_near(keyNums, b1, tol)
    bool in2      = f_near(keyNums, b2, tol)
    bool in3      = f_near(keyNums, b3, tol)
    bool trig     = (n1 and f_has(keyNums, b1)) or (n2 and f_has(keyNums, b2)) or (n3 and f_has(keyNums, b3))
    [trig, chartHit and (in1 or in2 or in3), chartHit, in1, in2, in3]
 
// Callout text, built only on the bars that need it
f_sideText(int cN, int b1, int b2, int b3, bool c0, bool c1, bool c2, bool c3) =>
    array<string> names = array.new<string>()
    array<int>    nums  = array.new<int>()
    if c0
        names.push(chLbl)
        nums.push(cN)
    if c1
        names.push(h1Lbl)
        nums.push(b1)
    if c2
        names.push(h2Lbl)
        nums.push(b2)
    if c3
        names.push(h3Lbl)
        nums.push(b3)
    f_callText(names, nums)
 
[topTrig, topAlign, topC0, topC1, topC2, topC3] = f_side(bullN, h1Bull, h2Bull, h3Bull, newH1, newH2, newH3)
[botTrig, botAlign, botC0, botC1, botC2, botC3] = f_side(bearN, h1Bear, h2Bear, h3Bear, newH1, newH2, newH3)
 
// A higher timeframe key hit is always shown. Alignment callouts: at most one per
// side for each candle of the first higher timeframe.
var int lastTopK = na
var int lastBotK = na
int  candleKey = h1Ok ? h1I : bar_index
bool topShow   = (topTrig and not htfMarked) or (topAlign and candleKey != lastTopK)
bool botShow   = (botTrig and not htfMarked) or (botAlign and candleKey != lastBotK)
if showCall and conf and drawOK
    if topShow
        string tt = f_sideText(bullN, h1Bull, h2Bull, h3Bull, topC0, topC1, topC2, topC3)
        callLbls.push(label.new(bar_index, high + 0.3 * nz(atr, high - low), tt, color = callCol, style = label.style_label_down, textcolor = color.white, size = size.small))
        lastTopK := candleKey
    if botShow
        string bt = f_sideText(bearN, h1Bear, h2Bear, h3Bear, botC0, botC1, botC2, botC3)
        callLbls.push(label.new(bar_index, low - 0.3 * nz(atr, high - low), bt, color = callCol, style = label.style_label_up, textcolor = color.white, size = size.small))
        lastBotK := candleKey
    while callLbls.size() > 80
        callLbls.shift().delete()
 
// =============================================================================
// ENTRY WINDOWS AND PHASES
// =============================================================================
var array<int>    wS = array.from(7, 12, 20, 31, 40, 90)
var array<int>    wE = array.from(8, 13, 21, 34, 42, 90)
var array<string> wT = array.from("FVG / OB", "Turtle soup or FVG / OB", "Turtle soup (best)", "FVG / OB", "Turtle soup (last shift)", "Long-term cycle change")
 
f_window(int n) =>
    int inW = -1
    int nxt = -1
    if not na(n)
        for [i, s] in wS
            if n >= s and n <= wE.get(i) and inW < 0
                inW := i
            if s > n and nxt < 0
                nxt := i
    [inW, nxt]
 
f_winText(int n) =>
    [inW, nxt] = f_window(n)
    string t = "-"
    if inW >= 0
        t := str.tostring(wS.get(inW)) + "-" + str.tostring(wE.get(inW)) + "  " + wT.get(inW)
    else if nxt >= 0
        t := "next " + str.tostring(wS.get(nxt)) + "-" + str.tostring(wE.get(nxt)) + " in " + str.tostring(wS.get(nxt) - n)
    [inW >= 0, t]
 
f_phaseText(int n) =>
    string t = "-"
    if not na(n)
        string p = f_phase(n)
        if p != ""
            t := p
        else
            array<int> pn = array.from(3, 4, 7, 13, 21)
            for v in pn
                if v > n and t == "-"
                    t := f_phase(v) + " in " + str.tostring(v - n)
    t
 
f_nextLevel(int n) =>
    string t = "-"
    if not na(n)
        for v in lv
            if v > n and t == "-"
                t := str.tostring(v) + " in " + str.tostring(v - n)
    t
 
[bullInW, bullWinT] = f_winText(bullN)
[bearInW, bearWinT] = f_winText(bearN)
bool latestIsBull = not na(bZ) and (na(sZ) or bZ >= sZ)
bool latestInW    = latestIsBull ? bullInW : bearInW
bgcolor(showWinBg and latestInW ? winCol : na, title = "Entry window")
 
// =============================================================================
// DASHBOARD
// =============================================================================
f_pos(string p) =>
    p == D_BR ? position.bottom_right : p == D_TL ? position.top_left : p == D_BL ? position.bottom_left : position.top_right
 
var table dash = table.new(f_pos(dashPosS), 4, 14, bgcolor = color.new(#131722, 8), border_color = color.new(#787B86, 70), border_width = 1, frame_color = color.new(#787B86, 50), frame_width = 1)
 
// Scalp entries inside a higher timeframe retracement (7th-9th HTF
// candle), continuation entries after the 13th HTF candle confirms the reversal.
// Uses the most recent count of the first higher timeframe.
f_htfSetup(int nb, int ns, string lbl) =>
    string t = "-"
    if not na(nb) or not na(ns)
        bool   up = na(ns) or (not na(nb) and nb <= ns)
        int    n  = up ? nb : ns
        string hd = lbl + " " + str.tostring(n) + (up ? " from low: " : " from high: ")
        if n >= 7 and n <= 9
            t := hd + "scalp inside the retracement (7-9)"
        else if n >= 13 and n <= cycleEnd
            t := hd + "continuation after the 13th"
        else if n < 7
            t := hd + "retracement 7-9 in " + str.tostring(7 - n)
        else if n < 13
            t := hd + "13th confirms in " + str.tostring(13 - n)
        else
            t := hd + "cycle ended"
    t
 
// Stop loss guide by trade type (pips)
f_slGuide() =>
    int s = timeframe.in_seconds(timeframe.period)
    s <= 60 ? "Scalps: 10 pips minimum" : s <= 300 ? "Scalps 10 pips min  |  Daytrades 20-30 pips" : s <= 1800 ? "Daytrades 20-30  |  Short term 30-50 pips" : s <= 3600 ? "Short term 30-50 pips" : "-"
 
// Count text: "end" once the cycle is over (past the cycle end)
f_cnt(int n) =>
    na(n) ? "-" : n > cycleEnd ? str.tostring(n) + " end" : str.tostring(n)
 
// The most recent count gives the direction of that timeframe
f_latest(int b, int s) =>
    na(b) and na(s) ? "-" : na(s) or (not na(b) and b >= s) ? "Up" : "Down"
 
f_cell(int c, int r, string t, color tc, color bg, string sz) =>
    table.cell(dash, c, r, t, text_color = tc, bgcolor = bg, text_size = sz, text_halign = text.align_center)
 
// Count cell: the running count, its tag and the second count when shown
f_cntCell(int n, int n2, string tag) =>
    f_cnt(n) + tag + (not na(n2) ? "  (2nd " + str.tostring(n2) + ")" : "")
 
if showDash and barstate.islast
    string dsz = f_size(dashSzS)
    color  txt = #D1D4DC
    color  hdr = color.new(#2A98A6, 20)
    color  hot = color.new(#2A98A6, 55)
    color  non = color(na)
    table.cell(dash, 0, 0, "TDT  Time Dilation  |  " + f_style(), text_color = color.white, bgcolor = hdr, text_size = dsz)
    table.merge_cells(dash, 0, 0, 3, 0)
    f_cell(0, 1, "TF", txt, non, dsz)
    f_cell(1, 1, "Count from low", llCol, non, dsz)
    f_cell(2, 1, "Count from high", hhCol, non, dsz)
    f_cell(3, 1, "Latest", txt, non, dsz)
    string bullTag = na(bullS) ? "" : bullS.exp ? "  EXP" : bullS.rev ? "  REV" : bullS.kl ? "  KL" : ""
    string bearTag = na(bearS) ? "" : bearS.exp ? "  EXP" : bearS.rev ? "  REV" : bearS.kl ? "  KL" : ""
    f_cell(0, 2, chLbl, txt, non, dsz)
    f_cell(1, 2, f_cntCell(bullN, bullN2, bullTag), txt, f_has(keyNums, bullN) ? hot : non, dsz)
    f_cell(2, 2, f_cntCell(bearN, bearN2, bearTag), txt, f_has(keyNums, bearN) ? hot : non, dsz)
    f_cell(3, 2, f_latest(bZ, sZ), txt, non, dsz)
    f_cell(0, 3, h1Lbl, txt, non, dsz)
    f_cell(1, 3, f_cnt(h1Bull), txt, f_has(keyNums, h1Bull) ? hot : non, dsz)
    f_cell(2, 3, f_cnt(h1Bear), txt, f_has(keyNums, h1Bear) ? hot : non, dsz)
    f_cell(3, 3, h1Ok ? f_latest(h1B, h1S) : "-", txt, non, dsz)
    f_cell(0, 4, h2Lbl, txt, non, dsz)
    f_cell(1, 4, f_cnt(h2Bull), txt, f_has(keyNums, h2Bull) ? hot : non, dsz)
    f_cell(2, 4, f_cnt(h2Bear), txt, f_has(keyNums, h2Bear) ? hot : non, dsz)
    f_cell(3, 4, h2Ok ? f_latest(h2B, h2S) : "-", txt, non, dsz)
    f_cell(0, 5, h3Lbl, txt, non, dsz)
    f_cell(1, 5, f_cnt(h3Bull), txt, f_has(keyNums, h3Bull) ? hot : non, dsz)
    f_cell(2, 5, f_cnt(h3Bear), txt, f_has(keyNums, h3Bear) ? hot : non, dsz)
    f_cell(3, 5, h3Ok ? f_latest(h3B, h3S) : "-", txt, non, dsz)
    f_cell(0, 6, "Next level", txt, non, dsz)
    f_cell(1, 6, f_nextLevel(bullN), txt, non, dsz)
    f_cell(2, 6, f_nextLevel(bearN), txt, non, dsz)
    f_cell(0, 7, "Phase", txt, non, dsz)
    if inCons
        int    cn = bar_index - cSt + 1
        string ct = "Consolidation: " + str.tostring(cn) + " candles (usually 10 or 20)"
        f_cell(1, 7, ct, txt, hot, dsz)
        table.merge_cells(dash, 1, 7, 2, 7)
    else
        f_cell(1, 7, f_phaseText(bullN), txt, f_phase(nz(bullN, -1)) != "" ? hot : non, dsz)
        f_cell(2, 7, f_phaseText(bearN), txt, f_phase(nz(bearN, -1)) != "" ? hot : non, dsz)
    f_cell(0, 8, "Entry window", txt, non, dsz)
    f_cell(1, 8, bullWinT, txt, bullInW ? hot : non, dsz)
    f_cell(2, 8, bearWinT, txt, bearInW ? hot : non, dsz)
    f_cell(0, 9, "Shift", txt, non, dsz)
    f_cell(1, 9, na(bullS) or na(bullS.sLvl) ? "-" : bullS.conf ? "Confirmed" : "Waiting", txt, non, dsz)
    f_cell(2, 9, na(bearS) or na(bearS.sLvl) ? "-" : bearS.conf ? "Confirmed" : "Waiting", txt, non, dsz)
    if showGuide
        string hs = h1Ok ? f_htfSetup(h1Bull, h1Bear, h1Lbl) : "-"
        bool   hsHot = str.contains(hs, "scalp") or str.contains(hs, "continuation")
        f_cell(0, 10, "HTF setup", txt, non, dsz)
        f_cell(1, 10, hs, txt, hsHot ? hot : non, dsz)
        table.merge_cells(dash, 1, 10, 3, 10)
        f_cell(0, 11, "Entry / Conf / Bias", txt, non, dsz)
        f_cell(1, 11, "m5-m1 / m15 / h4-h1   or   m5 / h1-m15 / D1-h4", txt, non, dsz)
        table.merge_cells(dash, 1, 11, 3, 11)
        f_cell(0, 12, "Stop loss guide", txt, non, dsz)
        f_cell(1, 12, f_slGuide(), txt, non, dsz)
        table.merge_cells(dash, 1, 12, 3, 12)
    if xSess and intraday
        f_cell(0, 13, "Prev day session", txt, non, dsz)
        f_cell(1, 13, sessOk ? pdSess : "Single-session market (no Asia / London)", txt, non, dsz)
        table.merge_cells(dash, 1, 13, 3, 13)
 
// =============================================================================
// ALERTS
// =============================================================================
tick0() =>
    syminfo.ticker + " " + chLbl + ": "
 
bool aBullNum = conf and f_has(alrNums, bullN)
bool aBearNum = conf and f_has(alrNums, bearN)
bool aAlign   = conf and (topAlign or botAlign)
[bullWinNow, bullNext] = f_window(bullN)
[bearWinNow, bearNext] = f_window(bearN)
bool bullWinStart = bullWinNow >= 0 and bullN == wS.get(math.max(bullWinNow, 0))
bool bearWinStart = bearWinNow >= 0 and bearN == wS.get(math.max(bearWinNow, 0))
bool aWindow  = conf and (bullWinStart or bearWinStart)
 
alertcondition(newBull or newBear, "TDT new count", "TDT: a new count started from a high, a low or a consolidation breakout")
alertcondition(aBullNum or aBearNum, "TDT reversal number", "TDT: a count reached a reversal number")
alertcondition(aWindow, "TDT entry window", "TDT: a count entered an entry window")
alertcondition(aAlign, "TDT time alignment", "TDT: higher and lower timeframe counts are aligned")
 
// HTF setup windows open: the 7th or 13th candle of the first higher timeframe
int  h1Latest = na(h1Bear) or (not na(h1Bull) and h1Bull <= h1Bear) ? h1Bull : h1Bear
bool aHtfSet  = conf and newH1 and (h1Latest == 7 or h1Latest == 13)
alertcondition(aHtfSet, "TDT HTF setup", "TDT: the higher timeframe count opened a 7-9 retracement or reached the 13th candle")
if aHtfSet
    alert(tick0() + h1Lbl + " count = " + str.tostring(h1Latest) + (h1Latest == 7 ? ", scalp inside the retracement (7-9)" : ", continuation after the 13th"), alert.freq_once_per_bar_close)
 
string tick = tick0()
if newBull
    alert(tick + (expB ? "bullish count started at the candle leaving a consolidation" : "bullish count started at [LL]"), alert.freq_once_per_bar_close)
if newBear
    alert(tick + (expS ? "bearish count started at the candle leaving a consolidation" : "bearish count started at [HH]"), alert.freq_once_per_bar_close)
if aBullNum
    alert(tick + "count from the low = " + str.tostring(bullN) + ", watch for a top", alert.freq_once_per_bar_close)
if aBearNum
    alert(tick + "count from the high = " + str.tostring(bearN) + ", watch for a bottom", alert.freq_once_per_bar_close)
if aWindow
    alert(tick + "entry window  from the low: " + bullWinT + "  |  from the high: " + bearWinT, alert.freq_once_per_bar_close)
if conf and topAlign
    alert(tick + "time alignment (top): " + str.replace_all(f_sideText(bullN, h1Bull, h2Bull, h3Bull, topC0, topC1, topC2, topC3), "\n", " "), alert.freq_once_per_bar_close)
if conf and botAlign
    alert(tick + "time alignment (bottom): " + str.replace_all(f_sideText(bearN, h1Bear, h2Bear, h3Bear, botC0, botC1, botC2, botC3), "\n", " "), alert.freq_once_per_bar_close)

← 返回列表