RTH Gap - Advanced

JahSent · study · 873 行 · 点赞 4 · TradingView 原页

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

Pine Script

//@version=6
// RTH Gap — Advanced v1.1
// Rebuilt from the supplied "Regular Trading Hours GAP" script.
// NY times: previous RTH 16:14 one-minute close -> next 09:30 one-minute open.
// SPY uses 15:59 one-minute close (16:00 RTH close).
// Probability percentages are 2026 MNQ/NQ in-sample descriptive frequencies,
// conditional on gap magnitude, for 09:30–10:29 NY only.
indicator("RTH Gap — Advanced v1.1", "RTHGap", overlay = true,
     max_boxes_count = 200, max_lines_count = 500, max_labels_count = 500)
 
const string NY = "America/New_York"
const int MINUTE_MS = 60000
const int KEEP_EVENTS = 420
 
// Every configured gap uses the EXACT same settings structure.
type GapStyle
    bool enabled
    string source
    string mode
    int panelOffset
    int panelWidth
    color fillColor
    color borderColor
    string borderStyle
    int borderWidth
    bool showCE
    color ceColor
    string ceStyle
    int ceWidth
    bool cePrice
    bool ceProbability
    bool fullPrice
    bool fullProbability
    string divisions
    color levelColor
    string levelStyle
    int levelWidth
    bool levelPrice
    bool levelProbability
    color valuesColor
    string valuesSize
    string valuesPosition
    int valuesOffset
    bool showTitle
    bool showPoints
    string titleCustom
    color titleColor
    string titleSize
    string titlePosition
    int titleX
    float titleY
 
type GapEvent
    int eventTime
    int rthEndTime
    int refTime
    int dayKey
    int weekDay
    float rthOpen
    float previousClose
    float highLowFrom
    float highLowTo
    float standardFill
    float highLowFill
 
const string MODE_END = "RTH End"
const string MODE_NOW = "To Current Bar"
const string MODE_PANEL = "Right Panel"
const string SRC_STANDARD = "Close/Open"
const string SRC_HILO = "Hi-Lo"
const string SRC_BOTH = "Both"
const string DIV_OFF = "Off"
const string DIV_QUARTERS = "Quarters"
const string DIV_OCTANTS = "Octants"
 
// ────────────── 01. TODAY + HISTORY ──────────────
const string G1 = "01  |  TODAY + HISTORY"
bool g1_enabled = input.bool(true,"Enabled  /  Gap source", group=G1, inline="active")
string g1_source = input.string("Close/Open","", options=[SRC_STANDARD,SRC_HILO,SRC_BOTH],group=G1,inline="active")
string g1_mode = input.string("RTH End","Placement",options=[MODE_END,MODE_NOW,MODE_PANEL],group=G1)
int g1_panelOffset = input.int(40,"Panel offset  /  Width",minval=1,maxval=20000,group=G1,inline="panel",tooltip="Only Right Panel. Time-based units of the chart timeframe; weekends / session closures are not skipped. Not subject to bar_index 500-forward restriction.")
int g1_panelWidth = input.int(22,"",minval=1,maxval=5000,group=G1,inline="panel")
int historyCount = input.int(1,"Previous trading days (shared style)",minval=0,maxval=20,group=G1,tooltip="These are ADDITIONAL past gaps. Each label displays its own formation weekday. Previous days use identical visual settings.")
color g1_fillColor = input.color(#9C27B019,"Box fill  /  Outline",group=G1,inline="box")
color g1_borderColor = input.color(#9C27B019,"",group=G1,inline="box")
string g1_borderStyle = input.string("Solid","Outline style  /  Width",options=["Solid","Dashed","Dotted"],group=G1,inline="edge")
int g1_borderWidth = input.int(1,"",minval=1,maxval=4,group=G1,inline="edge")
bool g1_showCE = input.bool(true,"Show CE  /  CE color",group=G1,inline="ce")
color g1_ceColor = input.color(#F236454D,"",group=G1,inline="ce")
string g1_ceStyle = input.string("Solid","CE style  /  Width",options=["Solid","Dashed","Dotted"],group=G1,inline="ces")
int g1_ceWidth = input.int(1,"",minval=1,maxval=4,group=G1,inline="ces")
bool g1_cePrice = input.bool(true,"CE price  /  Probability",group=G1,inline="cevals")
bool g1_ceProbability = input.bool(false,"",group=G1,inline="cevals")
bool g1_fullPrice = input.bool(false,"100% price  /  Probability",group=G1,inline="edgevals")
bool g1_fullProbability = input.bool(false,"",group=G1,inline="edgevals")
string g1_divisions = input.string("Off","Divisions  /  Line color",options=[DIV_OFF,DIV_QUARTERS,DIV_OCTANTS],group=G1,inline="levels")
color g1_levelColor = input.color(#9C27B0B2,"",group=G1,inline="levels")
string g1_levelStyle = input.string("Dotted","Levels style  /  Width",options=["Solid","Dashed","Dotted"],group=G1,inline="levs")
int g1_levelWidth = input.int(1,"",minval=1,maxval=4,group=G1,inline="levs")
bool g1_levelPrice = input.bool(false,"Levels price  /  Probability",group=G1,inline="lvals")
bool g1_levelProbability = input.bool(false,"",group=G1,inline="lvals",tooltip="Empirical frequencies exist ONLY for 25% and 75% (and CE 50%), for MNQ/NQ standard gaps; no invented estimates for octant-only levels or Hi-Lo gaps.")
color g1_valuesColor = input.color(#787B86,"Values color  /  Text size",group=G1,inline="vtxt")
string g1_valuesSize = input.string("Tiny","",options=["Tiny","Small","Normal","Large","Huge"],group=G1,inline="vtxt")
string g1_valuesPosition = input.string("Inside Right","Values position  /  Offset",options=["Inside Left","Inside Right","Outside Right"],group=G1,inline="vpos")
int g1_valuesOffset = input.int(3,"",minval=0,maxval=20000,group=G1,inline="vpos")
bool g1_showTitle = input.bool(false,"Show name  /  Show points",group=G1,inline="title")
bool g1_showPoints = input.bool(false,"",group=G1,inline="title",tooltip="When both enabled: L-Mon 110Pt. Rounded half-up: 110.25 -> 110; 110.50 -> 111.")
string g1_titleCustom = input.string("","Custom name",group=G1,tooltip="Empty: Mon/Tue/Wed/Thu/Fri. For Today + History, custom name affects TODAY only; historical names always show their own weekday.")
color g1_titleColor = input.color(#787B86,"Title color  /  Text size",group=G1,inline="ntxt")
string g1_titleSize = input.string("Small","",options=["Tiny","Small","Normal","Large","Huge"],group=G1,inline="ntxt")
string g1_titlePosition = input.string("Inside Center","Name position",options=["Inside Top Left","Inside Top Center","Inside Top Right","Inside Center Left","Inside Center","Inside Center Right","Inside Bottom Left","Inside Bottom Center","Inside Bottom Right","Outside Left Center","Outside Right Center","Outside Top Center","Outside Bottom Center"],group=G1)
int g1_titleX = input.int(0,"Title X shift  /  Y shift",minval=-20000,maxval=20000,group=G1,inline="noffs")
float g1_titleY = input.float(0.0,"",step=0.25,group=G1,inline="noffs")
GapStyle g1 = GapStyle.new(
    g1_enabled,
    g1_source,
    g1_mode,
    g1_panelOffset,
    g1_panelWidth,
    g1_fillColor,
    g1_borderColor,
    g1_borderStyle,
    g1_borderWidth,
    g1_showCE,
    g1_ceColor,
    g1_ceStyle,
    g1_ceWidth,
    g1_cePrice,
    g1_ceProbability,
    g1_fullPrice,
    g1_fullProbability,
    g1_divisions,
    g1_levelColor,
    g1_levelStyle,
    g1_levelWidth,
    g1_levelPrice,
    g1_levelProbability,
    g1_valuesColor,
    g1_valuesSize,
    g1_valuesPosition,
    g1_valuesOffset,
    g1_showTitle,
    g1_showPoints,
    g1_titleCustom,
    g1_titleColor,
    g1_titleSize,
    g1_titlePosition,
    g1_titleX,
    g1_titleY
)
 
// ────────────── 02. LAST MONDAY  ·  L-Mon ──────────────
const string G2 = "02  |  LAST MONDAY  ·  L-Mon"
bool g2_enabled = input.bool(true,"Enabled  /  Gap source", group=G2, inline="active")
string g2_source = input.string("Close/Open","", options=[SRC_STANDARD,SRC_HILO,SRC_BOTH],group=G2,inline="active")
string g2_mode = input.string("Right Panel","Placement",options=[MODE_END,MODE_NOW,MODE_PANEL],group=G2)
int g2_panelOffset = input.int(75,"Panel offset  /  Width",minval=1,maxval=20000,group=G2,inline="panel",tooltip="Only Right Panel. Time-based units of the chart timeframe; weekends / session closures are not skipped. Not subject to bar_index 500-forward restriction.")
int g2_panelWidth = input.int(10,"",minval=1,maxval=5000,group=G2,inline="panel")
color g2_fillColor = input.color(#FF980019,"Box fill  /  Outline",group=G2,inline="box")
color g2_borderColor = input.color(#FF980019,"",group=G2,inline="box")
string g2_borderStyle = input.string("Solid","Outline style  /  Width",options=["Solid","Dashed","Dotted"],group=G2,inline="edge")
int g2_borderWidth = input.int(1,"",minval=1,maxval=4,group=G2,inline="edge")
bool g2_showCE = input.bool(true,"Show CE  /  CE color",group=G2,inline="ce")
color g2_ceColor = input.color(#FF980033,"",group=G2,inline="ce")
string g2_ceStyle = input.string("Solid","CE style  /  Width",options=["Solid","Dashed","Dotted"],group=G2,inline="ces")
int g2_ceWidth = input.int(1,"",minval=1,maxval=4,group=G2,inline="ces")
bool g2_cePrice = input.bool(false,"CE price  /  Probability",group=G2,inline="cevals")
bool g2_ceProbability = input.bool(false,"",group=G2,inline="cevals")
bool g2_fullPrice = input.bool(false,"100% price  /  Probability",group=G2,inline="edgevals")
bool g2_fullProbability = input.bool(false,"",group=G2,inline="edgevals")
string g2_divisions = input.string("Quarters","Divisions  /  Line color",options=[DIV_OFF,DIV_QUARTERS,DIV_OCTANTS],group=G2,inline="levels")
color g2_levelColor = input.color(#FF9800B2,"",group=G2,inline="levels")
string g2_levelStyle = input.string("Dotted","Levels style  /  Width",options=["Solid","Dashed","Dotted"],group=G2,inline="levs")
int g2_levelWidth = input.int(1,"",minval=1,maxval=4,group=G2,inline="levs")
bool g2_levelPrice = input.bool(false,"Levels price  /  Probability",group=G2,inline="lvals")
bool g2_levelProbability = input.bool(false,"",group=G2,inline="lvals",tooltip="Empirical frequencies exist ONLY for 25% and 75% (and CE 50%), for MNQ/NQ standard gaps; no invented estimates for octant-only levels or Hi-Lo gaps.")
color g2_valuesColor = input.color(#787B86,"Values color  /  Text size",group=G2,inline="vtxt")
string g2_valuesSize = input.string("Tiny","",options=["Tiny","Small","Normal","Large","Huge"],group=G2,inline="vtxt")
string g2_valuesPosition = input.string("Inside Right","Values position  /  Offset",options=["Inside Left","Inside Right","Outside Right"],group=G2,inline="vpos")
int g2_valuesOffset = input.int(2,"",minval=0,maxval=20000,group=G2,inline="vpos")
bool g2_showTitle = input.bool(true,"Show name  /  Show points",group=G2,inline="title")
bool g2_showPoints = input.bool(true,"",group=G2,inline="title",tooltip="When both enabled: L-Mon 110Pt. Rounded half-up: 110.25 -> 110; 110.50 -> 111.")
string g2_titleCustom = input.string("L-Mon","Custom name",group=G2,tooltip="Empty: Mon/Tue/Wed/Thu/Fri. For Today + History, custom name affects TODAY only; historical names always show their own weekday.")
color g2_titleColor = input.color(#787B86,"Title color  /  Text size",group=G2,inline="ntxt")
string g2_titleSize = input.string("Small","",options=["Tiny","Small","Normal","Large","Huge"],group=G2,inline="ntxt")
string g2_titlePosition = input.string("Inside Center","Name position",options=["Inside Top Left","Inside Top Center","Inside Top Right","Inside Center Left","Inside Center","Inside Center Right","Inside Bottom Left","Inside Bottom Center","Inside Bottom Right","Outside Left Center","Outside Right Center","Outside Top Center","Outside Bottom Center"],group=G2)
int g2_titleX = input.int(0,"Title X shift  /  Y shift",minval=-20000,maxval=20000,group=G2,inline="noffs")
float g2_titleY = input.float(0.0,"",step=0.25,group=G2,inline="noffs")
GapStyle g2 = GapStyle.new(
    g2_enabled,
    g2_source,
    g2_mode,
    g2_panelOffset,
    g2_panelWidth,
    g2_fillColor,
    g2_borderColor,
    g2_borderStyle,
    g2_borderWidth,
    g2_showCE,
    g2_ceColor,
    g2_ceStyle,
    g2_ceWidth,
    g2_cePrice,
    g2_ceProbability,
    g2_fullPrice,
    g2_fullProbability,
    g2_divisions,
    g2_levelColor,
    g2_levelStyle,
    g2_levelWidth,
    g2_levelPrice,
    g2_levelProbability,
    g2_valuesColor,
    g2_valuesSize,
    g2_valuesPosition,
    g2_valuesOffset,
    g2_showTitle,
    g2_showPoints,
    g2_titleCustom,
    g2_titleColor,
    g2_titleSize,
    g2_titlePosition,
    g2_titleX,
    g2_titleY
)
 
// ────────────── 03. PREVIOUS MONDAY  ·  P-Mon ──────────────
const string G3 = "03  |  PREVIOUS MONDAY  ·  P-Mon"
bool g3_enabled = input.bool(true,"Enabled  /  Gap source", group=G3, inline="active")
string g3_source = input.string("Close/Open","", options=[SRC_STANDARD,SRC_HILO,SRC_BOTH],group=G3,inline="active")
string g3_mode = input.string("Right Panel","Placement",options=[MODE_END,MODE_NOW,MODE_PANEL],group=G3)
int g3_panelOffset = input.int(75,"Panel offset  /  Width",minval=1,maxval=20000,group=G3,inline="panel",tooltip="Only Right Panel. Time-based units of the chart timeframe; weekends / session closures are not skipped. Not subject to bar_index 500-forward restriction.")
int g3_panelWidth = input.int(10,"",minval=1,maxval=5000,group=G3,inline="panel")
color g3_fillColor = input.color(#08998119,"Box fill  /  Outline",group=G3,inline="box")
color g3_borderColor = input.color(#08998119,"",group=G3,inline="box")
string g3_borderStyle = input.string("Solid","Outline style  /  Width",options=["Solid","Dashed","Dotted"],group=G3,inline="edge")
int g3_borderWidth = input.int(1,"",minval=1,maxval=4,group=G3,inline="edge")
bool g3_showCE = input.bool(true,"Show CE  /  CE color",group=G3,inline="ce")
color g3_ceColor = input.color(#089981E6,"",group=G3,inline="ce")
string g3_ceStyle = input.string("Dotted","CE style  /  Width",options=["Solid","Dashed","Dotted"],group=G3,inline="ces")
int g3_ceWidth = input.int(1,"",minval=1,maxval=4,group=G3,inline="ces")
bool g3_cePrice = input.bool(false,"CE price  /  Probability",group=G3,inline="cevals")
bool g3_ceProbability = input.bool(false,"",group=G3,inline="cevals")
bool g3_fullPrice = input.bool(false,"100% price  /  Probability",group=G3,inline="edgevals")
bool g3_fullProbability = input.bool(false,"",group=G3,inline="edgevals")
string g3_divisions = input.string("Quarters","Divisions  /  Line color",options=[DIV_OFF,DIV_QUARTERS,DIV_OCTANTS],group=G3,inline="levels")
color g3_levelColor = input.color(#00BCD4B2,"",group=G3,inline="levels")
string g3_levelStyle = input.string("Dotted","Levels style  /  Width",options=["Solid","Dashed","Dotted"],group=G3,inline="levs")
int g3_levelWidth = input.int(1,"",minval=1,maxval=4,group=G3,inline="levs")
bool g3_levelPrice = input.bool(false,"Levels price  /  Probability",group=G3,inline="lvals")
bool g3_levelProbability = input.bool(false,"",group=G3,inline="lvals",tooltip="Empirical frequencies exist ONLY for 25% and 75% (and CE 50%), for MNQ/NQ standard gaps; no invented estimates for octant-only levels or Hi-Lo gaps.")
color g3_valuesColor = input.color(#787B86,"Values color  /  Text size",group=G3,inline="vtxt")
string g3_valuesSize = input.string("Tiny","",options=["Tiny","Small","Normal","Large","Huge"],group=G3,inline="vtxt")
string g3_valuesPosition = input.string("Inside Right","Values position  /  Offset",options=["Inside Left","Inside Right","Outside Right"],group=G3,inline="vpos")
int g3_valuesOffset = input.int(2,"",minval=0,maxval=20000,group=G3,inline="vpos")
bool g3_showTitle = input.bool(true,"Show name  /  Show points",group=G3,inline="title")
bool g3_showPoints = input.bool(true,"",group=G3,inline="title",tooltip="When both enabled: L-Mon 110Pt. Rounded half-up: 110.25 -> 110; 110.50 -> 111.")
string g3_titleCustom = input.string("P-Mon","Custom name",group=G3,tooltip="Empty: Mon/Tue/Wed/Thu/Fri. For Today + History, custom name affects TODAY only; historical names always show their own weekday.")
color g3_titleColor = input.color(#787B86,"Title color  /  Text size",group=G3,inline="ntxt")
string g3_titleSize = input.string("Small","",options=["Tiny","Small","Normal","Large","Huge"],group=G3,inline="ntxt")
string g3_titlePosition = input.string("Inside Center","Name position",options=["Inside Top Left","Inside Top Center","Inside Top Right","Inside Center Left","Inside Center","Inside Center Right","Inside Bottom Left","Inside Bottom Center","Inside Bottom Right","Outside Left Center","Outside Right Center","Outside Top Center","Outside Bottom Center"],group=G3)
int g3_titleX = input.int(0,"Title X shift  /  Y shift",minval=-20000,maxval=20000,group=G3,inline="noffs")
float g3_titleY = input.float(0.0,"",step=0.25,group=G3,inline="noffs")
GapStyle g3 = GapStyle.new(
    g3_enabled,
    g3_source,
    g3_mode,
    g3_panelOffset,
    g3_panelWidth,
    g3_fillColor,
    g3_borderColor,
    g3_borderStyle,
    g3_borderWidth,
    g3_showCE,
    g3_ceColor,
    g3_ceStyle,
    g3_ceWidth,
    g3_cePrice,
    g3_ceProbability,
    g3_fullPrice,
    g3_fullProbability,
    g3_divisions,
    g3_levelColor,
    g3_levelStyle,
    g3_levelWidth,
    g3_levelPrice,
    g3_levelProbability,
    g3_valuesColor,
    g3_valuesSize,
    g3_valuesPosition,
    g3_valuesOffset,
    g3_showTitle,
    g3_showPoints,
    g3_titleCustom,
    g3_titleColor,
    g3_titleSize,
    g3_titlePosition,
    g3_titleX,
    g3_titleY
)
 
// ────────────── 04. LAST FRIDAY  ·  L-Fri ──────────────
const string G4 = "04  |  LAST FRIDAY  ·  L-Fri"
bool g4_enabled = input.bool(true,"Enabled  /  Gap source", group=G4, inline="active")
string g4_source = input.string("Close/Open","", options=[SRC_STANDARD,SRC_HILO,SRC_BOTH],group=G4,inline="active")
string g4_mode = input.string("Right Panel","Placement",options=[MODE_END,MODE_NOW,MODE_PANEL],group=G4)
int g4_panelOffset = input.int(75,"Panel offset  /  Width",minval=1,maxval=20000,group=G4,inline="panel",tooltip="Only Right Panel. Time-based units of the chart timeframe; weekends / session closures are not skipped. Not subject to bar_index 500-forward restriction.")
int g4_panelWidth = input.int(10,"",minval=1,maxval=5000,group=G4,inline="panel")
color g4_fillColor = input.color(#E040FB19,"Box fill  /  Outline",group=G4,inline="box")
color g4_borderColor = input.color(#9C27B019,"",group=G4,inline="box")
string g4_borderStyle = input.string("Solid","Outline style  /  Width",options=["Solid","Dashed","Dotted"],group=G4,inline="edge")
int g4_borderWidth = input.int(1,"",minval=1,maxval=4,group=G4,inline="edge")
bool g4_showCE = input.bool(true,"Show CE  /  CE color",group=G4,inline="ce")
color g4_ceColor = input.color(#E040FBE6,"",group=G4,inline="ce")
string g4_ceStyle = input.string("Dotted","CE style  /  Width",options=["Solid","Dashed","Dotted"],group=G4,inline="ces")
int g4_ceWidth = input.int(1,"",minval=1,maxval=4,group=G4,inline="ces")
bool g4_cePrice = input.bool(false,"CE price  /  Probability",group=G4,inline="cevals")
bool g4_ceProbability = input.bool(false,"",group=G4,inline="cevals")
bool g4_fullPrice = input.bool(false,"100% price  /  Probability",group=G4,inline="edgevals")
bool g4_fullProbability = input.bool(false,"",group=G4,inline="edgevals")
string g4_divisions = input.string("Off","Divisions  /  Line color",options=[DIV_OFF,DIV_QUARTERS,DIV_OCTANTS],group=G4,inline="levels")
color g4_levelColor = input.color(#9C27B0B2,"",group=G4,inline="levels")
string g4_levelStyle = input.string("Dotted","Levels style  /  Width",options=["Solid","Dashed","Dotted"],group=G4,inline="levs")
int g4_levelWidth = input.int(1,"",minval=1,maxval=4,group=G4,inline="levs")
bool g4_levelPrice = input.bool(false,"Levels price  /  Probability",group=G4,inline="lvals")
bool g4_levelProbability = input.bool(false,"",group=G4,inline="lvals",tooltip="Empirical frequencies exist ONLY for 25% and 75% (and CE 50%), for MNQ/NQ standard gaps; no invented estimates for octant-only levels or Hi-Lo gaps.")
color g4_valuesColor = input.color(#787B86,"Values color  /  Text size",group=G4,inline="vtxt")
string g4_valuesSize = input.string("Tiny","",options=["Tiny","Small","Normal","Large","Huge"],group=G4,inline="vtxt")
string g4_valuesPosition = input.string("Inside Right","Values position  /  Offset",options=["Inside Left","Inside Right","Outside Right"],group=G4,inline="vpos")
int g4_valuesOffset = input.int(2,"",minval=0,maxval=20000,group=G4,inline="vpos")
bool g4_showTitle = input.bool(true,"Show name  /  Show points",group=G4,inline="title")
bool g4_showPoints = input.bool(true,"",group=G4,inline="title",tooltip="When both enabled: L-Mon 110Pt. Rounded half-up: 110.25 -> 110; 110.50 -> 111.")
string g4_titleCustom = input.string("L-Fri","Custom name",group=G4,tooltip="Empty: Mon/Tue/Wed/Thu/Fri. For Today + History, custom name affects TODAY only; historical names always show their own weekday.")
color g4_titleColor = input.color(#787B86,"Title color  /  Text size",group=G4,inline="ntxt")
string g4_titleSize = input.string("Small","",options=["Tiny","Small","Normal","Large","Huge"],group=G4,inline="ntxt")
string g4_titlePosition = input.string("Inside Center","Name position",options=["Inside Top Left","Inside Top Center","Inside Top Right","Inside Center Left","Inside Center","Inside Center Right","Inside Bottom Left","Inside Bottom Center","Inside Bottom Right","Outside Left Center","Outside Right Center","Outside Top Center","Outside Bottom Center"],group=G4)
int g4_titleX = input.int(0,"Title X shift  /  Y shift",minval=-20000,maxval=20000,group=G4,inline="noffs")
float g4_titleY = input.float(0.0,"",step=0.25,group=G4,inline="noffs")
GapStyle g4 = GapStyle.new(
    g4_enabled,
    g4_source,
    g4_mode,
    g4_panelOffset,
    g4_panelWidth,
    g4_fillColor,
    g4_borderColor,
    g4_borderStyle,
    g4_borderWidth,
    g4_showCE,
    g4_ceColor,
    g4_ceStyle,
    g4_ceWidth,
    g4_cePrice,
    g4_ceProbability,
    g4_fullPrice,
    g4_fullProbability,
    g4_divisions,
    g4_levelColor,
    g4_levelStyle,
    g4_levelWidth,
    g4_levelPrice,
    g4_levelProbability,
    g4_valuesColor,
    g4_valuesSize,
    g4_valuesPosition,
    g4_valuesOffset,
    g4_showTitle,
    g4_showPoints,
    g4_titleCustom,
    g4_titleColor,
    g4_titleSize,
    g4_titlePosition,
    g4_titleX,
    g4_titleY
)
 
// ────────────── 05. PREVIOUS FRIDAY  ·  P-Fri ──────────────
const string G5 = "05  |  PREVIOUS FRIDAY  ·  P-Fri"
bool g5_enabled = input.bool(true,"Enabled  /  Gap source", group=G5, inline="active")
string g5_source = input.string("Close/Open","", options=[SRC_STANDARD,SRC_HILO,SRC_BOTH],group=G5,inline="active")
string g5_mode = input.string("Right Panel","Placement",options=[MODE_END,MODE_NOW,MODE_PANEL],group=G5)
int g5_panelOffset = input.int(75,"Panel offset  /  Width",minval=1,maxval=20000,group=G5,inline="panel",tooltip="Only Right Panel. Time-based units of the chart timeframe; weekends / session closures are not skipped. Not subject to bar_index 500-forward restriction.")
int g5_panelWidth = input.int(10,"",minval=1,maxval=5000,group=G5,inline="panel")
color g5_fillColor = input.color(#311B9219,"Box fill  /  Outline",group=G5,inline="box")
color g5_borderColor = input.color(#2962FF19,"",group=G5,inline="box")
string g5_borderStyle = input.string("Solid","Outline style  /  Width",options=["Solid","Dashed","Dotted"],group=G5,inline="edge")
int g5_borderWidth = input.int(1,"",minval=1,maxval=4,group=G5,inline="edge")
bool g5_showCE = input.bool(true,"Show CE  /  CE color",group=G5,inline="ce")
color g5_ceColor = input.color(#2962FFE6,"",group=G5,inline="ce")
string g5_ceStyle = input.string("Dotted","CE style  /  Width",options=["Solid","Dashed","Dotted"],group=G5,inline="ces")
int g5_ceWidth = input.int(1,"",minval=1,maxval=4,group=G5,inline="ces")
bool g5_cePrice = input.bool(false,"CE price  /  Probability",group=G5,inline="cevals")
bool g5_ceProbability = input.bool(false,"",group=G5,inline="cevals")
bool g5_fullPrice = input.bool(false,"100% price  /  Probability",group=G5,inline="edgevals")
bool g5_fullProbability = input.bool(false,"",group=G5,inline="edgevals")
string g5_divisions = input.string("Quarters","Divisions  /  Line color",options=[DIV_OFF,DIV_QUARTERS,DIV_OCTANTS],group=G5,inline="levels")
color g5_levelColor = input.color(#2962FFB2,"",group=G5,inline="levels")
string g5_levelStyle = input.string("Dotted","Levels style  /  Width",options=["Solid","Dashed","Dotted"],group=G5,inline="levs")
int g5_levelWidth = input.int(1,"",minval=1,maxval=4,group=G5,inline="levs")
bool g5_levelPrice = input.bool(false,"Levels price  /  Probability",group=G5,inline="lvals")
bool g5_levelProbability = input.bool(false,"",group=G5,inline="lvals",tooltip="Empirical frequencies exist ONLY for 25% and 75% (and CE 50%), for MNQ/NQ standard gaps; no invented estimates for octant-only levels or Hi-Lo gaps.")
color g5_valuesColor = input.color(#787B86,"Values color  /  Text size",group=G5,inline="vtxt")
string g5_valuesSize = input.string("Tiny","",options=["Tiny","Small","Normal","Large","Huge"],group=G5,inline="vtxt")
string g5_valuesPosition = input.string("Inside Right","Values position  /  Offset",options=["Inside Left","Inside Right","Outside Right"],group=G5,inline="vpos")
int g5_valuesOffset = input.int(2,"",minval=0,maxval=20000,group=G5,inline="vpos")
bool g5_showTitle = input.bool(true,"Show name  /  Show points",group=G5,inline="title")
bool g5_showPoints = input.bool(true,"",group=G5,inline="title",tooltip="When both enabled: L-Mon 110Pt. Rounded half-up: 110.25 -> 110; 110.50 -> 111.")
string g5_titleCustom = input.string("P-Fri","Custom name",group=G5,tooltip="Empty: Mon/Tue/Wed/Thu/Fri. For Today + History, custom name affects TODAY only; historical names always show their own weekday.")
color g5_titleColor = input.color(#787B86,"Title color  /  Text size",group=G5,inline="ntxt")
string g5_titleSize = input.string("Small","",options=["Tiny","Small","Normal","Large","Huge"],group=G5,inline="ntxt")
string g5_titlePosition = input.string("Inside Center","Name position",options=["Inside Top Left","Inside Top Center","Inside Top Right","Inside Center Left","Inside Center","Inside Center Right","Inside Bottom Left","Inside Bottom Center","Inside Bottom Right","Outside Left Center","Outside Right Center","Outside Top Center","Outside Bottom Center"],group=G5)
int g5_titleX = input.int(0,"Title X shift  /  Y shift",minval=-20000,maxval=20000,group=G5,inline="noffs")
float g5_titleY = input.float(0.0,"",step=0.25,group=G5,inline="noffs")
GapStyle g5 = GapStyle.new(
    g5_enabled,
    g5_source,
    g5_mode,
    g5_panelOffset,
    g5_panelWidth,
    g5_fillColor,
    g5_borderColor,
    g5_borderStyle,
    g5_borderWidth,
    g5_showCE,
    g5_ceColor,
    g5_ceStyle,
    g5_ceWidth,
    g5_cePrice,
    g5_ceProbability,
    g5_fullPrice,
    g5_fullProbability,
    g5_divisions,
    g5_levelColor,
    g5_levelStyle,
    g5_levelWidth,
    g5_levelPrice,
    g5_levelProbability,
    g5_valuesColor,
    g5_valuesSize,
    g5_valuesPosition,
    g5_valuesOffset,
    g5_showTitle,
    g5_showPoints,
    g5_titleCustom,
    g5_titleColor,
    g5_titleSize,
    g5_titlePosition,
    g5_titleX,
    g5_titleY
)
 
// ────────────── 06. MANUAL DATE ──────────────
const string G6 = "06  |  MANUAL DATE"
bool g6_enabled = input.bool(false,"Enabled  /  Gap source", group=G6, inline="active")
string g6_source = input.string("Close/Open","", options=[SRC_STANDARD,SRC_HILO,SRC_BOTH],group=G6,inline="active")
string g6_mode = input.string("RTH End","Placement",options=[MODE_END,MODE_NOW,MODE_PANEL],group=G6)
int g6_panelOffset = input.int(40,"Panel offset  /  Width",minval=1,maxval=20000,group=G6,inline="panel",tooltip="Only Right Panel. Time-based units of the chart timeframe; weekends / session closures are not skipped. Not subject to bar_index 500-forward restriction.")
int g6_panelWidth = input.int(22,"",minval=1,maxval=5000,group=G6,inline="panel")
int manualDate = input.time(1792133100000,"RTH formation date (NY)",group=G6,tooltip="Select any NY trading date whose 09:30 event is available in loaded chart history. The time component is ignored.")
color g6_fillColor = input.color(#787B8619,"Box fill  /  Outline",group=G6,inline="box")
color g6_borderColor = input.color(#B2B5BEE6,"",group=G6,inline="box")
string g6_borderStyle = input.string("Solid","Outline style  /  Width",options=["Solid","Dashed","Dotted"],group=G6,inline="edge")
int g6_borderWidth = input.int(1,"",minval=1,maxval=4,group=G6,inline="edge")
bool g6_showCE = input.bool(false,"Show CE  /  CE color",group=G6,inline="ce")
color g6_ceColor = input.color(#FFFFFFE6,"",group=G6,inline="ce")
string g6_ceStyle = input.string("Dotted","CE style  /  Width",options=["Solid","Dashed","Dotted"],group=G6,inline="ces")
int g6_ceWidth = input.int(1,"",minval=1,maxval=4,group=G6,inline="ces")
bool g6_cePrice = input.bool(false,"CE price  /  Probability",group=G6,inline="cevals")
bool g6_ceProbability = input.bool(false,"",group=G6,inline="cevals")
bool g6_fullPrice = input.bool(false,"100% price  /  Probability",group=G6,inline="edgevals")
bool g6_fullProbability = input.bool(false,"",group=G6,inline="edgevals")
string g6_divisions = input.string("Quarters","Divisions  /  Line color",options=[DIV_OFF,DIV_QUARTERS,DIV_OCTANTS],group=G6,inline="levels")
color g6_levelColor = input.color(#B2B5BEB2,"",group=G6,inline="levels")
string g6_levelStyle = input.string("Dotted","Levels style  /  Width",options=["Solid","Dashed","Dotted"],group=G6,inline="levs")
int g6_levelWidth = input.int(1,"",minval=1,maxval=4,group=G6,inline="levs")
bool g6_levelPrice = input.bool(false,"Levels price  /  Probability",group=G6,inline="lvals")
bool g6_levelProbability = input.bool(false,"",group=G6,inline="lvals",tooltip="Empirical frequencies exist ONLY for 25% and 75% (and CE 50%), for MNQ/NQ standard gaps; no invented estimates for octant-only levels or Hi-Lo gaps.")
color g6_valuesColor = input.color(#787B86,"Values color  /  Text size",group=G6,inline="vtxt")
string g6_valuesSize = input.string("Tiny","",options=["Tiny","Small","Normal","Large","Huge"],group=G6,inline="vtxt")
string g6_valuesPosition = input.string("Inside Right","Values position  /  Offset",options=["Inside Left","Inside Right","Outside Right"],group=G6,inline="vpos")
int g6_valuesOffset = input.int(2,"",minval=0,maxval=20000,group=G6,inline="vpos")
bool g6_showTitle = input.bool(false,"Show name  /  Show points",group=G6,inline="title")
bool g6_showPoints = input.bool(false,"",group=G6,inline="title",tooltip="When both enabled: L-Mon 110Pt. Rounded half-up: 110.25 -> 110; 110.50 -> 111.")
string g6_titleCustom = input.string("Manual","Custom name",group=G6,tooltip="Empty: Mon/Tue/Wed/Thu/Fri. For Today + History, custom name affects TODAY only; historical names always show their own weekday.")
color g6_titleColor = input.color(#787B86,"Title color  /  Text size",group=G6,inline="ntxt")
string g6_titleSize = input.string("Small","",options=["Tiny","Small","Normal","Large","Huge"],group=G6,inline="ntxt")
string g6_titlePosition = input.string("Inside Center","Name position",options=["Inside Top Left","Inside Top Center","Inside Top Right","Inside Center Left","Inside Center","Inside Center Right","Inside Bottom Left","Inside Bottom Center","Inside Bottom Right","Outside Left Center","Outside Right Center","Outside Top Center","Outside Bottom Center"],group=G6)
int g6_titleX = input.int(0,"Title X shift  /  Y shift",minval=-20000,maxval=20000,group=G6,inline="noffs")
float g6_titleY = input.float(0.0,"",step=0.25,group=G6,inline="noffs")
GapStyle g6 = GapStyle.new(
    g6_enabled,
    g6_source,
    g6_mode,
    g6_panelOffset,
    g6_panelWidth,
    g6_fillColor,
    g6_borderColor,
    g6_borderStyle,
    g6_borderWidth,
    g6_showCE,
    g6_ceColor,
    g6_ceStyle,
    g6_ceWidth,
    g6_cePrice,
    g6_ceProbability,
    g6_fullPrice,
    g6_fullProbability,
    g6_divisions,
    g6_levelColor,
    g6_levelStyle,
    g6_levelWidth,
    g6_levelPrice,
    g6_levelProbability,
    g6_valuesColor,
    g6_valuesSize,
    g6_valuesPosition,
    g6_valuesOffset,
    g6_showTitle,
    g6_showPoints,
    g6_titleCustom,
    g6_titleColor,
    g6_titleSize,
    g6_titlePosition,
    g6_titleX,
    g6_titleY
)
 
// ────────────── 07. PROBABILITIES ──────────────
const string PROB_GROUP = "07  |  PROBABILITIES • MODEL NOTE"
bool showProbabilityNote = input.bool(false, "Show sample/limitation note", group=PROB_GROUP,
    tooltip="2026-01-05 to 2026-10-21, 201 gap observations per symbol, descriptive in-sample only. Not a forward-validated forecast. Applies only to standard NQ/MNQ gaps; first RTH hour.")
 
// ────────────── 08. ORIGINAL RTH-CLOSE REFERENCES ──────────────
const string REF_GROUP = "08  |  RTH CLOSE REFERENCE LINES"
bool showReferenceLines = input.bool(false, "Display old close references", group=REF_GROUP)
int referenceCount = input.int(2,"Number of lines",minval=1,maxval=20,group=REF_GROUP)
color referenceColor = input.color(#2962FFE6,"Reference line color / style",group=REF_GROUP,inline="rline")
string referenceStyle = input.string("Dotted","",options=["Solid","Dashed","Dotted"],group=REF_GROUP,inline="rline")
int referenceWidth = input.int(2,"Width",minval=1,maxval=4,group=REF_GROUP)
bool referencePrice = input.bool(false,"Show reference price / extension",group=REF_GROUP,inline="rprice")
string referenceMode = input.string("RTH End","",options=[MODE_END,MODE_NOW],group=REF_GROUP,inline="rprice")
 
// ────────────── 09. RECORD / PERFORMANCE ──────────────
const string SYS_GROUP = "09  |  DATA / DISPLAY"
bool showDataStatus = input.bool(false,"Show source coverage status",group=SYS_GROUP,
    tooltip="Requires 1-minute history containing both 16:14 NY and 09:30 NY. Manual dates not loaded by TradingView cannot be recreated.")
 
fLineStyle(string sty) =>
    sty == "Dotted" ? line.style_dotted : sty == "Dashed" ? line.style_dashed : line.style_solid
 
fTextSize(string sz) =>
    sz == "Tiny" ? size.tiny : sz == "Small" ? size.small : sz == "Large" ? size.large : sz == "Huge" ? size.huge : size.normal
 
fDay(int t) =>
    int d = dayofweek(t, NY)
    d == dayofweek.monday ? "Mon" : d == dayofweek.tuesday ? "Tue" : d == dayofweek.wednesday ? "Wed" : d == dayofweek.thursday ? "Thu" : d == dayofweek.friday ? "Fri" : "Day"
 
fDayKey(int t) =>
    year(t, NY) * 10000 + month(t, NY) * 100 + dayofmonth(t, NY)
 
// Obtain EVERY gap's source values from 1-minute data so that a 5m/15m chart
// does not accidentally use a large wick/candle instead of the 16:14 close.
// Capturing the reference at 09:30 is critical: the 16:14 on the current day
// must never change the stored gap's reference after RTH has ended.
fOneMinuteEvent() =>
    bool isSPY = syminfo.ticker == "SPY"
    bool atOpen = hour(time, NY) == 9 and minute(time, NY) == 30
    bool atClose = hour(time, NY) == (isSPY ? 15 : 16) and minute(time, NY) == (isSPY ? 59 : 14)
    float previousClose = ta.valuewhen(atClose, close, 0)
    float previousHigh = ta.valuewhen(atClose, high, 0)
    float previousLow = ta.valuewhen(atClose, low, 0)
    int closeStamp = ta.valuewhen(atClose, time_close, 0)
    int previousOpenStamp = ta.valuewhen(atOpen, time, 1)
    bool valid = atOpen and not na(previousClose) and not na(previousOpenStamp) and closeStamp > previousOpenStamp and closeStamp < time
    float hiLoA = low > previousHigh ? previousHigh : high < previousLow ? previousLow : na
    float hiLoB = low > previousHigh ? low : high < previousLow ? high : na
    float capturedOpen = ta.valuewhen(atOpen, open, 0)
    float capturedClose = ta.valuewhen(atOpen, previousClose, 0)
    int capturedTime = ta.valuewhen(atOpen, time, 0)
    int capturedCloseStamp = ta.valuewhen(atOpen, closeStamp, 0)
    float capturedHiLoA = ta.valuewhen(atOpen, hiLoA, 0)
    float capturedHiLoB = ta.valuewhen(atOpen, hiLoB, 0)
    int capturedValid = ta.valuewhen(atOpen, valid ? 1 : 0, 0)
    int minuteNY = hour(time, NY) * 60 + minute(time, NY)
    int weekdayNY = dayofweek(time, NY)
    bool inRth = weekdayNY >= dayofweek.monday and weekdayNY <= dayofweek.friday and minuteNY >= 570 and minuteNY < (isSPY ? 960 : 975)
    int dayKey = fDayKey(time)
    var int rangeDay = na
    var float rthHigh = na
    var float rthLow = na
    if inRth
        bool newRange = na(rangeDay) or rangeDay != dayKey
        rthHigh := newRange ? high : math.max(rthHigh, high)
        rthLow := newRange ? low : math.min(rthLow, low)
        rangeDay := dayKey
    [capturedOpen, capturedClose, capturedTime, capturedCloseStamp, capturedHiLoA, capturedHiLoB, capturedValid, rangeDay, rthHigh, rthLow]
 
[srcOpen,srcClose,srcTime,srcRefTime,srcHLA,srcHLB,srcValid,srcRangeDay,srcRthHigh,srcRthLow] = request.security(
    syminfo.tickerid, "1", fOneMinuteEvent(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
 
var array<GapEvent> events = array.new<GapEvent>()
bool eventChanged = not na(srcTime) and (na(srcTime[1]) or srcTime != srcTime[1])
if eventChanged and srcValid == 1 and not na(srcOpen) and not na(srcClose)
    int endHour = 16
    int endMinute = syminfo.ticker == "SPY" ? 0 : 15
    int endT = timestamp(NY, year(srcTime, NY), month(srcTime, NY), dayofmonth(srcTime, NY), endHour, endMinute)
    events.push(GapEvent.new(srcTime, endT, srcRefTime, fDayKey(srcTime), dayofweek(srcTime, NY), srcOpen, srcClose, srcHLA, srcHLB, srcOpen, srcHLB))
    if events.size() > KEEP_EVENTS
        events.shift()
 
// Advance from the opening edge toward the prior close. A later RTH that
// jumps over the frontier must reach it before it can extend the fill.
fAdvanceFill(float frontier, float target, float rthHigh, float rthLow) =>
    float next = frontier
    if not na(frontier) and frontier != target and rthLow <= frontier and rthHigh >= frontier
        next := target < frontier ? math.max(target, rthLow) : math.min(target, rthHigh)
    next
 
bool rthRangeChanged = not na(srcRangeDay) and (na(srcRangeDay[1]) or srcRangeDay != srcRangeDay[1] or srcRthHigh != srcRthHigh[1] or srcRthLow != srcRthLow[1])
if rthRangeChanged
    for gap in events
        if srcRangeDay >= gap.dayKey
            gap.standardFill := fAdvanceFill(gap.standardFill, gap.previousClose, srcRthHigh, srcRthLow)
            gap.highLowFill := fAdvanceFill(gap.highLowFill, gap.highLowFrom, srcRthHigh, srcRthLow)
 
// Probabilities: exactly retained from the original attached script.
// Direction: from today's 09:30 OPEN toward the preceding 16:14 CLOSE.
// 25%, 50%, 75% = first-hour visitation, not probability at a clock time.
string family = syminfo.root == "MNQ" ? "MNQ" : syminfo.root == "NQ" ? "NQ" : "OTHER"
 
fProb(float gapPts, int step, string instrument) =>
    float result = na
    int eventIx = step == 2 ? 1 : step == 4 ? 2 : step == 6 ? 3 : step == 8 ? 4 : -1
    if eventIx >= 0 and (instrument == "MNQ" or instrument == "NQ")
        int loBound = instrument == "MNQ" ? 40 : 39
        int hiBound = instrument == "MNQ" ? 231 : 230
        int bucket = gapPts < loBound ? 0 : gapPts < hiBound ? 1 : 2
        int n = bucket == 0 ? 35 : bucket == 1 ? 100 : 66
        int hits = 0
        if bucket == 0
            hits := eventIx == 1 ? 35 : eventIx == 2 ? 34 : eventIx == 3 ? 33 : 31
        else if bucket == 1
            if instrument == "MNQ"
                hits := eventIx == 1 ? 87 : eventIx == 2 ? 67 : eventIx == 3 ? 50 : 34
            else
                hits := eventIx == 1 ? 86 : eventIx == 2 ? 67 : eventIx == 3 ? 48 : 35
        else
            if instrument == "MNQ"
                hits := eventIx == 1 ? 44 : eventIx == 2 ? 17 : eventIx == 3 ? 10 : 7
            else
                hits := eventIx == 1 ? 44 : eventIx == 2 ? 16 : eventIx == 3 ? 10 : 7
        result := 100.0 * hits / n
    result
 
// Keep a separate registry for each drawing class to avoid old/ghost drawings.
var array<box> boxes = array.new<box>()
var array<line> lines = array.new<line>()
var array<label> labels = array.new<label>()
 
// Hard drawing budgets; newest/specially-selected gaps remain visible.
fKeepBox(box id) =>
    boxes.push(id)
    if boxes.size() > 190
        box.delete(boxes.shift())
 
fKeepLine(line id) =>
    lines.push(id)
    if lines.size() > 475
        line.delete(lines.shift())
 
fKeepLabel(label id) =>
    labels.push(id)
    if labels.size() > 475
        label.delete(labels.shift())
 
fClear() =>
    for b in boxes
        box.delete(b)
    for l in lines
        line.delete(l)
    for la in labels
        label.delete(la)
    boxes.clear()
    lines.clear()
    labels.clear()
 
fAddValues(int x1, int x2, int stepMs, float px, int levelIndex, bool isCE,
           bool isStandard, float absGap, GapStyle cfg) =>
    bool wantPrice = isCE ? cfg.cePrice : cfg.levelPrice
    bool wantProb = isCE ? cfg.ceProbability : cfg.levelProbability
    float probability = isStandard and wantProb ? fProb(absGap, levelIndex, family) : na
    string priceText = wantPrice ? str.tostring(px, format.mintick) : ""
    string probText = not na(probability) ? str.tostring(probability, "#.0") + "%" : ""
    string labelText = priceText + (priceText != "" and probText != "" ? "  |  " : "") + probText
    if labelText != ""
        labelText := isCE ? "CE  " + labelText : labelText
        int xVal = cfg.valuesPosition == "Inside Left" ? x1 + cfg.valuesOffset * stepMs : cfg.valuesPosition == "Inside Right" ? x2 - cfg.valuesOffset * stepMs : x2 + cfg.valuesOffset * stepMs
        fKeepLabel(label.new(x=xVal, y=px, text=labelText, xloc=xloc.bar_time, yloc=yloc.price,
            style=label.style_none, textcolor=cfg.valuesColor, size=fTextSize(cfg.valuesSize),
            textalign=cfg.valuesPosition == "Inside Left" ? text.align_left : cfg.valuesPosition == "Inside Right" ? text.align_right : text.align_left))
 
fAddTitle(int x1, int x2, int ms, float hi, float lo, GapStyle cfg, string fallbackName) =>
    string userName = cfg.titleCustom == "" ? fallbackName : cfg.titleCustom
    string pts = str.tostring(int(math.floor(math.abs(hi - lo) + 0.5))) + "Pt"
    string titleText = (cfg.showTitle ? userName : "") + (cfg.showTitle and cfg.showPoints ? " " : "") + (cfg.showPoints ? pts : "")
    if titleText != ""
        string where = cfg.titlePosition
        bool outside = str.startswith(where, "Outside")
        bool left = str.contains(where,"Left")
        bool right = str.contains(where,"Right")
        bool top = str.contains(where,"Top")
        bool bottom = str.contains(where,"Bottom")
        int gapX = math.max(ms, 60000)
        int x = left ? (outside ? x1-gapX : x1+gapX) : right ? (outside ? x2+gapX : x2-gapX) : int(math.round((x1+x2)/2.0))
        float insetY = math.max(math.abs(hi-lo)*0.075, syminfo.mintick*2)
        float y = top ? (outside ? hi+insetY : hi-insetY) : bottom ? (outside ? lo-insetY : lo+insetY) : (hi+lo)/2.0
        x += cfg.titleX * ms
        y += cfg.titleY
        fKeepLabel(label.new(x=x,y=y,text=titleText,xloc=xloc.bar_time,yloc=yloc.price,
            style=label.style_none,color=color.new(color.black,100),textcolor=cfg.titleColor,
            size=fTextSize(cfg.titleSize),textalign=left ? text.align_left : right ? text.align_right : text.align_center))
 
// For each chosen event, draw one style-controlled gap. All 6 groups call THIS.
// panelIndex is used to place current + historical panels side-by-side.
fDrawOne(GapEvent e, GapStyle cfg, float pA, float pB, string name, bool standard, int panelIndex) =>
    if not na(pA) and not na(pB) and pA != pB
        int ms = int(math.max(timeframe.in_seconds(timeframe.period), 60) * 1000)
        int x1 = e.eventTime
        int x2 = e.rthEndTime
        if cfg.mode == MODE_NOW
            x2 := math.max(last_bar_time, e.eventTime + ms)
        else if cfg.mode == MODE_PANEL
            x1 := last_bar_time + (cfg.panelOffset + panelIndex*(cfg.panelWidth+5)) * ms
            x2 := x1 + cfg.panelWidth * ms
        float hi = math.max(pA,pB)
        float lo = math.min(pA,pB)
        float filledTo = standard ? e.standardFill : e.highLowFill
        bool filled = not na(filledTo) and filledTo == pB
        int filledWidth = cfg.borderWidth + 2
        fKeepBox(box.new(left=x1,top=hi,right=x2,bottom=lo,xloc=xloc.bar_time,
            bgcolor=cfg.fillColor,border_color=cfg.borderColor,
            border_style=fLineStyle(cfg.borderStyle),border_width=filled ? filledWidth : cfg.borderWidth))
        if not filled and not na(filledTo) and filledTo != pA
            string outlineStyle = fLineStyle(cfg.borderStyle)
            fKeepLine(line.new(x1, pA, x2, pA, xloc=xloc.bar_time, color=cfg.borderColor, style=outlineStyle, width=filledWidth))
            fKeepLine(line.new(x1, pA, x1, filledTo, xloc=xloc.bar_time, color=cfg.borderColor, style=outlineStyle, width=filledWidth))
            fKeepLine(line.new(x2, pA, x2, filledTo, xloc=xloc.bar_time, color=cfg.borderColor, style=outlineStyle, width=filledWidth))
        float gapDelta = pB - pA
        float absGap = math.abs(gapDelta)
        for step = 1 to 7
            bool isCE = step == 4
            bool isOther = not isCE and (cfg.divisions == DIV_OCTANTS or (cfg.divisions == DIV_QUARTERS and (step == 2 or step == 6)))
            if (isCE and cfg.showCE) or isOther
                float level = pA + gapDelta * step / 8.0
                color lnColor = isCE ? cfg.ceColor : cfg.levelColor
                string lnStyle = isCE ? cfg.ceStyle : cfg.levelStyle
                int lnWidth = isCE ? cfg.ceWidth : cfg.levelWidth
                fKeepLine(line.new(x1,level,x2,level,xloc=xloc.bar_time,
                    color=lnColor,style=fLineStyle(lnStyle),width=lnWidth))
                fAddValues(x1,x2,ms,level,step,isCE,standard,absGap,cfg)
        // 100% is the prior close: optional boundary price/probability.
        if cfg.fullPrice or cfg.fullProbability
            float prob100 = standard and cfg.fullProbability ? fProb(absGap,8,family) : na
            string text100 = ((cfg.fullPrice ? str.tostring(pB,format.mintick) : "") +
                (cfg.fullPrice and not na(prob100) ? "  |  " : "") +
                (not na(prob100) ? str.tostring(prob100,"#.0") + "%" : ""))
            if text100 != ""
                int x100 = cfg.valuesPosition == "Inside Left" ? x1 + cfg.valuesOffset*ms : cfg.valuesPosition == "Inside Right" ? x2-cfg.valuesOffset*ms : x2+cfg.valuesOffset*ms
                fKeepLabel(label.new(x100,pB,"100%  " + text100,xloc=xloc.bar_time,yloc=yloc.price,
                    style=label.style_none,textcolor=cfg.valuesColor,size=fTextSize(cfg.valuesSize)))
        fAddTitle(x1,x2,ms,hi,lo,cfg,name)
 
fDrawEvent(int idx, GapStyle cfg, string labelOverride, int panelIndex) =>
    if cfg.enabled and idx >= 0 and idx < events.size()
        GapEvent e = events.get(idx)
        string autoName = labelOverride == "" ? fDay(e.eventTime) : labelOverride
        if cfg.source == SRC_STANDARD or cfg.source == SRC_BOTH
            fDrawOne(e,cfg,e.rthOpen,e.previousClose,autoName,true,panelIndex)
        if cfg.source == SRC_HILO or cfg.source == SRC_BOTH
            // Original secondary High/Low mode is retained as an optional source.
            string hlName = cfg.source == SRC_BOTH ? autoName + " HL" : autoName
            GapStyle hiLoStyle = cfg.copy()
            if cfg.source == SRC_BOTH
                hiLoStyle.titleCustom := (cfg.titleCustom == "" ? autoName : cfg.titleCustom) + " HL"
            fDrawOne(e,hiLoStyle,e.highLowTo,e.highLowFrom,hlName,false,panelIndex)
 
// A last weekday is the last COMPLETED occurrence. Today's newly formed
// Monday/Friday is excluded, so Monday can show Today + L-Mon + P-Mon.
fWeekdayIndex(int targetDay, int rank, int todayKey) =>
    int found = na
    int count = 0
    if events.size() > 0
        for i = events.size()-1 to 0
            GapEvent e = events.get(i)
            if e.weekDay == targetDay and e.dayKey != todayKey and na(found)
                count += 1
                if count == rank
                    found := i
    found
 
fDateIndex(int key) =>
    int found = na
    if events.size() > 0
        for i = events.size()-1 to 0
            if events.get(i).dayKey == key and na(found)
                found := i
    found
 
if barstate.islast
    fClear()
    int n = events.size()
    int todayKey = fDayKey(timeframe.isdaily ? time_close : time)
    bool haveToday = n > 0 and events.get(n-1).dayKey == todayKey
    if g1.enabled and n > 0
        if haveToday
            // Use a custom title for TODAY, but keep historic weekday titles.
            fDrawEvent(n-1,g1,"",0)
        if historyCount > 0
            for h = 1 to historyCount
                int idx = n - (haveToday ? 1 + h : h)
                if idx >= 0
                    // Copy the style: only the titles vary by historical weekday.
                    GapStyle historyStyle = g1.copy()
                    historyStyle.titleCustom := ""
                    fDrawEvent(idx,historyStyle,"",h)
    int mon1 = fWeekdayIndex(dayofweek.monday,1,todayKey)
    int mon2 = fWeekdayIndex(dayofweek.monday,2,todayKey)
    int fri1 = fWeekdayIndex(dayofweek.friday,1,todayKey)
    int fri2 = fWeekdayIndex(dayofweek.friday,2,todayKey)
    if not na(mon1)
        fDrawEvent(mon1,g2,"L-Mon",0)
    if not na(mon2)
        fDrawEvent(mon2,g3,"P-Mon",0)
    if not na(fri1)
        fDrawEvent(fri1,g4,"L-Fri",0)
    if not na(fri2)
        fDrawEvent(fri2,g5,"P-Fri",0)
    int man = fDateIndex(fDayKey(manualDate))
    if not na(man)
        fDrawEvent(man,g6,"Manual",0)
 
    // Legacy RTH-close reference lines, independently controlled.
    if showReferenceLines and n > 0
        for k = 0 to referenceCount-1
            int idx = n-1-k
            if idx >= 0
                GapEvent ev = events.get(idx)
                int endX = referenceMode == MODE_NOW ? last_bar_time : ev.rthEndTime
                endX := math.max(endX,ev.refTime + 60000)
                fKeepLine(line.new(ev.refTime,ev.previousClose,endX,ev.previousClose,
                    xloc=xloc.bar_time,color=referenceColor,style=fLineStyle(referenceStyle),width=referenceWidth))
                if referencePrice
                    fKeepLabel(label.new(endX,ev.previousClose,
                        fDay(ev.eventTime) + " prior RTH close: " + str.tostring(ev.previousClose,format.mintick),
                        xloc=xloc.bar_time,style=label.style_none,textcolor=referenceColor,size=size.tiny))
 
var table modelNote = table.new(position.top_right, 1, 2, frame_width=0)
if barstate.islast
    bool probabilityWanted = (g1.enabled and (g1.ceProbability or g1.levelProbability or g1.fullProbability)) or
         (g2.enabled and (g2.ceProbability or g2.levelProbability or g2.fullProbability)) or
         (g3.enabled and (g3.ceProbability or g3.levelProbability or g3.fullProbability)) or
         (g4.enabled and (g4.ceProbability or g4.levelProbability or g4.fullProbability)) or
         (g5.enabled and (g5.ceProbability or g5.levelProbability or g5.fullProbability)) or
         (g6.enabled and (g6.ceProbability or g6.levelProbability or g6.fullProbability))
    string note = family == "OTHER" ? "No calibrated RTH gap stats for " + syminfo.root :
         "MNQ/NQ • 2026 in-sample • First RTH hour\n25 / 50 / 75% only; octants unmodeled"
    table.cell(modelNote,0,0,showProbabilityNote and probabilityWanted ? note : "",
        text_color=color.gray,text_size=size.tiny,bgcolor=color.new(color.black,100))
    string coverage = ""
    if showDataStatus
        coverage := "1m-sourced RTH gaps: " + str.tostring(events.size()) + " | " +
           (not na(fDateIndex(fDayKey(manualDate))) ? "Manual date found" : "Manual date NOT in loaded history")
    table.cell(modelNote,0,1,coverage,text_color=color.gray,text_size=size.tiny,bgcolor=color.new(color.black,100))

← 返回列表