CatalystCalendarDataData component of the Catalyst economic calendar indicator.
WHAT THIS CONTAINS
A compiled release schedule for economic and commodity events across US, Euro
Area, UK, Japan, Australia, New Zealand, Canada, Switzerland and China, plus
energy and agricultural reports, Treasury auctions and market-structure dates.
Roughly 24 months of history and 12 months of forward schedule.
The schedule is compiled offline from official agency calendars: the Federal
Reserve, FRED, the US Bureau of Labor Statistics, the US Energy Information
Administration, and the published policy meeting calendars of the ECB, Bank of
England, Bank of Canada, Reserve Bank of Australia, Reserve Bank of New Zealand,
Bank of Japan and Swiss National Bank.
This library holds dates only. Released values are read separately through
request.economic().
EXPORTS
monthChunk(year, month) the encoded occurrence records for one UTC month
keyTable() event metadata, one record per line
buildStamp() UTC milliseconds at which this data was generated
horizon() the first and last timestamp covered
FORMAT
Each occurrence is a fixed-width 10-character record, DDHHMMKKKI. The encoding is
documented inline in the source in enough detail to decode a record by hand.
UPDATE CADENCE
Regenerated and republished quarterly. Scripts pin a version number, so an
existing import keeps working until it is deliberately updated.
``` ספרייה

CryptonianEWViewLibrary "CryptonianEWView"
Cryptonian Elliott Wave View /1. Dedicated presentation-policy layer for Minimal Trader, Balanced, Full Audit and Custom chart modes. Presentation only; no Elliott, Forecast, Trade, Runtime or Audit methodology.
resolve(mode, cleanChart, primaryDegreeLinesOn, secondaryDegreeLinesOn, subSecondaryDegreeLinesOn, alternateCountLinesOn, correctionLinesOn, showPivotSkeleton, showElliottChannels, showPrimaryCount, secondaryDegreeLabelsOn, subSecondaryDegreeLabelsOn, showAlternateCount, showCorrection, showPivotIds, showDevelopingPivot, showCorrectionLevels, showFibModel, showFreshFvg, showInvalidationLevel, showInvalidationTags, showRevisionTags, showTradeLevels, showTradeSignals, showPotentialForecast, forecastAuditOn, forecastAuditLabelsOn, contextForecastRoadmapOn, contextForecastMainLabelOn, contextForecastTargetLabelsOn, htfTradeBridgeGeometryOn, maxTradeLifecycleLabels)
Parameters:
mode (string)
cleanChart (bool)
primaryDegreeLinesOn (bool)
secondaryDegreeLinesOn (bool)
subSecondaryDegreeLinesOn (bool)
alternateCountLinesOn (bool)
correctionLinesOn (bool)
showPivotSkeleton (bool)
showElliottChannels (bool)
showPrimaryCount (bool)
secondaryDegreeLabelsOn (bool)
subSecondaryDegreeLabelsOn (bool)
showAlternateCount (bool)
showCorrection (bool)
showPivotIds (bool)
showDevelopingPivot (bool)
showCorrectionLevels (bool)
showFibModel (bool)
showFreshFvg (bool)
showInvalidationLevel (bool)
showInvalidationTags (bool)
showRevisionTags (bool)
showTradeLevels (bool)
showTradeSignals (bool)
showPotentialForecast (bool)
forecastAuditOn (bool)
forecastAuditLabelsOn (bool)
contextForecastRoadmapOn (bool)
contextForecastMainLabelOn (bool)
contextForecastTargetLabelsOn (bool)
htfTradeBridgeGeometryOn (bool)
maxTradeLifecycleLabels (int)
drawActiveZone(boxStore, labelStore, enabled, startBar, projectionBars, zoneTop, zoneBottom, zoneName, zoneColor, panelColor, labelSize)
Parameters:
boxStore (array)
labelStore (array)
enabled (bool)
startBar (int)
projectionBars (int)
zoneTop (float)
zoneBottom (float)
zoneName (string)
zoneColor (color)
panelColor (color)
labelSize (string) ספרייה

CryptonianEWAuditLibrary "CryptonianEWAudit"
Cryptonian Elliott Wave Audit /1. Owns production integrity auditing, compact event-state construction, universal-event aggregation and alert deduplication for the library-first Elliott architecture. The audit rules are migrated from Elliott Wave Engine 11.8b2 without changing Elliott or trade methodology.
addUniqueLimited(values, value, maximumSize)
Adds one unique string and caps the registry size.
Parameters:
values (array)
value (string)
maximumSize (int)
eventOnce(eventRegistry, eventCondition, eventName, sourceKey, maximumSize, deduplicate)
Generic event de-duplication helper. This preserves the 11.8b2 event
key contract: eventName | sourceKey | time.
Parameters:
eventRegistry (array)
eventCondition (bool)
eventName (string)
sourceKey (string)
maximumSize (int)
deduplicate (bool)
eventState(lastEvent, currentCountKey, lastInvalidCountKey, forecastKey, tradeId, countStarted, countRevised, countInvalidated, forecastNew, forecastRevised, forecastInvalidated, tradeWaiting, tradeActivated, tradeResolved, tradeCountInvalidExit)
Creates the shared Model.EventState. The code field is a bit-mask for
future audit/UI use; the named booleans remain the authoritative contract.
Parameters:
lastEvent (string)
currentCountKey (string)
lastInvalidCountKey (string)
forecastKey (string)
tradeId (string)
countStarted (bool)
countRevised (bool)
countInvalidated (bool)
forecastNew (bool)
forecastRevised (bool)
forecastInvalidated (bool)
tradeWaiting (bool)
tradeActivated (bool)
tradeResolved (bool)
tradeCountInvalidExit (bool)
tradeLifecycleEvent(resolution)
True when Trade's per-bar resolution contains any lifecycle event.
TP1 is intentionally included even when the trade remains live because 11.8b2
treats TP1 as an alert-worthy lifecycle event.
Parameters:
resolution (TradeResolution type from AYEHAN/CryptonianEWModel/1)
productionAudit(pivotPrices, pivotBars, pivotTimes, pivotTypes, pivotIds, nestedPivotPrices, nestedPivotTimes, fvgOriginalTops, fvgOriginalBottoms, fvgLiveTops, fvgLiveBottoms, fvgDirections, fvgBirthBars, tradeActivationCount, tradeResolutionCount, tradeProfitableResolutions, tradeLosingResolutions, tradeFlatResolutions, tradeCancelled, tradeWaitingCancellationCount, tradeTp1ReachedCount, tradeTp2ReachedCount, tradeLive, tradeSetupId, tradeDirection, tradeEntry, tradeStop, tradeTp1)
Runs the original 11.8b2 production audit and owns persistent issue
history internally. Call this once per host bar.
Parameters:
pivotPrices (array)
pivotBars (array)
pivotTimes (array)
pivotTypes (array)
pivotIds (array)
nestedPivotPrices (array)
nestedPivotTimes (array)
fvgOriginalTops (array)
fvgOriginalBottoms (array)
fvgLiveTops (array)
fvgLiveBottoms (array)
fvgDirections (array)
fvgBirthBars (array)
tradeActivationCount (int)
tradeResolutionCount (int)
tradeProfitableResolutions (int)
tradeLosingResolutions (int)
tradeFlatResolutions (int)
tradeCancelled (int)
tradeWaitingCancellationCount (int)
tradeTp1ReachedCount (int)
tradeTp2ReachedCount (int)
tradeLive (bool)
tradeSetupId (string)
tradeDirection (int)
tradeEntry (float)
tradeStop (float)
tradeTp1 (float)
universalEventRaw(events, committedPivotNow, impulseCompletedNow, correctionCompletedNow, freshFvgConfluenceNow, mtfContextChangedNow, mtfPrimaryGateReadyNow, tradeLifecycleNow, forecastAuditTargetHit, primaryW5TargetHitNow, productionStructuralGate, productionTradeActivationGate, productionAuditChangedNow)
Reproduces the 11.8b2 universal-event OR tree using the compact shared
EventState plus the few event families not represented by Model /1.
Parameters:
events (EventState type from AYEHAN/CryptonianEWModel/1)
committedPivotNow (bool)
impulseCompletedNow (bool)
correctionCompletedNow (bool)
freshFvgConfluenceNow (bool)
mtfContextChangedNow (bool)
mtfPrimaryGateReadyNow (bool)
tradeLifecycleNow (bool)
forecastAuditTargetHit (bool)
primaryW5TargetHitNow (bool)
productionStructuralGate (bool)
productionTradeActivationGate (bool)
productionAuditChangedNow (bool)
universalAlert(rawEvent, maximumSize, deduplicate)
Stateful universal alert. The registry lives in Audit /1 rather than
the indicator host. This preserves 11.8b2's ANY_EW_EVENT | bar_index | time key.
Call once per host bar, then feed .fire to the single alertcondition().
Parameters:
rawEvent (bool)
maximumSize (int)
deduplicate (bool)
processUniversalAlert(events, committedPivotNow, impulseCompletedNow, correctionCompletedNow, freshFvgConfluenceNow, mtfContextChangedNow, mtfPrimaryGateReadyNow, tradeLifecycleNow, forecastAuditTargetHit, primaryW5TargetHitNow, productionStructuralGate, productionTradeActivationGate, productionAuditChangedNow, maximumSize, deduplicate)
Convenience wrapper: aggregate + deduplicate in one host call.
Parameters:
events (EventState type from AYEHAN/CryptonianEWModel/1)
committedPivotNow (bool)
impulseCompletedNow (bool)
correctionCompletedNow (bool)
freshFvgConfluenceNow (bool)
mtfContextChangedNow (bool)
mtfPrimaryGateReadyNow (bool)
tradeLifecycleNow (bool)
forecastAuditTargetHit (bool)
primaryW5TargetHitNow (bool)
productionStructuralGate (bool)
productionTradeActivationGate (bool)
productionAuditChangedNow (bool)
maximumSize (int)
deduplicate (bool)
ProductionAuditState
Complete production-integrity result. Individual checks are retained so
Fields:
pass (series bool)
status (series string)
currentIssue (series string)
signature (series string)
unresolvedActivations (series int)
issueCount (series int)
lastIssue (series string)
changedNow (series bool)
pivotArraysAligned (series bool)
nestedArraysAligned (series bool)
fvgArraysAligned (series bool)
tradeAccounting (series bool)
tradeResultAccounting (series bool)
cancellationAccounting (series bool)
liveIdentity (series bool)
liveOrdering (series bool)
tp1Accounting (series bool)
UniversalEventState
Compact result from the universal Elliott event aggregator.
Fields:
raw (series bool)
fire (series bool)
key (series string) ספרייה

Pine Script Utility Library [1CG]Pine Script Utilities
Building a Pine script often means writing the same supporting code again: setting up timezone choices, converting prices to ticks or pips, updating chart drawings, or working out which candles belong to a trading session.
Pine Script Utilities brings these everyday tasks into one reusable toolbox. Its purpose is to help script authors spend more time on what makes their indicator useful and less time rebuilding common tools.
This is a library for Pine Script v6. You use it inside your own indicator or strategy; adding the library alone does not produce a chart display. You can use a single helper or combine several parts of the library as your script grows.
Consistent choices for your settings
Give users familiar choices without recreating the same lists in every script. The library supplies reusable options for:
Timezones, including the symbol's exchange timezone.
Hours, minutes, quarter-hour times and common durations.
Line styles, thickness, extension direction and label styles.
Text size and horizontal or vertical alignment.
Session presets and the starting points for session high and low lines.
It also turns these selections into the values Pine needs to use them. Your script still decides which settings to offer and how to arrange them.
Time and timezone tools
Work with clock times, session schedules and chart timing without repeatedly writing the conversion code yourself. Helpers let you build and read time values, convert between clock times and minutes, calculate durations, check session membership and limit processing to a chosen history window.
For example, you can define a session in New York time even when the symbol uses a different exchange timezone. Named timezones allow session boundaries to follow local daylight-saving changes. Overnight schedules are supported, so a session can start in the afternoon and finish the following morning.
Everyday price and quantity conversions
Use the same conversion tools across different scripts:
Convert a price movement into ticks or pips, or convert those distances back into price.
Override the pip size when a broker's price feed needs a different convention.
Read the symbol's price precision, tick value and asset category.
Round quantities down to a chosen increment.
Calculate a position's notional value from quantity, price and the symbol's point value.
For example, a candle-range display could show its size in ticks instead of a raw price difference. These are general conversions; account-risk sizing and risk/reward calculations belong in a separate risk library.
Easier drawing maintenance
Once your script has created a drawing, the library can help keep it up to date. Change the position, appearance or text of lines, labels and boxes, and update existing table cells. Supply the properties you want to change and leave the others as they are.
Cleanup helpers remove groups of lines, labels, boxes or connected-line drawings called polylines. You can also keep a line collection within a chosen size and turn lists of times and prices into points for chart drawings. This gives scripts a common way to manage their chart objects as new data arrives.
Session tracking beyond simple clock checks
For scripts that need session ranges, the library can track the opening price, high, low and latest closing price, along with the times of the highs and lows. Use a preset schedule or define your own, track multiple sessions separately, and retrieve the current session or earlier completed sessions.
It also handles several details that can otherwise produce confusing chart results:
A session can start or finish partway through a candle. Where needed, available one-minute data helps exclude prices from outside the session. For example, a 09:10 start on a 15-minute chart should not include the earlier prices from the 09:00 candle.
Session prices and displayed line lengths stay separate. You can collect prices until noon and keep the resulting levels visible later without changing the session's high or low.
High and low lines can start from the session opening, the session end, or the time each extreme occurred.
When trading reopens after a long closure, eligible line endpoints can carry forward across the missed days. An overnight session interrupted by the closure can resume as the same session, preserving its earlier prices.
Stored sessions can be kept by record count, so a script can retain actual observations instead of treating empty weekend dates as trading sessions.
The session tools use ordinary chart candles where those candles are sufficient. They can request one-minute data for candles that contain a session boundary, and several sessions can share that data.
Building blocks for your own indicators
You could use these tools for a session-range overlay, a candle-size display, a dashboard with consistent text and styles, or an indicator that marks a chosen time window. Time-window helpers provide the opening and closing times and help your script decide when to draw the window.
The companion session example demonstrates how these pieces fit together. It keeps a chosen number of session records, draws the retained history, and updates the current session as prices arrive. Its complete appearance and additional features are choices made in the example; you can build a different display using the same utilities.
Getting started
Import the library into a Pine v6 script and start with the helpers you need. Simple conversions and drawing helpers can be used independently. Session tracking needs a little more setup because your script keeps the session records and decides how to display them. The full guide explains that workflow, while the API reference lists the available functions and their arguments.
A few things to know
Session tracking is intended for standard intraday time-based charts. Its one-minute boundary checks apply to chart timeframes above one minute.
Custom session tracking uses one start and end time, such as 1600-0400. Presets describe regular clock schedules, not complete holiday or lunch-break calendars.
Weekend and closure adjustments happen when reopening data arrives. The library does not predict future market closures.
Accurate ranges depend on available price history. If required one-minute data is missing, the library does not replace it with a whole candle that could contain out-of-session prices; the resulting range may be incomplete.
Pip sizes, quantity increments and contract values can differ between feeds and instruments. Use the appropriate values for your symbol.
Your script controls its drawings, alerts and history limits. TradingView's data and drawing limits still apply.
ספרייה

XZ_SD_Session_ContextLibrary "XZ_SD_Session_Context"
XZ S&D; Session Context v1. Display-only S&D; support library for bounded recurring session High-Low frames. It owns S&D; session window storage, Horizon clipping, occurrence retention, frame rendering and live session text while delegating canonical clocks/masks to XZ Session Authority.
newState()
Creates one persistent S&D; Session Context runtime state.
customSpec(open_hhmm, close_hhmm, weekdays_only)
Builds the Custom session specification used by the chart/lower-TF membership sample request.
Parameters:
open_hhmm (simple string)
close_hhmm (simple string)
weekdays_only (simple bool)
processDirect(state, enabled, standard, show_sydney, show_tokyo, show_london, show_new_york, custom_timezone, exchange_timezone, horizon, horizon_timezone, sample_time, sample_close_time, sample_high, sample_low, native_market_bar, custom_bar)
Processes one direct chart-context sample. Repeated realtime calls are allowed so the live session High/Low can expand intrabar.
Parameters:
state (State)
enabled (bool)
standard (simple string)
show_sydney (bool)
show_tokyo (bool)
show_london (bool)
show_new_york (bool)
custom_timezone (simple string)
exchange_timezone (simple string)
horizon (simple string)
horizon_timezone (simple string)
sample_time (int)
sample_close_time (int)
sample_high (float)
sample_low (float)
native_market_bar (bool)
custom_bar (bool)
processLower(state, enabled, standard, show_sydney, show_tokyo, show_london, show_new_york, custom_timezone, exchange_timezone, horizon, horizon_timezone, sample_time, sample_close_time, sample_high, sample_low, native_market_bar, custom_bar)
Processes one reconstructed lower-timeframe sample. Duplicate/previous sample timestamps are ignored internally.
Parameters:
state (State)
enabled (bool)
standard (simple string)
show_sydney (bool)
show_tokyo (bool)
show_london (bool)
show_new_york (bool)
custom_timezone (simple string)
exchange_timezone (simple string)
horizon (simple string)
horizon_timezone (simple string)
sample_time (int)
sample_close_time (int)
sample_high (float)
sample_low (float)
native_market_bar (bool)
custom_bar (bool)
render(state, enabled, standard, show_sydney, show_tokyo, show_london, show_new_york, history_occurrences, show_codes, frame_transparency, single_color, sydney_color, tokyo_color, london_color, new_york_color, horizon, horizon_timezone, reference_time)
Renders bounded Session Context frames. This display layer never feeds S&D; authority.
Parameters:
state (State)
enabled (bool)
standard (simple string)
show_sydney (bool)
show_tokyo (bool)
show_london (bool)
show_new_york (bool)
history_occurrences (int)
show_codes (bool)
frame_transparency (int)
single_color (color)
sydney_color (color)
tokyo_color (color)
london_color (color)
new_york_color (color)
horizon (simple string)
horizon_timezone (simple string)
reference_time (int)
displayCount(state)
Number of currently rendered Session Context boxes.
Parameters:
state (State)
liveText(state, enabled, standard)
Live active-session text for Status.
Parameters:
state (State)
enabled (bool)
standard (simple string)
Window
Fields:
session_index (series int)
occurrence_key (series int)
open_time (series int)
scheduled_close_time (series int)
last_sample_time (series int)
high (series float)
low (series float)
State
Fields:
active (array)
completed (array)
displayed (array)
parent_cutoff (series int)
active_mask (series int)
last_processed_lower_time (series int) ספרייה

XZ Session CoreLibrary "XZ_Session_Authority"
XZ Session Authority v1. Canonical suite-wide session-time authority for XZ indicators. Defines deterministic session standards, DST-aware IANA timezones, fixed session segments, custom-session reconstruction, occurrence keys and overlap masks. It deliberately contains no indicator-specific lifecycle, qualification, Supply/Demand, FVG, IL, market-structure or Research methodology.
sessionCount()
Number of canonical market-list session indexes used by XZ: Sydney, Tokyo, London, New York.
usesMarketList(standard)
True when the selected standard uses the canonical four-market session list.
Parameters:
standard (simple string)
standardCode(standard)
Short code for a session standard.
Parameters:
standard (simple string)
sessionName(standard, sessionIndex)
Full display name for one session index.
Parameters:
standard (simple string)
sessionIndex (int)
sessionCode(standard, sessionIndex)
Compact display code for one session index.
Parameters:
standard (simple string)
sessionIndex (int)
sessionTimezone(standard, sessionIndex, customTimezone, symbolTimezone)
Authoritative timezone for one session index.
Parameters:
standard (simple string)
sessionIndex (int)
customTimezone (simple string)
symbolTimezone (simple string)
isLocalWeekday(timestampValue, tz)
True when timestampValue is Monday-Friday in tz.
Parameters:
timestampValue (int)
tz (string)
occurrenceKey(timestampValue, tz)
Stable YYYYMMDD occurrence key in the supplied timezone.
Parameters:
timestampValue (int)
tz (string)
segmentCount(standard, sessionIndex)
Number of finite fixed segments for one market session occurrence. Tokyo Exchange Cash Hours uses two segments so the lunch break remains real.
Parameters:
standard (simple string)
sessionIndex (int)
segmentBounds(standard, sessionIndex, segmentIndex, timestampValue, customTimezone, symbolTimezone)
Market Centres and Exchange Cash Hours use fixed local schedules plus IANA timezone/DST authority. Consumers must not use this helper to infer exchange holidays or early closes on unrelated symbols.
Parameters:
standard (simple string)
sessionIndex (int)
segmentIndex (int)
timestampValue (int)
customTimezone (simple string)
symbolTimezone (simple string)
customSpec(openHHMM, closeHHMM, weekdaysOnly)
Reconstructs a Pine custom-session string from vertically stacked HHMM inputs.
Parameters:
openHHMM (simple string)
closeHHMM (simple string)
weekdaysOnly (simple bool)
sessionBit(sessionIndex)
Bit assigned to one canonical session index.
Parameters:
sessionIndex (int)
maskHas(sessionMask, sessionIndex)
Tests membership in the canonical four-session bit mask.
Parameters:
sessionMask (int)
sessionIndex (int)
maskAdd(sessionMask, sessionIndex)
Adds one canonical session index to a four-session bit mask.
Parameters:
sessionMask (int)
sessionIndex (int)
maskIntersection(firstMask, secondMask)
Intersection of two canonical session masks.
Parameters:
firstMask (int)
secondMask (int)
maskCount(sessionMask)
Number of active session bits in a mask.
Parameters:
sessionMask (int)
maskIsOverlap(sessionMask)
True when more than one canonical session is active in a mask.
Parameters:
sessionMask (int)
singleSessionIndex(sessionMask)
Returns the session index only when exactly one session bit is set; otherwise -1.
Parameters:
sessionMask (int)
maskCode(standard, sessionMask)
Compact human-readable code for a session mask.
Parameters:
standard (simple string)
sessionMask (int) ספרייה

ReadableTimeframeAlertsFixes the "what timeframe is this?" problem.
Pine's timeframe.period gives you raw values like "60", "240", "1D", "3M" — accurate, but not something a normal user can read at a glance. If your alert says "Zone formed on 360," most people have no idea that 360 means the 6-hour timeframe.
This library converts that raw string into a proper readable label: "60" becomes "1 Hour", "240" becomes "4 Hours", "1D" becomes "Daily", "3M" becomes "3 Months", and so on — covering minutes, hours, days, weeks, months, seconds, and ticks.
I built this after running into the exact issue in my own — a user kept seeing numbers like 360 in their alerts and couldn't tell what timeframe it referred to. This library is what fixed it, and I'm sharing it so anyone facing the same confusion can drop it into their own script.
Usage:
import AfnanTAjuddin/ReadableTimeframeAlerts/1 as tf
alert("Zone formed on " + tf.f_tf_label(timeframe.period))
One line, and your alert messages, labels, or tables show a timeframe users actually understand instead of a raw number.
Found an edge case it doesn't handle correctly? Drop a comment and I'll take a look. ספרייה

std_timestd_time is a full calendar for Pine Script v6: the class of time infrastructure other ecosystems get from java.time, C++20 chrono and exchange_calendars, written natively in Pine. Civil dates, durations and periods, time zones with real daylight-saving rules, twelve exchange calendars (NYSE, LSE, CME, JPX, EUREX, HKEX, ASX, TSX, SSE, BSE, SGX, and 24/7 crypto) with holidays, half days and lunch breaks, trading-day arithmetic, sessions with on-the-bar close markers, option expiries including VIX settlement, ISDA day counts and business-day conventions, an economic release calendar, and an ISO-8601 formatter and parser. A calendar, not a bag of helpers.
One conversion sits at the bottom: Hinnant's civil-to-epoch pair, the algorithm C++20 chrono adopted. Weekdays, ISO weeks, DST boundaries, adjusters and holiday rules all derive from it, so no second implementation exists to quietly disagree with the first. The API keeps calendar arithmetic and instant arithmetic as separate families, because plus one day across a clock change is not plus 24 hours, and it treats an offset and a zone as different things, because they are. When a DST transition makes a local time impossible or ambiguous, you choose the resolution policy instead of inheriting one.
Rules do the work wherever the world runs on rules: VIX settlement is derived, not tabled, and reproduces every published Cboe settlement from 2021 through 2026, including all four Tuesday exceptions. The calendars are checked date-by-date against reference records over their stated ranges: NYSE and LSE on every single day from 1976 to 2035, HKEX through 2049, EUREX across its full window with zero differences. Every calendar declares the years it answers exactly, and past that horizon it returns UNKNOWN, a real three-valued answer, rather than reading an untabled holiday as a trading day. Completeness is a claim with a date on it, and every calendar states its date.
Full documentation, per-calendar coverage windows, the error model, and design rationale: github.com ספרייה

S2F Data Release CalendarStatic U.S. data-release calendar for S2F range profiles.
• Alpenglow: selected 07:30 CT (08:30 ET) releases, including CPI, NFP, PPI, Retail Sales, GDP, PCE, Jobless Claims, Durable Goods, Housing Starts, Trade Balance, and Import/Export Prices.
• Swiper / Teo: selected 09:00 CT (10:00 ET) releases, including Michigan Sentiment, ISM Manufacturing/Services, JOLTS, Consumer Confidence, New Home Sales, and Existing Home Sales.
Use is_alpenglow_day() / alpenglow_events() for the 07:30 CT calendar and is_swiper_teo_release_day() / swiper_teo_events() for the 09:00 CT calendar.
Coverage: 2026-08-01 through 2026-12-31. Update and republish each quarter using the official release schedules. ספרייה

KC Institutional Core LibraryKC Institutional Core Library v1.0
KCInstitutionalCore is a reusable Pine Script v6 utility library created to support structured technical-analysis workflows without duplicating common helper logic across multiple indicators and strategies.
The library provides transparent and independently reusable functions for:
Score normalization and trade-quality grading
Premium, Discount and Equilibrium classification
Risk-to-reward calculation
Risk-based position-size estimation
Timeframe-aware trading-style classification
Adaptive higher-timeframe selection
Directional alignment analysis
Execution-blocker identification
The exported functions are deterministic utilities. They do not generate guaranteed trading signals, predict future price movement or execute trades.
Basic import example
import Kelly_Carter12/KCInstitutionalCore/1 as kc
string grade = kc.scoreToGrade(78)
string style = kc.tradeStyle(timeframe.in_seconds())
= kc.rangeLocation(close, ta.highest(high, 50), ta.lowest(low, 50))
The detailed function documentation below explains every exported function, parameter and return value.
Library "KCInstitutionalCore"
Reusable Pine Script v6 utilities for timeframe context, score grading, premium/discount classification, alignment, risk-to-reward and position-size calculations. Designed as a transparent helper library for indicators and strategies.
clamp(value, minimum, maximum)
Restricts a numeric value to the supplied minimum and maximum boundaries.
Parameters:
value (float) : Value to restrict.
minimum (float) : Lower boundary.
maximum (float) : Upper boundary.
Returns: The restricted value.
scoreToGrade(score)
Converts a numeric score into a concise quality grade.
Parameters:
score (float) : Score expressed on a 0–100 scale.
Returns: A grade string from AA to D.
normalizeScore(rawScore, maximumScore)
Normalizes a raw score to a 0–100 scale.
Parameters:
rawScore (float) : Current raw score.
maximumScore (float) : Maximum possible raw score.
Returns: Normalized score from 0 to 100, or na when maximumScore is not positive.
rangeLocation(price, rangeHigh, rangeLow)
Classifies the current price inside a supplied dealing range.
Parameters:
price (float) : Current or evaluated price.
rangeHigh (float) : Upper boundary of the range.
rangeLow (float) : Lower boundary of the range.
Returns: A tuple containing PREMIUM, DISCOUNT, or EQUILIBRIUM and the 0–100 range percentage.
riskReward(entry, stop, target)
Calculates reward-to-risk from entry, stop and target prices.
Parameters:
entry (float) : Entry price.
stop (float) : Stop-loss price.
target (float) : Target price.
Returns: Absolute reward-to-risk ratio, or na when the stop distance is zero.
positionSize(accountSize, riskPercent, entry, stop, pointValue)
Estimates position size from account risk and stop distance.
Parameters:
accountSize (float) : Account balance or planning capital.
riskPercent (float) : Percentage of account risked.
entry (float) : Entry price.
stop (float) : Stop-loss price.
pointValue (float) : Monetary value per price point for one unit.
Returns: Estimated units or lots according to the supplied pointValue, or na for invalid inputs.
tradeStyle(chartSeconds)
Maps chart duration in seconds to a general planning style.
Parameters:
chartSeconds (float) : Chart timeframe duration in seconds, normally supplied with timeframe.in_seconds().
Returns: SCALP, INTRADAY, SWING, or POSITION.
adaptiveTimeframes(chartSeconds)
Suggests two broader context timeframes from the chart duration.
Parameters:
chartSeconds (float) : Chart timeframe duration in seconds, normally supplied with timeframe.in_seconds().
Returns: A tuple containing primary and secondary context timeframe strings.
alignmentState(localBias, htfBias, mtfBias)
Summarizes local, higher-timeframe and multi-timeframe directional agreement.
Parameters:
localBias (int) : Local direction: 1 bullish, -1 bearish, 0 neutral.
htfBias (int) : Higher-timeframe direction: 1 bullish, -1 bearish, 0 neutral.
mtfBias (int) : Broader alignment direction: 1 bullish, -1 bearish, 0 neutral.
Returns: BULL ALIGNED, BEAR ALIGNED, PARTIAL, CONFLICT, or NEUTRAL.
executionBlocker(direction, htfBias, mtfBias, location, structureConfirmed, liquidityConfirmed, newsBlocked)
Returns the first material execution blocker in a transparent priority order.
Parameters:
direction (int) : Intended direction: 1 long, -1 short, 0 neutral.
htfBias (int) : Higher-timeframe direction: 1 bullish, -1 bearish, 0 neutral.
mtfBias (int) : Multi-timeframe direction: 1 bullish, -1 bearish, 0 neutral.
location (string) : PREMIUM, DISCOUNT, or EQUILIBRIUM.
structureConfirmed (bool) : True when the required structure event is confirmed.
liquidityConfirmed (bool) : True when the required liquidity event is confirmed.
newsBlocked (bool) : True when a manual news blackout is active.
Returns: A concise blocker description, or CLEAR when no listed blocker is active. ספרייה

ספרייה

MarketReactionLibrary "MarketReaction"
Modular library for sessions, Initial Balance, PSY ranges, VWAPs, alerts, and macro sentiment helpers.
getSessionConfig(source)
Returns session config by source name.
Parameters:
source (simple string) : Session source: Tokyo, New York, London, Jerusalem, EU B, US B.
Returns: SessionConfig.
sessionModule(session, timeZone, sessionText, sessionColor, sessionDuration, showVisuals, showLabels, showLines, showMiddleLine, showBg, bgTransp)
Builds session high/low/middle lines, label, background fill and VWAP.
Parameters:
session (simple string) : Session string.
timeZone (simple string) : IANA timezone.
sessionText (simple string) : Label text.
sessionColor (color) : Session color.
sessionDuration (simple int) : Approximate session duration in ms.
showVisuals (bool) : Show this session visuals.
showLabels (bool) : Show labels.
showLines (bool) : Show high/low lines.
showMiddleLine (bool) : Show middle line.
showBg (bool) : Show background fill.
bgTransp (int) : Background transparency.
Returns: SessionResult.
initialBalanceModule(session, ibSession, timeZone, sessionLabel, showDLabels, showWLabels, showMLabels, showPrevD, showPrevW, showPrevM, dColor, wColor, mColor)
Calculates Daily, Weekly, Monthly Initial Balance and W/M IB VWAPs.
Parameters:
session (simple string) : Full session string.
ibSession (simple string) : IB sub-session string.
timeZone (simple string) : IANA timezone.
sessionLabel (simple string) : Session label.
showDLabels (bool) : Show D.IB labels.
showWLabels (bool) : Show W.IB labels.
showMLabels (bool) : Show M.IB labels.
showPrevD (bool) : Calculate previous daily IB.
showPrevW (bool) : Calculate previous weekly IB.
showPrevM (bool) : Calculate previous monthly IB.
dColor (color) : Daily IB label color.
wColor (color) : Weekly IB label color.
mColor (color) : Monthly IB label color.
Returns: IBResult.
psyRangeModule(session, timeZone, showLabels, showPrev, sessionColor)
Calculates PSY high/low, previous PSY levels, labels, and VWAP.
Parameters:
session (simple string) : Session string.
timeZone (simple string) : Timezone.
showLabels (bool) : Show PSY labels.
showPrev (bool) : Show previous PSY levels.
sessionColor (color) : PSY color.
Returns: PSYResult.
rangeSignal(highLevel, lowLevel, price)
Returns enter/exit signals for a range.
Parameters:
highLevel (float) : Range high.
lowLevel (float) : Range low.
price (float) : Price source.
Returns: RangeSignal.
tablePosition(pos)
Converts table position string to Pine position.
Parameters:
pos (simple string) : Position text.
Returns: Pine table position.
SessionConfig
Session configuration.
Fields:
session (series string) : Full session time.
ib (series string) : Initial Balance sub-session time.
tz (series string) : Session timezone.
label (series string) : Session label.
col (series color) : Session color.
duration (series int) : Approximate session duration in milliseconds.
SessionResult
Session result.
Fields:
high (series float) : Session high.
low (series float) : Session low.
mid (series float) : Session middle.
vwap (series float) : Session VWAP.
inSession (series bool) : True if bar is inside session.
firstBar (series bool) : True on first session bar.
highLine (series line) : Session high line.
lowLine (series line) : Session low line.
midLine (series line) : Session middle line.
IBResult
Initial Balance result.
Fields:
dHigh (series float) : Daily IB high.
dLow (series float) : Daily IB low.
pdHigh (series float) : Previous daily IB high.
pdLow (series float) : Previous daily IB low.
wHigh (series float) : Weekly IB high.
wLow (series float) : Weekly IB low.
pwHigh (series float) : Previous weekly IB high.
pwLow (series float) : Previous weekly IB low.
mHigh (series float) : Monthly IB high.
mLow (series float) : Monthly IB low.
pmHigh (series float) : Previous monthly IB high.
pmLow (series float) : Previous monthly IB low.
wVwap (series float) : Weekly IB VWAP.
mVwap (series float) : Monthly IB VWAP.
inSession (series bool) : True if bar is inside selected full session.
inIB (series bool) : True if bar is inside selected IB session.
ibFirstBar (series bool) : True on first IB bar.
sessionFirstBar (series bool) : True on first full-session bar.
PSYResult
PSY range result.
Fields:
high (series float) : Current PSY high.
low (series float) : Current PSY low.
pHigh (series float) : Previous PSY high.
pLow (series float) : Previous PSY low.
vwap (series float) : PSY VWAP.
inSession (series bool) : True if bar is inside PSY range.
firstBar (series bool) : True on first PSY bar.
RangeSignal
Range signal result.
Fields:
enter (series bool) : True when price enters range.
exit (series bool) : True when price exits range.
topDn (series bool) : Crossunder from above high.
topUp (series bool) : Crossover above high.
botUp (series bool) : Crossover from below low.
botDn (series bool) : Crossunder below low. ספרייה

ספרייה

ספרייה

ספרייה

CyberMarketLib# CyberMarketLib v2
CyberMarketLib provides market structure analysis combining swing point detection, Break of Structure (BoS) / Change of Character (CHoCH) identification, session classification, and volatility regime tracking.
## What it does
Delivers four core capabilities: swing point tracking (configurable left/right bar lookback), market structure events (BoS/CHoCH for trend continuation vs reversal), session classification (Asia/London/NY via UTC bucketing), and volatility regimes (LOW/NORMAL/HIGH/EXTREME via ATR percentiles). Build context-aware indicators that adapt to market conditions.
Outputs FractalData structs, StructureEvent/Session/VolRegime enums. All pivots use confirmed swing points (requires right_len bars validation), preventing repainting.
## How it works
Swing detection: `high < high > high `. Stores pivots in SwingHistory circular buffers with automatic capacity management.
BoS/CHoCH follows Smart Money Concepts:
- BOS_UP/DOWN: Price breaks recent swing (trend continuation)
- CHOCH_UP/DOWN: Pivot break after opposite swing (reversal)
Sessions via UTC hours: ASIA (00-08), LONDON (08-13), NY_OVERLAP (13-17), NY_AFTERNOON (17-21), OFF_HOURS (21-24).
Volatility regimes via ATR percentiles (100-bar window): LOW (<25th), NORMAL (25-75th), HIGH (75-90th), EXTREME (>90th).
## Why this is original
Only TradingView library combining BoS/CHoCH, sessions, and volatility regimes. Existing SMC indicators lack reusable libraries.
Unique features:
- Confirmed pivots only (no repainting)
- CHoCH sequence analysis (pivot pattern detection)
- UTC-based sessions (exchange-agnostic, DST-safe)
- Percentile volatility (asset-adaptive)
- Circular buffer (O(1) operations, memory-efficient)
Designed for composability: sessions → conditional logic, regimes → stop multipliers, BoS/CHoCH → entry/exit signals.
## How to use it
```pine
//@version=6
indicator("CyberMarketLib Demo", overlay=true)
import cybermediaboy/CyberMarketLib/2 as ML
// Swing points + BoS/CHoCH detection
var swing_hist = ML.f_swing_history_new(max_n=20)
var fractal = ML.f_detect_pivot(left_len=5, right_len=5)
if not na(fractal)
swing_hist.push(fractal)
var event = ML.f_detect_structure_event(swing_hist, close)
// event: BOS_UP, BOS_DOWN, CHOCH_UP, CHOCH_DOWN, NONE
// Session + volatility regime
session = ML.f_current_session() // ASIA, LONDON, NY_OVERLAP, etc.
vol_regime = ML.f_volatility_regime(14, 100) // LOW, NORMAL, HIGH, EXTREME
// Adaptive stops
atr = ta.atr(14)
stop_mult = vol_regime == ML.VolRegime.EXTREME ? 3.0 : 1.5
plot(close - atr * stop_mult, "Stop", color.red)
```
## Key functions
- `f_detect_pivot()` - Confirmed swing points (no repainting)
- `f_detect_structure_event()` - BoS/CHoCH detection
- `f_current_session()` - UTC-based session classification
- `f_volatility_regime()` - ATR percentile regimes
- `f_htf_for()` - Higher timeframe string generation
- SwingHistory UDT - Circular buffer for pivot storage
## Limitations
- Swing detection: `right_len` bars confirmation delay (lag vs repainting indicators)
- BoS/CHoCH: Assumes trending markets (false signals in choppy ranges)
- Sessions: UTC-only (no exchange-native or DST-aware sessions)
- Volatility: ATR-based only (may lag on sudden spikes)
- SwingHistory: Fixed capacity at initialization
- CHoCH: Requires manual state tracking to avoid duplicate signals
ספרייה

CyberAssetLib# CyberAssetLib v2
CyberAssetLib provides a typed asset registry for Pine Script traders managing multi-asset indicators, offering centralized metadata for asset classes, trading hours, parent blockchains, and venue selection across spot, perpetual, and futures markets.
## What it does
CyberAssetLib delivers a single source of truth for asset metadata, replacing scattered hardcoded lookups with a structured registry. Traders use this library to build cross-asset indicators that adapt behavior based on asset type—for example, applying different volatility filters to 24/7 crypto vs 9:30-16:00 US equities, or aggregating volume across multiple venues (Binance spot + Coinbase + CME futures) with liquidity-tier weighting. The library supports symbol aliasing (e.g., "BINANCE:BTCUSDT" → "BTC"), parent chain lookups (e.g., "MATIC" → "ETH" for Polygon), and venue filtering by kind (spot/perp/fut) and liquidity tier (T1/T2/T3).
The library outputs AssetRecord structs containing asset class (CRYPTO_MAIN, ALTS, SHARES, COMMODITY, INDEX, FX), trading hours regime (24x7, 23x5, EU, US), parent chain symbol, and arrays of Venue objects with exchange, ticker, kind, and tier. Traders query the registry via canonical symbol ("BTC") or full ticker alias ("BINANCE:BTCUSDT"), receiving structured metadata for downstream logic (e.g., "if asset.hours == H_24X7, disable session filters").
## How it works
The registry uses two hash maps: `bysymbol` (canonical symbol → AssetRecord) and `byalias` (full ticker → canonical symbol). Initialization populates these maps with hardcoded entries for major assets (BTC, ETH, SOL, SPX, GOLD, etc.). The `byalias` map enables O(1) ticker normalization: "BINANCE:BTCUSDT" → "BTC", eliminating 66-iteration if-else chains from prior implementations.
Each AssetRecord stores:
- **symbol**: Canonical key (e.g., "BTC")
- **cls**: AssetClass enum (CRYPTO_MAIN, ALTS, SHARES, COMMODITY, INDEX, FX)
- **subtype**: Fine-grained label (e.g., "bitcoin", "sp500-fut", "natgas-cfd")
- **chain**: Parent L1 blockchain symbol (e.g., "ETH" for MATIC, "SOL" for BONK)
- **isl1**: Boolean flag (true if asset IS its own chain, e.g., BTC, ETH, SOL)
- **hours**: TradingHours enum (H_24X7 for crypto, H_US for NYSE, H_EU for DAX)
- **venues**: Array of Venue objects (spot, perp, fut combined)
- **aliases**: Array of full ticker strings for byalias map population
Venue objects contain:
- **ticker**: Full TradingView ticker (e.g., "BINANCE:BTCUSDT")
- **kind**: VenueKind enum (SPOT, PERP, FUT)
- **exchange**: Exchange name (e.g., "BINANCE", "CME")
- **tier**: LiquidityTier enum (T1 for Binance/Coinbase/CME, T2 for OKX/Bybit, T3 for others)
The `f_build_venue` function auto-detects venue kind from ticker patterns: ".P" or "PERP" → PERP, "1!" or "FUT" → FUT, else SPOT. Exchange is extracted via string split on ":".
Volume aggregation uses AggregationPolicy to filter venues: `include_spot/perp/fut` (booleans), `max_tier` (1=T1 only, 3=all), `max_venues` (cap on returned venues). The VolumeAggregator struct stores selected venues with normalized weights (e.g., T1 venues get 2x weight vs T2).
## Why this is original
CyberAssetLib is the only TradingView library providing a typed, enum-based asset registry with multi-venue support. Existing solutions use hardcoded if-else chains (unmaintainable for 100+ assets), string-based classification (error-prone, no type safety), or single-venue assumptions (ignore liquidity fragmentation across exchanges).
Unique features:
- **Enum-typed fields**: AssetClass, TradingHours, VenueKind, LiquidityTier are frozen enums (backward-compatible with kNN integer casts), preventing typos and enabling exhaustive switch statements
- **Parent chain tracking**: `chain` field links L2 tokens to L1 blockchains (e.g., MATIC → ETH), enabling cross-chain correlation analysis
- **Multi-venue aggregation**: Single asset can have 10+ venues (Binance spot, Coinbase, Kraken, CME futures, Bybit perp), with policy-based filtering and liquidity-tier weighting
- **Alias normalization**: O(1) ticker → canonical symbol lookup (e.g., "BINANCE:BTCUSDT" → "BTC"), eliminating regex parsing or 66-iteration if-else chains
- **Trading hours metadata**: Enables session-aware indicators (e.g., "disable mean-reversion signals during US market close for equities, but keep active for 24/7 crypto")
The library is designed for extensibility: adding a new asset requires one AssetRecord entry, not scattered updates across multiple functions. Enum ordering is frozen (P11 convention) to ensure backward compatibility with indicators that serialize enum values to integers for kNN training data.
## How to use it
```pine
//@version=6
indicator("CyberAssetLib Demo", overlay=false)
import cybermediaboy/CyberAssetLib/2 as AL
// Example 1: Initialize registry and lookup asset by symbol
var reg = AL.f_registry_new()
AL.f_registry_init(reg) // Populate with default assets
var btc = reg.bysymbol.get("BTC")
if not na(btc)
label.new(bar_index, high, "BTC Class: " + str.tostring(btc.cls),
color=color.blue, textcolor=color.white)
// Example 2: Normalize ticker to canonical symbol
string current_ticker = syminfo.tickerid
string canonical = reg.byalias.get(current_ticker)
if not na(canonical)
label.new(bar_index, low, "Canonical: " + canonical,
color=color.orange, textcolor=color.white)
// Example 3: Filter venues by kind (get all perpetual venues for BTC)
if not na(btc)
var perp_venues = btc.venues_of(AL.VenueKind.PERP)
if array.size(perp_venues) > 0
var first_perp = array.get(perp_venues, 0)
label.new(bar_index, close, "First Perp: " + first_perp.ticker,
color=color.green, textcolor=color.white)
// Example 4: Build volume aggregator with policy
if not na(btc)
var policy = AL.AggregationPolicy.new(
include_spot=true, include_perp=true, include_fut=false,
max_tier=2, max_venues=5)
var agg = AL.f_build_aggregator(btc, policy)
if array.size(agg.selected) > 0
string venues_str = ""
for i = 0 to math.min(array.size(agg.selected) - 1, 2)
var v = array.get(agg.selected, i)
venues_str += v.ticker + " "
label.new(bar_index, high * 1.01, "Top Venues: " + venues_str,
color=color.purple, textcolor=color.white)
// Example 5: Check trading hours and adapt indicator behavior
if not na(btc)
bool is_24x7 = btc.hours == AL.TradingHours.H_24X7
bgcolor(is_24x7 ? color.new(color.green, 90) : color.new(color.red, 90),
title="24x7 Market")
```
## Inputs, outputs, expected behavior
**Registry initialization** (`f_registry_new`, `f_registry_init`):
- **Inputs**: None (uses hardcoded asset definitions)
- **Outputs**: AssetRegistry with populated `bysymbol` and `byalias` maps
- **Edge cases**: `f_registry_init` must be called once before lookups, idempotent (safe to call multiple times)
**Asset lookup** (`bysymbol.get`, `byalias.get`):
- **Inputs**: `symbol` (string, canonical like "BTC") or `ticker` (string, full like "BINANCE:BTCUSDT")
- **Outputs**: AssetRecord or na if not found
- **Edge cases**: Returns na for unknown symbols (no silent fallback to "ETH" like prior versions), case-sensitive keys
**Venue filtering** (`venues_of`, `venues_t1`, `venues_spot`):
- **Inputs**: `rec` (AssetRecord), `kind` (VenueKind enum)
- **Outputs**: array (filtered subset)
- **Edge cases**: Returns empty array if no venues match, preserves insertion order
**Venue builder** (`f_build_venue`):
- **Inputs**: `ticker` (string, e.g., "BINANCE:BTCUSDT.P"), `tier` (LiquidityTier enum)
- **Outputs**: Venue with auto-detected kind and exchange
- **Edge cases**: Defaults to SPOT if no perp/fut pattern detected, exchange is empty string if ticker lacks ":"
**Aggregation policy** (`f_build_aggregator`, `AggregationPolicy`):
- **Inputs**: `rec` (AssetRecord), `policy` (include_spot/perp/fut bools, max_tier int, max_venues int)
- **Outputs**: VolumeAggregator with selected venues and normalized weights
- **Edge cases**: Returns empty selected array if no venues match policy, weights sum to 1.0 (or 0.0 if no venues)
**Parent chain lookup** (`rec.chain`, `rec.isl1`):
- **Inputs**: AssetRecord
- **Outputs**: `chain` (string, parent L1 symbol), `isl1` (bool, true if asset IS its own chain)
- **Edge cases**: For L1 assets (BTC, ETH, SOL), `chain == symbol` and `isl1 == true`
## Limitations
1. **Hardcoded asset list**: The library ships with ~50 pre-defined assets (major crypto, indices, commodities). Adding new assets requires library source modification and republishing. No runtime registration API exists (Pine Script limitations on dynamic map population).
2. **No real-time venue discovery**: Venue lists are static (defined at library publication). If Binance launches a new BTC perpetual contract, the library won't auto-detect it. Users must manually update the library or use custom venue builders.
3. **Liquidity tier assignments are subjective**: T1/T2/T3 classifications are based on typical volume rankings (Binance/Coinbase/CME = T1, OKX/Bybit = T2, others = T3). Actual liquidity varies by asset and time. The library does not query real-time volume data to adjust tiers.
4. **No support for exotic derivatives**: The library covers spot, perpetual, and dated futures. Options, structured products, and leveraged tokens are not classified. VenueKind.FUT assumes CME-style dated contracts, not perpetual futures with funding rates.
5. **Trading hours are regime-level, not session-precise**: `TradingHours.H_US` means "US market hours" but doesn't encode exact open/close times (9:30-16:00 ET). Indicators needing precise session boundaries must implement additional logic (e.g., via `time()` and timezone offsets).
6. **Alias map requires exact ticker match**: `byalias.get("BINANCE:BTCUSDT")` works, but `byalias.get("binance:btcusdt")` (lowercase) returns na. The library does not auto-normalize case. Use `str.upper(syminfo.tickerid)` before lookup.
7. **No FIGI or ISIN support**: The library uses TradingView ticker strings as identifiers. Financial Instrument Global Identifiers (FIGI) or International Securities Identification Numbers (ISIN) are not supported. Cross-platform symbol mapping (e.g., Bloomberg → TradingView) requires external tools.
8. **Parent chain field is single-valued**: Assets with multi-chain deployments (e.g., USDC on Ethereum, Solana, Polygon) store only one parent chain. The library does not model multi-chain tokens or cross-chain bridges.
ספרייה

SessionLibLibrary "SessionLib"
SessionLib — timezone, session detection, and timeframe utilities.
Extracted from TaUtilityLib during Step 13 decomposition.
Layer L0 (leaf utility, depends only on Pine builtins).
CHANGELOG v1:
- SessionState UDT for US/Asia/EU session detection
- Timeframe navigation: f_get_next_tf, f_get_prev_tf, f_get_lower_tf
- Session parsing: f_sess_part, f_hhmm_to_h, f_hhmm_to_m, f_session_tz
- Symbol activity: f_symbol_activity_1m, f_is_trading_now, f_is_active_symbol
- Status icons: f_status_icon, f_status_icon_from_1m, f_symbol_status_icon
- Utilities: f_tf_ms, f_symbol_base
f_session_state()
Detect RTH session (US/Asia/EU)
Returns: SessionState with session flags and label
f_tf_ms(tf)
Convert timeframe to milliseconds
Parameters:
tf (string) : Timeframe string (e.g., "15", "240", "D")
Returns: Milliseconds as int
f_get_next_tf(tf, steps)
Gets next higher timeframe(s) from current
Parameters:
tf (string) : Current timeframe string
steps (string) : "1 TF Higher" for next TF, any other value for 2 TFs higher
Returns: Next timeframe string or na if at maximum
f_get_prev_tf(tf)
Gets previous lower timeframe from current
Parameters:
tf (string) : Current timeframe string
Returns: Previous timeframe string or na if at minimum
f_get_lower_tf(tf)
Gets standard lower timeframe mapping
Parameters:
tf (string) : Current timeframe string
Returns: Lower timeframe string or empty if at minimum
f_sess_part(sess, want_start)
Extract start or end part from session string
Parameters:
sess (string) : Session string (e.g., "0900-1600")
want_start (bool) : true for start, false for end
Returns: Time part string (HHMM format)
f_hhmm_to_h(hhmm)
Extract hour from HHMM string
Parameters:
hhmm (string) : Time string in HHMM format
Returns: Hour as int (0-23)
f_hhmm_to_m(hhmm)
Extract minute from HHMM string
Parameters:
hhmm (string) : Time string in HHMM format
Returns: Minute as int (0-59)
f_session_tz(session_tz_sel)
Convert session timezone selector to IANA timezone string
Parameters:
session_tz_sel (string) : Session timezone selector
Returns: IANA timezone string
f_symbol_activity_1m(s_timeClose_1m, s_inAnySess_1m, fresh_secs)
Check symbol activity from 1m security data
Parameters:
s_timeClose_1m (float) : 1m bar close time from request.security
s_inAnySess_1m (bool) : 1m session status from request.security
fresh_secs (float) : Freshness threshold in seconds
Returns:
f_is_trading_now(sym, fresh_secs)
Check if symbol is actively trading
Parameters:
sym (string) : Symbol string
fresh_secs (float) : Freshness threshold in seconds
Returns:
f_is_active_symbol(sym, fresh_secs)
Check if symbol is active (trading now)
Parameters:
sym (string) : Symbol string
fresh_secs (float) : Freshness threshold in seconds
Returns: true if trading
f_is_active_symbol(tradingNow)
Check if symbol is active (boolean overload)
Parameters:
tradingNow (bool) : Trading status boolean
Returns: Same boolean (passthrough for API consistency)
f_status_icon(sym, fresh_secs)
Get status icon from symbol
Parameters:
sym (string) : Symbol string
fresh_secs (float) : Freshness threshold in seconds
Returns: Status emoji string
f_symbol_status_icon(tradingNow, exchangeClosed, sessionOpenButStale)
Get status icon from boolean flags
Parameters:
tradingNow (bool) : Is trading
exchangeClosed (bool) : Is exchange closed
sessionOpenButStale (bool) : Session open but stale
Returns: Status emoji string
f_status_icon_from_1m(s_timeClose_1m, s_inAnySess_1m, fresh_secs)
Get status icon from 1m data
Parameters:
s_timeClose_1m (float) : 1m bar close time
s_inAnySess_1m (bool) : 1m session status
fresh_secs (float) : Freshness threshold in seconds
Returns: Status emoji string
f_symbol_base(ticker_id)
Extract symbol base from ticker (removes USDT suffix)
Parameters:
ticker_id (string) : Ticker ID string (e.g., "BINANCE:BTCUSDT")
Returns: Base symbol string (e.g., "BTC")
SessionState
SessionState — session detection container
Fields:
inUS (series bool) : US session active (14:30-22:00 UTC)
inAsia (series bool) : Asia session active (00:00-07:00 UTC)
inEU (series bool) : EU session active (07:00-14:30 UTC)
label (series string) : Session label string ("US", "Asia", "EU", "Off") ספרייה

fpa_unified_libLibrary "fpa_unified_lib"
lineStyle(styleText)
Parameters:
styleText (string)
labelSize(sizeText)
Parameters:
sizeText (string)
normalizeSession(sessionInput, hideWeekends)
Parameters:
sessionInput (string)
hideWeekends (bool)
isSessionActive(sessionInput, timezoneInput)
Parameters:
sessionInput (string)
timezoneInput (string)
tfInRange(lowTf, highTf)
Parameters:
lowTf (string)
highTf (string)
parseTradingDayOpenMinutes(sessionInput)
Parameters:
sessionInput (string)
safeColor(c, transp)
Parameters:
c (color)
transp (int)
updateRay(lineRef, shouldShow, startBarIndex, yPrice, lineColor, lineWidth, lineStyleText, rightOffsetBars, lookbackBars)
Parameters:
lineRef (line)
shouldShow (bool)
startBarIndex (int)
yPrice (float)
lineColor (color)
lineWidth (int)
lineStyleText (string)
rightOffsetBars (int)
lookbackBars (int)
updateLabel(labelRef, shouldShow, yPrice, textValue, labelColor, rightOffsetBars, sizeText)
Parameters:
labelRef (label)
shouldShow (bool)
yPrice (float)
textValue (string)
labelColor (color)
rightOffsetBars (int)
sizeText (string)
trimLines(arr, limit)
Parameters:
arr (array)
limit (int)
trimLabels(arr, limit)
Parameters:
arr (array)
limit (int)
parseFloatList(textArea)
Parameters:
textArea (string) ספרייה

ספרייה

Vantage_UtilsVantage_Utils — Non-trading utilities for Pine Script strategies. A news-calendar state machine and a per-trade P&L tracker, both built as UDT pseudo-classes you instantiate and drive from your script.
─────────────────────────────────────────
WHAT IT DOES
Two capabilities are packaged as instantiable objects (UDT pseudo-classes) so your script holds the state and calls methods rather than threading raw values and globals: a news-calendar state machine that tells you whether the current bar is blocked or delayed by an economic event, and a P&L tracker that accumulates per-trade, session, and daily totals with on-chart labels.
─────────────────────────────────────────
WHAT IT PROVIDES
A news-calendar state machine that consolidates the Vantage_News_Types vocabulary and the Vantage_News / Vantage_News_Historical calendar data behind a single NewsState object. Your strategy asks whether the current bar is blocked or delayed, or when the next trading window starts, and gets the answer back — no need to join event rows against a severity table yourself. Per-type policy overrides and per-severity defaults are configurable. Allows avoiding trading news volatile moments in back testing and live trading.
A P&L tracker (PnLTracker) that computes realized trade P&L with commission, accumulates session and daily totals, detects day boundaries for automatic reset, and manages the per-trade P&L label lifecycle on the chart.
─────────────────────────────────────────
HOW TO USE
A minimal usage example is in the comment block at the top of the source file — import the library, copy the pattern, adjust to your strategy. Hover any exported type or function in the Pine Editor for per-parameter documentation.
Imports Vantage_News, Vantage_News_Historical, and Vantage_News_Types to expose the consolidated news calendar. ספרייה

Vantage_News_TypesVantage_News_Types — Shared vocabulary of US economic event types and a default severity taxonomy for Pine Script news-filtering strategies.
─────────────────────────────────────────
WHAT IT DOES
Publishes a shared set of named event-type constants and a default severity mapping so that news-calendar data libraries, severity-override tables, and consuming strategies can all agree on what each event type means without maintaining their own copy of the list.
─────────────────────────────────────────
WHAT IT PROVIDES
Named constants for 125+ tracked US economic events — CPI, PPI, PCE, FOMC statements and speakers, non-farm payrolls, ISM, retail sales, GDP, housing, consumer confidence, crude inventories, Treasury auctions, bank holidays, and more. Each is a compact integer ID you can store in a packed news table.
A default severity taxonomy expressed relative to equity-index futures — Severity 1 — Watch (low-impact, not expected to move the market), Severity 2 — Delay entry (pause entries until a configurable window after release), and Severity 3 — Block the session (do not trade on a day carrying this event). Callers for other instruments can still use the type IDs and apply their own mapping.
Time helpers for the HHMM → milliseconds conversion used by packed news tables, and append helpers for building up parallel date / time / type-id arrays.
─────────────────────────────────────────
HOW TO USE
A minimal usage example is in the comment block at the top of the source file. Updated weekly as new event types are observed or severity defaults change. ספרייה

KeyLevelsLibrary "KeyLevels"
Library for common trading levels including VWAP, session levels (Asia, London, NYC, Comex IB), HTF OHLC, and Opening Ranges.
--- IMPLEMENTATION INSTRUCTIONS ---
1. Save this script as a Library named "KeyLevels".
2. In your indicator/strategy, import it: `import /KeyLevels/1 as kl`
3. To get the data object, call: `levels = kl.getLevels()`
4. Access levels using dot notation: `levels.loH` (London High), `levels.nycH` (NYC High), `levels.cibH` (Comex IB High).
5. To get all levels in a single array for loops: `levelArray = kl.toArray(levels)`
--- TIMEZONE NOTE ---
The default timezone is "UTC-5" (New York). For accurate seasonal adjustments, use "America/New_York".
getLevels(vwapAnchor, vwapMult, rollingLen, htfAnchor, tz)
getLevels Calculates and returns a KeyLevelsData object with comprehensive trading levels.
Parameters:
vwapAnchor (string) : Anchor condition for the main VWAP (e.g., "1D", "1W").
vwapMult (float) : Standard deviation multiplier for VWAP bands.
rollingLen (int) : Length for the rolling VWAP calculation.
htfAnchor (string) : Anchor for the HTF VWAP (e.g., "1W", "1M").
tz (string) : Timezone for session calculations (default: "UTC-5").
Returns: A `KeyLevelsData` object containing the levels.
toArray(data)
toArray Converts a KeyLevelsData object into a flat array of floats.
Parameters:
data (KeyLevelsData) : The KeyLevelsData object to convert.
Returns: An array of floats containing all levels.
KeyLevelsData
KeyLevelsData Master structure to hold all calculated key levels (Flattened).
Fields:
vwapCenter (series float)
vwapUpper (series float)
vwapLower (series float)
htfVwapCenter (series float)
htfVwapUpper (series float)
htfVwapLower (series float)
rollingVwap (series float)
dailyOpen (series float)
asO (series float)
asH (series float)
asL (series float)
asC (series float)
loO (series float)
loH (series float)
loL (series float)
loC (series float)
nycO (series float)
nycH (series float)
nycL (series float)
nycC (series float)
cibO (series float)
cibH (series float)
cibL (series float)
cibC (series float)
ibO (series float)
ibH (series float)
ibL (series float)
ibC (series float)
ibMid (series float)
o5O (series float)
o5H (series float)
o5L (series float)
o5C (series float)
o15O (series float)
o15H (series float)
o15L (series float)
o15C (series float)
o30O (series float)
o30H (series float)
o30L (series float)
o30C (series float)
pdO (series float)
pdH (series float)
pdL (series float)
pdC (series float)
pwO (series float)
pwH (series float)
pwL (series float)
pwC (series float)
cwO (series float)
cwH (series float)
cwL (series float)
cwC (series float)
cmO (series float)
cmH (series float)
cmL (series float)
cmC (series float)
settlement (series float) ספרייה
