PINE LIBRARY

EKGapEngine

173
Library "EKGapEngine"
Gap engine library: NWOG (New Week Opening Gaps), NDOG (New Day Opening Gaps),
9:30 NY Opening Range Gap, and PXH/L (Previous X High/Low) levels.
Extracted from qt-pro-enigma.pine to avoid TradingView compiler timeouts.

GAP_VOID_BULL()
  Gap type constant: Void Bullish
  Returns: 1

GAP_VOID_BEAR()
  Gap type constant: Void Bearish
  Returns: 2

GAP_OVERLAP_BULL()
  Gap type constant: Overlap Bullish
  Returns: 3

GAP_OVERLAP_BEAR()
  Gap type constant: Overlap Bearish
  Returns: 4

getLineStyle(styleStr)
  Convert a style string to a line style constant
  Parameters:
    styleStr (string): Style string ("Solid", "Dashed", "Dotted")
  Returns: line.style_solid, line.style_dashed, or line.style_dotted

getLabelSize(labelSize)
  Convert a label size string to a size constant
  Parameters:
    labelSize (string): Label size string ("Tiny", "Small", "Normal", "Large")
  Returns: size.tiny, size.small, size.normal, or size.large

calcTradingDaysAgo(creationTimestamp)
  Calculate approximate trading days since a timestamp
  Parameters:
    creationTimestamp (int): The creation timestamp to measure from
  Returns: Approximate number of trading days elapsed

getNwogSubtypeName(gapType)
  Get the human-readable name for an NWOG gap subtype
  Parameters:
    gapType (int): Gap type constant (1-4)
  Returns: String name of the gap subtype

buildNwogLabelText(gapType, daysAgo, labelStyle)
  Build label text for an NWOG
  Parameters:
    gapType (int): Gap type constant (1-4)
    daysAgo (int): Number of trading days ago the gap was created
    labelStyle (string): Label style ("Simple" or "Descriptive")
  Returns: Formatted label text string

buildNdogLabelText(isBullish, daysAgo, labelStyle)
  Build label text for an NDOG
  Parameters:
    isBullish (bool): Whether the gap is bullish
    daysAgo (int): Number of trading days ago the gap was created
    labelStyle (string): Label style ("Simple" or "Descriptive")
  Returns: Formatted label text string

getGapColors(nwogColor, boxFillTransp, boxBorderTransp, midLineColor, quadLineColor)
  Compute fill, border, mid, and quad colors for an NWOG
  Parameters:
    nwogColor (color): Base NWOG color
    boxFillTransp (int): Box fill transparency (0-100)
    boxBorderTransp (int): Box border transparency (0-100)
    midLineColor (color): Midline color
    quadLineColor (color): Quadrant line color
  Returns: Tuple of [fillCol, borderCol, midCol, quadCol]

getNdogColors(ndogColor, boxFillTransp, boxBorderTransp, midLineColor, quadLineColor)
  Compute fill, border, mid, and quad colors for an NDOG
  Parameters:
    ndogColor (color): Base NDOG color
    boxFillTransp (int): Box fill transparency (0-100)
    boxBorderTransp (int): Box border transparency (0-100)
    midLineColor (color): Midline color
    quadLineColor (color): Quadrant line color
  Returns: Tuple of [fillCol, borderCol, midCol, quadCol]

classifyGap(friClose, friOpen, monOpen)
  Classify a weekend gap as Void Bull/Bear or Overlap Bull/Bear
  Parameters:
    friClose (float): Friday close price
    friOpen (float): Friday open price
    monOpen (float): Monday open price
  Returns: Gap type constant (0 if no gap)

passesAtrFilter(gapSize, atr, multiplier)
  Check if a gap passes the ATR size filter
  Parameters:
    gapSize (float): Absolute size of the gap
    atr (float): Current ATR value
    multiplier (float): ATR multiplier threshold
  Returns: true if the gap passes the filter

isWithinPriceDistance(topPrice, bottomPrice, currentPrice, atr, onlyShowNearPrice, maxDistanceAtr)
  Check if a gap is within the max price distance
  Parameters:
    topPrice (float): Top of gap zone
    bottomPrice (float): Bottom of gap zone
    currentPrice (float): Current price (close)
    atr (float): Current ATR value
    onlyShowNearPrice (bool): Whether the near-price filter is enabled
    maxDistanceAtr (float): Maximum distance in ATR multiples
  Returns: true if within distance (or filter is disabled)

shouldDisplayGapType(gapType, showVoidGaps, showOverlapGaps)
  Check if a gap type should be displayed based on settings
  Parameters:
    gapType (int): Gap type constant (1-4)
    showVoidGaps (bool): Whether void gaps are enabled
    showOverlapGaps (bool): Whether overlap gaps are enabled
  Returns: true if this gap type should be shown

createNwog(nwogArray, cfg, friClose, friOpen, monOpen, atrVal, fridayBarIdx)
  Create a new NWOG and add it to the array, removing oldest if over max count
  Parameters:
    nwogArray (array<NWOGBox>): Array of NWOGBox objects
    cfg (GapConfig): GapConfig with all settings
    friClose (float): Friday close price
    friOpen (float): Friday open price
    monOpen (float): Monday open price
    atrVal (float): Current ATR value for size filtering
    fridayBarIdx (int): Bar index of Friday (for left edge of box)

createNdog(ndogArray, cfg, prevClose, todayOpn, atrVal, prevDayBarIdx)
  Create a new NDOG and add it to the array, removing oldest if over max count
  Parameters:
    ndogArray (array<NDOGBox>): Array of NDOGBox objects
    cfg (GapConfig): GapConfig with all settings
    prevClose (float): Previous day close price
    todayOpn (float): Today open price
    atrVal (float): Current ATR value for size filtering
    prevDayBarIdx (int): Bar index of previous day (for left edge of box)

updateNwogExtensions(nwogArray, cfg, dailyAtr, shouldRunCleanup)
  Update all NWOG box/line/label extensions and handle cleanup
  Parameters:
    nwogArray (array<NWOGBox>): Array of NWOGBox objects
    cfg (GapConfig): GapConfig with all settings
    dailyAtr (float): Current daily ATR value for distance filtering
    shouldRunCleanup (bool): Whether cleanup should run this bar (based on interval)

updateNdogExtensions(ndogArray, cfg, dailyAtr, shouldRunCleanup)
  Update all NDOG box/line/label extensions and handle cleanup
  Parameters:
    ndogArray (array<NDOGBox>): Array of NDOGBox objects
    cfg (GapConfig): GapConfig with all settings
    dailyAtr (float): Current daily ATR value for distance filtering
    shouldRunCleanup (bool): Whether cleanup should run this bar (based on interval)

markWeekEndForNwogs(nwogArray, isWeekCloseRisingEdge)
  Mark week end for all active NWOGs when week close rising edge detected
  Parameters:
    nwogArray (array<NWOGBox>): Array of NWOGBox objects
    isWeekCloseRisingEdge (bool): Whether the week close rising edge was detected this bar

markDayEndForNdogs(ndogArray, isNewTradingDay)
  Mark day end for all active NDOGs when new trading day detected
  Parameters:
    ndogArray (array<NDOGBox>): Array of NDOGBox objects
    isNewTradingDay (bool): Whether a new trading day started this bar

f_get_size(s)
  Convert a size string to a size constant
  Parameters:
    s (string): Size string ("Auto", "Tiny", "Small", "Normal", "Large")
  Returns: Corresponding size constant

f_get_pxhl_style(str)
  Convert a style string to a line style constant (PXH/L version)
  Parameters:
    str (string): Style string ("Solid", "Dotted", "Dashed")
  Returns: Corresponding line style constant

f_is_within_distance(target_price, filter_enabled, daily_atr, filter_preset)
  Check if a target price is within distance filter range
  Parameters:
    target_price (float): The price to check
    filter_enabled (bool): Whether the distance filter is enabled
    daily_atr (float): Current daily ATR value
    filter_preset (string): Filter preset string ("Really Close", "Balanced", "Slightly Far")
  Returns: true if within distance (or filter disabled)

f_find_exact_in_window(target_price, p_start, p_end, is_high)
  Find the exact bar time where a high/low occurred within a period window
  Parameters:
    target_price (float): The price to find
    p_start (int): Period start time
    p_end (int): Period end time
    is_high (bool): Whether looking for a high (true) or low (false)
  Returns: Timestamp of the exact bar where the price was found

f_add_level_smart(arr, h, l, t_start, t_end, count)
  Smart-add high/low levels to an array, maintaining count limit
  Parameters:
    arr (array<Level>): Array of Level objects
    h (float): High price to add
    l (float): Low price to add
    t_start (int): Period start time
    t_end (int): Period end time
    count (int): Maximum number of level pairs

f_check_mitigation(arr)
  Check mitigation of levels in an array (price broke through)
  Parameters:
    arr (array<Level>): Array of Level objects to check

f_draw_single_level(draw_lines, draw_labels, t_start, t_end, price, txt, col, sty, show_lbl, size_val, font_val, filter_enabled, daily_atr, filter_preset)
  Draw a single PXH/L level line and optional label
  Parameters:
    draw_lines (array<line>): Array to store created line objects
    draw_labels (array<label>): Array to store created label objects
    t_start (int): Start time for the line
    t_end (int): End time for the line
    price (float): Price level
    txt (string): Label text
    col (color): Line/label color
    sty (string): Line style constant
    show_lbl (bool): Whether to show the label
    size_val (string): Label size constant
    font_val (string): Font family constant
    filter_enabled (bool): Whether distance filter is enabled
    daily_atr (float): Current daily ATR
    filter_preset (string): Distance filter preset string

f_clear_drawings(draw_lines, draw_labels)
  Clear all PXH/L drawing objects (lines and labels)
  Parameters:
    draw_lines (array<line>): Array of line objects to delete
    draw_labels (array<label>): Array of label objects to delete

f_draw_levels(arr, show, mode, show_lbl, col, sty_global, txt_base, txt_size_val, font_val, draw_lines, draw_labels, filter_enabled, daily_atr, filter_preset)
  Draw all levels from a PXH/L level array with EQ/Quadrant support
  Parameters:
    arr (array<Level>): Array of Level objects
    show (bool): Whether to show this timeframe's levels
    mode (string): Midline mode ("None", "EQ", "Quadrants")
    show_lbl (bool): Whether to show labels
    col (color): Level color
    sty_global (string): Global style string ("Solid", "Dotted", "Dashed")
    txt_base (string): Base text for labels (e.g. "pD", "pW", "pM")
    txt_size_val (string): Label size string
    font_val (string): Font family constant
    draw_lines (array<line>): Array to store created line objects
    draw_labels (array<label>): Array to store created label objects
    filter_enabled (bool): Whether distance filter is enabled
    daily_atr (float): Current daily ATR
    filter_preset (string): Distance filter preset string

process_930_gap(cfg930, m1_time, m1_open, m1_close, g930_prevClosePrice, g930_boxArray, g930_lineArray, isStock, isValidTimeframe930)
  Process 9:30 NY opening range gap from 1-minute lower timeframe data.
Handles the entire gap creation logic: detects the 16:14 (or 15:59 for stocks) close,
then at 9:30 creates box/midline/quadrant drawings.
  Parameters:
    cfg930 (Gap930Config): Gap930Config with all 9:30 gap settings
    m1_time (array<int>): Array of 1-minute bar timestamps from request.security_lower_tf
    m1_open (array<float>): Array of 1-minute bar open prices from request.security_lower_tf
    m1_close (array<float>): Array of 1-minute bar close prices from request.security_lower_tf
    g930_prevClosePrice (float): Previous close price state (pass in, returns updated value)
    g930_boxArray (array<box>): Array to store created box objects
    g930_lineArray (array<line>): Array to store created line objects
    isStock (bool): Whether the symbol is a stock/fund/dr
    isValidTimeframe930 (bool): Whether the current timeframe is valid for 9:30 gaps (intraday <= 15min)
  Returns: Updated g930_prevClosePrice value

NWOGBox
  New Week Opening Gap box with all price levels and drawing references
  Fields:
    gapType (series int): Gap classification (1=Void Bull, 2=Void Bear, 3=Overlap Bull, 4=Overlap Bear)
    fridayClose (series float): Friday close price
    fridayOpen (series float): Friday open price
    mondayOpen (series float): Monday open price
    topPrice (series float): Top of gap zone
    bottomPrice (series float): Bottom of gap zone
    midPrice (series float): Midpoint of gap zone
    upperQuad (series float): Upper quadrant (75%) of gap zone
    lowerQuad (series float): Lower quadrant (25%) of gap zone
    gapSize (series float): Absolute size of gap
    startBar (series int): Bar index where gap starts
    creationTime (series int): Timestamp of gap creation
    weekEndBar (series int): Bar index where the week ended
    weekEnded (series bool): Whether the week has ended for this NWOG
    nwogBox (series box): Box drawing object
    midLine (series line): Midline drawing object
    q3Line (series line): Upper quadrant line drawing object
    q1Line (series line): Lower quadrant line drawing object
    infoLabel (series label): Label drawing object
    isActive (series bool): Whether this NWOG is still active

NDOGBox
  New Day Opening Gap box with all price levels and drawing references
  Fields:
    isBullish (series bool): Whether the gap opened bullish (today open > prev close)
    prevClose (series float): Previous day close price
    todayOpen (series float): Today open price
    topPrice (series float): Top of gap zone
    bottomPrice (series float): Bottom of gap zone
    midPrice (series float): Midpoint of gap zone
    upperQuad (series float): Upper quadrant (75%) of gap zone
    lowerQuad (series float): Lower quadrant (25%) of gap zone
    gapSize (series float): Absolute size of gap
    startBar (series int): Bar index where gap starts
    creationTime (series int): Timestamp of gap creation
    dayEndBar (series int): Bar index where the day ended
    dayEnded (series bool): Whether the day has ended for this NDOG
    ndogBox (series box): Box drawing object
    midLine (series line): Midline drawing object
    q3Line (series line): Upper quadrant line drawing object
    q1Line (series line): Lower quadrant line drawing object
    infoLabel (series label): Label drawing object
    isActive (series bool): Whether this NDOG is still active

Level
  PXH/L level with price, time range, and mitigation state
  Fields:
    price (series float): The price level
    start_time (series int): Timestamp where the level starts
    is_high (series bool): Whether this is a high (true) or low (false)
    broken (series bool): Whether the level has been mitigated
    stop_time (series int): Timestamp where the level was mitigated

GapConfig
  Configuration for NWOG/NDOG gap display and filtering
  Fields:
    showNwogs (series bool): Enable NWOGs
    showVoidGaps (series bool): Show void gap types
    showOverlapGaps (series bool): Show overlap gap types
    showNwogLabels (series bool): Show NWOG labels
    extensionMode (series string): NWOG extension mode ("Extend Live" or "Extend to Week Close")
    maxNwogCount (series int): Maximum number of NWOGs to display
    showNdogs (series bool): Enable NDOGs
    showNdogLabels (series bool): Show NDOG labels
    ndogExtensionMode (series string): NDOG extension mode ("Extend Live" or "Extend to Day Close")
    maxNdogCount (series int): Maximum number of NDOGs to display
    force1800 (series bool): Force 18:00 open for NDOG calculation
    customOpenSession (series string): Session string for custom open time
    nwogColor (series color): Base color for NWOGs
    ndogColor (series color): Base color for NDOGs
    boxFillTransp (series int): Box fill transparency
    boxBorderTransp (series int): Box border transparency
    boxBorderWidth (series int): Box border width
    showMidline (series bool): Show midline on gaps
    showQuadrants (series bool): Show quadrant lines on gaps
    midLineColor (series color): Midline color
    quadLineColor (series color): Quadrant line color
    midLineStyle (series string): Midline style string ("Solid", "Dotted", "Dashed")
    quadLineStyle (series string): Quadrant line style string ("Solid", "Dotted", "Dashed")
    labelSize (series string): Label size string ("Tiny", "Small", "Normal", "Large")
    nwogTextColor (series color): NWOG label text color
    labelStyle (series string): Label style ("Simple" or "Descriptive")
    hideHistoryLabels (series bool): Hide labels on historical gaps
    atrMultiplier (series float): Pre-computed ATR multiplier for NWOG size filter
    ndogAtrMultiplier (series float): Pre-computed ATR multiplier for NDOG size filter
    maxDistanceAtr (series float): Pre-computed max distance in ATR multiples
    onlyShowNearPrice (series bool): Only show gaps near current price
    cleanupIntervalMs (series int): Cleanup interval in milliseconds (0 = immediate)
    barOffset (series int): Bar offset for right edge of drawings

PXHLConfig
  Configuration for PXH/L (Previous X High/Low) display
  Fields:
    global_sty (series string): Global line style ("Solid", "Dotted", "Dashed")
    lbl_size_str (series string): Label size string ("Auto", "Tiny", "Small", "Normal", "Large")
    use_mono (series bool): Use monospace font for labels
    filter_enabled (series bool): Enable distance filter
    filter_preset (series string): Distance filter preset ("Really Close", "Balanced", "Slightly Far")
    filter_atr_len (series int): ATR length for distance filter
    show_d (series bool): Show daily levels
    show_w (series bool): Show weekly levels
    show_m (series bool): Show monthly levels
    col_d (series color): Daily level color
    col_w (series color): Weekly level color
    col_m (series color): Monthly level color
    cnt_d (series int): Daily level count
    cnt_w (series int): Weekly level count
    cnt_m (series int): Monthly level count
    mode_d (series string): Daily midline mode ("None", "EQ", "Quadrants")
    mode_w (series string): Weekly midline mode ("None", "EQ", "Quadrants")
    mode_m (series string): Monthly midline mode ("None", "EQ", "Quadrants")
    show_lbl_d (series bool): Show daily labels
    show_lbl_w (series bool): Show weekly labels
    show_lbl_m (series bool): Show monthly labels

Gap930Config
  Configuration for 9:30 NY Opening Range Gap
  Fields:
    g930_historyCount (series int): Number of historical 9:30 gaps to show
    g930_projEndH (series int): End hour for gap projection (NY time)
    g930_projEndM (series int): End minute for gap projection (NY time)
    g930_showBox (series bool): Show gap box
    g930_boxColor (series color): Gap box color
    g930_showMid (series bool): Show midline
    g930_midColor (series color): Midline color
    g930_midStyleStr (series string): Midline style string ("Solid", "Dashed", "Dotted")
    g930_showQuad (series bool): Show quadrant lines
    g930_quadColor (series color): Quadrant line color
    g930_quadStyleStr (series string): Quadrant line style string ("Solid", "Dashed", "Dotted")

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.