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. Biblioteca

Biblioteca

OhMyHtfLibraryLibrary "OhMyHtfLibrary"
HTF candle platform: timeframe alignment, profiles, and (future) packed OHLC / draw helpers. Import as `import daggerok/OhMyHtfLibrary/1 as omhl`. Sweep/OB domain → future `OhMyHtfSweepLibrary` (`omhsl`).
resolveHtfContext(chart_tf_seconds, default_htf, default_candle_count, align_ctf_max_seconds, align_htf, align_enabled, profile_ctf_exact_seconds, profile_htf, profile_enabled, profile_candle_counts)
Resolves HTF string, enable flag, and candle count from Timeframes Alignment + Profiles.
TFA: first alignment row where `chart_tf_seconds <= align_ctf_max_seconds ` wins.
Profiles: first enabled row where `chart_tf_seconds == profile_ctf_exact_seconds ` overrides TFA.
Parameters:
chart_tf_seconds (int) : Chart timeframe in seconds.
default_htf (string) : Fallback HTF when no alignment rule matches.
default_candle_count (int) : Default HTF candle count (HTF Candles input).
align_ctf_max_seconds (array) : Upper-bound CTF seconds per TFA row (length 14).
align_htf (array) : HTF string per TFA row.
align_enabled (array) : Enabled flag per TFA row.
profile_ctf_exact_seconds (array) : Exact chart TF seconds per profile row (length 12).
profile_htf (array) : HTF string per profile row.
profile_enabled (array) : Profile row enabled flags.
profile_candle_counts (array) : Candle count per profile row.
Returns: `HtfContext` with resolved settings.
HtfContext
Resolved HTF timeframe settings for the current chart.
Fields:
htf (series string) : Higher timeframe string for `request.security` and draw logic.
is_enabled (series bool) : Whether HTF features are active for this chart TF (TFA enable flag or profile override).
candle_count (series int) : Number of HTF candles to display (profile may override default).
profile_override (series bool) : True when a profile row matched (exact CTF). Biblioteca

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. Biblioteca

Biblioteca

Biblioteca

Biblioteca

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
Biblioteca

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.
Biblioteca

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") Biblioteca

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) Biblioteca

Biblioteca

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. Biblioteca

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. Biblioteca

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) Biblioteca

Biblioteca

Vantage_News_HistoricalVantage News is a Pine Script library that provides pre-market economic event filtering defaults intended for strategies that trade on YM futures. It determines a default for whether trading should be blocked, delayed, or allowed on any given day. This Historical file contains prior years.
Core Concept
News events are pre-compiled into Pine Script data libraries organized by half-year (LO1_News2025H1, LO1_News2025H2, etc.), updated weekly on Sundays. There are no API calls — events are baked into arrays of dates, times, type IDs, and severities.
Severity System
Can be configured to define or override three default severity tiers:
- Sev 3 (CPI, NFP, FOMC) — defaults to blocks the entire day or delays, depending on policy
- Sev 2 (ISM PMI, claims) — defaults to delay trading until the event time + a configurable post-delay window
- Sev 1 (secondary indicators) — defaults to no delays
Blocking vs Delaying
- Block: No trading for the full session. WillTradeToday() returns false.
- Delay: Trading allowed after eventTime + delayMinutes. IsDelayed(currentTimeMs) returns true until the release time passes.
Provides a per-event-type policy mechanism so overrides can force any event to block, delay, or be ignored regardless of its base severity.
Next Trading Window Calculation
FindNextTradingWindow() scans forward up to 14 days, skipping weekends and blocked days based on the provided configuration. If the next tradeable day has a delay, it returns the delayed start time — so an info panel can show e.g. "Mon 7:35 AM" to indicate the next trading opening
Exception Mappings
Each half-year library can ship per-event-type overrides (different severity, custom delay minutes, tags). When the applyLibExceptionMappings configuration is enabled, these override the base severity — allowing the data to carry date-specific adjustments.
Special Handling
CME early close days are encoded as a special event type. CheckCmeEarlyClose() returns a halt timestamp so a strategy can truncate the session.
Caching
Evaluation is lazy and memoized by date string — EvaluateForDate() only recomputes when the date changes. The event cache is built once at initialization via a day index for fast date lookups. Biblioteca

Biblioteca

ONS_ForexSessionLibLibrary "ONS_ForexSessionLib"
Library for DST-adjusted Forex session detection. Returns session state and timing for a given bar.
Thanks to the author of "Sessions Full Markets Forex Stocks Index 7 Time by TFlab"
DST_Detector(Start_Month, Start_Day, Start_CountDay, End_Month, End_Day, End_CountDay, TimeZone)
Detects whether DST is Active or Inactive for a given timezone.
Parameters:
Start_Month (int) : Month DST begins (int)
Start_Day (int) : Day-of-week DST begins (int, use dayofweek.* constants)
Start_CountDay (int) : Nth occurrence of Start_Day in Start_Month (int)
End_Month (int) : Month DST ends (int)
End_Day (int) : Day-of-week DST ends (int)
End_CountDay (int) : Nth occurrence of End_Day in End_Month (int)
TimeZone (string) : IANA timezone string, use "Australia/Sydney" to invert logic (string)
Returns: "Active" or "Inactive" (string)
getDSTStates()
Returns DST state for Sydney, London and New York at the current bar.
Returns: — each "Active" or "Inactive" (tuple of strings)
getForexSessionStrings(Sydney_DST, London_DST, NewYork_DST)
Returns UTC session strings for all Forex sessions, DST-adjusted.
Parameters:
Sydney_DST (string) : DST state string for Sydney ("Active"/"Inactive")
London_DST (string) : DST state string for London ("Active"/"Inactive")
NewYork_DST (string) : DST state string for New York ("Active"/"Inactive")
Returns: session strings (tuple of strings)
isInSession(sessionStr, tz)
Returns 1 if the bar at the current series position is inside a session, 0 otherwise.
Parameters:
sessionStr (string) : Session string in "HHMM-HHMM" format (string)
tz (string) : IANA or UTC offset timezone string for the session (string)
Returns: 1 if inside session, 0 if outside (int)
isBarInSession(targetIndex, sessionStr, tz)
Returns 1 if a specific bar_index is inside a session (for point-in-time lookup).
Parameters:
targetIndex (int) : bar_index to test (int)
sessionStr (string) : Session string "HHMM-HHMM" (string)
tz (string) : IANA or UTC offset timezone string (string)
Returns: 1 if the target bar is/was inside session, 0 otherwise (int)
getAllForexSessions()
One-shot helper: given the current bar, returns open/closed state for all
DST-adjusted Forex sessions simultaneously.
Returns:
Each value is 1 (open) or 0 (closed). (tuple of ints) Biblioteca

Vantage_LO1_Sizing**Overview**
Position-sizing library for the LO1 breakout box day-trading strategy. Provides a unified recoup (opposite-add) sizing pipeline and dollar-risk/profit helpers. Extracting these functions into a library avoids Pine Script's function inlining, reducing compiled token count in the main strategy.
**Exported Type: RecoupSizingResult**
Holds the output of the 8-step sizing pipeline:
• Micro-level quantities (raw, DLL-capped, final)
• YM-level quantities (pre/post min-1-YM policy, proxy-capped)
• Risk gate values (projected loss, worst-case drawdown, pass/fail)
• Recoup scenario P&L (net outcome if T1 stops and recoup wins)
**Exported Functions**
`f_calcTradeRiskDollars(entry, stop, qty)` → float
Projected risk in dollars. Converts price distance to ticks via syminfo.mintick, then to dollars via syminfo.pointvalue.
`f_calcTradeProfitDollars(entry, tp, qty)` → float
Projected profit in dollars. Same tick-to-dollar conversion applied to the take-profit distance.
`f_computeRecoupSizing(...)` → RecoupSizingResult
8-step recoup sizing pipeline:
1. Raw micro qty from risk multiplier (CEILING)
2. Daily loss limit cap at micro level
3. Micro-to-YM conversion (FLOOR)
4. Minimum-1-YM policy
5. Proxy capacity cap
6. Micro-equivalent for risk gating
7. Worst-case projection (base stop + opposing flatten + recoup stop)
8. Risk gate pass/fail
Plus scenario P&L: net recoup outcome and T1-win profit.
**Usage**
import Vantage-Stack/Vantage_LO1_Sizing/1 as sz
float risk = sz.f_calcTradeRiskDollars(entry, stop, qty)
sz.RecoupSizingResult r = sz.f_computeRecoupSizing(baseQty, baseEntry, baseStop, recoupEntry, recoupStop,
recoupTP, multiplier, proxyMul, minOneYM, curLoss, maxLoss, maxProxy, t1TP, oppTP, oppFrac, oppRemoval)
======================
Library "Vantage_LO1_Sizing"
Position sizing library for LO1 breakout box strategy.
Extracts pure-computation functions to reduce compiled token count in the main script.
f_calcTradeRiskDollars(_entry, _stop, _qty)
Calculates projected risk in dollars for a position (qty × |entry−stop| in ticks × pointvalue).
Parameters:
_entry (float) : Entry price
_stop (float) : Stop-loss price
_qty (float) : Position quantity (contracts)
Returns: Risk in dollars
f_calcTradeProfitDollars(_entry, _tp, _qty)
Calculates projected profit in dollars for a position (qty × |tp−entry| in ticks × pointvalue).
Parameters:
_entry (float) : Entry price
_tp (float) : Take-profit price
_qty (float) : Position quantity (contracts)
Returns: Profit in dollars
f_computeRecoupSizing(baseQtyMicro, baseEntry, baseStop, recoupEntry, recoupStop, recoupTP, oppositeMultiplier, proxyQtyMul, minOneYMEnabled, currentLossDollars, maxDailyLossLimit, maxProxyCap, t1TPPrice, oppTPPrice, oppAddStopFrac, opposingRemovalEnabled)
Computes recoup (opposite-add) position sizing through an 8-step pipeline: raw micro qty, DLL cap, micro-to-YM conversion, min-1-YM policy, proxy cap, risk gating, worst-case projection, and recoup scenario P&L.
Parameters:
baseQtyMicro (int) : T1 micro-contract quantity
baseEntry (float) : T1 entry price
baseStop (float) : T1 stop-loss price
recoupEntry (float) : Recoup entry price
recoupStop (float) : Recoup stop-loss price
recoupTP (float) : Recoup take-profit price
oppositeMultiplier (float) : Target risk multiplier for recoup vs T1 (e.g., 4.0)
proxyQtyMul (float) : Micro-to-YM conversion factor (0 = no proxy)
minOneYMEnabled (bool) : Force minimum 1 YM contract when proxy is active
currentLossDollars (float) : Running session loss in dollars (0 for estimate mode)
maxDailyLossLimit (float) : Daily loss limit in dollars (-1 = disabled)
maxProxyCap (int) : Maximum proxy contracts cap (0 = unlimited)
t1TPPrice (float) : T1 take-profit price (for scenario P&L calculation)
oppTPPrice (float) : Opposing MYM TP price when T1 stops (for scenario profit calc)
oppAddStopFrac (float) : Fraction of base risk for opposite MYM emergency flatten
opposingRemovalEnabled (bool) : Whether opposing removal entry mode is active
Returns: RecoupSizingResult with quantities, risk values, and scenario P&L
RecoupSizingResult
Holds the complete output of the 8-step recoup sizing pipeline: micro/YM quantities, risk gate results, worst-case projections, and recoup-scenario P&L.
Fields:
microQtyRaw (series int)
microCapByDLL (series int)
microQtyCapped (series int)
ymQtyPre (series int)
ymQtyFinal (series int)
microEqForGate (series int)
projectedLossRecoup (series float)
dllRemaining (series float)
totalWorstCase (series float)
riskOK (series bool)
oppMYMLoss (series float)
didMinOneOverride (series bool)
dllForcedZero (series bool)
recoupScenarioNet (series float)
t1WinProfit (series float) Biblioteca

Biblioteca

Vantage_NewsVantage News is a Pine Script library that provides pre-market economic event filtering defaults intended for strategies that trade on YM futures. It determines a default for whether trading should be blocked, delayed, or allowed on any given day.
Core Concept
News events are pre-compiled into Pine Script data libraries organized by half-year (LO1_News2025H1, LO1_News2025H2, etc.), updated weekly on Sundays. There are no API calls — events are baked into arrays of dates, times, type IDs, and severities.
Severity System
Can be configured to define or override three default severity tiers:
- Sev 3 (CPI, NFP, FOMC) — defaults to blocks the entire day or delays, depending on policy
- Sev 2 (ISM PMI, claims) — defaults to delay trading until the event time + a configurable post-delay window
- Sev 1 (secondary indicators) — defaults to no delays
Blocking vs Delaying
- Block: No trading for the full session. WillTradeToday() returns false.
- Delay: Trading allowed after eventTime + delayMinutes. IsDelayed(currentTimeMs) returns true until the release time passes.
Provides a per-event-type policy mechanism so overrides can force any event to block, delay, or be ignored regardless of its base severity.
Next Trading Window Calculation
FindNextTradingWindow() scans forward up to 14 days, skipping weekends and blocked days based on the provided configuration. If the next tradeable day has a delay, it returns the delayed start time — so an info panel can show e.g. "Mon 7:35 AM" to indicate the next trading opening
Exception Mappings
Each half-year library can ship per-event-type overrides (different severity, custom delay minutes, tags). When the applyLibExceptionMappings configuration is enabled, these override the base severity — allowing the data to carry date-specific adjustments.
Special Handling
CME early close days are encoded as a special event type. CheckCmeEarlyClose() returns a halt timestamp so a strategy can truncate the session.
Caching
Evaluation is lazy and memoized by date string — EvaluateForDate() only recomputes when the date changes. The event cache is built once at initialization via a day index for fast date lookups.
Biblioteca

TPOSmartMoneyLibLibrary "TPOSmartMoneyLib"
Library for TPO (Time Price Opportunity) and Smart Money concepts including session management, PDH/PDL detection, sweeping logic, and volume profile utilities
f_price_to_tick(p)
Convert price to tick
Parameters:
p (float) : Price value
Returns: Tick value
f_tick_to_row(t, row_ticks_in)
Convert tick to row
Parameters:
t (int) : Tick value
row_ticks_in (int) : Number of ticks per row
Returns: Row index
f_row_to_price(row, row_ticks_in)
Convert row to price (midpoint)
Parameters:
row (int) : Row index
row_ticks_in (int) : Number of ticks per row
Returns: Price at row midpoint
f_calc_row_ticks(natr_ref, row_gran_mult)
Calculate dynamic row size based on normalized ATR
Parameters:
natr_ref (float) : Daily normalized ATR reference value
row_gran_mult (float) : Row granularity multiplier
Returns: Number of ticks per row
f_more_transp_pct(c, pct)
Increase color transparency by percentage
Parameters:
c (color) : Input color
pct (float) : Percentage to increase transparency (0.0 to 1.0)
Returns: Color with increased transparency
f_dom_color(dom, buy_col, sell_col, gamma, transp_weak, transp_strong)
Calculate dominance color based on buy/sell ratio
Parameters:
dom (float) : Dominance ratio (-1 to 1, negative = sell, positive = buy)
buy_col (color) : Buy dominant color
sell_col (color) : Sell dominant color
gamma (float) : Gamma correction for color intensity
transp_weak (int) : Transparency for weak dominance
transp_strong (int) : Transparency for strong dominance
Returns: Blended color
f_sess_part(sess_str, get_start)
Parse session string to get start or end time
Parameters:
sess_str (string) : Session string in format "HHMM-HHMM"
get_start (bool) : True to get start time, false to get end time
Returns: Time string in HHMM format
f_hhmm_to_h(hhmm)
Convert HHMM string to hours
Parameters:
hhmm (string) : Time string in HHMM format
Returns: Hours (0-23)
f_hhmm_to_m(hhmm)
Convert HHMM string to minutes
Parameters:
hhmm (string) : Time string in HHMM format
Returns: Minutes (0-59)
f_prev_day_window_bounds(today_day_rth, win_start, win_end, session_tz)
Calculate previous day window bounds
Parameters:
today_day_rth (int) : Today's RTH start timestamp
win_start (string) : Window start time in HHMM format
win_end (string) : Window end time in HHMM format
session_tz (string) : Session timezone
Returns: Tuple of
f_default_session_colors()
Get default session colors
Returns: Array of 4 colors
f_session_names()
Get session names
Returns: Array of 4 session names
f_process_hl(arr, rng, keep_bars, lock_to_live)
Process high/low lines with sweeping detection
Parameters:
arr (array) : Array of HLLine objects
rng (float) : Price range for visibility filtering
keep_bars (int) : Maximum bars to keep lines
lock_to_live (bool) : Whether to lock line end to current bar
Returns: 0 (for chaining)
f_process_naked_lines(arr, calc_bars, bars_per_day, keep_to_day_end)
Process naked lines (POC/VAH/VAL) with sweeping detection
Parameters:
arr (array) : Array of NakedLine objects
calc_bars (int) : Maximum calculation bars
bars_per_day (int) : Bars per day for scope calculation
keep_to_day_end (bool) : Whether to extend to day end
Returns: 0 (for chaining)
f_update_pdhl_lines(pd_hl, pdh, pdl, new_day, pd_rng, bars_per_day, pdh_color, pdl_color)
Detect and create PDH/PDL lines
Parameters:
pd_hl (array) : Array to store HLLine objects
pdh (float) : Previous day high
pdl (float) : Previous day low
new_day (bool) : Whether it's a new day
pd_rng (float) : Price range for visibility
bars_per_day (int) : Bars per day
pdh_color (color) : PDH line color
pdl_color (color) : PDL line color
Returns: 0 (for chaining)
f_poc_from_vals(keys, vals)
Calculate POC from sorted keys and values
Parameters:
keys (array) : Sorted array of row keys
vals (array) : Array of volume values
Returns: POC row key
f_value_area(keys, vals, poc_key, va_pct)
Calculate Value Area from volume distribution
Parameters:
keys (array) : Sorted array of row keys
vals (array) : Array of volume values
poc_key (int) : POC row key
va_pct (float) : Value Area percentage (typically 0.70)
Returns: Tuple of
f_find_key_sorted(keys, target)
Find key in sorted array using binary search
Parameters:
keys (array) : Sorted array of keys
target (int) : Target key to find
Returns: Index of key, or -1 if not found
f_zscore_safe(x, len)
Safe z-score calculation using built-in functions
Parameters:
x (float) : Input series
len (int) : Lookback length
Returns: Z-score
HLLine
Represents a high/low line with sweeping detection
Fields:
ln (series line) : Line object
lb (series label) : Label object
lvl (series float) : Price level
startBar (series int) : Bar index where line starts
swept (series bool) : Whether the level has been swept
isHigh (series bool) : True if this is a high, false if low
col (series color) : Line color
NakedLine
Represents a naked POC/VAH/VAL line
Fields:
ln (series line) : Line object
lb (series label) : Label object
lvl (series float) : Price level
startBar (series int) : Bar index where line starts
swept (series bool) : Whether the level has been swept
sweptBar (series int) : Bar index where swept occurred
endBar (series int) : Bar index where line should end Biblioteca
