SSMT Divergence- Multi Asset & True Opens

PythonbacktestDev · study · 808 行 · 点赞 21 · TradingView 原页

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

Pine Script

//@version=6
indicator("PROBE SSMT Divergence", "PROBE SSMT", overlay = true, max_lines_count = 500, max_labels_count = 500, dynamic_requests = true)
 
// PROBE SSMT compares each market with its own prior cycle-quarter extreme.
// A partial high break is bearish SSMT; a partial low break is bullish SSMT.
 
const string TZ = "America/New_York"
const int MINUTE_MS = 60 * 1000
const int DAY_MS = 24 * 60 * MINUTE_MS
const int WEEK_MS = 7 * DAY_MS
 
const string GROUP_ASSETS = "Assets"
const string GROUP_CUSTOM = "Custom assets"
const string GROUP_DISPLAY = "Display"
const string GROUP_MICRO = "Micro cycle"
const string GROUP_HIDDEN_MICRO = "Hidden Micro cycle"
const string GROUP_90M = "90-minute cycle"
const string GROUP_HIDDEN_90M = "Hidden 90-minute cycle"
const string GROUP_DAILY = "Daily cycle"
const string GROUP_HIDDEN_DAILY = "Hidden Daily cycle"
const string GROUP_WEEKLY = "Weekly cycle"
const string GROUP_HIDDEN_WEEKLY = "Hidden Weekly cycle"
const string GROUP_MONTHLY = "Monthly cycle"
const string GROUP_HIDDEN_MONTHLY = "Hidden Monthly cycle"
const string GROUP_YEARLY = "Yearly cycle"
const string GROUP_HIDDEN_YEARLY = "Hidden Yearly cycle"
 
assetGroupInput = input.string("Auto", "Comparison group", options = ["Auto", "Indices", "Metals", "Crypto", "Forex", "Oil", "Custom"], group = GROUP_ASSETS)
chartAssetInput = input.string("Auto", "Chart represents", options = ["Auto", "ES", "NQ", "YM", "GC", "SI", "HG", "BTCUSD", "ETHUSD", "XRPUSD", "EURUSD", "GBPUSD", "DXY", "RB", "HO", "CL"], group = GROUP_ASSETS, tooltip = "For preset groups. Custom mode uses the chart selector in Custom assets.")
esSymbol = input.symbol("CME_MINI:ES1!", "ES comparison symbol", group = GROUP_ASSETS)
nqSymbol = input.symbol("CME_MINI:NQ1!", "NQ comparison symbol", group = GROUP_ASSETS)
ymSymbol = input.symbol("CBOT_MINI:YM1!", "YM comparison symbol", group = GROUP_ASSETS)
gcSymbol = input.symbol("COMEX:GC1!", "GC comparison symbol", group = GROUP_ASSETS)
siSymbol = input.symbol("COMEX:SI1!", "SI comparison symbol", group = GROUP_ASSETS)
hgSymbol = input.symbol("COMEX:HG1!", "HG comparison symbol", group = GROUP_ASSETS)
 
btcSymbol = input.symbol("CRYPTO:BTCUSD", "BTCUSD comparison symbol", group = GROUP_ASSETS)
ethSymbol = input.symbol("CRYPTO:ETHUSD", "ETHUSD comparison symbol", group = GROUP_ASSETS)
xrpSymbol = input.symbol("CRYPTO:XRPUSD", "XRPUSD comparison symbol", group = GROUP_ASSETS)
eurSymbol = input.symbol("FX_IDC:EURUSD", "EURUSD comparison symbol", group = GROUP_ASSETS)
gbpSymbol = input.symbol("FX_IDC:GBPUSD", "GBPUSD comparison symbol", group = GROUP_ASSETS)
dxySymbol = input.symbol("TVC:DXY", "DXY comparison symbol", group = GROUP_ASSETS)
rbSymbol = input.symbol("NYMEX:RB1!", "RB comparison symbol", group = GROUP_ASSETS)
hoSymbol = input.symbol("NYMEX:HO1!", "HO comparison symbol", group = GROUP_ASSETS)
clSymbol = input.symbol("NYMEX:CL1!", "CL comparison symbol", group = GROUP_ASSETS)
 
customSymbol1 = input.symbol("CME_MINI:ES1!", "Custom asset 1", group = GROUP_CUSTOM)
customSymbol2 = input.symbol("CME_MINI:NQ1!", "Custom asset 2", group = GROUP_CUSTOM)
customSymbol3 = input.symbol("CBOT_MINI:YM1!", "Custom asset 3", group = GROUP_CUSTOM)
customChartInput = input.string("Auto", "Custom chart represents", options = ["Auto", "Custom asset 1", "Custom asset 2", "Custom asset 3"], group = GROUP_CUSTOM, tooltip = "Auto matches the chart's full exchange:symbol identifier to a selected custom asset. An override treats the displayed chart as that slot, including when using an alternate feed. All cycles retain the existing New York anchors.")
 
lineStyleInput = input.string("Solid", "Line style", options = ["Solid", "Dashed", "Dotted"], group = GROUP_DISPLAY)
lineWidth = input.int(1, "Line width", minval = 1, maxval = 4, group = GROUP_DISPLAY)
labelSizeInput = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal", "Large"], group = GROUP_DISPLAY)
compactLabels = input.bool(true, "Compact labels", group = GROUP_DISPLAY)
showLabels = input.bool(true, "Show labels", group = GROUP_DISPLAY)
showStatus = input.bool(true, "Show status panel", group = GROUP_DISPLAY)
historyLimit = input.int(150, "Signals to retain", minval = 10, maxval = 450, group = GROUP_DISPLAY)
 
const string GROUP_OPENS = "True market opens"
showTrueOpens = input.bool(false, "Show true market opens", group = GROUP_OPENS, tooltip = "New York 00:00, 07:30 and 13:30. Each level replaces its previous daily occurrence. Intraday standard charts only; exact one-minute anchor data is required above 1 minute.")
trueDayColor = input.color(color.gray, "True Day Open", group = GROUP_OPENS)
trueNyColor = input.color(color.orange, "True New York Open", group = GROUP_OPENS)
truePmColor = input.color(color.purple, "True Afternoon Open", group = GROUP_OPENS)
 
microEnabled = input.bool(true, "Enable Micro", group = GROUP_MICRO)
microBull = input.color(color.rgb(37, 99, 235), "Bullish", inline = "microColor", group = GROUP_MICRO)
microBear = input.color(color.rgb(220, 38, 38), "Bearish", inline = "microColor", group = GROUP_MICRO)
microMinTf = input.timeframe("1", "Min chart TF", inline = "microTf", group = GROUP_MICRO)
microMaxTf = input.timeframe("1", "Max chart TF", inline = "microTf", group = GROUP_MICRO)
 
hiddenMicroEnabled = input.bool(true, "Enable Hidden Micro", group = GROUP_HIDDEN_MICRO)
hiddenMicroBull = input.color(color.rgb(37, 99, 235), "Bullish", inline = "hiddenMicroColor", group = GROUP_HIDDEN_MICRO)
hiddenMicroBear = input.color(color.rgb(220, 38, 38), "Bearish", inline = "hiddenMicroColor", group = GROUP_HIDDEN_MICRO)
hiddenMicroStyle = input.string("Dotted", "Line style", options = ["Solid", "Dashed", "Dotted"], inline = "hiddenMicroLine", group = GROUP_HIDDEN_MICRO)
hiddenMicroWidth = input.int(1, "Width", minval = 1, maxval = 4, inline = "hiddenMicroLine", group = GROUP_HIDDEN_MICRO)
hiddenMicroLabelSize = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal", "Large"], inline = "hiddenMicroLabel", group = GROUP_HIDDEN_MICRO)
hiddenMicroLabelColor = input.color(color.gray, "Text", inline = "hiddenMicroLabel", group = GROUP_HIDDEN_MICRO)
hiddenMicroMinTf = input.timeframe("1", "Min chart TF", inline = "hiddenMicroTf", group = GROUP_HIDDEN_MICRO)
hiddenMicroMaxTf = input.timeframe("1", "Max chart TF", inline = "hiddenMicroTf", group = GROUP_HIDDEN_MICRO)
 
ninetyEnabled = input.bool(true, "Enable 90m", group = GROUP_90M)
ninetyBull = input.color(color.rgb(37, 99, 235), "Bullish", inline = "ninetyColor", group = GROUP_90M)
ninetyBear = input.color(color.rgb(220, 38, 38), "Bearish", inline = "ninetyColor", group = GROUP_90M)
ninetyMinTf = input.timeframe("1", "Min chart TF", inline = "ninetyTf", group = GROUP_90M)
ninetyMaxTf = input.timeframe("1", "Max chart TF", inline = "ninetyTf", group = GROUP_90M)
 
hiddenNinetyEnabled = input.bool(true, "Enable Hidden 90m", group = GROUP_HIDDEN_90M)
hiddenNinetyBull = input.color(color.rgb(37, 99, 235), "Bullish", inline = "hiddenNinetyColor", group = GROUP_HIDDEN_90M)
hiddenNinetyBear = input.color(color.rgb(220, 38, 38), "Bearish", inline = "hiddenNinetyColor", group = GROUP_HIDDEN_90M)
hiddenNinetyStyle = input.string("Dotted", "Line style", options = ["Solid", "Dashed", "Dotted"], inline = "hiddenNinetyLine", group = GROUP_HIDDEN_90M)
hiddenNinetyWidth = input.int(1, "Width", minval = 1, maxval = 4, inline = "hiddenNinetyLine", group = GROUP_HIDDEN_90M)
hiddenNinetyLabelSize = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal", "Large"], inline = "hiddenNinetyLabel", group = GROUP_HIDDEN_90M)
hiddenNinetyLabelColor = input.color(color.gray, "Text", inline = "hiddenNinetyLabel", group = GROUP_HIDDEN_90M)
hiddenNinetyMinTf = input.timeframe("1", "Min chart TF", inline = "hiddenNinetyTf", group = GROUP_HIDDEN_90M)
hiddenNinetyMaxTf = input.timeframe("1", "Max chart TF", inline = "hiddenNinetyTf", group = GROUP_HIDDEN_90M)
 
dailyEnabled = input.bool(true, "Enable Daily", group = GROUP_DAILY)
dailyBull = input.color(color.rgb(37, 99, 235), "Bullish", inline = "dailyColor", group = GROUP_DAILY)
dailyBear = input.color(color.rgb(220, 38, 38), "Bearish", inline = "dailyColor", group = GROUP_DAILY)
dailyMinTf = input.timeframe("15", "Min chart TF", inline = "dailyTf", group = GROUP_DAILY)
dailyMaxTf = input.timeframe("15", "Max chart TF", inline = "dailyTf", group = GROUP_DAILY)
 
hiddenDailyEnabled = input.bool(true, "Enable Hidden Daily", group = GROUP_HIDDEN_DAILY)
hiddenDailyBull = input.color(color.rgb(37, 99, 235), "Bullish", inline = "hiddenDailyColor", group = GROUP_HIDDEN_DAILY)
hiddenDailyBear = input.color(color.rgb(220, 38, 38), "Bearish", inline = "hiddenDailyColor", group = GROUP_HIDDEN_DAILY)
hiddenDailyStyle = input.string("Dotted", "Line style", options = ["Solid", "Dashed", "Dotted"], inline = "hiddenDailyLine", group = GROUP_HIDDEN_DAILY)
hiddenDailyWidth = input.int(1, "Width", minval = 1, maxval = 4, inline = "hiddenDailyLine", group = GROUP_HIDDEN_DAILY)
hiddenDailyLabelSize = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal", "Large"], inline = "hiddenDailyLabel", group = GROUP_HIDDEN_DAILY)
hiddenDailyLabelColor = input.color(color.gray, "Text", inline = "hiddenDailyLabel", group = GROUP_HIDDEN_DAILY)
hiddenDailyMinTf = input.timeframe("15", "Min chart TF", inline = "hiddenDailyTf", group = GROUP_HIDDEN_DAILY)
hiddenDailyMaxTf = input.timeframe("15", "Max chart TF", inline = "hiddenDailyTf", group = GROUP_HIDDEN_DAILY)
 
weeklyEnabled = input.bool(true, "Enable Weekly", group = GROUP_WEEKLY)
weeklyBull = input.color(color.rgb(37, 99, 235), "Bullish", inline = "weeklyColor", group = GROUP_WEEKLY)
weeklyBear = input.color(color.rgb(220, 38, 38), "Bearish", inline = "weeklyColor", group = GROUP_WEEKLY)
weeklyMinTf = input.timeframe("60", "Min chart TF", inline = "weeklyTf", group = GROUP_WEEKLY)
weeklyMaxTf = input.timeframe("60", "Max chart TF", inline = "weeklyTf", group = GROUP_WEEKLY)
 
hiddenWeeklyEnabled = input.bool(true, "Enable Hidden Weekly", group = GROUP_HIDDEN_WEEKLY)
hiddenWeeklyBull = input.color(color.rgb(37, 99, 235), "Bullish", inline = "hiddenWeeklyColor", group = GROUP_HIDDEN_WEEKLY)
hiddenWeeklyBear = input.color(color.rgb(220, 38, 38), "Bearish", inline = "hiddenWeeklyColor", group = GROUP_HIDDEN_WEEKLY)
hiddenWeeklyStyle = input.string("Dotted", "Line style", options = ["Solid", "Dashed", "Dotted"], inline = "hiddenWeeklyLine", group = GROUP_HIDDEN_WEEKLY)
hiddenWeeklyWidth = input.int(1, "Width", minval = 1, maxval = 4, inline = "hiddenWeeklyLine", group = GROUP_HIDDEN_WEEKLY)
hiddenWeeklyLabelSize = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal", "Large"], inline = "hiddenWeeklyLabel", group = GROUP_HIDDEN_WEEKLY)
hiddenWeeklyLabelColor = input.color(color.gray, "Text", inline = "hiddenWeeklyLabel", group = GROUP_HIDDEN_WEEKLY)
hiddenWeeklyMinTf = input.timeframe("60", "Min chart TF", inline = "hiddenWeeklyTf", group = GROUP_HIDDEN_WEEKLY)
hiddenWeeklyMaxTf = input.timeframe("60", "Max chart TF", inline = "hiddenWeeklyTf", group = GROUP_HIDDEN_WEEKLY)
 
monthlyEnabled = input.bool(true, "Enable Monthly", group = GROUP_MONTHLY)
monthlyBull = input.color(color.rgb(37, 99, 235), "Bullish", inline = "monthlyColor", group = GROUP_MONTHLY)
monthlyBear = input.color(color.rgb(220, 38, 38), "Bearish", inline = "monthlyColor", group = GROUP_MONTHLY)
monthlyMinTf = input.timeframe("240", "Min chart TF", inline = "monthlyTf", group = GROUP_MONTHLY)
monthlyMaxTf = input.timeframe("240", "Max chart TF", inline = "monthlyTf", group = GROUP_MONTHLY)
 
hiddenMonthlyEnabled = input.bool(true, "Enable Hidden Monthly", group = GROUP_HIDDEN_MONTHLY)
hiddenMonthlyBull = input.color(color.rgb(37, 99, 235), "Bullish", inline = "hiddenMonthlyColor", group = GROUP_HIDDEN_MONTHLY)
hiddenMonthlyBear = input.color(color.rgb(220, 38, 38), "Bearish", inline = "hiddenMonthlyColor", group = GROUP_HIDDEN_MONTHLY)
hiddenMonthlyStyle = input.string("Dotted", "Line style", options = ["Solid", "Dashed", "Dotted"], inline = "hiddenMonthlyLine", group = GROUP_HIDDEN_MONTHLY)
hiddenMonthlyWidth = input.int(1, "Width", minval = 1, maxval = 4, inline = "hiddenMonthlyLine", group = GROUP_HIDDEN_MONTHLY)
hiddenMonthlyLabelSize = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal", "Large"], inline = "hiddenMonthlyLabel", group = GROUP_HIDDEN_MONTHLY)
hiddenMonthlyLabelColor = input.color(color.gray, "Text", inline = "hiddenMonthlyLabel", group = GROUP_HIDDEN_MONTHLY)
hiddenMonthlyMinTf = input.timeframe("240", "Min chart TF", inline = "hiddenMonthlyTf", group = GROUP_HIDDEN_MONTHLY)
hiddenMonthlyMaxTf = input.timeframe("240", "Max chart TF", inline = "hiddenMonthlyTf", group = GROUP_HIDDEN_MONTHLY)
 
yearlyEnabled = input.bool(true, "Enable Yearly", group = GROUP_YEARLY)
yearlyBull = input.color(color.rgb(37, 99, 235), "Bullish", inline = "yearlyColor", group = GROUP_YEARLY)
yearlyBear = input.color(color.rgb(220, 38, 38), "Bearish", inline = "yearlyColor", group = GROUP_YEARLY)
yearlyMinTf = input.timeframe("1W", "Min chart TF", inline = "yearlyTf", group = GROUP_YEARLY)
yearlyMaxTf = input.timeframe("1W", "Max chart TF", inline = "yearlyTf", group = GROUP_YEARLY)
 
hiddenYearlyEnabled = input.bool(true, "Enable Hidden Yearly", group = GROUP_HIDDEN_YEARLY)
hiddenYearlyBull = input.color(color.rgb(37, 99, 235), "Bullish", inline = "hiddenYearlyColor", group = GROUP_HIDDEN_YEARLY)
hiddenYearlyBear = input.color(color.rgb(220, 38, 38), "Bearish", inline = "hiddenYearlyColor", group = GROUP_HIDDEN_YEARLY)
hiddenYearlyStyle = input.string("Dotted", "Line style", options = ["Solid", "Dashed", "Dotted"], inline = "hiddenYearlyLine", group = GROUP_HIDDEN_YEARLY)
hiddenYearlyWidth = input.int(1, "Width", minval = 1, maxval = 4, inline = "hiddenYearlyLine", group = GROUP_HIDDEN_YEARLY)
hiddenYearlyLabelSize = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal", "Large"], inline = "hiddenYearlyLabel", group = GROUP_HIDDEN_YEARLY)
hiddenYearlyLabelColor = input.color(color.gray, "Text", inline = "hiddenYearlyLabel", group = GROUP_HIDDEN_YEARLY)
hiddenYearlyMinTf = input.timeframe("1W", "Min chart TF", inline = "hiddenYearlyTf", group = GROUP_HIDDEN_YEARLY)
hiddenYearlyMaxTf = input.timeframe("1W", "Max chart TF", inline = "hiddenYearlyTf", group = GROUP_HIDDEN_YEARLY)
 
f_standard_symbol(string symbol) =>
    str.upper(ticker.standard(symbol))
 
f_custom_name(string symbol) =>
    array<string> parts = str.split(f_standard_symbol(symbol), ":")
    array.get(parts, array.size(parts) - 1)
 
f_custom_role(string selection, string chartSymbol, string symbol1, string symbol2, string symbol3) =>
    int matchedRole = f_standard_symbol(chartSymbol) == f_standard_symbol(symbol1) ? 1 : f_standard_symbol(chartSymbol) == f_standard_symbol(symbol2) ? 2 : f_standard_symbol(chartSymbol) == f_standard_symbol(symbol3) ? 4 : 0
    selection == "Auto" ? matchedRole : selection == "Custom asset 1" ? 1 : selection == "Custom asset 2" ? 2 : selection == "Custom asset 3" ? 4 : 0
 
bool useCustom = assetGroupInput == "Custom"
string chartTicker = str.upper(syminfo.ticker)
bool autoCrypto = chartTicker == "BTCUSD" or chartTicker == "ETHUSD" or chartTicker == "XRPUSD"
bool autoForex = chartTicker == "EURUSD" or chartTicker == "GBPUSD" or chartTicker == "DXY"
bool autoOil = syminfo.root == "RB" or syminfo.root == "HO" or syminfo.root == "CL"
bool useCrypto = assetGroupInput == "Crypto" or (assetGroupInput == "Auto" and autoCrypto)
bool useForex = assetGroupInput == "Forex" or (assetGroupInput == "Auto" and autoForex)
bool useOil = assetGroupInput == "Oil" or (assetGroupInput == "Auto" and autoOil)
string customName1 = f_custom_name(customSymbol1)
string customName2 = f_custom_name(customSymbol2)
string customName3 = f_custom_name(customSymbol3)
 
f_line_style(string styleName) =>
    styleName == "Dashed" ? line.style_dashed : styleName == "Dotted" ? line.style_dotted : line.style_solid
 
f_label_size(string sizeName) =>
    sizeName == "Tiny" ? size.tiny : sizeName == "Normal" ? size.normal : sizeName == "Large" ? size.large : size.small
 
f_tf_visible(string minimum, string maximum) =>
    float chartSeconds = timeframe.in_seconds(timeframe.period)
    float minimumSeconds = timeframe.in_seconds(minimum)
    float maximumSeconds = timeframe.in_seconds(maximum)
    not na(chartSeconds) and chartSeconds >= minimumSeconds and chartSeconds <= maximumSeconds
 
f_days_in_month(int y, int m) =>
    bool leap = y % 400 == 0 or (y % 4 == 0 and y % 100 != 0)
    m == 2 ? (leap ? 29 : 28) : (m == 4 or m == 6 or m == 9 or m == 11 ? 30 : 31)
 
f_previous_month(int y, int m) =>
    int previousYear = y
    int previousMonth = m - 1
    if m == 1
        previousYear := y - 1
        previousMonth := 12
    [previousYear, previousMonth]
 
f_next_month(int y, int m) =>
    int nextYear = y
    int nextMonth = m + 1
    if m == 12
        nextYear := y + 1
        nextMonth := 1
    [nextYear, nextMonth]
 
f_month_anchor_for(int y, int m) =>
    int firstDay = timestamp(TZ, y, m, 1, 0, 0)
    int firstDow = dayofweek(firstDay, TZ)
    int firstSunday = 1 + (dayofweek.sunday - firstDow + 7) % 7
    int monthDays = f_days_in_month(y, m)
    int sundayCount = firstSunday + 28 <= monthDays ? 5 : 4
    [py, pm] = f_previous_month(y, m)
    int previousDays = f_days_in_month(py, pm)
    bool usePreviousSunday = previousDays == 31 and dayofweek(timestamp(TZ, py, pm, 31, 0, 0), TZ) == dayofweek.sunday and sundayCount == 4
    usePreviousSunday ? timestamp(TZ, py, pm, 31, 18, 0) : timestamp(TZ, y, m, firstSunday, 18, 0)
 
f_daily_anchor(int t) =>
    int y = year(t, TZ)
    int m = month(t, TZ)
    int d = dayofmonth(t, TZ)
    int todayAnchor = timestamp(TZ, y, m, d, 18, 0)
    t >= todayAnchor ? todayAnchor : timestamp(TZ, y, m, d - 1, 18, 0)
 
f_weekly_anchor(int t) =>
    int y = year(t, TZ)
    int m = month(t, TZ)
    int d = dayofmonth(t, TZ)
    int dow = dayofweek(t, TZ)
    int todayAnchor = timestamp(TZ, y, m, d, 18, 0)
    int daysBack = dow - dayofweek.sunday
    daysBack := dow == dayofweek.sunday and t < todayAnchor ? 7 : daysBack
    timestamp(TZ, y, m, d - daysBack, 18, 0)
 
f_monthly_anchor(int t) =>
    int y = year(t, TZ)
    int m = month(t, TZ)
    [py, pm] = f_previous_month(y, m)
    [ny, nm] = f_next_month(y, m)
    int previousCandidate = f_month_anchor_for(py, pm)
    int currentCandidate = f_month_anchor_for(y, m)
    int nextCandidate = f_month_anchor_for(ny, nm)
    int candidate = previousCandidate
    candidate := currentCandidate <= t and currentCandidate > candidate ? currentCandidate : candidate
    candidate := nextCandidate <= t and nextCandidate > candidate ? nextCandidate : candidate
    candidate
 
f_daily_key(int t) =>
    int anchor = f_daily_anchor(t)
    int quarter = int(math.floor((t - anchor) / (6.0 * 60.0 * MINUTE_MS))) + 1
    int(math.floor(anchor / float(MINUTE_MS))) * 10 + quarter
 
f_ninety_key(int t) =>
    int anchor = f_daily_anchor(t)
    int cycle = int(math.floor((t - anchor) / (90.0 * MINUTE_MS))) + 1
    int(math.floor(anchor / float(MINUTE_MS))) * 100 + cycle
 
f_micro_key(int t) =>
    int anchor = f_daily_anchor(t)
    int elapsedMinutes = int(math.floor((t - anchor) / float(MINUTE_MS)))
    int cycle = int(math.floor(elapsedMinutes / 90.0)) + 1
    int cycleElapsedMinutes = elapsedMinutes - (cycle - 1) * 90
    int microQuarter = int(math.floor(cycleElapsedMinutes / 22.5)) + 1
    int(math.floor(anchor / float(MINUTE_MS))) * 1000 + cycle * 10 + microQuarter
 
f_weekly_key(int t) =>
    int anchor = f_weekly_anchor(t)
    int period = int(math.floor((t - anchor) / float(DAY_MS))) + 1
    period >= 1 and period <= 5 ? int(math.floor(anchor / float(MINUTE_MS))) * 10 + period : 0
 
f_monthly_key(int t) =>
    int anchor = f_monthly_anchor(t)
    int ay = year(anchor, TZ)
    int am = month(anchor, TZ)
    int ad = dayofmonth(anchor, TZ)
    int q2At = timestamp(TZ, ay, am, ad + 7, 18, 0)
    int q3At = timestamp(TZ, ay, am, ad + 14, 18, 0)
    int q4At = timestamp(TZ, ay, am, ad + 21, 18, 0)
    int endAt = timestamp(TZ, ay, am, ad + 28, 18, 0)
    int quarter = t < q2At ? 1 : t < q3At ? 2 : t < q4At ? 3 : t < endAt ? 4 : 0
    quarter >= 1 and quarter <= 4 ? int(math.floor(anchor / float(MINUTE_MS))) * 10 + quarter : 0
 
f_yearly_key(int t) =>
    int y = year(t, TZ)
    int quarter = int(math.floor((month(t, TZ) - 1) / 3.0)) + 1
    y * 10 + quarter
 
f_mask_has(int mask, int role) =>
    role == 1 ? mask % 2 == 1 : role == 2 ? int(math.floor(mask / 2.0)) % 2 == 1 : mask >= 4
 
f_symbol_list(int mask, bool selected, bool metals) =>
    string result = ""
    if f_mask_has(mask, 1) == selected
        result := result + (str.length(result) > 0 ? "/" : "") + (useCustom ? customName1 : useCrypto ? "BTCUSD" : useForex ? "EURUSD" : useOil ? "RB" : metals ? "GC" : "ES")
    if f_mask_has(mask, 2) == selected
        result := result + (str.length(result) > 0 ? "/" : "") + (useCustom ? customName2 : useCrypto ? "ETHUSD" : useForex ? "GBPUSD" : useOil ? "HO" : metals ? "SI" : "NQ")
    if f_mask_has(mask, 4) == selected
        result := result + (str.length(result) > 0 ? "/" : "") + (useCustom ? customName3 : useCrypto ? "XRPUSD" : useForex ? "DXY" : useOil ? "CL" : metals ? "HG" : "YM")
    result
 
var line[] signalLines = array.new_line()
var label[] signalLabels = array.new_label()
var int[] signalCycleKeys = array.new_int()
var string[] signalCycleNames = array.new_string()
var bool[] signalBullish = array.new_bool()
var bool[] signalUsesBody = array.new_bool()
var bool[] signalIsHidden = array.new_bool()
var bool[] signalVisible = array.new_bool()
var float[] signalPoint2 = array.new_float()
var color[] signalColors = array.new_color()
var color[] signalLabelColors = array.new_color()
 
f_trim_history() =>
    while array.size(signalLines) > historyLimit
        line oldestLine = array.shift(signalLines)
        label oldestLabel = array.shift(signalLabels)
        array.shift(signalCycleKeys)
        array.shift(signalCycleNames)
        array.shift(signalBullish)
        array.shift(signalUsesBody)
        array.shift(signalIsHidden)
        array.shift(signalVisible)
        array.shift(signalPoint2)
        array.shift(signalColors)
        array.shift(signalLabelColors)
        if not na(oldestLine)
            line.delete(oldestLine)
        if not na(oldestLabel)
            label.delete(oldestLabel)
 
f_delete_signal(line signalLine, label signalLabel) =>
    if not na(signalLine)
        line.delete(signalLine)
    if not na(signalLabel)
        label.delete(signalLabel)
 
f_set_signal_visibility(line signalLine, label signalLabel, bool visible, color signalColor, color labelTextColor) =>
    color resolvedTextColor = na(labelTextColor) ? signalColor : labelTextColor
    if not na(signalLine)
        line.set_color(signalLine, visible ? signalColor : color.new(signalColor, 100))
    if not na(signalLabel)
        label.set_color(signalLabel, visible ? color.new(signalColor, 82) : color.new(signalColor, 100))
        label.set_textcolor(signalLabel, visible ? resolvedTextColor : color.new(resolvedTextColor, 100))
 
f_archive_signal(line signalLine, label signalLabel, int cycleKey, string cycleName, bool bullish, bool usesBody, bool isHidden, bool visible, float point2, color signalColor, color labelTextColor) =>
    if not na(signalLine)
        array.push(signalLines, signalLine)
        array.push(signalLabels, signalLabel)
        array.push(signalCycleKeys, cycleKey)
        array.push(signalCycleNames, cycleName)
        array.push(signalBullish, bullish)
        array.push(signalUsesBody, usesBody)
        array.push(signalIsHidden, isHidden)
        array.push(signalVisible, visible)
        array.push(signalPoint2, point2)
        array.push(signalColors, signalColor)
        array.push(signalLabelColors, labelTextColor)
        f_trim_history()
 
f_reveal_archived_hidden(int cycleKey, string cycleName, bool bullish) =>
    int index = array.size(signalLines) - 1
    while index >= 0
        bool matchingHidden = array.get(signalIsHidden, index) and array.get(signalCycleKeys, index) == cycleKey and array.get(signalCycleNames, index) == cycleName and array.get(signalBullish, index) == bullish
        if matchingHidden and not array.get(signalVisible, index)
            line hiddenLine = array.get(signalLines, index)
            label hiddenLabel = array.get(signalLabels, index)
            color hiddenColor = array.get(signalColors, index)
            color hiddenLabelColor = array.get(signalLabelColors, index)
            f_set_signal_visibility(hiddenLine, hiddenLabel, true, hiddenColor, hiddenLabelColor)
            array.set(signalVisible, index, true)
        index -= 1
 
f_monitor_archived_signals(float chartHigh, float chartLow, float chartBodyHigh, float chartBodyLow) =>
    int index = array.size(signalLines) - 1
    while index >= 0
        bool bullish = array.get(signalBullish, index)
        bool usesBody = array.get(signalUsesBody, index)
        bool isHidden = array.get(signalIsHidden, index)
        float point2 = array.get(signalPoint2, index)
        float invalidationHigh = usesBody ? chartBodyHigh : chartHigh
        float invalidationLow = usesBody ? chartBodyLow : chartLow
        bool point2Broke = bullish ? invalidationLow < point2 : invalidationHigh > point2
        if point2Broke
            int invalidCycleKey = array.get(signalCycleKeys, index)
            string invalidCycleName = array.get(signalCycleNames, index)
            line invalidLine = array.remove(signalLines, index)
            label invalidLabel = array.remove(signalLabels, index)
            array.remove(signalCycleKeys, index)
            array.remove(signalCycleNames, index)
            array.remove(signalBullish, index)
            array.remove(signalUsesBody, index)
            array.remove(signalIsHidden, index)
            array.remove(signalVisible, index)
            array.remove(signalPoint2, index)
            array.remove(signalColors, index)
            array.remove(signalLabelColors, index)
            if not na(invalidLine)
                line.delete(invalidLine)
            if not na(invalidLabel)
                label.delete(invalidLabel)
            if not isHidden
                f_reveal_archived_hidden(invalidCycleKey, invalidCycleName, bullish)
        index -= 1
 
f_draw_signal(bool bullish, string cycleName, int mask, color signalColor, string styleName, int width, string labelSizeName, color labelTextColor, int chartRole, bool metals, bool visible, float previousPrice, int previousAt, float currentPrice, int currentAt) =>
    line newLine = na
    label newLabel = na
    if not na(previousPrice) and not na(currentPrice) and not na(previousAt) and not na(currentAt)
        color displayColor = visible ? signalColor : color.new(signalColor, 100)
        newLine := line.new(previousAt, previousPrice, currentAt, currentPrice, xloc = xloc.bar_time, extend = extend.none, color = displayColor, style = f_line_style(styleName), width = width)
        if showLabels
            bool chartBroke = f_mask_has(mask, chartRole)
            string counterpart = f_symbol_list(mask, not chartBroke, metals)
            string sideText = bullish ? "Bullish" : "Bearish"
            string brokenText = f_symbol_list(mask, true, metals)
            string heldText = f_symbol_list(mask, false, metals)
            string labelText = compactLabels ? cycleName + " " + counterpart : cycleName + " " + sideText + "\nBroke: " + brokenText + " | Held: " + heldText
            color resolvedTextColor = na(labelTextColor) ? signalColor : labelTextColor
            newLabel := label.new(currentAt, currentPrice, labelText, xloc = xloc.bar_time, style = bullish ? label.style_label_up : label.style_label_down, color = visible ? color.new(signalColor, 82) : color.new(signalColor, 100), textcolor = visible ? resolvedTextColor : color.new(resolvedTextColor, 100), size = f_label_size(labelSizeName))
            label.set_tooltip(newLabel, sideText + " " + cycleName + " SSMT\nBroken: " + brokenText + "\nHeld: " + heldText)
    [newLine, newLabel]
 
type CycleState
    int key = na
    float currentHigh1 = na
    float currentHigh2 = na
    float currentHigh3 = na
    float currentLow1 = na
    float currentLow2 = na
    float currentLow3 = na
    int currentHighAt1 = na
    int currentHighAt2 = na
    int currentHighAt3 = na
    int currentLowAt1 = na
    int currentLowAt2 = na
    int currentLowAt3 = na
    float previousHigh1 = na
    float previousHigh2 = na
    float previousHigh3 = na
    float previousLow1 = na
    float previousLow2 = na
    float previousLow3 = na
    int previousHighAt1 = na
    int previousHighAt2 = na
    int previousHighAt3 = na
    int previousLowAt1 = na
    int previousLowAt2 = na
    int previousLowAt3 = na
    int highMask = 0
    int lowMask = 0
    bool highDivergenceSeen = false
    bool lowDivergenceSeen = false
    bool highFallbackReady = false
    bool lowFallbackReady = false
    line activeHighLine = na
    label activeHighLabel = na
    bool activeHighVisible = false
    line activeLowLine = na
    label activeLowLabel = na
    bool activeLowVisible = false
 
method process(CycleState this, int cycleKey, bool trackActive, bool showBullish, bool showBearish, string cycleName, color bullColor, color bearColor, string styleName, int width, string labelSizeName, color labelTextColor, int chartRole, bool metals, bool usesBody, bool isHidden, float high1, float low1, float high2, float low2, float high3, float low3) =>
    bool bullishEvent = false
    bool bearishEvent = false
    bool dataReady = cycleKey != 0 and not na(high1) and not na(low1) and not na(high2) and not na(low2) and not na(high3) and not na(low3)
    if dataReady
        if na(this.key)
            this.key := cycleKey
            this.currentHigh1 := high1
            this.currentHigh2 := high2
            this.currentHigh3 := high3
            this.currentLow1 := low1
            this.currentLow2 := low2
            this.currentLow3 := low3
            this.currentHighAt1 := time
            this.currentHighAt2 := time
            this.currentHighAt3 := time
            this.currentLowAt1 := time
            this.currentLowAt2 := time
            this.currentLowAt3 := time
        else if cycleKey != this.key
            float archivedHighPoint2 = chartRole == 1 ? this.currentHigh1 : chartRole == 2 ? this.currentHigh2 : this.currentHigh3
            float archivedLowPoint2 = chartRole == 1 ? this.currentLow1 : chartRole == 2 ? this.currentLow2 : this.currentLow3
            f_archive_signal(this.activeHighLine, this.activeHighLabel, this.key, cycleName, false, usesBody, isHidden, this.activeHighVisible, archivedHighPoint2, bearColor, labelTextColor)
            f_archive_signal(this.activeLowLine, this.activeLowLabel, this.key, cycleName, true, usesBody, isHidden, this.activeLowVisible, archivedLowPoint2, bullColor, labelTextColor)
            this.activeHighLine := na
            this.activeHighLabel := na
            this.activeHighVisible := false
            this.activeLowLine := na
            this.activeLowLabel := na
            this.activeLowVisible := false
            this.previousHigh1 := this.currentHigh1
            this.previousHigh2 := this.currentHigh2
            this.previousHigh3 := this.currentHigh3
            this.previousLow1 := this.currentLow1
            this.previousLow2 := this.currentLow2
            this.previousLow3 := this.currentLow3
            this.previousHighAt1 := this.currentHighAt1
            this.previousHighAt2 := this.currentHighAt2
            this.previousHighAt3 := this.currentHighAt3
            this.previousLowAt1 := this.currentLowAt1
            this.previousLowAt2 := this.currentLowAt2
            this.previousLowAt3 := this.currentLowAt3
            this.key := cycleKey
            this.currentHigh1 := high1
            this.currentHigh2 := high2
            this.currentHigh3 := high3
            this.currentLow1 := low1
            this.currentLow2 := low2
            this.currentLow3 := low3
            this.currentHighAt1 := time
            this.currentHighAt2 := time
            this.currentHighAt3 := time
            this.currentLowAt1 := time
            this.currentLowAt2 := time
            this.currentLowAt3 := time
            this.highMask := 0
            this.lowMask := 0
            this.highDivergenceSeen := false
            this.lowDivergenceSeen := false
            this.highFallbackReady := false
            this.lowFallbackReady := false
        else
            if high1 > this.currentHigh1
                this.currentHigh1 := high1
                this.currentHighAt1 := time
            if high2 > this.currentHigh2
                this.currentHigh2 := high2
                this.currentHighAt2 := time
            if high3 > this.currentHigh3
                this.currentHigh3 := high3
                this.currentHighAt3 := time
            if low1 < this.currentLow1
                this.currentLow1 := low1
                this.currentLowAt1 := time
            if low2 < this.currentLow2
                this.currentLow2 := low2
                this.currentLowAt2 := time
            if low3 < this.currentLow3
                this.currentLow3 := low3
                this.currentLowAt3 := time
 
        bool previousReady = not na(this.previousHigh1) and not na(this.previousHigh2) and not na(this.previousHigh3) and not na(this.previousLow1) and not na(this.previousLow2) and not na(this.previousLow3)
        if previousReady
            int newHighMask = (this.currentHigh1 > this.previousHigh1 ? 1 : 0) + (this.currentHigh2 > this.previousHigh2 ? 2 : 0) + (this.currentHigh3 > this.previousHigh3 ? 4 : 0)
            int newLowMask = (this.currentLow1 < this.previousLow1 ? 1 : 0) + (this.currentLow2 < this.previousLow2 ? 2 : 0) + (this.currentLow3 < this.previousLow3 ? 4 : 0)
            bearishEvent := trackActive and newHighMask > 0 and newHighMask < 7 and newHighMask != this.highMask
            bullishEvent := trackActive and newLowMask > 0 and newLowMask < 7 and newLowMask != this.lowMask
 
            float previousHighPrice = chartRole == 1 ? this.previousHigh1 : chartRole == 2 ? this.previousHigh2 : this.previousHigh3
            int previousHighAt = chartRole == 1 ? this.previousHighAt1 : chartRole == 2 ? this.previousHighAt2 : this.previousHighAt3
            float currentHighPrice = chartRole == 1 ? this.currentHigh1 : chartRole == 2 ? this.currentHigh2 : this.currentHigh3
            int currentHighAt = chartRole == 1 ? this.currentHighAt1 : chartRole == 2 ? this.currentHighAt2 : this.currentHighAt3
            float previousLowPrice = chartRole == 1 ? this.previousLow1 : chartRole == 2 ? this.previousLow2 : this.previousLow3
            int previousLowAt = chartRole == 1 ? this.previousLowAt1 : chartRole == 2 ? this.previousLowAt2 : this.previousLowAt3
            float currentLowPrice = chartRole == 1 ? this.currentLow1 : chartRole == 2 ? this.currentLow2 : this.currentLow3
            int currentLowAt = chartRole == 1 ? this.currentLowAt1 : chartRole == 2 ? this.currentLowAt2 : this.currentLowAt3
 
            if newHighMask == 7
                this.highFallbackReady := this.highDivergenceSeen
                f_delete_signal(this.activeHighLine, this.activeHighLabel)
                this.activeHighLine := na
                this.activeHighLabel := na
                this.activeHighVisible := false
            else if trackActive and newHighMask > 0
                this.highDivergenceSeen := true
                if newHighMask != this.highMask or na(this.activeHighLine)
                    f_delete_signal(this.activeHighLine, this.activeHighLabel)
                    [newHighLine, newHighLabel] = f_draw_signal(false, isHidden ? cycleName + " Hidden" : cycleName, newHighMask, bearColor, styleName, width, labelSizeName, labelTextColor, chartRole, metals, showBearish, previousHighPrice, previousHighAt, currentHighPrice, currentHighAt)
                    this.activeHighLine := newHighLine
                    this.activeHighLabel := newHighLabel
                else
                    line.set_xy2(this.activeHighLine, currentHighAt, currentHighPrice)
                    if not na(this.activeHighLabel)
                        label.set_xy(this.activeHighLabel, currentHighAt, currentHighPrice)
                f_set_signal_visibility(this.activeHighLine, this.activeHighLabel, showBearish, bearColor, labelTextColor)
                this.activeHighVisible := showBearish
 
            if newLowMask == 7
                this.lowFallbackReady := this.lowDivergenceSeen
                f_delete_signal(this.activeLowLine, this.activeLowLabel)
                this.activeLowLine := na
                this.activeLowLabel := na
                this.activeLowVisible := false
            else if trackActive and newLowMask > 0
                this.lowDivergenceSeen := true
                if newLowMask != this.lowMask or na(this.activeLowLine)
                    f_delete_signal(this.activeLowLine, this.activeLowLabel)
                    [newLowLine, newLowLabel] = f_draw_signal(true, isHidden ? cycleName + " Hidden" : cycleName, newLowMask, bullColor, styleName, width, labelSizeName, labelTextColor, chartRole, metals, showBullish, previousLowPrice, previousLowAt, currentLowPrice, currentLowAt)
                    this.activeLowLine := newLowLine
                    this.activeLowLabel := newLowLabel
                else
                    line.set_xy2(this.activeLowLine, currentLowAt, currentLowPrice)
                    if not na(this.activeLowLabel)
                        label.set_xy(this.activeLowLabel, currentLowAt, currentLowPrice)
                f_set_signal_visibility(this.activeLowLine, this.activeLowLabel, showBullish, bullColor, labelTextColor)
                this.activeLowVisible := showBullish
 
            this.highMask := newHighMask
            this.lowMask := newLowMask
    [bullishEvent, bearishEvent]
 
string root = str.upper(syminfo.root)
bool rootIsEs = root == "ES" or root == "MES"
bool rootIsNq = root == "NQ" or root == "MNQ"
bool rootIsYm = root == "YM" or root == "MYM"
bool rootIsGc = root == "GC" or root == "MGC"
bool rootIsSi = root == "SI" or root == "SIL"
bool rootIsHg = root == "HG" or root == "MHG"
bool autoIndices = rootIsEs or rootIsNq or rootIsYm
bool autoMetals = rootIsGc or rootIsSi or rootIsHg
bool useMetals = assetGroupInput == "Metals" or (assetGroupInput == "Auto" and autoMetals)
bool supportedChart = assetGroupInput != "Auto" or autoIndices or autoMetals or autoCrypto or autoForex or autoOil
 
int newRole = chartTicker == "BTCUSD" or chartTicker == "EURUSD" or root == "RB" ? 1 : chartTicker == "ETHUSD" or chartTicker == "GBPUSD" or root == "HO" ? 2 : chartTicker == "XRPUSD" or chartTicker == "DXY" or root == "CL" ? 4 : 0
int autoRole = newRole != 0 ? newRole : rootIsEs or rootIsGc ? 1 : rootIsNq or rootIsSi ? 2 : rootIsYm or rootIsHg ? 4 : 0
int newManualRole = chartAssetInput == "BTCUSD" or chartAssetInput == "EURUSD" or chartAssetInput == "RB" ? 1 : chartAssetInput == "ETHUSD" or chartAssetInput == "GBPUSD" or chartAssetInput == "HO" ? 2 : chartAssetInput == "XRPUSD" or chartAssetInput == "DXY" or chartAssetInput == "CL" ? 4 : 0
int manualRole = newManualRole != 0 ? newManualRole : chartAssetInput == "ES" or chartAssetInput == "GC" ? 1 : chartAssetInput == "NQ" or chartAssetInput == "SI" ? 2 : chartAssetInput == "YM" or chartAssetInput == "HG" ? 4 : 0
int presetRole = chartAssetInput == "Auto" ? autoRole : manualRole
int chartRole = useCustom ? f_custom_role(customChartInput, syminfo.tickerid, customSymbol1, customSymbol2, customSymbol3) : presetRole
supportedChart := supportedChart and chartRole != 0
 
if barstate.isfirst and useCustom
    if customSymbol1 == "" or customSymbol2 == "" or customSymbol3 == ""
        runtime.error("Select all three custom assets explicitly.")
    if f_standard_symbol(customSymbol1) == f_standard_symbol(customSymbol2) or f_standard_symbol(customSymbol1) == f_standard_symbol(customSymbol3) or f_standard_symbol(customSymbol2) == f_standard_symbol(customSymbol3)
        runtime.error("Custom assets must be three different symbols.")
    if not chart.is_standard
        runtime.error("Custom SSMT comparisons require a standard price chart, not synthetic candles.")
 
string comparisonSymbol1 = useCustom ? customSymbol1 : useCrypto ? btcSymbol : useForex ? eurSymbol : useOil ? rbSymbol : useMetals ? gcSymbol : esSymbol
string comparisonSymbol2 = useCustom ? customSymbol2 : useCrypto ? ethSymbol : useForex ? gbpSymbol : useOil ? hoSymbol : useMetals ? siSymbol : nqSymbol
string comparisonSymbol3 = useCustom ? customSymbol3 : useCrypto ? xrpSymbol : useForex ? dxySymbol : useOil ? clSymbol : useMetals ? hgSymbol : ymSymbol
[requestedHigh1, requestedLow1, requestedBodyHigh1, requestedBodyLow1] = request.security(comparisonSymbol1, timeframe.period, [high, low, math.max(open, close), math.min(open, close)], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
[requestedHigh2, requestedLow2, requestedBodyHigh2, requestedBodyLow2] = request.security(comparisonSymbol2, timeframe.period, [high, low, math.max(open, close), math.min(open, close)], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
[requestedHigh3, requestedLow3, requestedBodyHigh3, requestedBodyLow3] = request.security(comparisonSymbol3, timeframe.period, [high, low, math.max(open, close), math.min(open, close)], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
float high1 = chartRole == 1 ? high : requestedHigh1
float low1 = chartRole == 1 ? low : requestedLow1
float high2 = chartRole == 2 ? high : requestedHigh2
float low2 = chartRole == 2 ? low : requestedLow2
float high3 = chartRole == 4 ? high : requestedHigh3
float low3 = chartRole == 4 ? low : requestedLow3
float chartBodyHigh = math.max(open, close)
float chartBodyLow = math.min(open, close)
float bodyHigh1 = chartRole == 1 ? chartBodyHigh : requestedBodyHigh1
float bodyLow1 = chartRole == 1 ? chartBodyLow : requestedBodyLow1
float bodyHigh2 = chartRole == 2 ? chartBodyHigh : requestedBodyHigh2
float bodyLow2 = chartRole == 2 ? chartBodyLow : requestedBodyLow2
float bodyHigh3 = chartRole == 4 ? chartBodyHigh : requestedBodyHigh3
float bodyLow3 = chartRole == 4 ? chartBodyLow : requestedBodyLow3
// Normalize inverse peers to the displayed chart's direction. Negation with
// high/low swapping preserves strict breaks and wick/body geometry. The chart
// slot itself remains native, including all Point 2 lifecycles and alert sides.
bool inverse12 = useForex and chartRole == 4
bool inverse3 = useForex and chartRole != 4
float rawHigh1 = high1
float rawHigh2 = high2
float rawHigh3 = high3
float rawBodyHigh1 = bodyHigh1
float rawBodyHigh2 = bodyHigh2
float rawBodyHigh3 = bodyHigh3
high1 := inverse12 ? -low1 : high1
low1 := inverse12 ? -rawHigh1 : low1
high2 := inverse12 ? -low2 : high2
low2 := inverse12 ? -rawHigh2 : low2
high3 := inverse3 ? -low3 : high3
low3 := inverse3 ? -rawHigh3 : low3
bodyHigh1 := inverse12 ? -bodyLow1 : bodyHigh1
bodyLow1 := inverse12 ? -rawBodyHigh1 : bodyLow1
bodyHigh2 := inverse12 ? -bodyLow2 : bodyHigh2
bodyLow2 := inverse12 ? -rawBodyHigh2 : bodyLow2
bodyHigh3 := inverse3 ? -bodyLow3 : bodyHigh3
bodyLow3 := inverse3 ? -rawBodyHigh3 : bodyLow3
bool missingCustomData = (na(high1) or na(low1) or na(high2) or na(low2) or na(high3) or na(low3) or na(bodyHigh1) or na(bodyLow1) or na(bodyHigh2) or na(bodyLow2) or na(bodyHigh3) or na(bodyLow3))
 
var CycleState microState = CycleState.new()
var CycleState hiddenMicroState = CycleState.new()
var CycleState ninetyState = CycleState.new()
var CycleState hiddenNinetyState = CycleState.new()
var CycleState dailyState = CycleState.new()
var CycleState hiddenDailyState = CycleState.new()
var CycleState weeklyState = CycleState.new()
var CycleState hiddenWeeklyState = CycleState.new()
var CycleState monthlyState = CycleState.new()
var CycleState hiddenMonthlyState = CycleState.new()
var CycleState yearlyState = CycleState.new()
var CycleState hiddenYearlyState = CycleState.new()
 
bool microActive = supportedChart and microEnabled and f_tf_visible(microMinTf, microMaxTf)
bool ninetyActive = supportedChart and ninetyEnabled and f_tf_visible(ninetyMinTf, ninetyMaxTf)
bool dailyActive = supportedChart and dailyEnabled and f_tf_visible(dailyMinTf, dailyMaxTf)
bool weeklyActive = supportedChart and weeklyEnabled and f_tf_visible(weeklyMinTf, weeklyMaxTf)
bool monthlyActive = supportedChart and monthlyEnabled and f_tf_visible(monthlyMinTf, monthlyMaxTf)
bool yearlyActive = supportedChart and yearlyEnabled and f_tf_visible(yearlyMinTf, yearlyMaxTf)
bool hiddenMicroActive = supportedChart and hiddenMicroEnabled and f_tf_visible(hiddenMicroMinTf, hiddenMicroMaxTf)
bool hiddenNinetyActive = supportedChart and hiddenNinetyEnabled and f_tf_visible(hiddenNinetyMinTf, hiddenNinetyMaxTf)
bool hiddenDailyActive = supportedChart and hiddenDailyEnabled and f_tf_visible(hiddenDailyMinTf, hiddenDailyMaxTf)
bool hiddenWeeklyActive = supportedChart and hiddenWeeklyEnabled and f_tf_visible(hiddenWeeklyMinTf, hiddenWeeklyMaxTf)
bool hiddenMonthlyActive = supportedChart and hiddenMonthlyEnabled and f_tf_visible(hiddenMonthlyMinTf, hiddenMonthlyMaxTf)
bool hiddenYearlyActive = supportedChart and hiddenYearlyEnabled and f_tf_visible(hiddenYearlyMinTf, hiddenYearlyMaxTf)
 
[microBullEvent, microBearEvent] = microState.process(f_micro_key(time), microActive, true, true, "Micro", microBull, microBear, lineStyleInput, lineWidth, labelSizeInput, color(na), chartRole, useMetals, false, false, high1, low1, high2, low2, high3, low3)
[hiddenMicroBullEvent, hiddenMicroBearEvent] = hiddenMicroState.process(f_micro_key(time), hiddenMicroActive, microState.lowFallbackReady, microState.highFallbackReady, "Micro", hiddenMicroBull, hiddenMicroBear, hiddenMicroStyle, hiddenMicroWidth, hiddenMicroLabelSize, hiddenMicroLabelColor, chartRole, useMetals, true, true, bodyHigh1, bodyLow1, bodyHigh2, bodyLow2, bodyHigh3, bodyLow3)
[ninetyBullEvent, ninetyBearEvent] = ninetyState.process(f_ninety_key(time), ninetyActive, true, true, "90m", ninetyBull, ninetyBear, lineStyleInput, lineWidth, labelSizeInput, color(na), chartRole, useMetals, false, false, high1, low1, high2, low2, high3, low3)
[hiddenNinetyBullEvent, hiddenNinetyBearEvent] = hiddenNinetyState.process(f_ninety_key(time), hiddenNinetyActive, ninetyState.lowFallbackReady, ninetyState.highFallbackReady, "90m", hiddenNinetyBull, hiddenNinetyBear, hiddenNinetyStyle, hiddenNinetyWidth, hiddenNinetyLabelSize, hiddenNinetyLabelColor, chartRole, useMetals, true, true, bodyHigh1, bodyLow1, bodyHigh2, bodyLow2, bodyHigh3, bodyLow3)
[dailyBullEvent, dailyBearEvent] = dailyState.process(f_daily_key(time), dailyActive, true, true, "Daily", dailyBull, dailyBear, lineStyleInput, lineWidth, labelSizeInput, color(na), chartRole, useMetals, false, false, high1, low1, high2, low2, high3, low3)
[hiddenDailyBullEvent, hiddenDailyBearEvent] = hiddenDailyState.process(f_daily_key(time), hiddenDailyActive, dailyState.lowFallbackReady, dailyState.highFallbackReady, "Daily", hiddenDailyBull, hiddenDailyBear, hiddenDailyStyle, hiddenDailyWidth, hiddenDailyLabelSize, hiddenDailyLabelColor, chartRole, useMetals, true, true, bodyHigh1, bodyLow1, bodyHigh2, bodyLow2, bodyHigh3, bodyLow3)
[weeklyBullEvent, weeklyBearEvent] = weeklyState.process(f_weekly_key(time), weeklyActive, true, true, "Weekly", weeklyBull, weeklyBear, lineStyleInput, lineWidth, labelSizeInput, color(na), chartRole, useMetals, false, false, high1, low1, high2, low2, high3, low3)
[hiddenWeeklyBullEvent, hiddenWeeklyBearEvent] = hiddenWeeklyState.process(f_weekly_key(time), hiddenWeeklyActive, weeklyState.lowFallbackReady, weeklyState.highFallbackReady, "Weekly", hiddenWeeklyBull, hiddenWeeklyBear, hiddenWeeklyStyle, hiddenWeeklyWidth, hiddenWeeklyLabelSize, hiddenWeeklyLabelColor, chartRole, useMetals, true, true, bodyHigh1, bodyLow1, bodyHigh2, bodyLow2, bodyHigh3, bodyLow3)
[monthlyBullEvent, monthlyBearEvent] = monthlyState.process(f_monthly_key(time), monthlyActive, true, true, "Monthly", monthlyBull, monthlyBear, lineStyleInput, lineWidth, labelSizeInput, color(na), chartRole, useMetals, false, false, high1, low1, high2, low2, high3, low3)
[hiddenMonthlyBullEvent, hiddenMonthlyBearEvent] = hiddenMonthlyState.process(f_monthly_key(time), hiddenMonthlyActive, monthlyState.lowFallbackReady, monthlyState.highFallbackReady, "Monthly", hiddenMonthlyBull, hiddenMonthlyBear, hiddenMonthlyStyle, hiddenMonthlyWidth, hiddenMonthlyLabelSize, hiddenMonthlyLabelColor, chartRole, useMetals, true, true, bodyHigh1, bodyLow1, bodyHigh2, bodyLow2, bodyHigh3, bodyLow3)
[yearlyBullEvent, yearlyBearEvent] = yearlyState.process(f_yearly_key(time), yearlyActive, true, true, "Yearly", yearlyBull, yearlyBear, lineStyleInput, lineWidth, labelSizeInput, color(na), chartRole, useMetals, false, false, high1, low1, high2, low2, high3, low3)
[hiddenYearlyBullEvent, hiddenYearlyBearEvent] = hiddenYearlyState.process(f_yearly_key(time), hiddenYearlyActive, yearlyState.lowFallbackReady, yearlyState.highFallbackReady, "Yearly", hiddenYearlyBull, hiddenYearlyBear, hiddenYearlyStyle, hiddenYearlyWidth, hiddenYearlyLabelSize, hiddenYearlyLabelColor, chartRole, useMetals, true, true, bodyHigh1, bodyLow1, bodyHigh2, bodyLow2, bodyHigh3, bodyLow3)
 
// Point 2 is frozen when the formation quarter closes. A later strict break of
// that endpoint removes the divergence from this asset's chart.
if supportedChart
    f_monitor_archived_signals(high, low, chartBodyHigh, chartBodyLow)
 
bool anyBullEvent = microBullEvent or ninetyBullEvent or dailyBullEvent or weeklyBullEvent or monthlyBullEvent or yearlyBullEvent
bool anyBearEvent = microBearEvent or ninetyBearEvent or dailyBearEvent or weeklyBearEvent or monthlyBearEvent or yearlyBearEvent
 
alertcondition(anyBullEvent, "PROBE Bullish SSMT", "PROBE detected a bullish SSMT divergence.")
alertcondition(anyBearEvent, "PROBE Bearish SSMT", "PROBE detected a bearish SSMT divergence.")
alertcondition(microBullEvent, "PROBE Micro Bullish SSMT", "PROBE detected a bullish Micro-cycle SSMT divergence.")
alertcondition(microBearEvent, "PROBE Micro Bearish SSMT", "PROBE detected a bearish Micro-cycle SSMT divergence.")
alertcondition(ninetyBullEvent, "PROBE 90m Bullish SSMT", "PROBE detected a bullish 90-minute SSMT divergence.")
alertcondition(ninetyBearEvent, "PROBE 90m Bearish SSMT", "PROBE detected a bearish 90-minute SSMT divergence.")
alertcondition(dailyBullEvent, "PROBE Daily Bullish SSMT", "PROBE detected a bullish Daily-cycle SSMT divergence.")
alertcondition(dailyBearEvent, "PROBE Daily Bearish SSMT", "PROBE detected a bearish Daily-cycle SSMT divergence.")
alertcondition(weeklyBullEvent, "PROBE Weekly Bullish SSMT", "PROBE detected a bullish Weekly-cycle SSMT divergence.")
alertcondition(weeklyBearEvent, "PROBE Weekly Bearish SSMT", "PROBE detected a bearish Weekly-cycle SSMT divergence.")
alertcondition(monthlyBullEvent, "PROBE Monthly Bullish SSMT", "PROBE detected a bullish Monthly-cycle SSMT divergence.")
alertcondition(monthlyBearEvent, "PROBE Monthly Bearish SSMT", "PROBE detected a bearish Monthly-cycle SSMT divergence.")
alertcondition(yearlyBullEvent, "PROBE Yearly Bullish SSMT", "PROBE detected a bullish Yearly-cycle SSMT divergence.")
alertcondition(yearlyBearEvent, "PROBE Yearly Bearish SSMT", "PROBE detected a bearish Yearly-cycle SSMT divergence.")
 
var table statusTable = table.new(position.top_right, 1, 2, border_width = 1)
if barstate.islast
    if showStatus or missingCustomData or (useCustom and not supportedChart)
        string groupText = useCustom ? customName1 + " / " + customName2 + " / " + customName3 : useCrypto ? "BTCUSD / ETHUSD / XRPUSD" : useForex ? "EURUSD / GBPUSD / DXY (inverse)" : useOil ? "RB / HO / CL" : useMetals ? "GC / SI / HG" : "ES / NQ / YM"
        bool anyHiddenActive = hiddenMicroActive or hiddenNinetyActive or hiddenDailyActive or hiddenWeeklyActive or hiddenMonthlyActive or hiddenYearlyActive
        string activeText = "Active: " + (microActive ? "Micro " : "") + (ninetyActive ? "90m " : "") + (dailyActive ? "Daily " : "") + (weeklyActive ? "Weekly " : "") + (monthlyActive ? "Monthly " : "") + (yearlyActive ? "Yearly " : "") + (anyHiddenActive ? "+ Hidden" : "")
        string statusText = supportedChart ? activeText : useCustom ? "Chart is not in the custom group. Set Custom chart represents." : "Choose the group and chart asset in Settings"
        if missingCustomData and supportedChart
            statusText := "Comparison data unavailable. Check comparison symbols and feed access."
        table.cell(statusTable, 0, 0, supportedChart ? "PROBE SSMT | " + groupText : "PROBE SSMT | Unsupported chart", text_color = supportedChart and not missingCustomData ? color.white : color.orange, bgcolor = color.new(color.black, 15))
        table.cell(statusTable, 0, 1, statusText, text_color = color.silver, bgcolor = color.new(color.black, 15))
    else
        table.clear(statusTable, 0, 0, 0, 1)
 
 
// A separate set of three rolling drawings; never archived with SSMT signals.
type TrueOpen
    int anchor = na
    int endTime = na
    line level = na
    label caption = na
 
method observe(TrueOpen this, int t, float price, int h, int m, string title, color tint, int endHour = -1) =>
    bool exactAnchor = hour(t, TZ) == h and minute(t, TZ) == m and second(t, TZ) == 0
    if exactAnchor and (na(this.anchor) or t > this.anchor) and not na(price)
        line.delete(this.level)
        label.delete(this.caption)
        this.anchor := t
        this.endTime := endHour < 0 ? na : timestamp(TZ, year(t, TZ), month(t, TZ), dayofmonth(t, TZ), endHour, 0)
        this.level := line.new(t, price, na(this.endTime) ? t + MINUTE_MS : this.endTime, price, xloc = xloc.bar_time, extend = na(this.endTime) ? extend.right : extend.none, color = tint, style = line.style_dashed)
        this.caption := label.new(t, price, title + "  " + str.tostring(price, format.mintick), xloc = xloc.bar_time, style = label.style_label_down, color = color.new(color.black, 100), textcolor = tint, size = size.normal)
 
method positionCaption(TrueOpen this, int visibleTime) =>
    if not na(this.caption)
        int captionTime = math.max(this.anchor, na(this.endTime) ? visibleTime : math.min(visibleTime, this.endTime))
        label.set_x(this.caption, captionTime)
 
var TrueOpen dayOpen = TrueOpen.new()
var TrueOpen nyOpen = TrueOpen.new()
var TrueOpen pmOpen = TrueOpen.new()
if showTrueOpens and chart.is_standard and timeframe.isintraday
    if timeframe.in_seconds() <= 60
        dayOpen.observe(time, open, 0, 0, "True Day Open", trueDayColor)
        nyOpen.observe(time, open, 7, 30, "True New York Open", trueNyColor, 12)
        pmOpen.observe(time, open, 13, 30, "True Afternoon Open", truePmColor, 18)
    else
        [openTimes, openPrices] = request.security_lower_tf(syminfo.tickerid, "1", [time, open])
        if array.size(openTimes) > 0
            for i = 0 to array.size(openTimes) - 1
                int t = array.get(openTimes, i)
                float price = array.get(openPrices, i)
                dayOpen.observe(t, price, 0, 0, "True Day Open", trueDayColor)
                nyOpen.observe(t, price, 7, 30, "True New York Open", trueNyColor, 12)
                pmOpen.observe(t, price, 13, 30, "True Afternoon Open", truePmColor, 18)
 
    // Names and recorded prices sit above the line; session labels stop at its end.
    if barstate.islast
        int captionTime = chart.right_visible_bar_time + int(timeframe.in_seconds() * 1000) * 2
        dayOpen.positionCaption(captionTime)
        nyOpen.positionCaption(captionTime)
        pmOpen.positionCaption(captionTime)

← 返回列表