PINE LIBRARY
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<Venue> (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.
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<Venue> (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.
Pine kitaplığı
Gerçek TradingView ruhuyla, yazar bu Pine kodunu açık kaynaklı bir kütüphane olarak yayınladı, böylece topluluğumuzdaki diğer Pine programcıları onu yeniden kullanabilir. Yazarı tebrik ederiz! Bu kütüphaneyi özel olarak veya diğer açık kaynaklı yayınlarda kullanabilirsiniz, ancak bu kodun yayınlarda yeniden kullanılması Topluluk Kuralları tarafından yönetilir.
Feragatname
Bilgiler ve yayınlar, TradingView tarafından sağlanan veya onaylanan finansal, yatırım, alım satım veya diğer türden tavsiye veya öneriler anlamına gelmez ve teşkil etmez. Kullanım Koşulları bölümünde daha fazlasını okuyun.
Pine kitaplığı
Gerçek TradingView ruhuyla, yazar bu Pine kodunu açık kaynaklı bir kütüphane olarak yayınladı, böylece topluluğumuzdaki diğer Pine programcıları onu yeniden kullanabilir. Yazarı tebrik ederiz! Bu kütüphaneyi özel olarak veya diğer açık kaynaklı yayınlarda kullanabilirsiniz, ancak bu kodun yayınlarda yeniden kullanılması Topluluk Kuralları tarafından yönetilir.
Feragatname
Bilgiler ve yayınlar, TradingView tarafından sağlanan veya onaylanan finansal, yatırım, alım satım veya diğer türden tavsiye veya öneriler anlamına gelmez ve teşkil etmez. Kullanım Koşulları bölümünde daha fazlasını okuyun.