VisualStructureToolsLibrary "VisualStructureTools"
MTF-safe drawing library (Unix-Time). Designed for high visual discrimination and efficient debugging of complex logic without cluttering the main script.
Optimized for Pine Script® v6 to prevent runtime errors in multi-timeframe environments.
setLine(price, startTime, labelText, labelPos, is_extend, l_width, l_col, l_style)
Draws a horizontal level or a segment with an optional label.
Parameters:
price (float) : Price level for the line.
startTime (int) : UNIX timestamp (ms) for the starting point.
labelText (string) : Text to display on the label. Use "none" to hide.
labelPos (string) : Position of the label relative to the price ('above' or 'below', 'none').
is_extend (bool) : If true, the line extends infinitely (extend.both).
l_width (int) : Width of the line in pixels.
l_col (color) : Color for the line and label text.
l_style (string) : Style of the line ('solid', 'dashed', 'dotted').
setBox(top, bottom, startTime, endTime, boxText, b_col, b_width, b_style, b_transp)
Draws a filled box with an optional synchronized text label.
Parameters:
top (float) : Price of the upper boundary.
bottom (float) : Price of the lower boundary.
startTime (int) : UNIX timestamp (ms) for the left side of the box.
endTime (int) : UNIX timestamp (ms) for the right side (defaults to current 'time').
boxText (string) : Optional text label for the box. Use "" to hide.
b_col (color) : Border and fill color.
b_width (int) : Border width.
b_style (string) : Border style ('solid', 'dashed', 'dotted').
b_transp (int) : Transparency for the background fill (0-100). Library

smaemarvwapClaireLibrary "smaemarvwapClaire"
repeat_character(count)
Parameters:
count (int)
f_1_k_line_width()
is_price_in_merge_range(p1, p2, label_merge_range)
Parameters:
p1 (float)
p2 (float)
label_merge_range (float)
get_pre_label_string(kc, t, is_every)
Parameters:
kc (VWAP_key_levels_draw_settings)
t (int)
is_every (bool)
f_is_new_period_from_str(str)
Parameters:
str (string)
total_for_time_when(source, days, ma_set)
Parameters:
source (float)
days (int)
ma_set (ma_setting)
f_calculate_sma_ema_rolling_vwap(src, length, ma_settings)
Parameters:
src (float)
length (simple int)
ma_settings (ma_setting)
f_calculate_sma_ema_rvwap(ma_settings)
Parameters:
ma_settings (ma_setting)
f_get_ma_pre_label(ma_settings, sma, ema, rolling_vwap)
Parameters:
ma_settings (ma_setting)
sma (float)
ema (float)
rolling_vwap (float)
f_smart_ma_calculation(ma_settings2)
Parameters:
ma_settings2 (ma_setting)
f_calculate_endpoint(start_time, kc, is_every, endp, extend1, extend2, line_label_extend_length)
Parameters:
start_time (int)
kc (VWAP_key_levels_draw_settings)
is_every (bool)
endp (int)
extend1 (bool)
extend2 (bool)
line_label_extend_length (int)
f_single_line_label_fatory(left_point, right_point, line_col, line_width, lines_style_select, labeltext_col, label_text_size, label_array, line_array, label_col, label_text, l1, label1)
根据两个点创建线段和/或标签,并将其添加到对应的数组中
Parameters:
left_point (chart.point) : 左侧起点坐标
right_point (chart.point) : 右侧终点坐标
line_col (color) : 线段颜色
line_width (int) : 线段宽度
lines_style_select (string) : 线段样式(实线、虚线等)
labeltext_col (color) : 标签文字颜色
label_text_size (string) : 标签文字大小
label_array (array) : 存储标签对象的数组
line_array (array) : 存储线段对象的数组
label_col (color) : 标签背景颜色(默认:半透明色)
label_text (string) : 标签文字内容(默认:空字符串)
l1 (bool) : 是否创建线段(默认:false)
label1 (bool) : 是否创建标签(默认:false)
Returns: void
f_line_and_label_merge_func(t, data, l_text, kc, is_every, endp, merge_str_map, label_array, line_array, extend1, extend2, line_label_extend_length, label_merge_control, line_width, lines_style_select, label_text_size)
Parameters:
t (int)
data (float)
l_text (string)
kc (VWAP_key_levels_draw_settings)
is_every (bool)
endp (int)
merge_str_map (map)
label_array (array)
line_array (array)
extend1 (bool)
extend2 (bool)
line_label_extend_length (int)
label_merge_control (bool)
line_width (int)
lines_style_select (string)
label_text_size (string)
plot_ohlc(kc, ohlc_data, extend1, extend2, merge_str_map, label_array, line_array, is_every, line_label_extend_length, label_merge_control, line_width, lines_style_select, label_text_size)
Parameters:
kc (VWAP_key_levels_draw_settings)
ohlc_data (bardata)
extend1 (bool)
extend2 (bool)
merge_str_map (map)
label_array (array)
line_array (array)
is_every (bool)
line_label_extend_length (int)
label_merge_control (bool)
line_width (int)
lines_style_select (string)
label_text_size (string)
plot_vwap_keylevels(kc, vwap_data, extend1, extend2, merge_str_map, label_array, line_array, is_every, line_label_extend_length, label_merge_control, line_width, lines_style_select, label_text_size)
Parameters:
kc (VWAP_key_levels_draw_settings)
vwap_data (vwap_snapshot)
extend1 (bool)
extend2 (bool)
merge_str_map (map)
label_array (array)
line_array (array)
is_every (bool)
line_label_extend_length (int)
label_merge_control (bool)
line_width (int)
lines_style_select (string)
label_text_size (string)
plot_vwap_bardata(kc, ohlc_data, vwap_data, extend1, extend2, merge_str_map, label_array, line_array, is_every, line_label_extend_length, label_merge_control, line_width, lines_style_select, label_text_size)
Parameters:
kc (VWAP_key_levels_draw_settings)
ohlc_data (bardata)
vwap_data (vwap_snapshot)
extend1 (bool)
extend2 (bool)
merge_str_map (map)
label_array (array)
line_array (array)
is_every (bool)
line_label_extend_length (int)
label_merge_control (bool)
line_width (int)
lines_style_select (string)
label_text_size (string)
f_start_end_total_min(session)
Parameters:
session (string)
f_get_vwap_array(anchor1, data_manager, is_historical)
Parameters:
anchor1 (string)
data_manager (data_manager)
is_historical (bool)
f_get_bardata_array(anchorh, data_manager, is_historical)
Parameters:
anchorh (string)
data_manager (data_manager)
is_historical (bool)
vwap_snapshot
Fields:
t (series int)
vwap (series float)
upper1 (series float)
lower1 (series float)
upper2 (series float)
lower2 (series float)
upper3 (series float)
lower3 (series float)
VWAP_key_levels_draw_settings
Fields:
enable (series bool)
index (series int)
anchor (series string)
session (series string)
vwap_col (series color)
bands_col (series color)
bg_color (series color)
text_color (series color)
val (series bool)
poc (series bool)
vah (series bool)
enable2x (series bool)
enable3x (series bool)
o_control (series bool)
h_control (series bool)
l_control (series bool)
c_control (series bool)
extend_control (series bool)
only_show_the_lastone_control (series bool)
bg_control (series bool)
line_col_labeltext_col (series color)
bardata
Fields:
o (series float)
h (series float)
l (series float)
c (series float)
v (series float)
start_time (series int)
end_time (series int)
ma_setting
Fields:
day_control (series bool)
kline_numbers (series int)
ma_color (series color)
ema_color (series color)
rvwap_color (series color)
ma_control (series bool)
ema_control (series bool)
rvwap_control (series bool)
session (series string)
merge_label_template
Fields:
left_point (chart.point)
right_point (chart.point)
label_text (series string)
p (series float)
label_color (series color)
merge_init_false (series bool)
anchor_snapshots
Fields:
vwap_current (array)
vwap_historical (array)
bardata_current (array)
bardata_historical (array)
data_manager
Fields:
snapshots_map (map)
draw_settings_map (map) Library

Strategy_Core_CalculationsLibrary "Strategy_Core_Calculations"
f_pctToPrice(pct, basePrice)
Parameters:
pct (float) : Percentage value (e.g., 2.0 = 2%)
basePrice (float) : Reference price
Returns: Price difference
f_pipsToPrice(pips, pipVal)
Parameters:
pips (float) : Number of pips (e.g., 100 pips)
pipVal (float) : Price value of 1 pip (XAUUSD: 0.01)
Returns: Price difference
f_toPrice(value, basePrice, isForex, pipVal)
Parameters:
value (float) : Distance value (% or pip)
basePrice (float) : Reference price (for percentage mode)
isForex (bool) : Is Forex mode
pipVal (float) : Pip value (for Forex mode)
Returns: Price difference
f_lotToNotional(lots, price, contractSize)
Parameters:
lots (float) : Lot amount (e.g., 0.01)
price (float) : Instrument price
contractSize (float) : Contract size (XAUUSD: 100)
Returns: Position value in Dollars
f_lotToMargin(lots, price, contractSize, leverage)
Parameters:
lots (float) : Lot amount
price (float) : Price
contractSize (float) : Contract size
leverage (int) : Leverage
Returns: Required margin (USD)
f_calcFee(notional, useFee, feePercent)
Parameters:
notional (float) : Trade volume
useFee (bool) : Is fee active
feePercent (float) : Fee percentage
Returns: Calculated fee
f_calcAvgPrice(oldAvg, oldNotional, newPrice, newNotional)
Parameters:
oldAvg (float) : Current average price
oldNotional (float) : Current position volume
newPrice (float) : New entry price
newNotional (float) : New entry volume
Returns: New weighted average price
f_multiplier(lvl, dcaMode)
Parameters:
lvl (int) : Current DCA level
dcaMode (string) : DCA mode ('Step', '2x', 'Off', 'Selection Step')
Returns: Multiplier value
f_unrealizedPnL(isLong, avgPrice, totalNotional, currentPrice)
Parameters:
isLong (bool) : Long or Short
avgPrice (float) : Average entry price
totalNotional (float) : Total volume
currentPrice (float) : Current price
Returns: Unrealized PnL
f_totalUnrealizedPnL(avgLongPrice, totalLongNotional, avgShortPrice, totalShortNotional, currentPrice)
Parameters:
avgLongPrice (float)
totalLongNotional (float)
avgShortPrice (float)
totalShortNotional (float)
currentPrice (float)
f_liqPrice_Long(avgPrice, totalNotional, availableEquity)
Parameters:
avgPrice (float) : Long average price
totalNotional (float) : Long total volume
availableEquity (float) : Available equity (balance + realized PNL - fee - short margin)
Returns: Estimated liquidation price
f_liqPrice_Short(avgPrice, totalNotional, availableEquity)
Parameters:
avgPrice (float) : Short average price
totalNotional (float) : Short total volume
availableEquity (float) : Available equity
Returns: Estimated liquidation price
f_calcTPLevels_Long(avgPrice, tp1_pct, tp2_pct, tp3_pct)
Parameters:
avgPrice (float) : Average entry price
tp1_pct (float) : TP1 percentage
tp2_pct (float) : TP2 percentage
tp3_pct (float) : TP3 percentage
Returns: TPVisuals structure
f_calcTPLevels_Short(avgPrice, tp1_pct, tp2_pct, tp3_pct)
Parameters:
avgPrice (float) : Average entry price
tp1_pct (float) : TP1 percentage
tp2_pct (float) : TP2 percentage
tp3_pct (float) : TP3 percentage
Returns: TPVisuals structure
f_calcTPLevels_Long_Unified(avgPrice, tp1_val, tp2_val, tp3_val, isForex, pipVal)
Parameters:
avgPrice (float) : Average entry price
tp1_val (float) : TP1 distance (% or pip)
tp2_val (float) : TP2 distance
tp3_val (float) : TP3 distance
isForex (bool) : Is Forex (pip) mode
pipVal (float) : Pip value (for Forex)
Returns: TPVisuals structure
f_calcTPLevels_Short_Unified(avgPrice, tp1_val, tp2_val, tp3_val, isForex, pipVal)
Parameters:
avgPrice (float)
tp1_val (float)
tp2_val (float)
tp3_val (float)
isForex (bool)
pipVal (float)
f_calcSL_Long(avgPrice, level, cfg, trailHigh)
Parameters:
avgPrice (float)
level (int)
cfg (SLConfig)
trailHigh (float)
f_calcSL_Short(avgPrice, level, cfg, trailLow)
Parameters:
avgPrice (float)
level (int)
cfg (SLConfig)
trailLow (float)
f_calcSL_Long_Unified(avgPrice, level, cfg, trailHigh, isForex, pipVal)
Parameters:
avgPrice (float)
level (int)
cfg (SLConfig)
trailHigh (float)
isForex (bool) : if true pip based, else % based
pipVal (float) : Forex pip value (for Forex mode)
Returns: tuple
f_calcSL_Short_Unified(avgPrice, level, cfg, trailLow, isForex, pipVal)
Parameters:
avgPrice (float)
level (int)
cfg (SLConfig)
trailLow (float)
isForex (bool)
pipVal (float)
f_effectiveSL(isLong, slFixed, slTrail)
Parameters:
isLong (bool) : True if Long
slFixed (float) : Fixed SL
slTrail (float) : Trailing SL (can be na)
Returns: Effective SL price
f_calcEquity(walletBalance, totalRealizedPnL, latchedPnL_L, latchedPnL_S, unrealizedTotal)
Parameters:
walletBalance (float)
totalRealizedPnL (float)
latchedPnL_L (float)
latchedPnL_S (float)
unrealizedTotal (float)
f_calcFreeMargin(equity, totalLongNotional, totalShortNotional, leverage)
Parameters:
equity (float)
totalLongNotional (float)
totalShortNotional (float)
leverage (int)
f_availableEquityForLiq(walletBalance, totalRealizedPnL, latchedPnL_L, latchedPnL_S, totalFees, useFee, otherSideNotional, leverage)
Parameters:
walletBalance (float)
totalRealizedPnL (float)
latchedPnL_L (float)
latchedPnL_S (float)
totalFees (float)
useFee (bool)
otherSideNotional (float)
leverage (int)
Returns: Available equity
f_shouldForceFullExit(posNotional, exitAmount, leverage, minThreshold)
Parameters:
posNotional (float) : Current position volume
exitAmount (float) : Amount to exit
leverage (int) : Leverage
minThreshold (float) : Minimum position size (USDT)
Returns: true if full close required
f_calcExitPnL(isLong, avgPrice, exitPrice, exitAmount)
Parameters:
isLong (bool) : Is Long
avgPrice (float) : Average price
exitPrice (float) : Exit price
exitAmount (float) : Exit amount
Returns: PnL value
f_isApproachingSL(isLong, priceExtreme, slPrice, avgPrice, approachPct)
Parameters:
isLong (bool) : Is Long
priceExtreme (float) : Low (Long) or High (Short)
slPrice (float) : SL price
avgPrice (float) : Average price
approachPct (float) : Approach threshold percentage
Returns: true if approaching
f_isApproachingLiq(isLong, priceExtreme, liqPrice, avgPrice, approachPct)
Parameters:
isLong (bool)
priceExtreme (float)
liqPrice (float)
avgPrice (float)
approachPct (float)
f_isApproachingSL_Unified(isLong, priceExtreme, slPrice, avgPrice, approachVal, isForex, pipVal)
Parameters:
isLong (bool)
priceExtreme (float)
slPrice (float)
avgPrice (float)
approachVal (float)
isForex (bool)
pipVal (float)
f_isApproachingLiq_Unified(isLong, priceExtreme, liqPrice, avgPrice, approachVal, isForex, pipVal)
Parameters:
isLong (bool)
priceExtreme (float)
liqPrice (float)
avgPrice (float)
approachVal (float)
isForex (bool)
pipVal (float)
f_forexUsedMargin(lots, price, contractSize, leverage)
Parameters:
lots (float) : Lot amount
price (float) : Price
contractSize (float) : Contract size
leverage (int) : Leverage
Returns: Used margin (USD)
f_forexFreeMargin(equity, usedMarginL, usedMarginS)
Parameters:
equity (float)
usedMarginL (float)
usedMarginS (float)
f_forexPnL(isLong, entryPrice, exitPrice, lots, contractSize, pipVal)
Parameters:
isLong (bool) : Is Long
entryPrice (float) : Entry price
exitPrice (float) : Exit price
lots (float) : Lot amount
contractSize (float) : Contract size
pipVal (float) : Pip value
Returns: PnL (USD)
f_calcPivots(method, h, l, c)
Parameters:
method (string) : Pivot method ('Traditional', 'Fibonacci', 'Woodie', 'Camarilla')
h (float) : Previous High
l (float) : Previous Low
c (float) : Previous Close
Returns:
f_getPrice(inlinePrice, currentClose)
Parameters:
inlinePrice (float)
currentClose (float)
f_stackOffset(h, l)
Parameters:
h (float)
l (float)
TPConfig
Fields:
tp1_pct (series float)
tp1_port (series float)
tp1_reverse (series bool)
tp2_active (series bool)
tp2_pct (series float)
tp2_port (series float)
tp3_active (series bool)
tp3_pct (series float)
tp3_port (series float)
DCATPConfig
Fields:
tp1_pct (series float)
tp1_port (series float)
tp2_pct (series float)
tp2_port (series float)
tp3_pct (series float)
tp3_port (series float)
SLConfig
Fields:
l1_pct (series float)
dca_pct (series float)
useBE (series bool)
be_act_pct (series float)
be_offset_pct (series float)
useTS (series bool)
ts_act_pct (series float)
ts_dev_pct (series float)
PositionConfig
Fields:
baseAmount (series float)
leverage (series int)
maxLevel (series int)
dcaMode (series string)
selectionStep (series int)
useFee (series bool)
feePercent (series float)
PositionState
Fields:
level (series int)
signalCounter (series int)
avgPrice (series float)
lastEntryPrice (series float)
totalNotional (series float)
peakNotional (series float)
pctLeft (series float)
tpStage (series int)
tpStageDCA (series int)
accumulatedPnL (series float)
TradeStats
Fields:
slCountWin (series int)
slCountLoss (series int)
liqCount (series int)
maxDcaHit (series int)
maxVol (series float)
maxLoss (series float)
grossLoss (series float)
totalFees (series float)
totalVolume (series float)
tradeCount (series int)
peakEquity (series float)
maxDrawdown (series float)
maxDrawdownPct (series float)
currentDrawdownPct (series float)
approachSL (series int)
approachLiq (series int)
TPVisuals
Fields:
tp1 (series float)
tp2 (series float)
tp3 (series float)
SLState
Fields:
slFixed (series float)
slTrail (series float)
trailExtreme (series float)
ForexConfig
Fields:
pipValue (series float)
contractSize (series float)
baseLot (series float)
isForex (series bool) Library

Library

SMC_CoreEN:
Trying to fix something that keeps breaking is exhausting; you’re done reopening the same file hoping for a different ending—because why do we keep reopening the same folder of memories when we already know it’s corrupted? 💾 It’s like loving someone who treated your heart like a draft they never planned to publish. Being ghosted is strange and unfinished 👻—it leaves you as a glitch in their timeline while you keep checking for updates on a story that isn’t yours anymore. You don’t need closure from someone who wasn’t brave enough to give it; their silence was the loudest answer 🔕. Stop waiting for notifications from someone who only appears when they need a backup plan. Some people aren’t meant to stay—and moving on isn’t dramatic. Sometimes it’s simply choosing clarity, stability, and a version of yourself that no longer settles for less ✨
ID:
Berusaha memperbaiki sesuatu yang terus rusak itu melelahkan; kamu berhenti membuka file yang sama dengan harapan ending-nya berubah—padahal kamu tahu folder itu sudah rusak 💾 Mencintai orang yang memperlakukan hatimu seperti draft yang tak pernah ingin dipublikasikan memang melelahkan. Di-ghosting itu aneh dan gantung 👻—kamu jadi seperti glitch di timeline mereka sementara terus mengecek update dari cerita yang bukan milikmu lagi. Kamu tidak butuh penjelasan dari orang yang bahkan tak cukup berani memberi perpisahan; diamnya mereka sudah jadi jawaban paling keras 🔕 Berhenti menunggu notifikasi dari orang yang muncul hanya saat butuh cadangan. Tidak semua orang ditakdirkan untuk tinggal—dan move on bukan selalu dramatis. Kadang itu hanya soal memilih kejelasan, kestabilan, dan versi diri yang tidak lagi mau menerima kurang dari yang pantas ✨
====
SMC Core Utilities Library
A comprehensive utility library designed for Smart Money Concepts (SMC) and ICT-based trading strategies. This library provides standardized objects and methods to detect price imbalances and manage trading sessions effectively.
Key Features:
- Gap Detection: Advanced logic to identify Fair Value Gaps (FVG), Volume Imbalances (VI), and Liquidity Voids (LV).
- Session Management: Automated parsing and validation of trading sessions with midnight-cross support.
- Visual Helpers: Standardized enums for line styles, font sizes, and labeling.
- Optimized: Uses custom Types and Methods for modular and efficient code execution.
Library utilitas lengkap yang dirancang untuk strategi berbasis Smart Money Concepts (SMC) dan ICT. Library ini menyediakan objek dan metode standar untuk mendeteksi ketidakseimbangan harga dan mengelola sesi trading.
Fitur Utama:
- Deteksi Gap: Logika untuk identifikasi Fair Value Gap (FVG), Volume Imbalance (VI), dan Liquidity Void (LV).
- Manajemen Sesi: Validasi sesi trading otomatis (London, NY, Asia) dengan dukungan perpindahan hari.
- Visual Helper: Standarisasi gaya garis, ukuran font, dan penamaan label.
- Optimal: Menggunakan Custom Types dan Methods agar kode lebih bersih dan ringan.
Library

ScaleScale Library v1 - The Ultimate UI Framework for Pine Script™
Construct. Visualize. Deploy.
📢 ABOUT
Scale is a comprehensive, open-source UI framework meticulously designed to simplify the creation of advanced visual scales, interactive progress bars, and complex dashboards in Pine Script™. It abstracts away the cumbersome and error-prone complexity of manual drawing (such as managing lines, labels, boxes, and calculations) into a clean, chainable, and highly intuitive method suite.
Whether you're building a simple RSI indicator, a dynamic MACD histogram, or a complex multi-metric trading dashboard, Scale handles the heavy lifting of:
• Auto-scaling : Intelligently calculates positions relative to bars or time, ensuring your UI elements are perfectly aligned regardless of chart zoom or resolution.
• Real-time updates : Flawlessly handles intra-bar price changes, providing smooth and accurate visualizations on every tick without flickering.
• Theming : Offers robust support for aesthetic customization, including smooth gradients, auto-coloring based on conditions, and custom branding.
• Responsive layout : Features granular padding, offset, and alignment controls so your visual components flexibly adapt to any chart environment.
✨ WHAT'S NEW IN v1
📛 Method Badges
Quickly identify method capabilities and execution context with visual badges:
• 🔵 method-primary — The core function required to initialize a specific feature or element.
• 🟣 chainable — Indicates the method returns the setup object itself, allowing for elegant, single-line method chaining (e.g., `scale.build().addMarker().show()`).
• 🟡 realtime — Specialized methods that update fluidly on every tick (realtime data), ideal for timers and loaders.
• 🔷 since-v6 — Leverages the latest Pine Script™ v6 features for maximum performance.
📊 Icon Reference Tables
No more guessing icon indices! Comprehensive tables are integrated directly into this documentation, showing every available icon for Markers, Rulers, Trends, and more.
🎯 Inline Examples
Every core module is accompanied by copy-paste ready examples, getting you from an empty script to a functioning UI in seconds.
🚀 QUICK START
1. Import the library
Bring the Scale framework into your script:
import cryptolinx/Scale/1 as s
2. Create a Theme (optional but recommended)
Define your aesthetic preferences early on:
// Example theme for a classic blue look
var theme = s.theme.new(
color_bar_filled = color.blue,
color_bar_unfilled = color.new(color.blue, 80)
)
3. Build and Deploy
Create your scale, feed it data, and add components:
// Simple RSI Scale with a marker and a background ruler
var myScale = s.setup.new()
myScale.build(theme, bar_index, high + 10, ta.rsi(close, 14), 14, 0, 100)
.addMarker(_icon = 0) // Pinpoints current value
.addRuler() // Adds a structural background
🔧 CORE METHODS
build() 🔵 primary 🟣 chainable
The foundational engine that initializes your scale's model, view, and controller. It explicitly defines *what* data is visualized, *where* it is anchored on the chart, and the dimensional constraints.
scale.build(__theme, _xOffset, _y, _src, _length, _minValue, _maxValue, ...)
• `__theme` (theme) — Required : Theme object encapsulating your colors/styling.
• `_xOffset` (int) — Required : Horizontal offset relative to `bar_index` (can be historical or future bars).
• `_y` (float) — Required : Vertical y-coordinate anchor (price/value level).
• `_src` (float) — Required : The incoming source value to visualize (e.g., RSI, Stochastic, custom oscillator).
• `_length` (int) — Required : Mathematical lookback length for internal calculations and dynamic ranges.
• `_minValue` (float) — Required : Minimum baseline value of the scale (representing 0%).
• `_maxValue` (float) — Required : Maximum ceiling value of the scale (representing 100%).
• `_numBars` (int) — Default: 10: Total number of discrete segments or 'ticks' comprising the bar.
• `_barWidth` (int) — Default: 2: Visual width of each individual segment in chart bars.
• `_barHeight` (int) — Default: 5: Visual vertical thickness of the bar in pixels.
• `_prefill` (bool) — Default: true: Determines fill behavior (Left-to-Right progression vs Center-out Range).
• `_dynamic` (bool) — Default: false: If explicitly set to true, minimum and maximum values will auto-adapt to the source data's historical extremes.
show() / hide() 🟣 chainable
Conditionally control visibility. Highly effective for decluttering the chart based on specific market conditions, timeframes, or user toggles.
// Only display the scale on the very last active bar
scale.show(barstate.islast)
// Automatically hide the scale during bearish price action
scale.hide(close < open)
🎨 ELEMENT METHODS
Modular add-ons that enhance the visual clarity and depth of your scale.
addLabel() 🔵 primary 🟣 chainable
Attaches a clean, customizable text label at specific anchor points relative to the scale geometry.
scale.addLabel(position.top_center, _text="RSI", _textColor=color.white)
addMarker() 🔵 primary 🟣 chainable
Places a precise symbol or shape exactly at the current value's interpolated position along the scale.
scale.addMarker(_icon=0, _color=color.yellow, _location=location.bottom)
📊 Marker Icon Table (_icon)
• 0 : ▼ : ▲ | 5 : ↧ : ↥ | 10 : ⁝
• 1 : ▽ : △ | 6 : ⇟ : ⇞ | 11 : ⋎ : ⋏
• 2 : ▾ : ▴ | 7 : ↓ : ↑ | 12 : ⋁ : ⋀
• 3 : ▿ : ▵ | 8 : |
• 4 : ⇣ : ⇡ | 9 : ⁞
addMark() 🔵 primary 🟣 chainable
Injects a static structural mark at a specific numerical offset. Highly useful for visualizing thresholds, midlines, or historic support/resistance levels.
// Places a '┼' symbol at the 2nd offset position
scale.addMark(_xOffset=2, _mark=2)
📊 Mark Icon Table (_mark)
• 0 : | | 4 : ⁞
• 1 : ¦ | 5 : ⁝
• 2 : ┼ | 6 : ▼ : ▲
• 3 : ≎ | 7 : ▽ : △
addBadge() 🔵 primary 🟣 chainable
Generates a prominent text badge with a dedicated background block. Perfect for communicating state, establishing titles, or flagging status alerts.
scale.addBadge("STRONG BUY", _position=position.top_left, _color=color.green)
📈 INDICATOR METHODS
Sophisticated overlays for visualizing statistical data, volatility, and market structure directly alongside your scale.
addRuler() 🔵 primary 🟣 chainable
Deploys a structural background ruler complete with distinct start, center, and end markers, defining the scale's boundaries for better readability.
// Injects a classic ├ -┼- ┤ style ruler framework
scale.addRuler(_icon=0)
📊 Ruler Icon Table (_icon)
• 0 : ├ -┼- ┤ | 6 : ╟ -╥- ╢
• 1 : ├ -┴- ┤ | 7 : ⥢ -≎- ⥤
• 2 : ├ -┬- ┤ | 8 : ⥏ -≏- ⥑
• 3 : ╞ -╧- ╡ | 9 : | - | - |
• 4 : ╞ -╤- ╡ | 10 : | - ¦ - |
• 5 : ╟ -╨- ╢ | 11 : ⁅ - ¦ - ⁆
addAvg() 🔵 primary 🟣 chainable
Computes and visually embeds a Simple Moving Average (SMA) of the incoming source data, allowing you to compare the current value to its historical mean.
scale.addAvg(_length=14, _markerIcon=3)
📊 Average Icon Table
*Text Icons (_textIcon)*: ⌀, Ø, ∅
*Marker Icons (_markerIcon)*: Utilizes the Standard Marker Set (0-12, refer to addMarker)
addRange() 🔵 primary 🟣 chainable
Tracks and plots the Highest High and Lowest Low over a specified period, visually expressing volatility and market extremities relative to the scale limits.
scale.addRange(_length=50, _showBg=true)
📊 Range Icon Table (_textIcon)
• 0 : L - H | 5 : ▼ : ▲
• 1 : ⇊ - ⇈ | 6 : ▽ : △
• 2 : ↓ - ↑ | 7 : ▾ : ▴
• 3 : ⇣ - ⇡ | 8 : ▿ : ▵
• 4 : ↧ - ↥
addTrend() 🔵 primary 🟣 chainable
Calculates and projects a directional trend indicator (rising, falling, or neutral) derived from the source data's momentum profile.
scale.addTrend(_length=14, _colored=true)
📊 Trend Icon Table (_icon)
• 0 : ◀-|-▶ | 6 : ⟪-|-⟫
• 1 : ◁-|-▷ | 7 : ↓-=-↑
• 2 : <-±-> | 8 : ⇊-=-⇈
• 3 : ‹-±-› | 9 : ↧-±-↥
• 4 : «-±-» | 10 : ⇣-±-⇡
• 5 : ⟨-|-⟩
addAlert() 🔵 primary 🟣 chainable
Flags the exact position where a crossover or crossunder event occurs relative to a critical target level.
Note: This acts as an on-chart visual companion; you must still configure a backend PulseWire alert system for notifications.
scale.addAlert(_target=70, _type="cross", _icon=0)
⚡ ANIMATION & DECORATION
addTimer() 🟡 realtime 🟣 chainable
Embeds an active countdown timer tied to the current bar's close, updating continuously tick-by-tick.
scale.addTimer(_position=position.bottom_left)
addLoader() 🟡 realtime 🟣 chainable
Attaches a kinetic spinning or loading animation that forces visual updates on every incoming tick, conveying active data processing to the user.
// Implements an active circular progression loader
scale.addLoader(_loaderIcon=1)
📊 Loader Icon Table (_loaderIcon)
• 0 : ◜-◝-◞-◟ | 4 : ⨫-⨬
• 1 : ◎-◉ | 5 : ▰▱▱...
• 2 : ⋮-⋰-⋯-⋱ | 6 : ⊶⊷⊶⊷...
• 3 : ≓-≒-≑
addDecoration() 🔵 primary 🟣 chainable
Caps your scale with polished decorative brackets or enclosing corners, framing the data and finalizing the professional aesthetic.
scale.addDecoration(_decor=0)
📊 Decoration Icon Table (_decor)
• 0 : ◤-◥ : ◣-◢ | 5 : ⊢-⊣
• 1 : ⌜-⌝ : ⌞-⌟ | 6 : ◖-◗
• 2 : ⌏-⌎ : ⌍-⌌ | 7 : ⟦-⟧
• 3 : ◜-◝ : ◟-◞ | 8 : ⟪-⟫
• 4 : ⊞-⊟ | 9 : ⟨-⟩
📋 CHANGELOG
✅ Initial release of the Scale UI framework
✅ Implemented multi-element coordinate management
✅ Added dynamic scaling and formatting options
✅ Included comprehensive visual decorators
🙏 RELATED LIBRARIES
Check out ScaleValidator for robust input validation that can be used alongside this framework.
Also check out Motion for animating labels and colors dynamically!
Happy coding! 🚀
Made with ☕ by @cryptolinx Library

ScaleValidator🛡️ ScaleValidator Library - Input Validation for PineScript
📢 ABOUT
ScaleValidator is a lightweight utility library that provides robust input validation for PineScript. It ensures your scripts receive valid arguments and throws helpful runtime errors when they don't.
✨ FEATURES
🛡️ Validation Methods
Validate inputs and throw descriptive runtime errors if invalid:
• isValidLocation() — Validate location strings
• isValidPosition() — Validate position strings
• isValidFormat() — Validate format strings
• isValidPOV() — Validate point-of-view (extend) strings
🔍 Helper Methods
Quick boolean checks without throwing errors:
• isLocationAbove() / isLocationBelow() — Check vertical location
• isPositionAbove() / isPositionCenter() / isPositionBelow() — Check position row
• isPositionLeft() / isPositionRight() — Check position column
💡 USAGE EXAMPLE
//@version=6
indicator("Validator Demo", overlay = true)
import cryptolinx/ScaleValidator/1 as v
// Validate inputs before using them
userPosition = input.string(position.top_center, "Position")
if v.isValidPosition(userPosition)
// Safe to use the position
label.new(bar_index, high, "Valid!",
xloc = xloc.bar_index,
style = label.style_label_down,
textcolor = color.white)
// Quick checks without throwing errors
if v.isPositionAbove(userPosition)
// Position is in top row
plotchar(close, char = "▲", location = location.abovebar)
📊 VALID CONSTANTS REFERENCE
Locations
• location.top — Top of pane
• location.bottom — Bottom of pane
• location.abovebar — Above price bar
• location.belowbar — Below price bar
• location.absolute — Absolute position
Positions (3x3 Grid)
• Top Row: top_left, top_center, top_right
• Middle Row: middle_left, middle_center, middle_right
• Bottom Row: bottom_left, bottom_center, bottom_right
Formats
• format.inherit — Inherit from parent
• format.percent — Percentage format
Point of View (Extend)
• extend.both — Extend in both directions
• extend.left — Extend to the left
• extend.right — Extend to the right
🔧 METHOD REFERENCE
Validators (throw runtime error if invalid)
• isValidLocation(string) → bool
• isValidPosition(string) → bool
• isValidFormat(string) → bool
• isValidPOV(string) → bool
Helpers (return bool, no errors)
• isLocationAbove(string) → bool
• isLocationBelow(string) → bool
• isPositionAbove(string) → bool
• isPositionCenter(string) → bool
• isPositionBelow(string) → bool
• isPositionLeft(string) → bool
• isPositionRight(string) → bool
🚀 WHY USE THIS?
• 🛡️ Defensive Programming — Catch invalid inputs early
• 📖 Helpful Errors — Descriptive messages show valid options
• ⚡ Lightweight — No dependencies, minimal overhead
• 🔗 Companion to ScalesDEV — Used internally by the Scale library
📋 CHANGELOG
✅ Added method badges (helper/validator)
✅ Created reference tables for valid constants
✅ Improved parameter descriptions
✅ Formatted return types
🙏 RELATED LIBRARIES
Check out Scales for building beautiful scale visualizations that use this validator!
Battries included! 🔋Happy coding! 🚀 @cryptolinx for the PulseWire community
Library

Library

TrinityCore30Library "TrinityCore30"
TRINITY CORE LIBRARY v30.1 (Diamond Final / Safety Sync Fixed)
Architecture: Fixed 7 Calls / Raw Kernels / State Machine / Array Math
Constitution:
1. Max 7 security calls.
2. Bible Compliance: CD (Corr), DDG (Ratio), Dynamic Lengths.
3. Ironclad Math: Volatility %, NaN-Guarded.
4. Semantics: Safety Valve correctly syncs is_ready/risk_gate flags.
calc_weights(sym, cp, cs, s1, s2, s3, s4, s5, cfg)
Parameters:
sym (string)
cp (string)
cs (string)
s1 (string)
s2 (string)
s3 (string)
s4 (string)
s5 (string)
cfg (TrinityConfig)
calc_diagnostics(sym, cp, cs, s1, s2, s3, s4, s5, cfg)
Parameters:
sym (string)
cp (string)
cs (string)
s1 (string)
s2 (string)
s3 (string)
s4 (string)
s5 (string)
cfg (TrinityConfig)
calc_weights_flat(sym, cp, cs, s1, s2, s3, s4, s5, en, l20, w20, l63, w63, l126, w126, l252, w252, rf, fac, tvs, tvsf, gmm, kl, kd, ks, tk, bl, wcp, wcd, wvs, wdd, sp, sv, ft, rf2, ra, r_cp, r_dd, pen_v, rb)
Parameters:
sym (string)
cp (string)
cs (string)
s1 (string)
s2 (string)
s3 (string)
s4 (string)
s5 (string)
en (bool)
l20 (int)
w20 (float)
l63 (int)
w63 (float)
l126 (int)
w126 (float)
l252 (int)
w252 (float)
rf (float)
fac (float)
tvs (float)
tvsf (float)
gmm (float)
kl (int)
kd (float)
ks (float)
tk (int)
bl (float)
wcp (float)
wcd (float)
wvs (float)
wdd (float)
sp (float)
sv (float)
ft (float)
rf2 (float)
ra (float)
r_cp (float)
r_dd (float)
pen_v (float)
rb (int)
core_build()
TrinityWeights
Fields:
stock (series float)
safe1 (series float)
safe2 (series float)
safe3 (series float)
safe4 (series float)
safe5 (series float)
cash (series float)
TrinityDiagLite
Fields:
is_ready (series bool)
ready_code (series int)
core_build (series int)
risk_gate (series bool)
wroc_stock (series float)
valid_safe_count (series int)
passed_safe_count (series int)
sum_ok (series bool)
TrinityDiagFull
Fields:
raw_stock (series float)
mvol_stock (series float)
mdecel_stock (series float)
gov_stock (series float)
safe_budget (series float)
top1_id (series int)
top2_id (series int)
sum_weights (series float)
SafeDiag
Fields:
enabled (series bool)
valid (series bool)
sqs (series float)
final_w (series float)
drop_code (series int)
TrinityConfig
Fields:
enabled (series bool)
len_20 (series int)
w_20 (series float)
len_63 (series int)
w_63 (series float)
len_126 (series int)
w_126 (series float)
len_252 (series int)
w_252 (series float)
risk_floor (series float)
risk_factor (series float)
target_vol_stock (series float)
target_vol_safe (series float)
gov_min_mult (series float)
k_len (series int)
k_decay (series float)
k_scale (series float)
top_k (series int)
baseline (series float)
w_cp (series float)
w_cd (series float)
w_vs (series float)
w_ddg (series float)
shock_price (series float)
shock_vol (series float)
fall_thr (series float)
rate_fall (series float)
rate_accel (series float)
penalty_val (series float)
range_cp (series float)
range_dd (series float)
ready_bars (series int) Library

TrinityCore1Library "TrinityCore1"
default_config()
calc_weights(sym, cp, cs, s1, s2, s3, s4, s5, cfg)
Parameters:
sym (string)
cp (string)
cs (string)
s1 (string)
s2 (string)
s3 (string)
s4 (string)
s5 (string)
cfg (TrinityConfig)
calc_diagnostics(sym, cp, cs, s1, s2, s3, s4, s5, cfg)
Parameters:
sym (string)
cp (string)
cs (string)
s1 (string)
s2 (string)
s3 (string)
s4 (string)
s5 (string)
cfg (TrinityConfig)
TrinityWeights
Fields:
stock (series float)
s1 (series float)
s2 (series float)
s3 (series float)
s4 (series float)
s5 (series float)
cash (series float)
SafeDiag
Fields:
id (series string)
vol (series float)
corr (series float)
dd (series float)
score (series float)
final_w (series float)
TrinityDiagLite
Fields:
ready_code (series int)
drop_code (series int)
is_ready (series bool)
risk_gate (series bool)
p_value (series float)
d_bar_index (series int)
TrinityDiagFull
Fields:
base (TrinityDiagLite)
raw_vol (series float)
adj_vol (series float)
target_w (series float)
penalty_mult (series float)
sd1 (SafeDiag)
sd2 (SafeDiag)
sd3 (SafeDiag)
sd4 (SafeDiag)
sd5 (SafeDiag)
TrinityConfig
Fields:
enabled (series bool)
len_20 (series int)
w_20 (series float)
len_63 (series int)
w_63 (series float)
len_126 (series int)
w_126 (series float)
len_252 (series int)
w_252 (series float)
risk_floor (series float)
risk_factor (series float)
target_vol_stock (series float)
target_vol_safe (series float)
gov_max_lev (series float)
gov_min_mult (series float)
top_k (series int)
sqs_base (series float)
sqs_w_corr (series float)
sqs_w_vol (series float)
sqs_w_dd (series float)
sqs_range_corr (series float)
sqs_range_dd (series float)
fall_thr (series float)
rate_fall (series float)
rate_accel (series float)
penalty_val (series float)
ready_bars (series int) Library

RSMPatternLibLibrary "RSMPatternLib"
RSM Pattern Library - All chart patterns from PATTERNS.md
Implements: Candlestick patterns, Support/Resistance, Gaps, Triangles, Volume Divergence, and more
ALL PATTERNS ARE OWN IMPLEMENTATION - No external dependencies
EDGE CASES HANDLED:
- Zero/tiny candle bodies
- Missing volume data
- Low bar count scenarios
- Integer division issues
- Price normalization for different instruments
bullishEngulfing(minBodyRatio, minPrevBodyRatio)
Detects Bullish Engulfing pattern
Parameters:
minBodyRatio (float) : Minimum body size as ratio of total range (default 0.3)
minPrevBodyRatio (float) : Minimum previous candle body ratio to filter dojis (default 0.1)
Returns: bool True when bullish engulfing detected
EDGE CASES: Handles doji previous candle, zero range, tiny bodies
bearishEngulfing(minBodyRatio, minPrevBodyRatio)
Detects Bearish Engulfing pattern
Parameters:
minBodyRatio (float) : Minimum body size as ratio of total range (default 0.3)
minPrevBodyRatio (float) : Minimum previous candle body ratio to filter dojis (default 0.1)
Returns: bool True when bearish engulfing detected
EDGE CASES: Handles doji previous candle, zero range, tiny bodies
doji(maxBodyRatio, minRangeAtr)
Detects Doji candle (indecision)
Parameters:
maxBodyRatio (float) : Maximum body size as ratio of total range (default 0.1)
minRangeAtr (float) : Minimum range as multiple of ATR to filter flat candles (default 0.3)
Returns: bool True when doji detected
EDGE CASES: Filters out no-movement bars, handles zero range
shootingStar(wickMultiplier, maxLowerWickRatio, minBodyAtrRatio)
Detects Shooting Star (bearish reversal)
Parameters:
wickMultiplier (float) : Upper wick must be at least this times the body (default 2.0)
maxLowerWickRatio (float) : Lower wick max as ratio of body (default 0.5)
minBodyAtrRatio (float) : Minimum body size as ratio of ATR (default 0.1)
Returns: bool True when shooting star detected
EDGE CASES: Handles zero body (uses range-based check), tiny bodies
hammer(wickMultiplier, maxUpperWickRatio, minBodyAtrRatio)
Detects Hammer (bullish reversal)
Parameters:
wickMultiplier (float) : Lower wick must be at least this times the body (default 2.0)
maxUpperWickRatio (float) : Upper wick max as ratio of body (default 0.5)
minBodyAtrRatio (float) : Minimum body size as ratio of ATR (default 0.1)
Returns: bool True when hammer detected
EDGE CASES: Handles zero body (uses range-based check), tiny bodies
invertedHammer(wickMultiplier, maxLowerWickRatio)
Detects Inverted Hammer (bullish reversal after downtrend)
Parameters:
wickMultiplier (float) : Upper wick must be at least this times the body (default 2.0)
maxLowerWickRatio (float) : Lower wick max as ratio of body (default 0.5)
Returns: bool True when inverted hammer detected
EDGE CASES: Same as shootingStar but requires bullish close
hangingMan(wickMultiplier, maxUpperWickRatio)
Detects Hanging Man (bearish reversal after uptrend)
Parameters:
wickMultiplier (float) : Lower wick must be at least this times the body (default 2.0)
maxUpperWickRatio (float) : Upper wick max as ratio of body (default 0.5)
Returns: bool True when hanging man detected
NOTE: Identical to hammer - context (uptrend) determines meaning
morningStar(requireGap, minAvgBars)
Detects Morning Star (3-candle bullish reversal)
Parameters:
requireGap (bool) : Whether to require gap between candles (default false for crypto/forex)
minAvgBars (int) : Minimum bars for average body calculation (default 14)
Returns: bool True when morning star pattern detected
EDGE CASES: Gap is optional, handles low bar count, uses shifted average
eveningStar(requireGap, minAvgBars)
Detects Evening Star (3-candle bearish reversal)
Parameters:
requireGap (bool) : Whether to require gap between candles (default false for crypto/forex)
minAvgBars (int) : Minimum bars for average body calculation (default 14)
Returns: bool True when evening star pattern detected
EDGE CASES: Gap is optional, handles low bar count
gapUp()
Detects Gap Up
Returns: bool True when current bar opens above previous bar's high
gapDown()
Detects Gap Down
Returns: bool True when current bar opens below previous bar's low
gapSize()
Returns gap size in price
Returns: float Gap size (positive for gap up, negative for gap down, 0 for no gap)
gapPercent()
Returns gap size as percentage
Returns: float Gap size as percentage of previous close
gapType(volAvgLen, breakawayMinPct, highVolMult)
Classifies gap type based on volume
Parameters:
volAvgLen (int) : Length for volume average (default 20)
breakawayMinPct (float) : Minimum gap % for breakaway (default 1.0)
highVolMult (float) : Volume multiplier for high volume (default 1.5)
Returns: string Gap type: "Breakaway", "Common", "Continuation", or "None"
EDGE CASES: Handles missing volume data, low bar count
swingHigh(leftBars, rightBars)
Detects swing high using pivot
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
Returns: float Swing high price or na
swingLow(leftBars, rightBars)
Detects swing low using pivot
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
Returns: float Swing low price or na
higherHigh(leftBars, rightBars, lookback)
Checks if current swing high is higher than previous swing high
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : How many bars back to search for previous pivot (default 50)
Returns: bool True when higher high pattern detected
EDGE CASES: Searches backwards for pivots instead of using var (library-safe)
higherLow(leftBars, rightBars, lookback)
Checks if current swing low is higher than previous swing low
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : How many bars back to search for previous pivot (default 50)
Returns: bool True when higher low pattern detected
lowerHigh(leftBars, rightBars, lookback)
Checks if current swing high is lower than previous swing high
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : How many bars back to search for previous pivot (default 50)
Returns: bool True when lower high pattern detected
lowerLow(leftBars, rightBars, lookback)
Checks if current swing low is lower than previous swing low
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : How many bars back to search for previous pivot (default 50)
Returns: bool True when lower low pattern detected
bullishTrend(leftBars, rightBars, lookback)
Detects Bullish Trend (HH + HL within lookback)
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : Lookback period (default 50)
Returns: bool True when making higher highs AND higher lows
bearishTrend(leftBars, rightBars, lookback)
Detects Bearish Trend (LH + LL within lookback)
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : Lookback period (default 50)
Returns: bool True when making lower highs AND lower lows
nearestResistance(lookback, leftBars, rightBars)
Finds nearest resistance level above current price
Parameters:
lookback (int) : Number of bars to look back (default 50)
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
Returns: float Nearest resistance level or na
EDGE CASES: Pre-computes pivots, handles bounds properly
nearestSupport(lookback, leftBars, rightBars)
Finds nearest support level below current price
Parameters:
lookback (int) : Number of bars to look back (default 50)
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
Returns: float Nearest support level or na
resistanceBreakout(lookback, leftBars, rightBars)
Detects resistance breakout
Parameters:
lookback (int) : Number of bars to look back (default 50)
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
Returns: bool True when price breaks above resistance
EDGE CASES: Uses previous bar's resistance to avoid lookahead
supportBreakdown(lookback, leftBars, rightBars)
Detects support breakdown
Parameters:
lookback (int) : Number of bars to look back (default 50)
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
Returns: bool True when price breaks below support
bullishVolumeDivergence(leftBars, rightBars, lookback)
Detects Bullish Volume Divergence (price makes lower low, volume decreases)
Parameters:
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
lookback (int) : Bars to search for previous pivot (default 50)
Returns: bool True when bullish volume divergence detected
EDGE CASES: Library-safe (no var), searches for previous pivot
bearishVolumeDivergence(leftBars, rightBars, lookback)
Detects Bearish Volume Divergence (price makes higher high, volume decreases)
Parameters:
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
lookback (int) : Bars to search for previous pivot (default 50)
Returns: bool True when bearish volume divergence detected
rangeContracting(lookback)
Detects if price is in a contracting range (triangle formation)
Parameters:
lookback (int) : Bars to analyze (default 20)
Returns: bool True when range is contracting
EDGE CASES: Uses safe integer division, checks minimum lookback
ascendingTriangle(lookback, flatTolerance)
Detects Ascending Triangle (flat top, rising bottom)
Parameters:
lookback (int) : Bars to analyze (default 20)
flatTolerance (float) : Max normalized slope for "flat" line (default 0.002)
Returns: bool True when ascending triangle detected
EDGE CASES: Safe division, normalized slope, minimum lookback
descendingTriangle(lookback, flatTolerance)
Detects Descending Triangle (falling top, flat bottom)
Parameters:
lookback (int) : Bars to analyze (default 20)
flatTolerance (float) : Max normalized slope for "flat" line (default 0.002)
Returns: bool True when descending triangle detected
symmetricalTriangle(lookback, minSlope)
Detects Symmetrical Triangle (converging trend lines)
Parameters:
lookback (int) : Bars to analyze (default 20)
minSlope (float) : Minimum normalized slope magnitude (default 0.0005)
Returns: bool True when symmetrical triangle detected
doubleBottom(tolerance, minSpanBars, lookback)
Detects Double Bottom (W pattern) - OWN IMPLEMENTATION
Two swing lows at similar price levels with a swing high between them
Parameters:
tolerance (float) : Max price difference between lows as % (default 3)
minSpanBars (int) : Minimum bars between the two lows (default 5)
lookback (int) : Max bars to search for pattern (default 100)
Returns: bool True when double bottom detected
doubleTop(tolerance, minSpanBars, lookback)
Detects Double Top (M pattern) - OWN IMPLEMENTATION
Two swing highs at similar price levels with a swing low between them
Parameters:
tolerance (float) : Max price difference between highs as % (default 3)
minSpanBars (int) : Minimum bars between the two highs (default 5)
lookback (int) : Max bars to search for pattern (default 100)
Returns: bool True when double top detected
tripleBottom(tolerance, minSpanBars, lookback)
Detects Triple Bottom - OWN IMPLEMENTATION
Three swing lows at similar price levels
Parameters:
tolerance (float) : Max price difference between lows as % (default 3)
minSpanBars (int) : Minimum total bars for pattern (default 10)
lookback (int) : Max bars to search for pattern (default 150)
Returns: bool True when triple bottom detected
tripleTop(tolerance, minSpanBars, lookback)
Detects Triple Top - OWN IMPLEMENTATION
Three swing highs at similar price levels
Parameters:
tolerance (float) : Max price difference between highs as % (default 3)
minSpanBars (int) : Minimum total bars for pattern (default 10)
lookback (int) : Max bars to search for pattern (default 150)
Returns: bool True when triple top detected
bearHeadShoulders()
Detects Bearish Head and Shoulders (OWN IMPLEMENTATION)
Head is higher than both shoulders, shoulders roughly equal, with valid neckline
STRICT VERSION - requires proper structure, neckline, and minimum span
Returns: bool True when bearish H&S detected
bullHeadShoulders()
Detects Bullish (Inverse) Head and Shoulders (OWN IMPLEMENTATION)
Head is lower than both shoulders, shoulders roughly equal, with valid neckline
STRICT VERSION - requires proper structure, neckline, and minimum span
Returns: bool True when bullish H&S detected
bearAscHeadShoulders()
Detects Bearish Ascending Head and Shoulders (variant)
Returns: bool True when pattern detected
bullAscHeadShoulders()
Detects Bullish Ascending Head and Shoulders (variant)
Returns: bool True when pattern detected
bearDescHeadShoulders()
Detects Bearish Descending Head and Shoulders (variant)
Returns: bool True when pattern detected
bullDescHeadShoulders()
Detects Bullish Descending Head and Shoulders (variant)
Returns: bool True when pattern detected
isSwingLow()
Re-export: Detects swing low
Returns: bool True when swing low detected
isSwingHigh()
Re-export: Detects swing high
Returns: bool True when swing high detected
swingHighPrice(idx)
Re-export: Gets swing high price at index
Parameters:
idx (int) : Index (0 = most recent)
Returns: float Swing high price
swingLowPrice(idx)
Re-export: Gets swing low price at index
Parameters:
idx (int) : Index (0 = most recent)
Returns: float Swing low price
swingHighBarIndex(idx)
Re-export: Gets swing high bar index
Parameters:
idx (int) : Index (0 = most recent)
Returns: int Bar index of swing high
swingLowBarIndex(idx)
Re-export: Gets swing low bar index
Parameters:
idx (int) : Index (0 = most recent)
Returns: int Bar index of swing low
cupBottom(smoothLen, minDepthAtr, maxDepthAtr)
Detects Cup and Handle pattern formation
Uses price acceleration and depth analysis
Parameters:
smoothLen (int) : Smoothing length for price (default 10)
minDepthAtr (float) : Minimum cup depth as ATR multiple (default 1.0)
maxDepthAtr (float) : Maximum cup depth as ATR multiple (default 5.0)
Returns: bool True when potential cup bottom detected
EDGE CASES: Added depth filter, ATR validation
cupHandle(lookback, maxHandleRetraceRatio)
Detects potential handle formation after cup
Parameters:
lookback (int) : Bars to look back for cup (default 30)
maxHandleRetraceRatio (float) : Maximum handle retracement of cup depth (default 0.5)
Returns: bool True when handle pattern detected
bullishPatternCount()
Returns count of bullish patterns detected
Returns: int Number of bullish patterns currently active
bearishPatternCount()
Returns count of bearish patterns detected
Returns: int Number of bearish patterns currently active
detectedPatterns()
Returns string description of detected patterns
Returns: string Comma-separated list of detected patterns Library

Library

Library

Plan Limit TimerA Pine Script library that helps developers monitor script execution time against PulseWire's plan-specific timeout limits. Displays a visual debug table with runtime metrics, percentage of limit consumed, and color-coded status warnings.
WHAT THIS LIBRARY DOES
PulseWire enforces different script timeout limits based on subscription tier:
• Basic : 20 seconds
• Essential / Plus / Premium : 40 seconds
• Ultimate : 100 seconds
This library measures your script's total execution time and displays it relative to these limits, helping you optimize indicators for users on different plans.
THE DEBUG TABLE
When enabled, a table appears on your chart showing:
• Plan : The selected PulseWire subscription tier
• Limit : Maximum allowed execution time for that plan
• Runtime : Measured script execution time
• Per Bar : Average time spent per bar
• Bars : Number of bars processed
• % Used : Percentage of timeout limit consumed (color-coded)
• Status : OK (green), WARNING (yellow), DANGER (orange), or EXCEEDED (red)
HOW IT WORKS
The library captures a timestamp at the start of your script using timenow, then calculates the elapsed time at the end. It compares this against the selected plan's timeout limit to determine percentage used and status.
Technical Note : Pine Script's timenow variable has approximately 1-second precision. Scripts that execute in under 1 second may display 0ms. This is a platform limitation, not a library issue. For detailed per-function profiling, use PulseWire's built-in Pine Profiler (More → Profiler mode in the Editor).
EXPORTED FUNCTIONS
startTimer()
Call at the very beginning of your script. Returns a timestamp.
getStats(startTime, plan)
Calculates timing statistics. Returns a TimingStats object with all metrics.
showTimingTable(stats, plan, tablePosition, showOnlyOnLast)
Renders the debug table on the chart.
debugTiming(startTime, plan, tablePosition)
Convenience function combining getStats() and showTimingTable() in one call.
isApproachingLimit(stats, threshold)
Returns true if execution time has reached the specified percentage of the limit.
getRemainingMs(stats)
Returns milliseconds remaining before timeout.
formatSummary(stats)
Returns a compact single-line string for labels or tooltips.
addTimingLabel(stats, barIdx, price, labelStyle, textSize)
Creates a color-coded chart label displaying timing statistics. Useful for visual debugging without the full table. Returns the label object for further customization.
EXPORTED CONSTANTS
• LIMIT_BASIC = 20
• LIMIT_ESSENTIAL = 40
• LIMIT_PLUS = 40
• LIMIT_PREMIUM = 40
• LIMIT_ULTIMATE = 100
EXPORTED TYPE: TimingStats
Object containing:
• totalTimeMs (float): Total execution time in milliseconds
• timePerBarMs (float): Average time per bar
• barsTimed (int): Number of bars measured
• barsSkipped (int): Bars excluded from measurement
• planLimitMs (int): Plan timeout in milliseconds
• percentUsed (float): Percentage of limit consumed
• status (string): "OK", "WARNING", "DANGER", or "EXCEEDED"
HOW TO USE IN YOUR INDICATOR
//@version=6
indicator("My Indicator", overlay = true)
import YourUsername/PlanLimitTimer/1 as timer
// User selects their PulseWire plan
planInput = input.string("basic", "Your Plan", options = )
// START TIMING - must be first
startTime = timer.startTimer()
// Your indicator calculations here
sma20 = ta.sma(close, 20)
rsi14 = ta.rsi(close, 14)
plot(sma20)
// END TIMING - must be last
timer.debugTiming(startTime, planInput)
ADVANCED USAGE EXAMPLE
//@version=6
indicator("Advanced Example", overlay = true)
import YourUsername/PlanLimitTimer/1 as timer
planInput = input.string("basic", "Plan", options = )
startTime = timer.startTimer()
// Your calculations...
sma = ta.sma(close, 200)
plot(sma)
// Get stats for programmatic use
stats = timer.getStats(startTime, planInput)
// Option 1: Use addTimingLabel for a quick visual indicator
if barstate.islast
timer.addTimingLabel(stats, bar_index, high)
// Option 2: Show custom warning label if approaching limit
if timer.isApproachingLimit(stats, 70.0) and barstate.islast
label.new(bar_index, low, "Warning: " + timer.formatSummary(stats),
color = color.orange, textcolor = color.white, style = label.style_label_up)
// Display the debug table
timer.showTimingTable(stats, planInput, position.bottom_right)
IMPORTANT LIMITATIONS
1. Precision : Timing precision is approximately 1 second due to timenow behavior. Fast scripts show 0ms.
2. Variability : Results vary based on PulseWire server load. The same script may show different times across runs.
3. Total Time Only : This library measures total script execution time, not individual function timing. For per-function analysis, use the Pine Profiler in the Editor.
4. Historical Bars : On historical bars, timenow reflects when the script loaded, not individual bar processing times.
USE CASES
• Optimization Debugging : See how close your script is to timeout limits
• Multi-Plan Support : Help users select appropriate settings for their subscription tier
• Performance Regression : Detect when changes increase execution time
• Documentation : Show users the performance characteristics of your indicator
Library

Library

T5_TradeEngineLibrary "T5_TradeEngine"
tick(close_, high_, low_, ema21, ema50, ema200, atrPct, emaGapPct, btcEma50, btcEma200, btcFilterEffective, isBarClose, crossUp21_50, crossDown21_50, allowEntries, exitOnOppositeCross, feeBps, useSR_TPSL, srLeft, srRight, srLookbackPivots, srBufferPct, srMinDistPct, srMinNetAfterFeesPct, srFallbackToATR, tp1CapPct, slCapPct, useTP2Trail, trailExitOnCloseOnly, tp2CapPct, trailCapPct, holdBars)
Parameters:
close_ (float)
high_ (float)
low_ (float)
ema21 (float)
ema50 (float)
ema200 (float)
atrPct (float)
emaGapPct (float)
btcEma50 (float)
btcEma200 (float)
btcFilterEffective (bool)
isBarClose (bool)
crossUp21_50 (bool)
crossDown21_50 (bool)
allowEntries (bool)
exitOnOppositeCross (bool)
feeBps (float)
useSR_TPSL (bool)
srLeft (int)
srRight (int)
srLookbackPivots (int)
srBufferPct (float)
srMinDistPct (float)
srMinNetAfterFeesPct (float)
srFallbackToATR (bool)
tp1CapPct (float)
slCapPct (float)
useTP2Trail (bool)
trailExitOnCloseOnly (bool)
tp2CapPct (float)
trailCapPct (float)
holdBars (int) Library

Library

Library

Library

Library

OKXJsonLibrary "OKXJson"
f_buildId(prefix, instrument)
Parameters:
prefix (string)
instrument (string)
f_utcTimestamp()
f_investmentType(internalAction, entryType, closeType)
Parameters:
internalAction (string)
entryType (string)
closeType (string)
f_build(id, okxAction, marketPosition, prevMarketPosition, instrument, signalToken, timestampUtc, investmentType, amount, maxLagSeconds)
Parameters:
id (string)
okxAction (string)
marketPosition (string)
prevMarketPosition (string)
instrument (string)
signalToken (string)
timestampUtc (string)
investmentType (string)
amount (string)
maxLagSeconds (string) Library

Library

RLSR logreg_support_libLibrary "logreg_support_lib"
sigmoid(z)
Parameters:
z (float)
prng01(seed1, seed2)
Parameters:
seed1 (float)
seed2 (float)
normalize(value, minval, maxval)
Parameters:
value (float)
minval (float)
maxval (float)
calcpercentilefast(arr, percentile)
Parameters:
arr (array)
percentile (float)
calcpercentile_series_sampled(s, length, percentile, stride)
Parameters:
s (float)
length (int)
percentile (float)
stride (int)
calcRangeWithLog(value, minval, maxval, uselog)
Parameters:
value (float)
minval (float)
maxval (float)
uselog (bool)
calcMomentumAdvanced(src, length, momType)
Parameters:
src (float)
length (simple int)
momType (string)
normalizeMomentumByType(rawMom, momType, momMin, momMax, momNorm)
Parameters:
rawMom (float)
momType (string)
momMin (float)
momMax (float)
momNorm (float)
normalizeMomentumByTypeExt(rawMom, momType, momMin, momMax, momNorm, bouncingdecay)
Parameters:
rawMom (float)
momType (string)
momMin (float)
momMax (float)
momNorm (float)
bouncingdecay (float)
calcrollingstddev(src, length)
Parameters:
src (float)
length (int)
addlog(buffer, level, msg)
Parameters:
buffer (string)
level (string)
msg (string)
calcfeaturecorrelation(x1, x2)
Parameters:
x1 (array)
x2 (array)
calcnoiseratio(src, lookback)
Parameters:
src (float)
lookback (int)
calccompatibilityscore(x1, x2)
Parameters:
x1 (array)
x2 (array)
getfuturereturn(offset, returnlookback)
Parameters:
offset (int)
returnlookback (int)
calculatema(source, length, matype)
Parameters:
source (float)
length (simple int)
matype (string)
adaptive_trigger_for_source(src, enabled, freeze, lookback, threshold, volahistory)
Parameters:
src (float)
enabled (bool)
freeze (bool)
lookback (int)
threshold (float)
volahistory (array)
checkadaptivetrigger5(s1, enabled1, freeze1, hist1, s2, enabled2, freeze2, hist2, s3, enabled3, freeze3, hist3, s4, enabled4, freeze4, hist4, s5, enabled5, freeze5, hist5, lookback, threshold)
Parameters:
s1 (float)
enabled1 (bool)
freeze1 (bool)
hist1 (array)
s2 (float)
enabled2 (bool)
freeze2 (bool)
hist2 (array)
s3 (float)
enabled3 (bool)
freeze3 (bool)
hist3 (array)
s4 (float)
enabled4 (bool)
freeze4 (bool)
hist4 (array)
s5 (float)
enabled5 (bool)
freeze5 (bool)
hist5 (array)
lookback (int)
threshold (float)
ring_start_index(rb_write_idx, rb_count, rb_cap)
Parameters:
rb_write_idx (int)
rb_count (int)
rb_cap (int) Library
