Helper Lib by tristanlee85Library "helpers"
This library offers various functions and types based on the algorithmic
concepts as authored by ICT.
kv(key, value)
Returns a string of the key/value set, suitable for debug logging
Parameters:
key (string)
value (string)
Returns: A string formatted as "{key}: {value}"
kv(key, value)
Parameters:
key (string)
value (int)
kv(key, value)
Parameters:
key (string)
value (float)
kv(key, value)
Parameters:
key (string)
value (bool)
method enable(this, enable)
Enable/Disable debug logging
Namespace types: Debugger
Parameters:
this (Debugger)
enable (bool) : Set to `true` by default.
method group(this, label)
Creates a group label for nested debug() invocations
Namespace types: Debugger
Parameters:
this (Debugger)
label (string)
method groupEnd(this, label)
Ends the specified debug group
Namespace types: Debugger
Parameters:
this (Debugger)
label (string)
method log(this, s, arg1, arg2, arg3, arg4, arg5)
Logs the param values if debug mode is enabled
Namespace types: Debugger
Parameters:
this (Debugger)
s (string) : Title of the log message
arg1 (string)
arg2 (string)
arg3 (string)
arg4 (string)
arg5 (string)
method logIf(this, expr, s, arg1, arg2, arg3, arg4, arg5)
Same behavior as debug() except will only log if the passed expression is true
Namespace types: Debugger
Parameters:
this (Debugger)
expr (bool) : Boolean expression to determine if debug logs should be logged
s (string) : Title of the log message
arg1 (string)
arg2 (string)
arg3 (string)
arg4 (string)
arg5 (string)
style_getLineStyleFromType(opt)
Returns the corresponding line style constant for the given LineStyleType
Parameters:
opt (series LineStyleType) : The selected line style type
Returns: The Pine Script line style constant
style_getTextSizeFromType(opt)
Returns the corresponding text size constant for the given TextSizeType
Parameters:
opt (series TextSizeType) : The selected text size type
Returns: The Pine Script text size constant
style_getTextHAlignFromType(t)
Returns the corresponding horizontal text align constant for the given HAlignType
Parameters:
t (series HAlignType) : The selected text align type
Returns: The Pine Script text align constant
style_getTextVAlignFromType(t)
Returns the corresponding vertical text align constant for the given VAlignType
Parameters:
t (series VAlignType) : The selected text align type
Returns: The Pine Script text align constant
format_sentimentType(sentiment, pd)
Used to produce a string with the sentiment and PD array type (e.g., "+FVG")
Parameters:
sentiment (series SentimentType) : The sentiment value (e.g., SentimentType.BULLISH)
pd (series PDArrayType) : The price data array (e.g., PDArrayType.FVG)
Returns: A formatted string with the sentiment and PD array (e.g., "+FVG")
format_timeToString(timestamp)
Formats a UNIX timestamp into a date and time string based on predefined formats
Parameters:
timestamp (int) : The UNIX timestamp to format
Returns: A formatted string as "MM-dd (E) - HH:mm"
method init(this)
Initializes the session and validates the configuration. This MUST be called immediately after creating a new instance.
Namespace types: Session
Parameters:
this (Session) : The Session object reference
Returns: The Session object (chainable) or throws a runtime error if invalid
method isActive(this, _time)
Determines if the session is active based on the current bar time
Namespace types: Session
Parameters:
this (Session) : The Session object reference
_time (int)
Returns: `true` if the session is currently active; `false` otherwise
method draw(this)
Draws the line and optional label
Namespace types: LineLabel
Parameters:
this (LineLabel) : The LineLabel object reference
Returns: The LineLabel object (chainable)
method extend(this, x)
Extends the line and label right to the specified bar index
Namespace types: LineLabel
Parameters:
this (LineLabel) : The LineLabel object reference
x (int) : The bar index to extend to
Returns: The LineLabel object (chainable)
method destroy(this)
Removes the line and label from the chart
Namespace types: LineLabel
Parameters:
this (LineLabel) : The LineLabel object reference
isFVG(includeVI, barIdx)
Checks if the previous bars form a Fair Value Gap (FVG)
Parameters:
includeVI (bool) : If true, includes Volume Imbalance in the FVG calculation
barIdx (int) : The index of the bar to check from (default is 0 for the current bar)
Returns: A Gap object if a FVG is detected; otherwise, `na`
isVolumeImbalance(barIdx)
Checks if the previous bars form a Volume Imbalance (VI)
Parameters:
barIdx (int) : The index of the bar to check from (default is 0 for the current bar)
Returns: A Gap object if a VI is detected; otherwise, `na`
isLiquidityVoid(barIdx)
Checks if the previous bars form a Liquidity Void (LV)
Parameters:
barIdx (int) : The index of the bar to check from (default is 0 for the current bar)
Returns: A Gap object if an LV is detected; otherwise, `na`
isSwingPoint(barIdx)
Checks if the previous bars form a swing point
Parameters:
barIdx (int) : The index of the bar to check from (default is 0 for the current bar)
Returns: A SwingPoint object if a swing point is detected; otherwise, `na`
Debugger
A debug logging utility with group support
Fields:
enabled (series bool)
_debugGroupStack (array)
Session
Defines a trading session with a name and time range. When creating a new instance of this type, you MUST call init() immediately.
Fields:
name (series string) : A display-friendly name (e.g., "NY AM")
session (series string) : A string defining the session time range (e.g., "1300-1400")
enabled (series bool) : Optional flag for custom logic; defaults to false
start (series int) : UNIX time representing the session start (set via isActive())
end (series int) : UNIX time representing the session end (set via isActive())
_t (series int)
_start_HH (series float)
_start_mm (series float)
_end_HH (series float)
_end_mm (series float)
Gap
Represents a price inefficiency (gap) with details on sentiment and price levels
Fields:
type (series SentimentType) : The sentiment of the gap (e.g., SentimentType.BULLISH)
name (series string) : A display-friendly name (e.g., "+FVG")
startTime (series int) : UNIX time value for the gap's start
endTime (series int) : UNIX time value for the gap's end
startIndex (series int) : Bar index where the gap starts
endIndex (series int) : Bar index where the gap ends
gapLow (series float) : The lowest price level of the gap
gapHigh (series float) : The highest price level of the gap
ce (series float) : The consequent encroachment level of the gap
SwingPoint
Represents a swing point with details on type and price level
Fields:
type (series SwingPointType) : The type of swing point (e.g., SwingPointType.HIGH)
time (series int) : UNIX time value for the swing point
barIdx (series int) : Bar index where the swing point occurs
price (series float) : The price level of the swing point which is either the high or low of the middle bar
LineLabel
Combines a line and box type to produce a line with a label that is properly aligned
Fields:
x (series int) : The X-axis starting point as a bar index
y (series float) : The Y-axis starting point as the price level
color (series color) : Both the line and text color
width (series int) : Thickness of the line
label (series string) : Text to display
showLabel (series bool) : Boolean to conditionally show/hide the label (default is false)
lineStyle (series LineStyleType) : The style of the line
textSize (series TextSizeType)
_b (series box)
_l (series line)
Penunjuk dan strategi
ICTHL_PublicLibrary "ICTSwingsPublic"
f_ictSwings(leftStrength, rightStrength, maxLines, highColor, lowColor)
Parameters:
leftStrength (int)
rightStrength (int)
maxLines (int)
highColor (color)
lowColor (color)
SMC_CommonLibrary "SMC_Common"
Common types and utilities for Smart Money Concepts indicators
get_future_time(bars_ahead)
Parameters:
bars_ahead (int)
get_time_at_offset(offset)
Parameters:
offset (int)
get_mid_time(time1, time2)
Parameters:
time1 (int)
time2 (int)
timeframe_to_string(tf)
Parameters:
tf (string)
is_psychological_level(price)
Parameters:
price (float)
detect_swing_high(src_high, lookback)
Parameters:
src_high (float)
lookback (int)
detect_swing_low(src_low, lookback)
Parameters:
src_low (float)
lookback (int)
detect_fvg(h, l, min_size)
Parameters:
h (float)
l (float)
min_size (float)
analyze_volume(vol, volume_ma)
Parameters:
vol (float)
volume_ma (float)
create_label(x, y, label_text, bg_color, label_size, use_time)
Parameters:
x (int)
y (float)
label_text (string)
bg_color (color)
label_size (string)
use_time (bool)
SwingPoint
Fields:
price (series float)
bar_index (series int)
bar_time (series int)
swing_type (series string)
strength (series int)
is_major (series bool)
timeframe (series string)
LiquidityLevel
Fields:
price (series float)
bar_index (series int)
bar_time (series int)
liq_type (series string)
touch_count (series int)
is_swept (series bool)
quality_score (series float)
level_type (series string)
OrderBlock
Fields:
start_bar (series int)
end_bar (series int)
start_time (series int)
end_time (series int)
top (series float)
bottom (series float)
ob_type (series string)
has_liquidity_sweep (series bool)
has_fvg (series bool)
is_mitigated (series bool)
is_breaker (series bool)
timeframe (series string)
mitigation_level (series float)
StructureBreak
Fields:
level (series float)
break_bar (series int)
break_time (series int)
break_type (series string)
direction (series string)
is_confirmed (series bool)
source_swing_bar (series int)
source_time (series int)
SignalData
Fields:
signal_type (series string)
entry_price (series float)
stop_loss (series float)
take_profit (series float)
risk_reward_ratio (series float)
confluence_count (series int)
confidence_score (series float)
strength (series string)
SITFX_FuturesSpec_v17SITFX_FuturesSpec_v17 – Universal Futures Contract Library
Full-scale futures contract specification library for Pine Script v6. Covers CME, CBOT, NYMEX, COMEX, CFE, Eurex, ICE, and more – including minis, micros, metals, energies, FX, and bonds.
Key Features:
✅ Instrument‑agnostic: ES/MES, NQ/MNQ, YM/MYM, RTY/M2K, metals, energies, FX, bonds
✅ Full contract data: Tick size, tick value, point value, margins
✅ Continuation‑safe: Single‑line logic, no arrays or continuation errors
✅ Foundation for SITFX tools: Gann, Fibs, structure, and risk modules
Usage example:
import SITFX_FuturesSpec_v17/1 as fs
spec = fs.get(syminfo.root)
label.new(bar_index, high, str.format("{0}: Tick={1}, Value=${2}", spec.name, spec.tickSize, spec.tickValue))
BestTimeFrameFinderLibrary "BestTimeFrameFinder"
adx(len)
Parameters:
len (simple int)
atrPercent(len)
Parameters:
len (simple int)
scaleFromTf(tf, atrWeight)
Parameters:
tf (string)
atrWeight (simple float)
scoreLocal(adxLen, atrLen, scale)
Parameters:
adxLen (simple int)
atrLen (simple int)
scale (simple float)
maxInArray(arr)
Parameters:
arr (array)
TFPS_EngineLibrary "TFPS_Engine"
f_calculate_lead_lag(series1, series2, length, max_lag)
Parameters:
series1 (float)
series2 (float)
length (int)
max_lag (int)
f_calculate_pressure_score(spx_ticker, vix_ticker, dxy_ticker, us10y_ticker, benchmark_source, trend_lookback, score_smoothing, use_dynamic_weights, corr_lookback, w_spx, w_vix, w_dxy, w_us10y, zscore_lookback, max_lag)
Parameters:
spx_ticker (string)
vix_ticker (string)
dxy_ticker (string)
us10y_ticker (string)
benchmark_source (float)
trend_lookback (int)
score_smoothing (simple int)
use_dynamic_weights (bool)
corr_lookback (int)
w_spx (float)
w_vix (float)
w_dxy (float)
w_us10y (float)
zscore_lookback (int)
max_lag (int)
LeadLagOutput
Fields:
best_lag (series int)
max_corr (series float)
TFPS_Output
Fields:
historical_score (series float)
smoothed_score (series float)
z_score (series float)
regime_signal (series int)
lead_lag_bars (series int)
lead_lag_corr (series float)
weight_spx (series float)
weight_vix (series float)
weight_dxy (series float)
weight_us10y (series float)
FunctionADFLibrary "FunctionADF"
Augmented Dickey-Fuller test (ADF), The ADF test is a statistical method used to assess whether a time series is stationary – meaning its statistical properties (like mean and variance) do not change over time. A time series with a unit root is considered non-stationary and often exhibits non-mean-reverting behavior, which is a key concept in technical analysis.
Reference:
-
- rtmath.net
- en.wikipedia.org
adftest(data, n_lag, conf)
: Augmented Dickey-Fuller test for stationarity.
Parameters:
data (array) : Data series.
n_lag (int) : Maximum lag.
conf (string) : Confidence Probability level used to test for critical value, (`90%`, `95%`, `99%`).
Returns: `adf` The test statistic. \
`crit` Critical value for the test statistic at the 10 % levels. \
`nobs` Number of observations used for the ADF regression and calculation of the critical values.
BarUtils: Get Bar Index from DateLibrary "BarUtils"
getBarIndexFromDate(targetTimestamp)
Parameters:
targetTimestamp (int)
**Description**:
This utility provides a reliable way to calculate the `bar_index` of a specific calendar date, regardless of chart resolution. It's especially useful for anchoring scripts to historical events, labeling macroeconomic moments, or marking custom time-based signals that must remain consistent across timeframes.
Unlike hardcoded `bar_index - N` approaches, this function dynamically estimates the number of bars between a given `timestamp()` and the current bar using the actual time-per-bar (`time - time `). It works correctly on intraday, daily, weekly, and monthly charts.
### 💡 **Function Provided**:
import TradeTitan120/BarUtils/1
* `getBarIndexFromDate(int targetTimestamp)`
→ Returns the estimated `bar_index` that aligns with a given timestamp
### ✅ **Use Cases**:
* Marking past events like FOMC meetings, market crashes, or personal signals
* Backtesting entry/exit conditions from specific calendar dates
* Anchoring visual elements (shapes, lines, labels) across resolutions
This tool is simple, fast, and built for accuracy. Use it to enhance multi-timeframe compatibility in any script.
lib_listaAtivos_PosseidonLibrary "lib_listaAtivos_Posseidon"
TODO: add library description here
ativos(loteSelected)
TODO: add function description here
Parameters:
loteSelected (simple int)
Returns: TODO: add what function returns
PulseLogicLibPulseLogicLib v3.6.1
PulseLogic breath-strength & momentum-structure calculator
Exports:
• getBreathScore() → int (0–100)
• hasGreenDot() → bool
• getTriangleColor() → string (“green”/“red”/“none”)
PulseLinesLibPulseLinesLib v1.3.1
PulseLines morphic-level calculator (support & resistance)
Exports:
• getLevels(lookback:int, wickRatioThresh:float, flatCandles:int, tolerancePips:float, atrMult:float) → float
hudDisplay_v1Library "hudDisplay_v1"
f_getPosition(loc)
Parameters:
loc (string)
f_getTableSize(layout, itemCount)
Parameters:
layout (string)
itemCount (int)
f_getCellPosition(layout, index)
Parameters:
layout (string)
index (int)
f_drawHUD(show, loc, layout, content, textColor, bgColor)
Parameters:
show (bool)
loc (string)
layout (string)
content (array)
textColor (color)
bgColor (color)
TrailingStopLibraryLibrary "TrailingStopLibrary"
专业移动止盈库 - 为Pine Script策略提供完整的追踪止盈功能。支持做多做空双向交易,基于风险回报比智能激活,提供收盘价和高低价两种判断模式。包含完整的状态管理、调试信息和易用的API接口。适用于股票、外汇、加密货币等各种市场的风险管理。
@version 1.0
@author runto2006
new_config(enabled, activation_ratio, pullback_percent, price_type)
创建移动止盈配置对象
Parameters:
enabled (bool) : (bool) 是否启用移动止盈,默认true
activation_ratio (float) : (float) 激活盈亏比,默认4.0,表示盈利4倍止损距离时激活
pullback_percent (float) : (float) 回撤百分比,默认1.0,表示回撤1%时触发止盈
price_type (string) : (string) 价格类型,默认"close"。"close"=收盘价模式,"hl"=高低价模式
Returns: Config 配置对象
new_state()
创建移动止盈状态对象
Returns: State 初始化的状态对象
reset(state)
重置移动止盈状态
Parameters:
state (State) : (State) 要重置的状态对象
Returns: void
calc_activation_target(entry_price, stop_price, activation_ratio, is_long)
计算激活目标价格
Parameters:
entry_price (float) : (float) 入场价格
stop_price (float) : (float) 止损价格
activation_ratio (float) : (float) 激活盈亏比
is_long (bool) : (bool) 是否为多头持仓
Returns: float 激活目标价格,如果输入无效则返回na
get_check_price(price_type, is_long, for_activation)
获取用于判断的价格
Parameters:
price_type (string) : (string) 价格类型:"close"或"hl"
is_long (bool) : (bool) 是否为多头持仓
for_activation (bool) : (bool) 是否用于激活判断,影响高低价的选择方向
Returns: float 当前判断价格
check_activation(config, state, entry_price, stop_price, is_long, has_position)
检查是否应该激活移动止盈
Parameters:
config (Config) : (Config) 移动止盈配置
state (State) : (State) 移动止盈状态
entry_price (float) : (float) 入场价格
stop_price (float) : (float) 止损价格
is_long (bool) : (bool) 是否为多头持仓
has_position (bool) : (bool) 是否有持仓
Returns: bool 是否成功激活
update_tracking(config, state, is_long)
更新移动止盈的追踪价格
Parameters:
config (Config) : (Config) 移动止盈配置
state (State) : (State) 移动止盈状态
is_long (bool) : (bool) 是否为多头持仓
Returns: void
check_trigger(config, state, entry_price, is_long)
检查是否触发移动止盈
Parameters:
config (Config) : (Config) 移动止盈配置
state (State) : (State) 移动止盈状态
entry_price (float) : (float) 入场价格
is_long (bool) : (bool) 是否为多头持仓
Returns: bool 是否触发止盈
process(config, state, entry_price, stop_price, is_long, has_position)
一体化处理移动止盈逻辑
Parameters:
config (Config) : (Config) 移动止盈配置
state (State) : (State) 移动止盈状态
entry_price (float) : (float) 入场价格
stop_price (float) : (float) 止损价格
is_long (bool) : (bool) 是否为多头持仓
has_position (bool) : (bool) 是否有持仓
Returns: bool 是否触发止盈
get_trigger_price(config, state, is_long)
获取当前触发价格
Parameters:
config (Config) : (Config) 移动止盈配置
state (State) : (State) 移动止盈状态
is_long (bool) : (bool) 是否为多头持仓
Returns: float 触发价格,未激活时返回na
get_pullback_percent(config, state, entry_price, is_long)
计算当前回撤百分比
Parameters:
config (Config) : (Config) 移动止盈配置
state (State) : (State) 移动止盈状态
entry_price (float) : (float) 入场价格
is_long (bool) : (bool) 是否为多头持仓
Returns: float 当前回撤百分比,未激活时返回na
get_status_info(config, state, entry_price, is_long)
获取状态信息字符串(用于调试)
Parameters:
config (Config) : (Config) 移动止盈配置
state (State) : (State) 移动止盈状态
entry_price (float) : (float) 入场价格
is_long (bool) : (bool) 是否为多头持仓
Returns: string 详细的状态信息
Config
移动止盈配置对象
Fields:
enabled (series bool) : (bool) 是否启用移动止盈功能
activation_ratio (series float) : (float) 激活盈亏比 - 盈利达到止损距离的多少倍时激活追踪
pullback_percent (series float) : (float) 回撤百分比 - 从最优价格回撤多少百分比时触发止盈
price_type (series string) : (string) 价格判断类型 - "close"使用收盘价,"hl"使用高低价
State
移动止盈状态对象
Fields:
activated (series bool) : (bool) 是否已激活追踪止盈
highest_price (series float) : (float) 激活后记录的最高价格
lowest_price (series float) : (float) 激活后记录的最低价格
activation_target (series float) : (float) 激活目标价格
PivotLibrary222Library "PivotLibrary222"
f_determinePivotStrength(_pivotCandidateRelativeIndex, _type, _maxStrength)
Determines the strength of a pivot (low or high).
Parameters:
_pivotCandidateRelativeIndex (int) : The relative bar index of the pivot candidate.
_type (string) : "low" for a pivot low, "high" for a pivot high.
_maxStrength (int) : The maximum number of bars to check on either side for strength.
Returns: An array containing .
f_getPlotColorForStrength(_strength)
Gets a plotting color based on pivot strength.
Parameters:
_strength (int) : The calculated pivot strength.
Returns: A color for plotting.
f_updateExistingPivotLow(f_pivotLows, f_pivotLowInfoIndex, f_newStrength, f_showLabels)
Updates an existing pivot LOW's strength and its corresponding chart label.
Parameters:
f_pivotLows (array) : The array of pivotLowInfo objects.
f_pivotLowInfoIndex (int) : The index of the pivot to update in the array.
f_newStrength (int) : The new (increased) strength of the pivot.
f_showLabels (bool) : A boolean to control if labels should be updated.
f_updateExistingPivotHigh(f_pivotHighs, f_pivotHighInfoIndex, f_newStrength, f_showLabels)
Updates an existing pivot HIGH's strength and its corresponding chart label.
Parameters:
f_pivotHighs (array) : The array of pivotHighInfo objects.
f_pivotHighInfoIndex (int) : The index of the pivot to update in the array.
f_newStrength (int) : The new (increased) strength of the pivot.
f_showLabels (bool) : A boolean to control if labels should be updated.
f_findPivotLows(f_pivotLows, f_minStrength, f_maxStrength, f_showLabels)
Finds and processes pivot lows.
Parameters:
f_pivotLows (array) : The array of pivotLowInfo objects to read from and modify.
f_minStrength (int) : Minimum strength required for a new pivot to be recorded.
f_maxStrength (int) : Maximum strength to search for when determining pivot strength.
f_showLabels (bool) : A boolean to control if new labels should be created.
f_findPivotHighs(f_pivotHighs, f_minStrength, f_maxStrength, f_showLabels)
Finds and processes pivot highs.
Parameters:
f_pivotHighs (array) : The array of pivotHighInfo objects to read from and modify.
f_minStrength (int) : Minimum strength required for a new pivot to be recorded.
f_maxStrength (int) : Maximum strength to search for when determining pivot strength.
f_showLabels (bool) : A boolean to control if new labels should be created.
pivotHighInfo
Represents a detected pivot high.
Fields:
abs_index (series int)
price (series float)
strength (series int)
label_id (series label)
pivotLowInfo
Represents a detected pivot low.
Fields:
abs_index (series int)
price (series float)
strength (series int)
label_id (series label)
DoublePatternsDetects Double Top and Double Bottom patterns from pivot points using structural symmetry, valley/peak depth, and extreme validation. Returns a detailed result object including similarity score, target price, and breakout quality.
WedgePatternsDetects Rising and Falling Wedge chart patterns using pivot points, trendline convergence, and volume confirmation. Includes adaptive wedge length analysis and a quality score for each match. Returns full wedge geometry and classification via WedgeResult.
HeadShouldersPatternsDetects Head & Shoulders and Inverse Head & Shoulders chart patterns from pivot point arrays. Includes neckline validation, shoulder symmetry checks, and head extremeness filtering. Returns a detailed result object with structure points, bar indices, and projected price target.
XABCD_HarmonicsLibrary for detecting harmonic patterns using ZigZag pivots or custom swing points. Supports Butterfly, Gartley, Bat, and Crab patterns with automatic Fibonacci ratio validation and optional D-point projection using extremes. Returns detailed PatternResult including structure points and target projection. Ideal for technical analysis, algorithmic detection, or overlay visualizations.
TextLibrary "Text"
library to format text in different fonts or cases plus a sort function.
🔸 Credits and Usage
This library is inspired by the work of three authors (in chronological order of publication date):
Unicode font function - JD - Duyck
UnicodeReplacementFunction - wlhm
font - kaigouthro
🔹 Fonts
Besides extra added font options, the toFont(fromText, font) method uses a different technique. On the first runtime bar (whether it is barstate.isfirst , barstate.islast , or between) regular letters and numbers and mapped with the chosen font. After this, each character is replaced using the build-in key - value pair map function .
Also an enum Efont is included.
Note: Some fonts are not complete, for example there isn't a replacement for every character in Superscript/Subscript.
Example of usage (besides the included table example):
import fikira/Text/1 as t
i_font = input.enum(t.Efont.Blocks)
if barstate.islast
sentence = "this sentence contains words"
label.new(bar_index, 0, t.toFont(fromText = sentence, font = str.tostring(i_font)), style=label.style_label_lower_right)
label.new(bar_index, 0, t.toFont(fromText = sentence, font = "Circled" ), style=label.style_label_lower_left )
label.new(bar_index, 0, t.toFont(fromText = sentence, font = "Wiggly" ), style=label.style_label_upper_right)
label.new(bar_index, 0, t.toFont(fromText = sentence, font = "Upside Latin" ), style=label.style_label_upper_left )
🔹 Cases
The script includes a toCase(fromText, case) method to transform text into snake_case, UPPER SNAKE_CASE, kebab-case, camelCase or PascalCase, as well as an enum Ecase .
Example of usage (besides the included table example):
import fikira/Text/1 as t
i_case = input.enum(t.Ecase.camel)
if barstate.islast
sentence = "this sentence contains words"
label.new(bar_index, 0, t.toCase(fromText = sentence, case = str.tostring(i_case)), style=label.style_label_lower_right)
label.new(bar_index, 0, t.toCase(fromText = sentence, case = "snake_case" ), style=label.style_label_lower_left )
label.new(bar_index, 0, t.toCase(fromText = sentence, case = "PascalCase" ), style=label.style_label_upper_right)
label.new(bar_index, 0, t.toCase(fromText = sentence, case = "SNAKE_CASE" ), style=label.style_label_upper_left )
🔹 Sort
The sort(strings, order, sortByUnicodeDecimalNumbers) method returns a sorted array of strings.
strings: array of strings, for example words = array.from("Aword", "beyond", "Space", "salt", "pepper", "swing", "someThing", "otherThing", "12345", "_firstWord")
order: "asc" / "desc" (ascending / descending)
sortByUnicodeDecimalNumbers: true/false; default = false
_____
• sortByUnicodeDecimalNumbers: every Unicode character is linked to a Unicode Decimal number ( wikipedia.org/wiki/List_of_Unicode_characters ), for example:
1 49
2 50
3 51
...
A 65
B 66
...
S 83
...
_ 95
` 96
a 97
b 98
...
o 111
p 112
q 113
r 114
s 115
...
This means, if we sort without adjusting ( sortByUnicodeDecimalNumbers = true ), in ascending order, the letter b (98 - small) would be after S (83 - Capital).
By disabling sortByUnicodeDecimalNumbers , Capital letters are intermediate transformed to str.lower() after which the Unicode Decimal number is retrieved from the small number instead of the capital number. For example S (83) -> s (115), after which the number 115 is used to sort instead of 83.
Example of usage (besides the included table example):
import fikira/Text/1 as t
if barstate.islast
aWords = array.from("Aword", "beyond", "Space", "salt", "pepper", "swing", "someThing", "otherThing", "12345", "_firstWord")
label.new(bar_index, 0, str.tostring(t.sort(strings= aWords, order = 'asc' , sortByUnicodeDecimalNumbers = false)), style=label.style_label_lower_right)
label.new(bar_index, 0, str.tostring(t.sort(strings= aWords, order = 'desc', sortByUnicodeDecimalNumbers = false)), style=label.style_label_lower_left )
label.new(bar_index, 0, str.tostring(t.sort(strings= aWords, order = 'asc' , sortByUnicodeDecimalNumbers = true )), style=label.style_label_upper_right)
label.new(bar_index, 0, str.tostring(t.sort(strings= aWords, order = 'desc', sortByUnicodeDecimalNumbers = true )), style=label.style_label_upper_left )
🔸 Methods/functions
method toFont(fromText, font)
toFont : Transforms text into the selected font
Namespace types: series string, simple string, input string, const string
Parameters:
fromText (string)
font (string)
Returns: `fromText` transformed to desired `font`
method toCase(fromText, case)
toCase : formats text to snake_case, UPPER SNAKE_CASE, kebab-case, camelCase or PascalCase
Namespace types: series string, simple string, input string, const string
Parameters:
fromText (string)
case (string)
Returns: `fromText` formatted to desired `case`
method sort(strings, order, sortByUnicodeDecimalNumbers)
sort : sorts an array of strings, ascending/descending and by Unicode Decimal numbers or not.
Namespace types: array
Parameters:
strings (array)
order (string)
sortByUnicodeDecimalNumbers (bool)
Returns: Sorted array of strings
AnnualizedReturnCalculatorLibrary "AnnualizedReturnCalculator"
TODO: add library description here
calculateAnnualizedReturn(isStartTime, enableLog)
Parameters:
isStartTime (bool) : 开始时间的BOOL值变量(用于标记策略开始时间)
enableLog (bool) : 是否输出日志
Returns:
返回持仓基准年化收益率、资金基准年化收益率、总收益、平均资金占用
LiliALHUNTERSystem_v2📚 **Library: LiliALHUNTERSystem_v2**
This library provides a powerful target management system for Pine Script developers.
It includes advanced calculators for EMA, RMA, and Supertrend, and introduces a central `createTargets()` function to dynamically render target lines and labels based on long/short trade logic.
🛠️ **Main Features:**
– Dynamic horizontal & vertical target lines
– Dual target configuration (Target 1 & Target 2)
– Directional logic via `isLong1`, `isLong2`
– Integrated Supertrend validation
– Visual dashboard and label display
– Works seamlessly with custom indicators
🎯 **Purpose:**
The `LiliALHUNTERSystem_v2` Library enables Pine coders to manage and visualize targets consistently across all trading strategies and indicators. It simplifies target logic while maintaining visual clarity and modular usage.
⚠️ **Disclaimer:**
This script is intended for educational and analytical purposes only. It does not constitute financial advice.
Library "LiliALHUNTERSystem_v2"
ema_calc(len, source)
Parameters:
len (simple int)
source (float)
rma_calc(len, source)
Parameters:
len (simple int)
source (float)
supertrend_calc(length, factor)
Parameters:
length (simple int)
factor (float)
createTargets(config, state, source1A, source1B, source2A, source2B)
Parameters:
config (TargetConfig)
state (TargetState)
source1A (float)
source1B (float)
source2A (float)
source2B (float)
showDashboard(state, dashLoc, textSize)
Parameters:
state (TargetState)
dashLoc (string)
textSize (string)
TargetConfig
Fields:
enableTarget1 (series bool)
enableTarget2 (series bool)
isLong1 (series bool)
isLong2 (series bool)
target1Condition (series string)
target2Condition (series string)
target1Color (series color)
target2Color (series color)
target1Style (series string)
target2Style (series string)
distTarget1 (series float)
distTarget2 (series float)
distOptions1 (series string)
distOptions2 (series string)
showLabels (series bool)
showDash (series bool)
TargetState
Fields:
target1LineV (series line)
target1LineH (series line)
target2LineV (series line)
target2LineH (series line)
target1Lbl (series label)
target2Lbl (series label)
target1Active (series bool)
target2Active (series bool)
target1Value (series float)
target2Value (series float)
countTargets1 (series int)
countTgReached1 (series int)
countTargets2 (series int)
countTgReached2 (series int)
SIC_TICKER_DATAThe SIC Ticker Data is an advanced and efficient library for ticker-to-industry classification and sector analysis. Built with enterprise-grade performance optimizations, this library provides instant access to SIC codes, industry classifications, and peer company data for comprehensive market analysis.
Perfect for: Sector rotation strategies, peer analysis, portfolio diversification, market screening, and financial research tools.
The simple idea behind this library is to pull any data related to SIC number of any US stock market ticker provided by SEC in order to see the industry and also see the exact competitors of the ticker.
The library stores 3 types of data: SIC number, Ticker, and Industry name. What makes it very useful is that you can pull any one of this data using the other. For example, if you would like to know which tickers are inside a certain SIC, or what's the SIC number of a specific ticker, or even which tickers are inside a certain industry, you can use this library to pull this data. The idea for data inside this library is to be accessible in any direction possible as long as they're related to each other.
We've also published a simple indicator that uses this library in order to demonstrate the inner workings of this library.
The library stores thousands of tickers and their relevant SIC code and industry for your use and is constantly updated with new data when available. This is a large library but it is optimized to run as fast as possible. The previous unpublished versions would take over 40 seconds to load any data but the final public version here loads the data in less than 5 seconds.
🔍 Primary Lookup Functions
createDataStore()
Initialize the library with all pre-loaded data.
store = data.createDataStore()
getSicByTicker(store, ticker)
Get SIC code for any ticker symbol.
sic = data.getSicByTicker(store, "AAPL") // Returns: "3571"
getIndustryByTicker(store, ticker)
Get industry classification for any ticker.
industry = data.getIndustryByTicker(store, "AAPL") // Returns: "Computer Hardware"
getTickersBySic(store, sic)
Get all companies in a specific SIC code.
software = data.getTickersBySic(store, "7372") // Returns: "MSFT,GOOGL,META,V,MA,CRM,ADBE,ORCL,NOW,INTU"
getTickersByIndustry(store, industry)
Get all companies in an industry.
retail = data.getTickersByIndustry(store, "Retail") // Returns: "AMZN,HD,WMT,TGT,COST,LOW"
📊 Array & Analysis Functions
getTickerArrayBySic(store, sic)
Get tickers as array for processing.
techArray = data.getTickerArrayBySic(store, "7372")
for i = 0 to array.size(techArray) - 1
ticker = array.get(techArray, i)
// Process each tech company
getTickerCountBySic(store, sic)
Count companies in a sector (ultra-fast).
pinescripttechCount = data.getTickerCountBySic(store, "7372") // Returns: 10
🎯 Utility Functions
tickerExists(store, ticker)
Check if ticker exists in database.
exists = data.tickerExists(store, "AAPL") // Returns: true
tickerInSic(store, ticker, sic)
Check if ticker belongs to specific sector.
isInTech = data.tickerInSic(store, "AAPL", "3571") // Returns: true
💡 Usage Examples
Example 1: Basic Ticker Lookup
// @version=6
import EdgeTerminal/SIC_TICKER_DATA/1 as data
indicator("Ticker Analysis", overlay=true)
store = data.createDataStore()
currentSic = data.getSicByTicker(store, syminfo.ticker)
currentIndustry = data.getIndustryByTicker(store, syminfo.ticker)
if barstate.islast and currentSic != "NOT_FOUND"
label.new(bar_index, high, syminfo.ticker + " SIC: " + currentSic + " Industry: " + currentIndustry)
Example 2: Sector Analysis
// @version=6
import EdgeTerminal/SIC_TICKER_DATA/1 as data
indicator("Sector Comparison", overlay=false)
store = data.createDataStore()
// Compare sector sizes
techCount = data.getTickerCountBySic(store, "7372") // Software
financeCount = data.getTickerCountBySic(store, "6199") // Finance
healthCount = data.getTickerCountBySic(store, "2834") // Pharmaceutical
plot(techCount, title="Tech Companies", color=color.blue)
plot(financeCount, title="Finance Companies", color=color.green)
plot(healthCount, title="Health Companies", color=color.red)
Example 3: Peer Analysis
// @version=6
import EdgeTerminal/SIC_TICKER_DATA/1 as data
indicator("Find Competitors", overlay=true)
store = data.createDataStore()
currentSic = data.getSicByTicker(store, syminfo.ticker)
if currentSic != "NOT_FOUND"
competitors = data.getTickersBySic(store, currentSic)
peerCount = data.getTickerCountBySic(store, currentSic)
if barstate.islast
label.new(bar_index, high, "Competitors (" + str.tostring(peerCount) + "): " + competitors)
Example 4: Portfolio Sector Allocation
// @version=6
import EdgeTerminal/SIC_TICKER_DATA/1 as data
indicator("Portfolio Analysis", overlay=false)
store = data.createDataStore()
// Analyze your portfolio's sector distribution
portfolioTickers = array.from("AAPL", "MSFT", "GOOGL", "JPM", "JNJ")
sectorCount = map.new()
for i = 0 to array.size(portfolioTickers) - 1
ticker = array.get(portfolioTickers, i)
industry = data.getIndustryByTicker(store, ticker)
if industry != "NOT_FOUND"
currentCount = map.get(sectorCount, industry)
newCount = na(currentCount) ? 1 : currentCount + 1
map.put(sectorCount, industry, newCount)
🔧 Advanced Feature
You can also bulk load data for large data sets like this:
// Pre-format your data as pipe-separated string
bulkData = "AAPL:3571:Computer Hardware|MSFT:7372:Software|GOOGL:7372:Software"
store = data.createDataStoreFromBulk(bulkData)