PINE LIBRARY

ImportantLevelsLinesLabels_Utilities

247
LevelsLinesLabels_Utilities is a shared Pine v6 utility library for scripts that already resolve their own level values, source candles, session logic, and visibility conditions, but want a reusable level-output layer.

It centralizes the pieces that tend to get rewritten across level-based scripts:

• line-style and label-size resolvers
• EM-space right-label padding
• compact price / $ difference / % difference formatting
• standardized right-side level label text
• above/below-current-price color routing
• bar-time horizontal level line management
• transparent right-side text label management
• synchronized line / label slot-array helpers
• float / int / line / label array pruning helpers
• newest-first history lookup helpers
• Active Period / Source Window / Source Candle start-time routing
• newest-first rolling highest / lowest helpers
• newest-first rolling highest / lowest helpers with matching source time

The example chart demonstrates how a calling script can use the library to render live close-style levels, previous-day high/low levels, rolling completed-window high/low levels, right-side label stacks, source-aware line starts, and reusable object slots.

This library is intentionally focused on output, formatting, object lifecycle, and history-array utilities.

It does not:
• request higher-timeframe data
• decide regular-session versus extended-session sources
• detect sessions, opens, closes, highs, lows, or pivots
• calculate candle levels, VWAPs, pivots, trendlines, or envelopes
• decide which levels should be shown
• own script inputs, tooltips, colors, or final visibility logic
• provide trading signals or directional recommendations

Calling scripts remain responsible for:
• the level engine
• the source engine
• session logic
• request.security() calls
• user inputs and tooltips
• final show/hide conditions
• color choices
• interpretation

How to use

Import the library near the top of your script in global scope, before calling its helpers.

Typical placement:

//version=6
indicator(...)
import MYNAMEISBRANDON/LevelsLinesLabels_Utilities/1 as LVL

Replace /1 with the latest published version if a newer version is available.

This library expects the calling script to already know the level value, source time, window time, active period start, display state, colors, and label text it wants to use. The library then handles the reusable formatting, line, label, object-slot, pruning, lookup, and rolling-window utility layer.

➖Style Helpers➖

These helpers convert simple user-facing strings into Pine style enums and route colors based on whether price is above or below a level.

levelLineStyle(styleIn)
Converts user-facing line-style text into a Pine line-style enum.

Parameters:
styleIn (simple string): Solid, Dashed, or Dotted

Returns:
Pine line style

levelLabelSize(sizeIn)
Converts user-facing label-size text into a Pine label-size enum.

Parameters:
sizeIn (simple string): Tiny, Small, Normal, Large, or Huge

Returns:
Pine label size

levelColor(level, currentPrice, aboveColor, belowColor)
Routes a level to the above-color or below-color based on the current/reference price.

Parameters:
level (float): Level price
currentPrice (float): Current/reference price
aboveColor (color): Color used when currentPrice is greater than or equal to level
belowColor (color): Color used when currentPrice is below level

Returns:
Resolved color

➖Text Formatting Helpers➖

These helpers keep level labels compact and readable across high-priced stocks, low-priced stocks, crypto pairs, futures-style symbols, and other price scales.

levelSpacer(pad)
Builds EM-space padding for right-side text labels.

levelTrimTrailingZeros(txt)
Removes unnecessary trailing zeros and trailing decimal points.

levelStripLeadingZero(txt)
Removes leading decimal zeroes such as 0.42 → .42 and -0.42 → -.42.

levelSigFig(value, figs)
Rounds a number to a requested number of significant figures.

levelNumberText(value, pattern)
Formats a number with a Pine pattern and then trims unnecessary zeros.

levelPriceText(value, sigFigs)
Formats a level price using significant figures and compact decimal trimming.

levelAbsMoneyText(absValue)
Formats an absolute money value rounded to two decimals.

levelAbsPctText(absValue)
Formats an absolute percent value rounded to two decimals.

levelMoneyChangeText(currentPrice, level)
Formats current price minus level as a signed $ difference.

levelPctChangeText(currentPrice, level)
Formats current price minus level as a signed % difference.

➖Level Label Text Helpers➖

levelLabelText(tag, level, currentPrice, pad, showPrice, showMoneyDiff, showPctDiff, sigFigs)

Builds a standardized right-side level label block.

The label model is:

• optional price row
• optional $ difference row
• optional % difference row
• required level tag row supplied by the calling script

Example output:

741.82
-$22.16
-2.90%
D[1]Hi

EM-space padding is applied to every row. This lets scripts visually stagger labels to the right while keeping the actual label pinned to the current bar_index.

➖Object Sync Helpers➖

These helpers create an object when enabled, update it in place while enabled, and delete it when the caller’s condition turns false.

syncTextLabel(lbl, show, y, txt, txtColor, sizeIn)
Creates, updates, or deletes a transparent right-side text label at the current bar_index.

syncBarTimeLevelLine(ln, show, t1, t2, y, lineColor, lineWidth, styleIn)
Creates, updates, or deletes a horizontal bar-time level line using xloc.bar_time.

This is useful for level scripts that want line starts based on a real timestamp instead of deep bar-index offsets.

➖Slot Array Helpers➖

These helpers let scripts store many repeated level lines and labels in fixed array slots instead of declaring one separate variable per object.

syncLineSlot(lines, slot, show, t1, t2, y, lineColor, lineWidth, styleIn)
Creates, updates, or deletes a bar-time level line stored in a fixed array slot.

syncLabelSlot(labels, slot, show, y, txt, txtColor, sizeIn)
Creates, updates, or deletes a transparent right-side text label stored in a fixed array slot.

Typical use:

const int SLOT_HI = 0
const int SLOT_LO = 1
const int SLOT_CL = 2

var array<line> rowLines = array.new_line(3, na)
var array<label> rowLabels = array.new_label(3, na)

LVL.syncLineSlot(rowLines, SLOT_HI, showHi, hiStartTime, time, hiLevel, hiColor, 2, "Dotted")
LVL.syncLabelSlot(rowLabels, SLOT_HI, showHiLabel, hiLevel, hiText, hiColor, "Normal")

This is especially useful for scripts with repeated rows such as:

• Previous Day High / Low / Close
• Weekly High / Low / Close
• Monthly High / Low / Close
• VWAP bands
• ATR levels
• rolling window levels
• trendline or envelope companion levels

➖History Array Helpers➖

These helpers support scripts that store completed records in arrays, especially newest-first arrays populated with array.unshift().

pruneFloat(arr, maxKeep)
Prunes a float array by popping old records from the end.

pruneInt(arr, maxKeep)
Prunes an int array by popping old records from the end.

pruneLineObjects(arr, maxKeep)
Prunes a line array and deletes removed line objects.

pruneLabelObjects(arr, maxKeep)
Prunes a label array and deletes removed label objects.

pruneHiLoHistory(highs, lows, highTimes, lowTimes, windowTimes, maxKeep)
Prunes synchronized high / low / high-time / low-time / window-time arrays.

pruneHlcHistory(highs, lows, closes, highTimes, lowTimes, closeTimes, windowTimes, maxKeep)
Prunes synchronized high / low / close / source-time / window-time arrays.

histFloat(arr, idx)
Returns a float history value at an array index, or na if unavailable.

histInt(arr, idx)
Returns an int history value at an array index, or na if unavailable.

requestOrManual(requestValue, manualValue)
Returns a requested value when available, otherwise the manual value.

manualOrRequest(manualValue, requestValue)
Returns a manual value when available, otherwise the requested value.

manualSourceTime(manualValue, times, idx)
Returns a matching manual source time only when the matching manual value exists.

➖Source Start-Time Helpers➖

These helpers route line-start timestamps using a common level-script model.

sourceLineStartTime(mode, sourceTime, activeTime)
Resolves Active Period versus Source Candle / Source Close Candle starts.

windowSourceLineStartTime(mode, windowTime, sourceTime, activeTime)
Resolves Active Period, Source Window, Source Candle, or Source Close Candle starts.

Start-time model:

Active Period:
Uses the active period start supplied by the calling script.

Source Window:
Uses the completed source window start supplied by the calling script.

Source Candle / Source Close Candle:
Uses the exact source candle time supplied by the calling script when available. If the exact source candle time is not available, it falls back to Source Window when available, then Active Period.

This keeps the library generic while allowing calling scripts to decide what a “source candle” means in their own context.

➖Newest-First Rolling Extreme Helpers➖

These helpers are built for arrays where index 0 is the most recent completed record.

Newest-first history model:

• index 0 = most recent completed record
• index 1 = one completed record back
• index 2 = two completed records back
• index 3 = three completed records back
• index 4 = four completed records back

A 5-record rolling high scans indexes 0 through 4 when available.

highestNewestFirst(values, lookback)
Returns the highest value and matching array index from a newest-first array window.

lowestNewestFirst(values, lookback)
Returns the lowest value and matching array index from a newest-first array window.

highestNewestFirstWithTime(values, times, lookback)
Returns the highest value, matching array index, and matching source time from synchronized newest-first arrays.

lowestNewestFirstWithTime(values, times, lookback)
Returns the lowest value, matching array index, and matching source time from synchronized newest-first arrays.

Important note:
The returned index is an array index, not a bar offset. If the calling script stores synchronized time arrays, the “with time” helpers can also return the matching source timestamp.

Example:

// Newest-first arrays populated with array.unshift().
[roll5High, roll5HighIdx, roll5HighTime] = LVL.highestNewestFirstWithTime(
dailyHighHistory,
dailyHighTimeHistory,
5)

[roll5Low, roll5LowIdx, roll5LowTime] = LVL.lowestNewestFirstWithTime(
dailyLowHistory,
dailyLowTimeHistory,
5)

➖Recommended Usage➖

This library works best when the calling script follows this workflow:

1. Resolve the level value in the script.
2. Resolve the source candle time or source window time in the script.
3. Resolve the final visibility condition in the script.
4. Use this library to format the label, route color, choose start time, and manage the line/label object.

This keeps source logic and interpretation script-level while making the reusable output layer cleaner and easier to maintain.

➖Important Notes➖

This library is a utility layer only.

It does not:
• request data
• detect sessions
• choose RTH or EXT behavior
• calculate previous-day levels
• calculate VWAP
• calculate pivots
• calculate trendlines
• decide trade direction
• generate signals

Calling scripts remain responsible for their own engine logic and interpretation.

The included demo script is meant to show how the library can be used to manage live levels, previous-day levels, rolling completed-record levels, label padding, object slots, and start-time routing.

Aviso legal

As informações e publicações não se destinam a ser, e não constituem, conselhos ou recomendações financeiras, de investimento, comerciais ou de outro tipo fornecidos ou endossados pela TradingView. Leia mais nos Termos de Uso.