NormalizedIndicatorsNormalizedIndicators Library - Comprehensive Trend Normalization & Pre-Calibrated Systems
Overview
The NormalizedIndicators Library is an advanced Pine Script™ collection that provides normalized trend-following indicators, calculation functions, and pre-calibrated consensus systems for technical analysis. This library extends beyond simple indicator normalization by offering battle-tested, optimized parameter sets for specific assets and timeframes.
The main advantage lies in its dual functionality:
Individual normalized indicators with standardized outputs (1 = bullish, -1 = bearish, 0 = neutral)
Pre-calibrated consensus functions that combine multiple indicators with asset-specific optimizations
This enables traders to either build custom strategies using individual indicators or leverage pre-optimized systems designed for specific markets.
📊 Library Structure
The library is organized into three main sections:
1. Trend-Following Indicators
Individual indicators normalized to standard output format
2. Calculation Indicators
Statistical and mathematical analysis functions
3. Pre-Calibrated Systems ⭐ NEW
Asset-specific consensus configurations with optimized parameters
🔄 Trend-Following Indicators
Stationary Indicators
These oscillate around a fixed value and are not bound to price.
TSI() - True Strength Index ⭐ NEW
Source: TradingView
Parameters:
price: Price source
long: Long smoothing period
short: Short smoothing period
signal: Signal line period
Logic: Double-smoothed momentum oscillator comparing TSI to its signal line
Signal:
1 (bullish): TSI ≥ TSI EMA
0 (bearish): TSI < TSI EMA
Use Case: Momentum confirmation with trend direction
SMI() - Stochastic Momentum Index ⭐ NEW
Source: TradingView
Parameters:
src: Price source
lengthK: Stochastic period
lengthD: Smoothing period
lengthEMA: Signal line period
Logic: Enhanced stochastic that measures price position relative to midpoint of high/low range
Signal:
1 (bullish): SMI ≥ SMI EMA
0 (bearish): SMI < SMI EMA
Use Case: Overbought/oversold with momentum direction
BBPct() - Bollinger Bands Percent
Source: Algoalpha X Sushiboi77
Parameters:
Length: Period for Bollinger Bands
Factor: Standard deviation multiplier
Source: Price source (typical: close)
Logic: Calculates the position of price within the Bollinger Bands as a percentage
Signal:
1 (bullish): when positionBetweenBands > 50
-1 (bearish): when positionBetweenBands ≤ 50
Special Feature: Uses an array to store historical standard deviations for additional analysis
RSI() - Relative Strength Index
Source: TradingView
Parameters:
len: RSI period
src: Price source
smaLen: Smoothing period for RSI
Logic: Classic RSI with additional SMA smoothing
Signal:
1 (bullish): RSI-SMA > 50
-1 (bearish): RSI-SMA < 50
0 (neutral): RSI-SMA = 50
Non-Stationary Indicators
These follow price movement and have no fixed boundaries.
NorosTrendRibbonSMA() & NorosTrendRibbonEMA()
Source: ROBO_Trading
Parameters:
Length: Moving average and channel period
Source: Price source
Logic: Creates a price channel based on the highest/lowest MA value over a specified period
Signal:
1 (bullish): Price breaks above upper band
-1 (bearish): Price breaks below lower band
0 (neutral): Price within channel (maintains last state)
Difference: SMA version uses simple moving averages, EMA version uses exponential
TrendBands()
Source: starlord_xrp
Parameters: src (price source)
Logic: Uses 12 EMAs (9-30 period) and checks if all are rising or falling simultaneously
Signal:
1 (bullish): All 12 EMAs are rising
-1 (bearish): All 12 EMAs are falling
0 (neutral): Mixed signals
Special Feature: Very strict conditions - extremely strong trend filter
Vidya() - Variable Index Dynamic Average
Source: loxx
Parameters:
source: Price source
length: Main period
histLength: Historical period for volatility calculation
Logic: Adaptive moving average that adjusts to volatility
Signal:
1 (bullish): VIDYA is rising
-1 (bearish): VIDYA is falling
VZO() - Volume Zone Oscillator
Parameters:
source: Price source
length: Smoothing period
volumesource: Volume data source
Logic: Combines price and volume direction, calculates the ratio of directional volume to total volume
Signal:
1 (bullish): VZO > 14.9
-1 (bearish): VZO < -14.9
0 (neutral): VZO between -14.9 and 14.9
TrendContinuation()
Source: AlgoAlpha
Parameters:
malen: First HMA period
malen1: Second HMA period
theclose: Price source
Logic: Uses two Hull Moving Averages for trend assessment with neutrality detection
Signal:
1 (bullish): Uptrend without divergence
-1 (bearish): Downtrend without divergence
0 (neutral): Trend and longer MA diverge
LeonidasTrendFollowingSystem()
Source: LeonidasCrypto
Parameters:
src: Price source
shortlen: Short EMA period
keylen: Long EMA period
Logic: Simple dual EMA crossover system
Signal:
1 (bullish): Short EMA < Key EMA
-1 (bearish): Short EMA ≥ Key EMA
ysanturtrendfollower()
Source: ysantur
Parameters:
src: Price source
depth: Depth of Fibonacci weighting
smooth: Smoothing period
bias: Percentage bias adjustment
Logic: Complex system with Fibonacci-weighted moving averages and bias bands
Signal:
1 (bullish): Weighted MA > smoothed MA (with upward bias)
-1 (bearish): Weighted MA < smoothed MA (with downward bias)
0 (neutral): Within bias zone
TRAMA() - Trend Regularity Adaptive Moving Average
Source: LuxAlgo
Parameters:
src: Price source
length: Adaptation period
Logic: Adapts to trend regularity - accelerates in stable trends, slows in consolidations
Signal:
1 (bullish): Price > TRAMA
-1 (bearish): Price < TRAMA
0 (neutral): Price = TRAMA
HullSuite()
Source: InSilico
Parameters:
_length: Base period
src: Price source
_lengthMult: Length multiplier
Logic: Uses Hull Moving Average with lagged comparisons for trend determination
Signal:
1 (bullish): Current Hull > Hull 2 bars ago
-1 (bearish): Current Hull < Hull 2 bars ago
0 (neutral): No change
STC() - Schaff Trend Cycle
Source: shayankm (described as "Better MACD")
Parameters:
length: Cycle period
fastLength: Fast MACD period
slowLength: Slow MACD period
src: Price source
Logic: Combines MACD concepts with stochastic normalization for early trend signals
Signal:
1 (bullish): STC is rising
-1 (bearish): STC is falling
🧮 Calculation Indicators
These functions provide specialized mathematical calculations for advanced analysis.
LCorrelation() - Long-term Correlation
Creator: unicorpusstocks
Parameters:
Input: First time series
Compare: Second time series
Logic: Calculates the average of correlations across 6 different periods (30, 60, 90, 120, 150, 180)
Returns: Correlation value between -1 and 1
Application: Long-term relationship analysis between assets, markets, or indicators
MCorrelation() - Medium-term Correlation
Creator: unicorpusstocks
Parameters:
Input: First time series
Compare: Second time series
Logic: Calculates the average of correlations across 6 different periods (15, 30, 45, 60, 75, 90)
Returns: Correlation value between -1 and 1
Application: Medium-term relationship analysis with higher sensitivity
assetBeta() - Beta Coefficient
Creator: unicorpusstocks
Parameters:
measuredSymbol: The asset to be measured
baseSymbol: The reference asset (e.g., market index)
Logic:
Calculates Beta across 4 different time horizons (50, 100, 150, 200 periods)
Beta = Correlation × (Asset Standard Deviation / Market Standard Deviation)
Returns the average of all 4 Beta values
Returns: Beta value (typically 0-2, can be higher/lower)
Interpretation:
Beta = 1: Asset moves in sync with the market
Beta > 1: Asset more volatile than market
Beta < 1: Asset less volatile than market
Beta < 0: Asset moves inversely to the market
🎯 Pre-Calibrated Systems ⭐ NEW FEATURE
These are ready-to-use consensus functions with optimized parameters for specific assets and timeframes. Each calibration has been fine-tuned through extensive backtesting to provide optimal performance for its target market.
Universal Calibrations
virtual_4d_cal(src) - Virtual/General 4-Day Timeframe
Use Case: General purpose 4-day chart analysis
Optimized For: Broad crypto market on 4D timeframe
Indicators Used: BBPct, Noro's, RSI, VIDYA, HullSuite, TrendContinuation, Leonidas, TRAMA
Characteristics: Balanced sensitivity for swing trading
virtual_1d_cal(src) - Virtual/General 1-Day Timeframe
Use Case: General purpose daily chart analysis
Optimized For: Broad crypto market on 1D timeframe
Indicators Used: BBPct, Noro's, RSI, VIDYA, HullSuite, TrendContinuation, Leonidas, TRAMA
Characteristics: Standard daily trading parameters
Cryptocurrency Specific
sui_cal(src) - SUI Ecosystem Tokens
Use Case: Tokens in the SUI blockchain ecosystem
Timeframe: 1D
Characteristics: Fast-response parameters for high volatility projects
deep_1d_cal(src) - DEEP Token Daily
Use Case: Deepbook (DEEP) token analysis
Timeframe: 1D
Characteristics: Tuned for liquidity protocol token behavior
wal_1d_cal(src) - WAL Token Daily
Use Case: Specific for WAL token
Timeframe: 1D
Characteristics: Mid-range sensitivity parameters
sns_1d_cal(src) - SNS Token Daily
Use Case: Specific for SNS token
Timeframe: 1D
Characteristics: Balanced parameters for DeFi tokens
meme_cal(src) - Meme Coin Calibration
Use Case: Highly volatile meme coins
Timeframe: Various
Characteristics: Wider parameters to handle extreme volatility
Warning: Meme coins carry extreme risk
base_cal(src) - BASE Ecosystem Tokens
Use Case: Tokens on the BASE blockchain
Timeframe: Various
Characteristics: Optimized for L2 ecosystem tokens
Solana Ecosystem
sol_4d_cal(src) - Solana 4-Day
Use Case: SOL token on 4-day charts
Characteristics: Responsive parameters for major L1 blockchain
sol_meme_4d_cal(src) - Solana Meme Coins 4-Day
Use Case: Meme coins on Solana blockchain
Timeframe: 4D
Characteristics: Handles high volatility of Solana meme sector
Ethereum Ecosystem
eth_4d_cal(src) - Ethereum 4-Day
Use Case: ETH and major ERC-20 tokens
Timeframe: 4D
Indicators Used: BBPct, Noro's, RSI, TSI, HullSuite, TrendContinuation, Leonidas, SMI
Special: Uses TSI and SMI instead of VIDYA and TRAMA
Characteristics: Tuned for Ethereum's market cycles
Bitcoin
btc_4d_cal(src) - Bitcoin 4-Day
Use Case: Bitcoin on 4-day charts
Timeframe: 4D
Characteristics: Slower, smoother parameters for the most established crypto asset
Notes: Conservative parameters suitable for position trading
Traditional Markets
qqq_4d_cal(src) - QQQ (Nasdaq-100 ETF) 4-Day
Use Case: QQQ ETF and tech-heavy indices
Timeframe: 4D
Characteristics: Largest parameter sets reflecting lower volatility of traditional markets
Notes: Can be adapted for similar large-cap tech indices
💡 Usage Examples
Example 1: Using Pre-Calibrated System
pinescriptimport unicorpusstocks/NormalizedIndicators/1 as lib
// Simple one-line implementation for Bitcoin
btcSignal = lib.btc_4d_cal(close)
// Trading logic
longCondition = btcSignal > 0.5
shortCondition = btcSignal < -0.5
// Plot
plot(btcSignal, "BTC 4D Consensus", color.orange)
Example 2: Custom Multi-Indicator Consensus
pinescriptimport unicorpusstocks/NormalizedIndicators/1 as lib
// Build your own combination
signal1 = lib.BBPct(20, 2.0, close)
signal2 = lib.RSI(14, close, 5)
signal3 = lib.TRAMA(close, 50)
signal4 = lib.TSI(close, 25, 13, 13)
// Custom consensus
customConsensus = math.avg(signal1, signal2, signal3, signal4)
plot(customConsensus, "Custom Consensus", color.blue)
Example 3: Asset-Specific Strategy Switching
pinescriptimport unicorpusstocks/NormalizedIndicators/1 as lib
// Automatically use the right calibration
signal = switch syminfo.ticker
"BTCUSD" => lib.btc_4d_cal(close)
"ETHUSD" => lib.eth_4d_cal(close)
"SOLUSD" => lib.sol_4d_cal(close)
"QQQ" => lib.qqq_4d_cal(close)
=> lib.virtual_4d_cal(close) // Default
plot(signal, "Auto-Calibrated Signal", color.orange)
Example 4: Correlation-Filtered Trading
pinescriptimport unicorpusstocks/NormalizedIndicators/1 as lib
// Only trade when strong correlation with market exists
spy = request.security("SPY", timeframe.period, close)
correlation = lib.MCorrelation(close, spy)
trendSignal = lib.virtual_1d_cal(close)
// Only signals with positive market correlation
tradeBuy = trendSignal > 0.5 and correlation > 0.5
tradeSell = trendSignal < -0.5 and correlation > 0.5
Example 5: Beta-Adjusted Position Sizing
pinescriptimport unicorpusstocks/NormalizedIndicators/1 as lib
spy = request.security("SPY", timeframe.period, close)
beta = lib.assetBeta(close, spy)
// Adjust position size based on Beta
basePositionSize = 100
adjustedSize = basePositionSize / beta // Less size with high Beta
// Use with calibrated signal
signal = lib.qqq_4d_cal(close)
🎯 Choosing the Right Calibration
Decision Tree
1. What asset are you trading?
Bitcoin → btc_4d_cal()
Ethereum/ERC-20 → eth_4d_cal()
Solana → sol_4d_cal()
Solana memes → sol_meme_4d_cal()
SUI ecosystem → sui_cal()
BASE ecosystem → base_cal()
Meme coins (any chain) → meme_cal()
QQQ/Tech indices → qqq_4d_cal()
Other/General → virtual_4d_cal() or virtual_1d_cal()
2. What timeframe?
Most calibrations are optimized for 4D (4-day) or 1D (daily)
For other timeframes, start with virtual calibrations and adjust
3. What's the asset's volatility?
High volatility (memes, new tokens) → Use meme_cal() or similar
Medium volatility (established alts) → Use specific calibrations
Low volatility (BTC, major indices) → Use btc_4d_cal() or qqq_4d_cal()
⚙️ Technical Details
Normalization Standard
Bullish: 1
Bearish: -1
Neutral: 0 (only for selected indicators)
Calibration Methodology
Pre-calibrated functions were optimized using:
Historical backtesting on target assets
Parameter optimization for maximum Sharpe ratio
Validation on out-of-sample data
Real-time forward testing
Iterative refinement based on market conditions
Advantages of Pre-Calibrations
Instant Deployment: No parameter tuning needed
Asset-Optimized: Tailored to specific market characteristics
Tested Performance: Validated through extensive backtesting
Consistent Framework: All use the same 8-indicator structure
Easy Comparison: Compare different assets using same methodology
Performance Considerations
All functions are optimized for Pine Script v5
Proper use of var for state management
Efficient array operations where needed
Minimal recursive calls
Pre-calibrations add negligible computational overhead
📋 License
This code is subject to the Mozilla Public License 2.0 at mozilla.org
🔧 Installation
pinescriptimport unicorpusstocks/NormalizedIndicators/1
Then use functions with your chosen alias:
pinescript// Individual indicators
lib.BBPct(20, 2.0, close)
lib.RSI(14, close, 5)
lib.TSI(close, 25, 13, 13)
// Pre-calibrated systems
lib.btc_4d_cal(close)
lib.eth_4d_cal(close)
lib.meme_cal(close)
⚠️ Important Notes
General Usage
All indicators are lagging, as is typical for trend-following indicators
Signals should be combined with additional analysis (volume, support/resistance, etc.)
Backtesting is recommended before starting live trading with these signals
Different assets and timeframes may require different parameter optimizations
Pre-Calibrated Systems
Calibrations are optimized for specific timeframes - using them on different timeframes may reduce effectiveness
Market conditions change - what worked historically may need adjustment
Pre-calibrations are starting points, not guaranteed solutions
Always validate performance on your specific use case
Consider current market regime (trending vs. ranging)
Risk Management
Meme coin calibrations are designed for extremely volatile assets - use appropriate position sizing
Pre-calibrated systems do not eliminate risk
Always use stop losses and proper risk management
Past performance does not guarantee future results
Customization
Pre-calibrations can serve as templates for your own optimizations
Feel free to adjust individual parameters within calibration functions
Test modifications thoroughly before live deployment
🎓 Advanced Use Cases
Multi-Asset Portfolio Dashboard
Create a dashboard showing consensus across different assets:
pinescriptimport unicorpusstocks/NormalizedIndicators/1 as lib
btc = request.security("BTCUSD", "4D", close)
eth = request.security("ETHUSD", "4D", close)
sol = request.security("SOLUSD", "4D", close)
btcSignal = lib.btc_4d_cal(btc)
ethSignal = lib.eth_4d_cal(eth)
solSignal = lib.sol_4d_cal(sol)
// Plot all three for comparison
plot(btcSignal, "BTC", color.orange)
plot(ethSignal, "ETH", color.blue)
plot(solSignal, "SOL", color.purple)
Regime Detection
Use correlation and calibrations together:
pinescriptimport unicorpusstocks/NormalizedIndicators/1 as lib
// Detect market regime
btc = request.security("BTCUSD", timeframe.period, close)
correlation = lib.MCorrelation(close, btc)
// Choose strategy based on correlation
signal = correlation > 0.7 ? lib.btc_4d_cal(close) : lib.virtual_4d_cal(close)
Comparative Analysis
Compare asset-specific vs. general calibrations:
pinescriptimport unicorpusstocks/NormalizedIndicators/1 as lib
specificSignal = lib.btc_4d_cal(close) // BTC-specific
generalSignal = lib.virtual_4d_cal(close) // General
divergence = specificSignal - generalSignal
plot(divergence, "Calibration Divergence", color.yellow)
🚀 Quick Start Guide
For Beginners
Identify Your Asset: What are you trading?
Find the Calibration: Use the decision tree above
One-Line Implementation: signal = lib.btc_4d_cal(close)
Set Thresholds: Buy when > 0.5, sell when < -0.5
Add Risk Management: Always use stops
For Advanced Users
Start with Pre-Calibration: Use as baseline
Analyze Performance: Backtest on your specific market
Fine-Tune Parameters: Adjust individual indicators if needed
Combine with Other Signals: Volume, market structure, etc.
Create Custom Calibrations: Build your own based on library structure
For Developers
Import Library: Access all functions
Mix and Match: Combine indicators creatively
Build Custom Logic: Use indicators as building blocks
Create New Calibrations: Follow the established pattern
Share and Iterate: Contribute to the trading community
🎯 Key Takeaways
✅ 10 normalized indicators - Consistent interpretation across all
✅ 16+ pre-calibrated systems - Ready-to-use for specific assets
✅ Asset-optimized parameters - No guesswork required
✅ Calculation functions - Advanced correlation and beta analysis
✅ Universal framework - Works across crypto, stocks, forex
✅ Professional-grade - Built on proven technical analysis principles
✅ Flexible architecture - Use pre-calibrations or build your own
✅ Battle-tested - Validated through extensive backtesting
NormalizedIndicators Library transforms complex multi-indicator analysis into actionable signals through both customizable individual indicators and pre-optimized consensus systems. Whether you're a beginner looking for plug-and-play solutions or an advanced trader building sophisticated strategies, this library provides the foundation for data-driven trading decisions.WiederholenClaude kann Fehler machen. Bitte überprüfen Sie die Antworten. Sonnet 4.5
Strategies
NormalizedIndicatorsNormalizedIndicators - Comprehensive Trend Normalization Library
Overview
This Pine Script™ library provides an extensive collection of normalized trend-following indicators and calculation functions for technical analysis. The main advantage of this library lies in its unified signal output: All trend indicators are normalized to a standardized format where 1 represents a bullish signal, -1 represents a bearish signal, and 0 (where applicable) represents a neutral signal.
This normalization enables traders to seamlessly combine different indicators, create consensus signals, and develop complex multi-indicator strategies without worrying about different scales and interpretations.
📊 Categories
The library is divided into two main categories:
1. Trend-Following Indicators
2. Calculation Indicators
🔄 Trend-Following Indicators
Stationary Indicators
These oscillate around a fixed value and are not bound to price.
BBPct() - Bollinger Bands Percent
Source: Algoalpha X Sushiboi77
Parameters:
Length: Period for Bollinger Bands
Factor: Standard deviation multiplier
Source: Price source (typical: close)
Logic: Calculates the position of price within the Bollinger Bands as a percentage
Signal:
1 (bullish): when positionBetweenBands > 50
-1 (bearish): when positionBetweenBands ≤ 50
Special Feature: Uses an array to store historical standard deviations for additional analysis
RSI() - Relative Strength Index
Source: TradingView
Parameters:
len: RSI period
src: Price source
smaLen: Smoothing period for RSI
Logic: Classic RSI with additional SMA smoothing
Signal:
1 (bullish): RSI-SMA > 50
-1 (bearish): RSI-SMA < 50
0 (neutral): RSI-SMA = 50
Non-Stationary Indicators
These follow price movement and have no fixed boundaries.
NorosTrendRibbonSMA() & NorosTrendRibbonEMA()
Source: ROBO_Trading
Parameters:
Length: Moving average and channel period
Source: Price source
Logic: Creates a price channel based on the highest/lowest MA value over a specified period
Signal:
1 (bullish): Price breaks above upper band
-1 (bearish): Price breaks below lower band
0 (neutral): Price within channel (maintains last state)
Difference: SMA version uses simple moving averages, EMA version uses exponential
TrendBands()
Source: starlord_xrp
Parameters: src (price source)
Logic: Uses 12 EMAs (9-30 period) and checks if all are rising or falling simultaneously
Signal:
1 (bullish): All 12 EMAs are rising
-1 (bearish): All 12 EMAs are falling
0 (neutral): Mixed signals
Special Feature: Very strict conditions - extremely strong trend filter
Vidya() - Variable Index Dynamic Average
Source: loxx
Parameters:
source: Price source
length: Main period
histLength: Historical period for volatility calculation
Logic: Adaptive moving average that adjusts to volatility
Signal:
1 (bullish): VIDYA is rising
-1 (bearish): VIDYA is falling
VZO() - Volume Zone Oscillator
Parameters:
source: Price source
length: Smoothing period
volumesource: Volume data source
Logic: Combines price and volume direction, calculates the ratio of directional volume to total volume
Signal:
1 (bullish): VZO > 14.9
-1 (bearish): VZO < -14.9
0 (neutral): VZO between -14.9 and 14.9
TrendContinuation()
Source: AlgoAlpha
Parameters:
malen: First HMA period
malen1: Second HMA period
theclose: Price source
Logic: Uses two Hull Moving Averages for trend assessment with neutrality detection
Signal:
1 (bullish): Uptrend without divergence
-1 (bearish): Downtrend without divergence
0 (neutral): Trend and longer MA diverge
LeonidasTrendFollowingSystem()
Source: LeonidasCrypto
Parameters:
src: Price source
shortlen: Short EMA period
keylen: Long EMA period
Logic: Simple dual EMA crossover system
Signal:
1 (bullish): Short EMA < Key EMA
-1 (bearish): Short EMA ≥ Key EMA
ysanturtrendfollower()
Source: ysantur
Parameters:
src: Price source
depth: Depth of Fibonacci weighting
smooth: Smoothing period
bias: Percentage bias adjustment
Logic: Complex system with Fibonacci-weighted moving averages and bias bands
Signal:
1 (bullish): Weighted MA > smoothed MA (with upward bias)
-1 (bearish): Weighted MA < smoothed MA (with downward bias)
0 (neutral): Within bias zone
TRAMA() - Trend Regularity Adaptive Moving Average
Source: LuxAlgo
Parameters:
src: Price source
length: Adaptation period
Logic: Adapts to trend regularity - accelerates in stable trends, slows in consolidations
Signal:
1 (bullish): Price > TRAMA
-1 (bearish): Price < TRAMA
0 (neutral): Price = TRAMA
HullSuite()
Source: InSilico
Parameters:
_length: Base period
src: Price source
_lengthMult: Length multiplier
Logic: Uses Hull Moving Average with lagged comparisons for trend determination
Signal:
1 (bullish): Current Hull > Hull 2 bars ago
-1 (bearish): Current Hull < Hull 2 bars ago
0 (neutral): No change
STC() - Schaff Trend Cycle
Source: shayankm (described as "Better MACD")
Parameters:
length: Cycle period
fastLength: Fast MACD period
slowLength: Slow MACD period
src: Price source
Logic: Combines MACD concepts with stochastic normalization for early trend signals
Signal:
1 (bullish): STC is rising
-1 (bearish): STC is falling
🧮 Calculation Indicators
These functions provide specialized mathematical calculations for advanced analysis.
LCorrelation() - Long-term Correlation
Creator: unicorpusstocks
Parameters:
Input: First time series
Compare: Second time series
Logic: Calculates the average of correlations across 6 different periods (30, 60, 90, 120, 150, 180)
Returns: Correlation value between -1 and 1
Application: Long-term relationship analysis between assets, markets, or indicators
MCorrelation() - Medium-term Correlation
Creator: unicorpusstocks
Parameters:
Input: First time series
Compare: Second time series
Logic: Calculates the average of correlations across 6 different periods (15, 30, 45, 60, 75, 90)
Returns: Correlation value between -1 and 1
Application: Medium-term relationship analysis with higher sensitivity
assetBeta() - Beta Coefficient
Creator: unicorpusstocks
Parameters:
measuredSymbol: The asset to be measured
baseSymbol: The reference asset (e.g., market index)
Logic:
Calculates Beta across 4 different time horizons (50, 100, 150, 200 periods)
Beta = Correlation × (Asset Standard Deviation / Market Standard Deviation)
Returns the average of all 4 Beta values
Returns: Beta value (typically 0-2, can be higher/lower)
Interpretation:
Beta = 1: Asset moves in sync with the market
Beta > 1: Asset more volatile than market
Beta < 1: Asset less volatile than market
Beta < 0: Asset moves inversely to the market
💡 Usage Examples
Example 1: Multi-Indicator Consensus
pinescriptimport unicorpusstocks/MyIndicatorLibrary/1 as lib
// Combine multiple indicators
signal1 = lib.BBPct(20, 2.0, close)
signal2 = lib.RSI(14, close, 5)
signal3 = lib.TRAMA(close, 50)
// Consensus signal: At least 2 of 3 must agree
consensus = (signal1 + signal2 + signal3)
strongBuy = consensus >= 2
strongSell = consensus <= -2
Example 2: Correlation-Filtered Trading
pinescriptimport unicorpusstocks/MyIndicatorLibrary/1 as lib
// Only trade when strong correlation with market exists
spy = request.security("SPY", timeframe.period, close)
correlation = lib.MCorrelation(close, spy)
trendSignal = lib.NorosTrendRibbonEMA(50, close)
// Only bullish signals with positive correlation
tradeBuy = trendSignal == 1 and correlation > 0.5
tradeSell = trendSignal == -1 and correlation > 0.5
Example 3: Beta-Adjusted Position Sizing
pinescriptimport unicorpusstocks/MyIndicatorLibrary/1 as lib
spy = request.security("SPY", timeframe.period, close)
beta = lib.assetBeta(close, spy)
// Adjust position size based on Beta
basePositionSize = 100
adjustedSize = basePositionSize / beta // Less size with high Beta
⚙️ Technical Details
Normalization Standard
Bullish: 1
Bearish: -1
Neutral: 0 (only for selected indicators)
Advantages of Normalization
Simple Aggregation: Signals can be added/averaged
Consistent Interpretation: No confusion about different scales
Strategy Development: Simplified logic for backtesting
Combinability: Seamlessly mix different indicator types
Performance Considerations
All functions are optimized for Pine Script v5
Proper use of var for state management
Efficient array operations where needed
Minimal recursive calls
📋 License
This code is subject to the Mozilla Public License 2.0. More details at: mozilla.org
🎯 Use Cases
This library is ideal for:
Quantitative Traders: Systematic strategy development with unified signals
Multi-Timeframe Analysis: Consensus across different timeframes
Portfolio Managers: Beta and correlation analysis for diversification
Algo Traders: Machine learning with standardized features
Retail Traders: Simplified signal interpretation without deep technical knowledge
🔧 Installation
pinescriptimport unicorpusstocks/MyIndicatorLibrary/1
Then use the functions with your chosen alias:
pinescriptlib.BBPct(20, 2.0, close)
lib.RSI(14, close, 5)
// etc.
⚠️ Important Notes
All indicators are lagging, as is typical for trend-following indicators
Signals should be combined with additional analysis (volume, support/resistance, etc.)
Backtesting is recommended before starting live trading with these signals
Different assets and timeframes may require different parameter optimizations
This library provides a solid foundation for professional trading system design with the flexibility to develop your own complex strategies while abstracting away technical complexity.
LapseBacktestingTableLibrary "LapseBacktestingMetrics"
This library provides a robust set of quantitative backtesting and performance evaluation functions for Pine Script strategies. It’s designed to help traders, quants, and developers assess risk, return, and robustness through detailed statistical metrics — including Sharpe, Sortino, Omega, drawdowns, and trade efficiency.
Built to enhance any trading strategy’s evaluation framework, this library allows you to visualize performance with the quantlapseTable() function, producing an interactive on-chart performance table.
Credit to EliCobra and BikeLife76 for original concept inspiration.
curve(disp_ind)
Retrieves a selected performance curve of your strategy.
Parameters:
disp_ind (simple string): Type of curve to plot. Options include "Equity", "Open Profit", "Net Profit", "Gross Profit".
Returns: (float) Corresponding performance curve value.
cleaner(disp_ind, plot)
Filters and displays selected strategy plots for clean visualization.
Parameters:
disp_ind (simple string): Type of display.
plot (simple float): Strategy plot variable.
Returns: (float) Filtered plot value.
maxEquityDrawDown()
Calculates the maximum equity drawdown during the strategy’s lifecycle.
Returns: (float) Maximum equity drawdown percentage.
maxTradeDrawDown()
Computes the worst intra-trade drawdown among all closed trades.
Returns: (float) Maximum intra-trade drawdown percentage.
consecutive_wins()
Finds the highest number of consecutive winning trades.
Returns: (int) Maximum consecutive wins.
consecutive_losses()
Finds the highest number of consecutive losing trades.
Returns: (int) Maximum consecutive losses.
no_position()
Counts the maximum consecutive bars where no position was held.
Returns: (int) Maximum flat days count.
long_profit()
Calculates total profit generated by long positions as a percentage of initial capital.
Returns: (float) Total long profit %.
short_profit()
Calculates total profit generated by short positions as a percentage of initial capital.
Returns: (float) Total short profit %.
prev_month()
Measures the previous month’s profit or loss based on equity change.
Returns: (float) Monthly equity delta.
w_months()
Counts the number of profitable months in the backtest.
Returns: (int) Total winning months.
l_months()
Counts the number of losing months in the backtest.
Returns: (int) Total losing months.
checktf()
Returns the time-adjusted scaling factor used in Sharpe and Sortino ratio calculations based on chart timeframe.
Returns: (float) Annualization multiplier.
stat_calc()
Performs complete statistical computation including drawdowns, Sharpe, Sortino, Omega, trade stats, and profit ratios.
Returns: (array)
.
f_colors(x, nv)
Generates a color gradient for performance values, supporting dynamic table visualization.
Parameters:
x (simple string): Metric label name.
nv (simple float): Metric numerical value.
Returns: (color) Gradient color value for table background.
quantlapseTable(option, position)
Displays an interactive Performance Table summarizing all major backtesting metrics.
Includes Sharpe, Sortino, Omega, Profit Factor, drawdowns, profitability %, and trade statistics.
Parameters:
option (simple string): Table type — "Full", "Simple", or "None".
position (simple string): Table position — "Top Left", "Middle Right", "Bottom Left", etc.
Returns: (table) On-chart performance visualization table.
This library empowers advanced quantitative evaluation directly within Pine Script®, ideal for strategy developers seeking deeper performance diagnostics and intuitive on-chart metrics.
UTBotLibrary "UTBot"
is a powerful and flexible trading toolkit implemented in Pine Script. Based on the widely recognized UT Bot strategy originally developed by Yo_adriiiiaan with important enhancements by HPotter, this library provides users with customizable functions for dynamic trailing stop calculations using ATR (Average True Range), trend detection, and signal generation. It enables developers and traders to seamlessly integrate UT Bot logic into their own indicators and strategies without duplicating code.
Key features include:
Accurate ATR-based trailing stop and reversal detection
Multi-timeframe support for enhanced signal reliability
Clean and efficient API for easy integration and customization
Detailed documentation and examples for quick adoption
Open-source and community-friendly, encouraging collaboration and improvements
We sincerely thank Yo_adriiiiaan for the original UT Bot concept and HPotter for valuable improvements that have made this strategy even more robust. This library aims to honor their work by making the UT Bot methodology accessible to Pine Script developers worldwide.
This library is designed for Pine Script programmers looking to leverage the proven UT Bot methodology to build robust trading systems with minimal effort and maximum maintainability.
UTBot(h, l, c, multi, leng)
Parameters:
h (float) - high
l (float) - low
c (float)-close
multi (float)- multi for ATR
leng (int)-length for ATR
Returns:
xATRTS - ATR Based TrailingStop Value
pos - pos==1, long position, pos==-1, shot position
signal - 0 no signal, 1 buy, -1 sell
AlertSenderLibrary_TradingFinderLibrary "AlertSenderLibrary_TradingFinder"
TODO: add library description here
AlertSender(Condition, Alert, AlertName, AlertType, DetectionType, SetupData, Frequncy, UTC, MoreInfo, Message, o, h, l, c, Entry, TP, SL, Distal, Proximal)
Parameters:
Condition (bool)
Alert (string)
AlertName (string)
AlertType (string)
DetectionType (string)
SetupData (string)
Frequncy (string)
UTC (string)
MoreInfo (string)
Message (string)
o (float)
h (float)
l (float)
c (float)
Entry (float)
TP (float)
SL (float)
Distal (float)
Proximal (float)
ApicodeLibrary "Apicode"
percentToTicks(percent, from)
Converts a percentage of the average entry price or a specified price to ticks when the
strategy has an open position.
Parameters:
percent (float) : (series int/float) The percentage of the `from` price to express in ticks, e.g.,
a value of 50 represents 50% (half) of the price.
from (float) : (series int/float) Optional. The price from which to calculate a percentage and convert
to ticks. The default is `strategy.position_avg_price`.
Returns: (float) The number of ticks within the specified percentage of the `from` price if
the strategy has an open position. Otherwise, it returns `na`.
percentToPrice(percent, from)
Calculates the price value that is a specific percentage distance away from the average
entry price or a specified price when the strategy has an open position.
Parameters:
percent (float) : (series int/float) The percentage of the `from` price to use as the distance. If the value
is positive, the calculated price is above the `from` price. If negative, the result is
below the `from` price. For example, a value of 10 calculates the price 10% higher than
the `from` price.
from (float) : (series int/float) Optional. The price from which to calculate a percentage distance.
The default is `strategy.position_avg_price`.
Returns: (float) The price value at the specified `percentage` distance away from the `from` price
if the strategy has an open position. Otherwise, it returns `na`.
percentToCurrency(price, percent)
Parameters:
price (float) : (series int/float) The price from which to calculate the percentage.
percent (float) : (series int/float) The percentage of the `price` to calculate.
Returns: (float) The amount of the symbol's currency represented by the percentage of the specified
`price`.
percentProfit(exitPrice)
Calculates the expected profit/loss of the open position if it were to close at the
specified `exitPrice`, expressed as a percentage of the average entry price.
NOTE: This function may not return precise values for positions with multiple open trades
because it only uses the average entry price.
Parameters:
exitPrice (float) : (series int/float) The position's hypothetical closing price.
Returns: (float) The expected profit percentage from exiting the position at the `exitPrice`. If
there is no open position, it returns `na`.
priceToTicks(price)
Converts a price value to ticks.
Parameters:
price (float) : (series int/float) The price to convert.
Returns: (float) The value of the `price`, expressed in ticks.
ticksToPrice(ticks, from)
Calculates the price value at the specified number of ticks away from the average entry
price or a specified price when the strategy has an open position.
Parameters:
ticks (float) : (series int/float) The number of ticks away from the `from` price. If the value is positive,
the calculated price is above the `from` price. If negative, the result is below the `from`
price.
from (float) : (series int/float) Optional. The price to evaluate the tick distance from. The default is
`strategy.position_avg_price`.
Returns: (float) The price value at the specified number of ticks away from the `from` price if
the strategy has an open position. Otherwise, it returns `na`.
ticksToCurrency(ticks)
Converts a specified number of ticks to an amount of the symbol's currency.
Parameters:
ticks (float) : (series int/float) The number of ticks to convert.
Returns: (float) The amount of the symbol's currency represented by the tick distance.
ticksToStopLevel(ticks)
Calculates a stop-loss level using a specified tick distance from the position's average
entry price. A script can plot the returned value and use it as the `stop` argument in a
`strategy.exit()` call.
Parameters:
ticks (float) : (series int/float) The number of ticks from the position's average entry price to the
stop-loss level. If the position is long, the value represents the number of ticks *below*
the average entry price. If short, it represents the number of ticks *above* the price.
Returns: (float) The calculated stop-loss value for the open position. If there is no open position,
it returns `na`.
ticksToTpLevel(ticks)
Calculates a take-profit level using a specified tick distance from the position's average
entry price. A script can plot the returned value and use it as the `limit` argument in a
`strategy.exit()` call.
Parameters:
ticks (float) : (series int/float) The number of ticks from the position's average entry price to the
take-profit level. If the position is long, the value represents the number of ticks *above*
the average entry price. If short, it represents the number of ticks *below* the price.
Returns: (float) The calculated take-profit value for the open position. If there is no open
position, it returns `na`.
calcPositionSizeByStopLossTicks(stopLossTicks, riskPercent)
Calculates the entry quantity required to risk a specified percentage of the strategy's
current equity at a tick-based stop-loss level.
Parameters:
stopLossTicks (float) : (series int/float) The number of ticks in the stop-loss distance.
riskPercent (float) : (series int/float) The percentage of the strategy's equity to risk if a trade moves
`stopLossTicks` away from the entry price in the unfavorable direction.
Returns: (int) The number of contracts/shares/lots/units to use as the entry quantity to risk the
specified percentage of equity at the stop-loss level.
calcPositionSizeByStopLossPercent(stopLossPercent, riskPercent, entryPrice)
Calculates the entry quantity required to risk a specified percentage of the strategy's
current equity at a percent-based stop-loss level.
Parameters:
stopLossPercent (float) : (series int/float) The percentage of the `entryPrice` to use as the stop-loss distance.
riskPercent (float) : (series int/float) The percentage of the strategy's equity to risk if a trade moves
`stopLossPercent` of the `entryPrice` in the unfavorable direction.
entryPrice (float) : (series int/float) Optional. The entry price to use in the calculation. The default is
`close`.
Returns: (int) The number of contracts/shares/lots/units to use as the entry quantity to risk the
specified percentage of equity at the stop-loss level.
exitPercent(id, lossPercent, profitPercent, qty, qtyPercent, comment, alertMessage)
A wrapper for the `strategy.exit()` function designed for creating stop-loss and
take-profit orders at percentage distances away from the position's average entry price.
NOTE: This function calls `strategy.exit()` without a `from_entry` ID, so it creates exit
orders for *every* entry in an open position until the position closes. Therefore, using
this function when the strategy has a pyramiding value greater than 1 can lead to
unexpected results. See the "Exits for multiple entries" section of our User Manual's
"Strategies" page to learn more about this behavior.
Parameters:
id (string) : (series string) Optional. The identifier of the stop-loss/take-profit orders, which
corresponds to an exit ID in the strategy's trades after an order fills. The default is
`"Exit"`.
lossPercent (float) : (series int/float) The percentage of the position's average entry price to use as the
stop-loss distance. The function does not create a stop-loss order if the value is `na`.
profitPercent (float) : (series int/float) The percentage of the position's average entry price to use as the
take-profit distance. The function does not create a take-profit order if the value is `na`.
qty (float) : (series int/float) Optional. The number of contracts/lots/shares/units to close when an
exit order fills. If specified, the call uses this value instead of `qtyPercent` to
determine the order size. The exit orders reserve this quantity from the position, meaning
other orders from `strategy.exit()` cannot close this portion until the strategy fills or
cancels those orders. The default is `na`, which means the order size depends on the
`qtyPercent` value.
qtyPercent (float) : (series int/float) Optional. A value between 0 and 100 representing the percentage of the
open trade quantity to close when an exit order fills. The exit orders reserve this
percentage from the open trades, meaning other calls to this command cannot close this
portion until the strategy fills or cancels those orders. The percentage calculation
depends on the total size of the applicable open trades without considering the reserved
amount from other `strategy.exit()` calls. The call ignores this parameter if the `qty`
value is not `na`. The default is 100.
comment (string) : (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the specified `id`. The default is `na`.
alertMessage (string) : (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
closeAllAtEndOfSession(comment, alertMessage)
A wrapper for the `strategy.close_all()` function designed to close all open trades with a
market order when the last bar in the current day's session closes. It uses the command's
`immediately` parameter to exit all trades at the last bar's `close` instead of the `open`
of the next session's first bar.
Parameters:
comment (string) : (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the automatically generated exit identifier. The default is `na`.
alertMessage (string) : (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
closeAtEndOfSession(entryId, comment, alertMessage)
A wrapper for the `strategy.close()` function designed to close specific open trades with a
market order when the last bar in the current day's session closes. It uses the command's
`immediately` parameter to exit the trades at the last bar's `close` instead of the `open`
of the next session's first bar.
Parameters:
entryId (string)
comment (string) : (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the automatically generated exit identifier. The default is `na`.
alertMessage (string) : (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
sortinoRatio(interestRate, forceCalc)
Calculates the Sortino ratio of the strategy based on realized monthly returns.
Parameters:
interestRate (simple float) : (simple int/float) Optional. The *annual* "risk-free" return percentage to compare against
strategy returns. The default is 2, meaning it uses an annual benchmark of 2%.
forceCalc (bool) : (series bool) Optional. A value of `true` forces the function to calculate the ratio on the
current bar. If the value is `false`, the function calculates the ratio only on the latest
available bar for efficiency. The default is `false`.
Returns: (float) The Sortino ratio, which estimates the strategy's excess return per unit of
downside volatility.
sharpeRatio(interestRate, forceCalc)
Calculates the Sharpe ratio of the strategy based on realized monthly returns.
Parameters:
interestRate (simple float) : (simple int/float) Optional. The *annual* "risk-free" return percentage to compare against
strategy returns. The default is 2, meaning it uses an annual benchmark of 2%.
forceCalc (bool) : (series bool) Optional. A value of `true` forces the function to calculate the ratio on the
current bar. If the value is `false`, the function calculates the ratio only on the latest
available bar for efficiency. The default is `false`.
Returns: (float) The Sortino ratio, which estimates the strategy's excess return per unit of
total volatility.
WCWebLibLibrary "WCWebLib"
method buildWebhookJson(msg, constants)
Builds the final JSON payload from a webhookMessage type.
Namespace types: webhookMessage
Parameters:
msg (webhookMessage) : (webhookMessage) A prepared webhookMessage.
constants (CONSTANTS)
Returns: A JSON Payload.
method buildTakeProfitJson(msg)
Builds the takeProfit JSON message to be used in a webhook message.
Namespace types: takeProfitMessage
Parameters:
msg (takeProfitMessage)
method buildStopLossJson(msg, constants)
Builds the stopLoss JSON message to be used in a webhook message.
Namespace types: stopLossMessage
Parameters:
msg (stopLossMessage)
constants (CONSTANTS)
CONSTANTS
Constants for payload values.
Fields:
ACTION_BUY (series string)
ACTION_SELL (series string)
ACTION_EXIT (series string)
ACTION_CANCEL (series string)
ACTION_ADD (series string)
SENTIMENT_BULLISH (series string)
SENTIMENT_BEARISH (series string)
SENTIMENT_LONG (series string)
SENTIMENT_SHORT (series string)
SENTIMENT_FLAT (series string)
STOP_LOSS_TYPE_STOP (series string)
STOP_LOSS_TYPE_STOP_LIMIT (series string)
STOP_LOSS_TYPE_TRAILING_STOP (series string)
EXTENDEDHOURS (series bool)
ORDER_TYPE_LIMIT (series string)
ORDER_TYPE_MARKET (series string)
TIF_DAY (series string)
webhookMessage
Final webhook message.
Fields:
ticker (series string)
action (series string)
sentiment (series string)
price (series float)
quantity (series int)
takeProfit (series string)
stopLoss (series string)
extendedHours (series bool)
type (series string)
timeInForce (series string)
takeProfitMessage
Take profit message.
Fields:
limitPrice (series float)
percent (series float)
amount (series float)
stopLossMessage
Stop loss message.
Fields:
type (series string)
percent (series float)
amount (series float)
stopPrice (series float)
limitPrice (series float)
trailPrice (series float)
trailPercent (series float)
RifleShooterLibLibrary "RifleShooterLib"
Provides a collection of helper functions in support of the Rifle Shooter Indicators.
Functions support the key components of the Rifle Trade algorithm including
* measuring momentum
* identifying paraboloic price action (to disable the algorthim during such time)
* determine the lookback criteria of X point movement in last N minutes
* processing and navigating between the 23/43/73 levels
* maintaining a status table of algorithm progress
toStrRnd(val, digits)
Parameters:
val (float)
digits (int)
_isValidTimeRange(startTimeInput, endTimeInput)
Parameters:
startTimeInput (string)
endTimeInput (string)
_normalize(_src, _min, _max)
_normalize Normalizes series with unknown min/max using historical min/max.
Parameters:
_src (float) : Source series to normalize
_min (float) : minimum value of the rescaled series
_max (float) : maximum value of the rescaled series
Returns: The series scaled with values between min and max
arrayToSeries(arrayInput)
arrayToSeries Return an array from the provided series.
Parameters:
arrayInput (array) : Source array to convert to a series
Returns: The array as a series datatype
f_parabolicFiltering(_activeCount, long, shooterRsi, shooterRsiLongThreshold, shooterRsiShortThreshold, fiveMinuteRsi, fiveMinRsiLongThreshold, fiveMinRsiShortThreshold, shooterRsiRoc, shooterRsiRocLongThreshold, shooterRsiRocShortThreshold, quickChangeLookbackBars, quckChangeThreshold, curBarChangeThreshold, changeFromPrevBarThreshold, maxBarsToholdParabolicMoveActive, generateLabels)
f_parabolicFiltering Return true when price action indicates a parabolic active movement based on the provided inputs and thresholds.
Parameters:
_activeCount (int)
long (bool)
shooterRsi (float)
shooterRsiLongThreshold (float)
shooterRsiShortThreshold (float)
fiveMinuteRsi (float)
fiveMinRsiLongThreshold (float)
fiveMinRsiShortThreshold (float)
shooterRsiRoc (float)
shooterRsiRocLongThreshold (float)
shooterRsiRocShortThreshold (float)
quickChangeLookbackBars (int)
quckChangeThreshold (int)
curBarChangeThreshold (int)
changeFromPrevBarThreshold (int)
maxBarsToholdParabolicMoveActive (int)
generateLabels (bool)
rsiValid(rsi, buyThreshold, sellThreshold)
rsiValid Returns true if the provided RSI value is withing the associated threshold. For the unused threshold set it to na
Parameters:
rsi (float)
buyThreshold (float)
sellThreshold (float)
squezeBands(source, length)
squezeBands Returns the squeeze bands momentum color of current source series input
Parameters:
source (float)
length (int)
f_momentumOscilator(source, length, transperency)
f_momentumOscilator Returns the squeeze pro momentum value and bar color states of the series input
Parameters:
source (float)
length (int)
transperency (int)
f_getLookbackExtreme(lowSeries, highSeries, lbBars, long)
f_getLookbackExtreme Return the highest high or lowest low over the look back window
Parameters:
lowSeries (float)
highSeries (float)
lbBars (int)
long (bool)
f_getInitialMoveTarget(lbExtreme, priveMoveOffset, long)
f_getInitialMoveTarget Return the point delta required to achieve an initial rifle move (X points over Y lookback)
Parameters:
lbExtreme (float)
priveMoveOffset (int)
long (bool)
isSymbolSupported(sym)
isSymbolSupported Return true if provided symbol is one of the supported DOW Rifle Indicator symbols
Parameters:
sym (string)
getBasePrice(price)
getBasePrice Returns integer portion of provided float
Parameters:
price (float)
getLastTwoDigitsOfPrice(price)
getBasePrice Returns last two integer numerals of provided float value
Parameters:
price (float)
getNextLevelDown(price, lowestLevel, middleLevel, highestLevel)
getNextLevelDown Returns the next level above the provided price value
Parameters:
price (float)
lowestLevel (float)
middleLevel (float)
highestLevel (float)
getNextLevelUp(price, lowestLevel, middleLevel, highestLevel)
getNextLevelUp Returns the next level below the provided price value
Parameters:
price (float)
lowestLevel (float)
middleLevel (float)
highestLevel (float)
isALevel(price, lowestLevel, middleLevel, highestLevel)
isALevel Returns true if the provided price is onve of the specified levels
Parameters:
price (float)
lowestLevel (float)
middleLevel (float)
highestLevel (float)
getClosestLevel(price, lowestLevel, middleLevel, highestLevel)
getClosestLevel Returns the level closest to the price value provided
Parameters:
price (float)
lowestLevel (float)
middleLevel (float)
highestLevel (float)
f_fillSetupTableCell(_table, _col, _row, _text, _bgcolor, _txtcolor, _text_size)
f_fillSetupTableCell Helper function to fill a setup table celll
Parameters:
_table (table)
_col (int)
_row (int)
_text (string)
_bgcolor (color)
_txtcolor (color)
_text_size (string)
f_fillSetupTableRow(_table, _row, _col0Str, _col1Str, _col2Str, _bgcolor, _textColor, _textSize)
f_fillSetupTableRow Helper function to fill a setup table row
Parameters:
_table (table)
_row (int)
_col0Str (string)
_col1Str (string)
_col2Str (string)
_bgcolor (color)
_textColor (color)
_textSize (string)
f_addBlankRow(_table, _row)
f_addBlankRow Helper function to fill a setup table row with empty values
Parameters:
_table (table)
_row (int)
f_updateVersionTable(versionTable, versionStr, versionDateStr)
f_updateVersionTable Helper function to fill the version table with provided values
Parameters:
versionTable (table)
versionStr (string)
versionDateStr (string)
f_updateSetupTable(_table, parabolicMoveActive, initialMoveTargetOffset, initialMoveAchieved, shooterRsi, shooterRsiValid, rsiRocEnterThreshold, shooterRsiRoc, fiveMinuteRsi, fiveMinuteRsiValid, requireValid5MinuteRsiForEntry, stallLevelOffset, stallLevelExceeded, stallTargetOffset, recoverStallLevelValid, curBarChangeValid, volumeRoc, volumeRocThreshold, enableVolumeRocForTrigger, tradeActive, entryPrice, curCloseOffset, curSymCashDelta, djiCashDelta, showDjiDelta, longIndicator, fontSize)
f_updateSetupTable Manages writing current data to the setup table
Parameters:
_table (table)
parabolicMoveActive (bool)
initialMoveTargetOffset (float)
initialMoveAchieved (bool)
shooterRsi (float)
shooterRsiValid (bool)
rsiRocEnterThreshold (float)
shooterRsiRoc (float)
fiveMinuteRsi (float)
fiveMinuteRsiValid (bool)
requireValid5MinuteRsiForEntry (bool)
stallLevelOffset (float)
stallLevelExceeded (bool)
stallTargetOffset (float)
recoverStallLevelValid (bool)
curBarChangeValid (bool)
volumeRoc (float)
volumeRocThreshold (float)
enableVolumeRocForTrigger (bool)
tradeActive (bool)
entryPrice (float)
curCloseOffset (float)
curSymCashDelta (float)
djiCashDelta (float)
showDjiDelta (bool)
longIndicator (bool)
fontSize (string)
BackTestLibLibrary "BackTestLib"
Allows backtesting indicator performance. Tracks typical metrics such as won/loss, profit factor, draw down, etc. Trading View strategy library provides similar (and more comprehensive)
functionality but only works with strategies. This libary was created to address performance tracking within indicators.
Two primary outputs are generated:
1. Summary Table: Displays overall performance metrics for the indicator over the chart's loaded timeframe and history
2. Details Table: Displays a table of individual trade entries and exits. This table can grow larger than the available chart space. It does have a max number of rows supported. I haven't
found a way to add scroll bars or scroll bar equivalents yet.
f_init(data, _defaultStopLoss, _defaultTakeProfit, _useTrailingStop, _useTraingStopToBreakEven, _trailingStopActivation, _trailingStopOffset)
f_init Initialize the backtest data type. Called prior to using the backtester functions
Parameters:
data (backtesterData) : backtesterData to initialize
_defaultStopLoss (float) : Default trade stop loss to apply
_defaultTakeProfit (float) : Default trade take profit to apply
_useTrailingStop (bool) : Trailing stop enabled
_useTraingStopToBreakEven (bool) : When trailing stop active, trailing stop will increase no further than the entry price
_trailingStopActivation (int) : When trailing stop active, trailing will begin once price exceeds base stop loss by this number of points
_trailingStopOffset (int) : When trailing stop active, it will trail the max price achieved by this number of points
Returns: Initialized data set
f_buildResultStr(_resultType, _price, _resultPoints, _numWins, _pointsWon, _numLoss, _pointsLost)
f_buildResultStr Helper function to construct a string of resutling data for exit tooltip labels
Parameters:
_resultType (string)
_price (float)
_resultPoints (float)
_numWins (int)
_pointsWon (float)
_numLoss (int)
_pointsLost (float)
f_buildResultLabel(data, labelVertical, labelOffset, long)
f_buildResultLabel Helper function to construct an Exit label for display on the chart
Parameters:
data (backtesterData)
labelVertical (bool)
labelOffset (int)
long (bool)
f_updateTrailingStop(_entryPrice, _curPrice, _sl, _tp, trailingStopActivationInput, trailingStopOffsetInput, useTrailingStopToBreakEven)
f_updateTrailingStop Helper function to advance the trailing stop as price action dictates
Parameters:
_entryPrice (float)
_curPrice (float)
_sl (float)
_tp (float)
trailingStopActivationInput (float)
trailingStopOffsetInput (float)
useTrailingStopToBreakEven (bool)
Returns: Updated stop loss for current price action
f_enterShort(data, entryPrice, fixedStopLoss)
f_enterShort Helper function to enter a short and collect data necessary for tracking the trade entry
Parameters:
data (backtesterData)
entryPrice (float)
fixedStopLoss (float)
Returns: Updated backtest data
f_enterLong(data, entryPrice, fixedStopLoss)
f_enterLong Helper function to enter a long and collect data necessary for tracking the trade entry
Parameters:
data (backtesterData)
entryPrice (float)
fixedStopLoss (float)
Returns: Updated backtest data
f_exitTrade(data)
f_enterLong Helper function to exit a trade and update/reset tracking data
Parameters:
data (backtesterData)
Returns: Updated backtest data
f_checkTradeConditionForExit(data, condition, curPrice, enableRealTime)
f_checkTradeConditionForExit Helper function to determine if provided condition indicates an exit
Parameters:
data (backtesterData)
condition (bool) : When true trade will exit
curPrice (float)
enableRealTime (bool) : When true trade will evaluate if barstate is relatime or barstate is confirmed; otherwise just checks on is confirmed
Returns: Updated backtest data
f_checkTrade(data, curPrice, curLow, curHigh, enableRealTime)
f_checkTrade Helper function to determine if current price action dictates stop loss or take profit exit
Parameters:
data (backtesterData)
curPrice (float)
curLow (float)
curHigh (float)
enableRealTime (bool) : When true trade will evaluate if barstate is relatime or barstate is confirmed; otherwise just checks on is confirmed
Returns: Updated backtest data
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor, _text_size)
f_fillCell Helper function to construct result table cells
Parameters:
_table (table)
_column (int)
_row (int)
_title (string)
_value (string)
_bgcolor (color)
_txtcolor (color)
_text_size (string)
Returns: Table cell
f_prepareStatsTable(data, drawTesterSummary, drawTesterDetails, summaryTableTextSize, detailsTableTextSize, displayRowZero, summaryTableLocation, detailsTableLocation)
f_fillCell Helper function to populate result table
Parameters:
data (backtesterData)
drawTesterSummary (bool)
drawTesterDetails (bool)
summaryTableTextSize (string)
detailsTableTextSize (string)
displayRowZero (bool)
summaryTableLocation (string)
detailsTableLocation (string)
Returns: Updated backtest data
backtesterData
backtesterData - container for backtest performance metrics
Fields:
tradesArray (array) : Array of strings with entries for each individual trade and its results
pointsBalance (series float) : Running sum of backtest points won/loss results
drawDown (series float) : Running sum of backtest total draw down points
maxDrawDown (series float) : Running sum of backtest total draw down points
maxRunup (series float) : Running sum of max points won over the backtest
numWins (series int) : Number of wins of current backtes set
numLoss (series int) : Number of losses of current backtes set
pointsWon (series float) : Running sum of points won to date
pointsLost (series float) : Running sum of points lost to date
entrySide (series string) : Current entry long/short
tradeActive (series bool) : Indicates if a trade is currently active
tradeComplete (series bool) : Indicates if a trade just exited (due to stop loss or take profit)
entryPrice (series float) : Current trade entry price
entryTime (series int) : Current trade entry time
sl (series float) : Current trade stop loss
tp (series float) : Current trade take profit
defaultStopLoss (series float) : Default trade stop loss to apply
defaultTakeProfit (series float) : Default trade take profit to apply
useTrailingStop (series bool) : Trailing stop enabled
useTrailingStopToBreakEven (series bool) : When trailing stop active, trailing stop will increase no further than the entry price
trailingStopActivation (series int) : When trailing stop active, trailing will begin once price exceeds base stop loss by this number of points
trailingStopOffset (series int) : When trailing stop active, it will trail the max price achieved by this number of points
resultType (series string) : Current trade won/lost
exitPrice (series float) : Current trade exit price
resultPoints (series float) : Current trade points won/lost
summaryTable (series table) : Table to deisplay summary info
tradesTable (series table) : Table to display per trade info
TradersPostDeluxeLibrary "TradersPostDeluxe"
TradersPost integration. It's currently not very deluxe
SendEntryAlert(ticker, action, quantity, orderType, takeProfit, stopLoss, id, price, timestamp, timezone)
Sends an alert to TradersPost to trigger an Entry
Parameters:
ticker (string) : Symbol to trade. Default is syminfo.ticker
action (series Action) : TradersPostAction (.buy, .sell) default = buy
quantity (float) : Amount to trade, default = 1
orderType (series OrderType) : TradersPostOrderType, default =e TradersPostOrderType.market
takeProfit (float) : Take profit limit price
stopLoss (float) : Stop loss price
id (string) : id for the trade
price (float) : Expected price
timestamp (int) : Time of the trade for reporting, defaults to timenow
timezone (string) : associated with the time, defaults to syminfo.timezone
Returns: Nothing
SendExitAlert(ticker, price, timestamp, timezone)
Sends an alert to TradersPost to trigger an Exit
Parameters:
ticker (string) : Symbol to flatten
price (float) : Documented planned price
timestamp (int) : Time of the trade for reporting, defaults to timenow
timezone (string) : associated with the time, defaults to syminfo.timezone
Returns: Nothing
WeightedVolumeUtilsLibrary "WeightedVolumeUtils"
fun(x)
Returns the input value (placeholder function).
Parameters:
x (float) : A float value.
Returns: The same float value passed as input.
weightedBSEVolume()
Calculates the weighted volume for BSE index based on top constituent stocks.
Returns: Weighted volume value based on fixed weights for BSE SENSEX stocks.
getAdjustedVolume()
Returns the adjusted volume for SENSEX or regular volume otherwise.
Returns: Weighted BSE volume if current symbol is SENSEX, else raw volume.
StrategyUtilsLibrary "StrategyUtils"
getHeikinAshi(open, high, low, close)
getHeikinAshi
Parameters:
open (float) : float: Raw open price
high (float) : float: Raw high price
low (float) : float: Raw low price
close (float) : float: Raw close price
Returns: tuple of haOpen, haClose, haHigh, haLow
getFibExtensions(high, low)
getFibExtensions
Parameters:
high (float) : float: Highest point before trade
low (float) : float: Lowest point before trade
Returns: tuple of extension levels
inBacktestWindow(time, start, end)
inBacktestWindow
Parameters:
time (int) : int: Current bar time
start (int) : int: Start timestamp
end (int) : int: End timestamp
Returns: bool: true if within Fbrange
getCurrentState(buy, sell)
getCurrentState
Parameters:
buy (bool) : bool: Buy signal condition
sell (bool) : bool: Sell signal condition
Returns: string: "Buy", "Sell", or "None"
formatPrice(price)
formatPrice
Parameters:
price (float) : float: Input price value
Returns: string: Formatted price string
getColorByProfit(netprofit, initial, green, red)
getColorByProfit
Parameters:
netprofit (float) : float: Strategy net profit
initial (float) : float: Initial capital
green (color) : color: Positive color
red (color) : color: Negative color
Returns: color: Display color based on PnL
UTSStrategyHelperLibrary "UTSStrategyHelper"
TODO: add library description here
stopLossPrice(sig, atr, factor, isLong)
Calculates the stop loss price using a distance determined by ATR multiplied by a factor. Example for Long trade SL: PRICE - (ATR * factor).
Parameters:
sig (float)
atr (float) : (float): The value of the atr.
factor (float)
isLong (bool) : (bool): The current trade direction.
Returns: (bool): A boolean value.
takeProfitPrice(sig, atr, factor, isLong)
Calculates the take profit price using a distance determined by ATR multiplied by a factor. Example for Long trade TP: PRICE + (ATR * factor). When take profit price is reached usually 50 % of the position is closed and the other 50 % get a trailing stop assigned.
Parameters:
sig (float)
atr (float) : (float): The value of the atr.
factor (float)
isLong (bool) : (bool): The current trade direction.
Returns: (bool): A boolean value.
trailingStopPrice(initialStopPrice, atr, factor, priceSource, isLong)
Calculates a trailing stop price using a distance determined by ATR multiplied by a factor. It takes an initial price and follows the price closely if it changes in a favourable way.
Parameters:
initialStopPrice (float) : (float): The initial stop price which, for consistency also should be ATR * factor behind price: e.g. Long trade: PRICE - (ATR * factor)
atr (float) : (float): The value of the atr. Ideally the ATR value at trade open is taken and used for subsequent calculations.
factor (float)
priceSource (float) : (float): The current price.
isLong (bool) : (bool): The current trade direction.
Returns: (bool): A boolean value.
hasGreaterPositionSize(positionSize)
Determines if the strategy's position size has grown since the last bar.
Parameters:
positionSize (float) : (float): The size of the position.
Returns: (bool): A boolean value.
hasSmallerPositionSize(positionSize)
Determines if the strategy's position size has decreased since the last bar.
Parameters:
positionSize (float) : (float): The size of the position.
Returns: (bool): A boolean value.
hasUnchangedPositionSize(positionSize)
Determines if the strategy's position size has changed since the last bar.
Parameters:
positionSize (float) : (float): The size of the position.
Returns: (bool): A boolean value.
exporthasLongPosition(positionSize)
Determines if the strategy has an open long position.
Parameters:
positionSize (float) : (float): The size of the position.
Returns: (bool): A boolean value.
hasShortPosition(positionSize)
Determines if the strategy has an open short position.
Parameters:
positionSize (float) : (float): The size of the position.
Returns: (bool): A boolean value.
hasAnyPosition(positionSize)
Determines if the strategy has any open position, regardless of short or long.
Parameters:
positionSize (float) : (float): The size of the position.
Returns: (bool): A boolean value.
hasSignal(value)
Determines if the given argument contains a valid value (means not 'na').
Parameters:
value (float) : (float): The actual value.
Returns: (bool): A boolean value.
TUF_LOGICTUF_LOGIC: Three-Value Logic for Pine Script v6
The TUF_LOGIC library implements a robust three-valued logic system (trilean logic) for Pine Script v6, providing a formal framework for reasoning about uncertain or incomplete information in financial markets. By extending beyond binary True/False states to include an explicit "Uncertain" state, this library enables more nuanced algorithmic decision-making, particularly valuable in environments characterized by imperfect information.
Core Architecture
TUF_LOGIC offers two complementary interfaces for working with trilean values:
Enum-Based API (Recommended): Leverages Pine Script v6's enum capabilities with Trilean.True , Trilean.Uncertain , and Trilean.False for improved type safety and performance.
Integer-Based API (Legacy Support): Maintains compatibility with existing code using integer values 1 (True), 0 (Uncertain), and -1 (False).
Fundamental Operations
The library provides type conversion methods for seamless interaction between integer representation and enum types ( to_trilean() , to_int() ), along with validation functions to maintain trilean invariants.
Logical Operators
TUF_LOGIC extends traditional boolean operators to the trilean domain with NOT , AND , OR , XOR , and EQUALITY functions that properly handle the Uncertain state according to the principles of three-valued logic.
The library implements three different implication operators providing flexibility for different logical requirements: IMP_K (Kleene's approach), IMP_L (Łukasiewicz's approach), and IMP_RM3 (Relevant implication under RM3 logic).
Inspired by Tarski-Łukasiewicz's modal logic formulations, TUF_LOGIC includes modal operators: MA (Modal Assertion) evaluates whether a state is possibly true; LA (Logical Assertion) determines if a state is necessarily true; and IA (Indeterminacy Assertion) identifies explicitly uncertain states.
The UNANIMOUS operator evaluates trilean values for complete agreement, returning the consensus value if one exists or Uncertain otherwise. This function is available for both pairs of values and arrays of trilean values.
Practical Applications
TUF_LOGIC excels in financial market scenarios where decision-making must account for uncertainty. It enables technical indicator consensus by combining signals with different confidence levels, supports multi-timeframe analysis by reconciling potentially contradictory signals, enhances risk management by explicitly modeling uncertainty, and handles partial information systems where some data sources may be unreliable.
By providing a mathematically sound framework for reasoning about uncertainty, TUF_LOGIC elevates trading system design beyond simplistic binary logic, allowing for more sophisticated decision-making that better reflects real-world market complexity.
Library "TUF_LOGIC"
Three-Value Logic (TUF: True, Uncertain, False) implementation for Pine Script.
This library provides a comprehensive set of logical operations supporting trilean logic systems,
including Kleene, Łukasiewicz, and RM3 implications. Compatible with Pine v6 enums.
method validate(self)
Ensures a valid trilean integer value by clamping to the appropriate range .
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The integer value to validate.
Returns: An integer value guaranteed to be within the valid trilean range.
method to_trilean(self)
Converts an integer value to a Trilean enum value.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The integer to convert (typically -1, 0, or 1).
Returns: A Trilean enum value: True (1), Uncertain (0), or False (-1).
method to_int(self)
Converts a Trilean enum value to its corresponding integer representation.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The Trilean enum value to convert.
Returns: Integer value: 1 (True), 0 (Uncertain), or -1 (False).
method NOT(self)
Negates a trilean integer value (NOT operation).
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The integer value to negate.
Returns: Negated integer value: 1 -> -1, 0 -> 0, -1 -> 1.
method NOT(self)
Negates a Trilean enum value (NOT operation).
Namespace types: series Trilean
Parameters:
self (series Trilean) : The Trilean enum value to negate.
Returns: Negated Trilean: True -> False, Uncertain -> Uncertain, False -> True.
method AND(self, comparator)
Logical AND operation for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The first integer value.
comparator (int) : The second integer value to compare with.
Returns: Integer result of the AND operation (minimum value).
method AND(self, comparator)
Logical AND operation for Trilean enum values following three-valued logic.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The first Trilean enum value.
comparator (series Trilean) : The second Trilean enum value to compare with.
Returns: Trilean result of the AND operation.
method OR(self, comparator)
Logical OR operation for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The first integer value.
comparator (int) : The second integer value to compare with.
Returns: Integer result of the OR operation (maximum value).
method OR(self, comparator)
Logical OR operation for Trilean enum values following three-valued logic.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The first Trilean enum value.
comparator (series Trilean) : The second Trilean enum value to compare with.
Returns: Trilean result of the OR operation.
method EQUALITY(self, comparator)
Logical EQUALITY operation for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The first integer value.
comparator (int) : The second integer value to compare with.
Returns: Integer representation (1/-1) indicating if values are equal.
method EQUALITY(self, comparator)
Logical EQUALITY operation for Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The first Trilean enum value.
comparator (series Trilean) : The second Trilean enum value to compare with.
Returns: Trilean.True if both values are equal, Trilean.False otherwise.
method XOR(self, comparator)
Logical XOR (Exclusive OR) operation for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The first integer value.
comparator (int) : The second integer value to compare with.
Returns: Integer result of the XOR operation.
method XOR(self, comparator)
Logical XOR (Exclusive OR) operation for Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The first Trilean enum value.
comparator (series Trilean) : The second Trilean enum value to compare with.
Returns: Trilean result of the XOR operation.
method IMP_K(self, comparator)
Material implication using Kleene's logic for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The antecedent integer value.
comparator (int) : The consequent integer value.
Returns: Integer result of Kleene's implication operation.
method IMP_K(self, comparator)
Material implication using Kleene's logic for Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The antecedent Trilean enum value.
comparator (series Trilean) : The consequent Trilean enum value.
Returns: Trilean result of Kleene's implication operation.
method IMP_L(self, comparator)
Logical implication using Łukasiewicz's logic for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The antecedent integer value.
comparator (int) : The consequent integer value.
Returns: Integer result of Łukasiewicz's implication operation.
method IMP_L(self, comparator)
Logical implication using Łukasiewicz's logic for Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The antecedent Trilean enum value.
comparator (series Trilean) : The consequent Trilean enum value.
Returns: Trilean result of Łukasiewicz's implication operation.
method IMP_RM3(self, comparator)
Logical implication using RM3 logic for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The antecedent integer value.
comparator (int) : The consequent integer value.
Returns: Integer result of the RM3 implication operation.
method IMP_RM3(self, comparator)
Logical implication using RM3 logic for Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The antecedent Trilean enum value.
comparator (series Trilean) : The consequent Trilean enum value.
Returns: Trilean result of the RM3 implication operation.
method MA(self)
Modal Assertion (MA) operation for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The integer value to evaluate.
Returns: 1 if the value is 1 or 0, -1 if the value is -1.
method MA(self)
Modal Assertion (MA) operation for Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The Trilean enum value to evaluate.
Returns: Trilean.True if value is True or Uncertain, Trilean.False if value is False.
method LA(self)
Logical Assertion (LA) operation for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The integer value to evaluate.
Returns: 1 if the value is 1, -1 otherwise.
method LA(self)
Logical Assertion (LA) operation for Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The Trilean enum value to evaluate.
Returns: Trilean.True if value is True, Trilean.False otherwise.
method IA(self)
Indeterminacy Assertion (IA) operation for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The integer value to evaluate.
Returns: 1 if the value is 0, -1 otherwise.
method IA(self)
Indeterminacy Assertion (IA) operation for Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The Trilean enum value to evaluate.
Returns: Trilean.True if value is Uncertain, Trilean.False otherwise.
method UNANIMOUS(self, comparator)
Evaluates the unanimity between two trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The first integer value.
comparator (int) : The second integer value.
Returns: Integer value of self if both values are equal, 0 (Uncertain) otherwise.
method UNANIMOUS(self, comparator)
Evaluates the unanimity between two Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The first Trilean enum value.
comparator (series Trilean) : The second Trilean enum value.
Returns: Value of self if both values are equal, Trilean.Uncertain otherwise.
method UNANIMOUS(self)
Evaluates the unanimity among an array of trilean integer values.
Namespace types: array
Parameters:
self (array) : The array of integer values.
Returns: First value if all values are identical, 0 (Uncertain) otherwise.
method UNANIMOUS(self)
Evaluates the unanimity among an array of Trilean enum values.
Namespace types: array
Parameters:
self (array) : The array of Trilean enum values.
Returns: First value if all values are identical, Trilean.Uncertain otherwise.
UtilLibrary "Util"
defines commonly used utility functions and constants
calc_shares(entry_price, stop, fund, riskPerc)
Calculate number of shares for a trade
Parameters:
entry_price (float)
stop (float) : stop loss price
fund (float) : amount of fund to put in this trade
riskPerc (float) : percentage of fund to be risked in this trade. Default is 5%
Returns: number of shares
trade_exist(trade_id)
Returns if a trade with the specific ID is already open
Parameters:
trade_id (string)
Returns: true/false
trade
Fields:
id (series string)
direction (series TradeDir)
entry_price (series float)
shares (series float)
bars_open (series int)
Cometreon_Public📚 Cometreon Public Library – Advanced Functions for Pine Script
This library contains advanced functions used in my public indicators on TradingView. The goal is to make the code more modular and efficient, allowing users to call pre-built functions for complex calculations without rewriting them from scratch.
🔹 Currently Available Functions:
1️⃣ Moving Average Function – Provides multiple types of moving averages to choose from, including:
SMA (Simple Moving Average)
EMA (Exponential Moving Average)
WMA (Weighted Moving Average)
RMA (Smoothed Moving Average)
HMA (Hull Moving Average)
JMA (Jurik Moving Average)
DEMA (Double Exponential Moving Average)
TEMA (Triple Exponential Moving Average)
LSMA (Least Squares Moving Average)
VWMA (Volume-Weighted Moving Average)
SMMA (Smoothed Moving Average)
KAMA (Kaufman’s Adaptive Moving Average)
ALMA (Arnaud Legoux Moving Average)
FRAMA (Fractal Adaptive Moving Average)
VIDYA (Variable Index Dynamic Average)
2️⃣ Custom RSI – Uses the Moving Average function to modify the calculation method, with an additional option for a dynamic version.
3️⃣ Custom MACD – Uses the Moving Average function to modify the calculation method, with an additional option for a dynamic version.
4️⃣ Custom Alligator – Uses the Moving Average function to modify generic calculations, allowing users to change the calculation method.
CapitalManagementLibrary "CapitalManagement"
TODO: Manage the capital
order_volume(percent_risk, order_entry_price, stop_loss_price)
: Function to calculate order volume according to give risk percent_risk
Parameters:
percent_risk (float)
order_entry_price (float)
stop_loss_price (float)
calculate_takeprofit_price(entry_price, stop_loss_price, risk_reward)
: Function to calculate take profit price according to given risk:reward ratio
Parameters:
entry_price (float)
stop_loss_price (float)
risk_reward (float)
Returns: Return take profit value according to given risk:reward ratio
capital_managementLibrary "capital_management"
TODO: add library description here
Volume_calculation(precent_risk, order_entry_price, stop_loss_price)
TODO: Volume calculation function by placing orders with fiven % risk
Parameters:
precent_risk (float)
order_entry_price (float)
stop_loss_price (float)
Returns: stop_loss_price: Price that place stop loss order
KalmanfilterLibrary "Kalmanfilter"
A sophisticated Kalman Filter implementation for financial time series analysis
@author Rocky-Studio
@version 1.0
initialize(initial_value, process_noise, measurement_noise)
Initializes Kalman Filter parameters
Parameters:
initial_value (float) : (float) The initial state estimate
process_noise (float) : (float) The process noise coefficient (Q)
measurement_noise (float) : (float) The measurement noise coefficient (R)
Returns: A tuple containing
update(prev_state, prev_covariance, measurement, process_noise, measurement_noise)
Update Kalman Filter state
Parameters:
prev_state (float)
prev_covariance (float)
measurement (float)
process_noise (float)
measurement_noise (float)
calculate_measurement_noise(price_series, length)
Adaptive measurement noise calculation
Parameters:
price_series (array)
length (int)
calculate_measurement_noise_simple(price_series)
Parameters:
price_series (array)
update_trading(prev_state, prev_velocity, prev_covariance, measurement, volatility_window)
Enhanced trading update with velocity
Parameters:
prev_state (float)
prev_velocity (float)
prev_covariance (float)
measurement (float)
volatility_window (int)
model4_update(prev_mean, prev_speed, prev_covariance, price, process_noise, measurement_noise)
Kalman Filter Model 4 implementation (Benhamou 2018)
Parameters:
prev_mean (float)
prev_speed (float)
prev_covariance (array)
price (float)
process_noise (array)
measurement_noise (float)
model4_initialize(initial_price)
Initialize Model 4 parameters
Parameters:
initial_price (float)
model4_default_process_noise()
Create default process noise matrix for Model 4
model4_calculate_measurement_noise(price_series, length)
Adaptive measurement noise calculation for Model 4
Parameters:
price_series (array)
length (int)
lib_statemachine_modifiedLibrary "lib_statemachine_modified"
Modified to fix bugs and create getState and priorState methods.
method step(this, before, after, condition)
Namespace types: StateMachine
Parameters:
this (StateMachine)
before (int) : (int): Current state before transition
after (int) : (int): State to transition to
condition (bool) : (bool): Condition to trigger the transition
Returns: (bool): True if the state changed, else False
method step(this, after, condition)
Namespace types: StateMachine
Parameters:
this (StateMachine)
after (int) : (int): State to transition to
condition (bool) : (bool): Condition to trigger the transition
Returns: (bool): True if the state changed, else False
method currentState(this)
Namespace types: StateMachine
Parameters:
this (StateMachine)
method previousState(this)
Namespace types: StateMachine
Parameters:
this (StateMachine)
method changed(this, within_bars)
Namespace types: StateMachine
Parameters:
this (StateMachine)
within_bars (int) : (int): Number of bars to look back for a state change
Returns: (bool): True if a state change occurred within the timeframe, else False
method reset(this, condition, min_occurrences)
Namespace types: StateMachine
Parameters:
this (StateMachine)
condition (bool) : (bool): Condition to trigger the reset
min_occurrences (int) : (int): Minimum number of times the condition must be true to reset
Returns: (bool): True if the state was reset, else False
StateMachine
Fields:
state (series int)
neutral (series int)
enabled (series bool)
reset_counter (series int)
prior_state (series int)
last_change_bar (series int)
Milvetti_Pineconnector_LibraryLibrary "Milvetti_Pineconnector_Library"
This library has methods that provide practical signal transmission for Pineconnector.Developed By Milvetti
buy(licenseId, symbol, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
Create a buy order message
Parameters:
licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
symbol (string) : Symbol. Default is syminfo.ticker
risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
atrPeriod (int) : ATR averaging period. Default is 0
atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
secret (string)
comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
sell(licenseId, symbol, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
Create a buy order message
Parameters:
licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
symbol (string) : Symbol. Default is syminfo.ticker
risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
atrPeriod (int) : ATR averaging period. Default is 0
atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
secret (string)
comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
buyLimit(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
Create a buy limit order message
Parameters:
licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
symbol (string) : Symbol. Default is syminfo.ticker
pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
atrPeriod (int) : ATR averaging period. Default is 0
atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
secret (string)
comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
buyStop(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
Create a buy stop order message
Parameters:
licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
symbol (string) : Symbol. Default is syminfo.ticker
pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
atrPeriod (int) : ATR averaging period. Default is 0
atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
secret (string)
comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
sellLimit(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
Create a sell limit order message
Parameters:
licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
symbol (string) : Symbol. Default is syminfo.ticker
pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
atrPeriod (int) : ATR averaging period. Default is 0
atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
secret (string)
comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
sellStop(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
Create a sell stop order message
Parameters:
licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
symbol (string) : Symbol. Default is syminfo.ticker
pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
atrPeriod (int) : ATR averaging period. Default is 0
atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
secret (string)
comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
BacktestLibraryLibrary "BacktestLibrary"
A library providing functions for equity calculation and performance metrics.
since(date, active)
: Calculates the number of candles since a specified date.
Parameters:
date (simple float) : (simple float): The starting date in timestamp format (e.g., input.time(timestamp()))
active (simple bool) : (simple bool): If true, counts the number of candles since the date; if false, returns 0.
Returns: (int): The number of candles since the specified date.
buy_and_hold(r, startDate)
: Calculates the Buy and Hold Equity from a specified date.
Parameters:
r (float) : (series float): Daily returns of the asset (e.g., 0.02 for 2% move).
startDate (simple float) : (simple float): Timestamp of the starting date for the equity calculation.
Returns: (float): Buy and Hold Equity of the asset from the specified date.
equity(sig, threshold, r, startDate, signals)
: Calculates the strategy's equity on a candle-by-candle basis.
Parameters:
sig (float) : (series float): Signal values; positive for long, negative for short.
threshold (simple float) : (simple float): Signal threshold for entering trades.
r (float) : (series float): Daily returns of the asset (e.g., 0.02 for 2% move).
startDate (simple float) : (simple float): Timestamp of the starting date for the equity calculation.
signals (simple string) : (simple string): Type of signals to backtest ("Long & Short", "Long Only", "Short Only").
Returns: (float): Strategy equity on a candle-by-candle basis.
PerformanceMetrics(base, Lookback, startDate)
: Calculates performance metrics of a strategy from a specified date.
Parameters:
base (float) : (series float): Equity values of the strategy or Buy and Hold equity.
Lookback (int) : (series int): Number of periods since the start date; recommended to use the 'since' function.
startDate (simple float) : (simple float): Timestamp of the starting date for the equity calculation.
Returns: (float ): Array of performance metrics.
PerfMetricTable(buy_and_hold, strategy)
: Plots a table comparing performance metrics of Buy and Hold and Strategy equity.
Parameters:
buy_and_hold (array) : (float ): Metrics from the PerformanceMetrics() function for Buy and Hold.
strategy (array) : (float ): Metrics from the PerformanceMetrics() function for the strategy.
Returns: : Table displaying the performance metrics comparison.
SnowdexUtilsLibrary "SnowdexUtils"
the various function that often use when create a strategy trading.
f_backtesting_date(train_start_date, train_end_date, test_date, deploy_date)
Backtesting within a specific window based on deployment and testing dates.
Parameters:
train_start_date (int) : the start date for training the strategy.
train_end_date (int) : the end date for training the strategy.
test_date (bool) : if true, backtests within the period from `train_end_date` to the current time.
deploy_date (bool) : if true, the strategy backtests up to the current time.
Returns: given time falls within the specified window for backtesting.
f_init_ma(ma_type, source, length)
Initializes a moving average based on the specified type.
Parameters:
ma_type (simple string) : the type of moving average (e.g., "RMA", "EMA", "SMA", "WMA").
source (float) : the input series for the moving average calculation.
length (simple int) : the length of the moving average window.
Returns: the calculated moving average value.
f_init_tp(side, entry_price, rr, sl_open_position)
Calculates the target profit based on entry price, risk-reward ratio, and stop loss. The formula is `tp = entry price + (rr * (entry price - stop loss))`.
Parameters:
side (bool) : the trading side (true for long, false for short).
entry_price (float) : the entry price of the position.
rr (float) : the risk-reward ratio.
sl_open_position (float) : the stop loss price for the open position.
Returns: the calculated target profit value.
f_round_up(number, decimals)
Rounds up a number to a specified number of decimals.
Parameters:
number (float)
decimals (int)
Returns: The rounded-up number.
f_get_pip_size()
Calculates the pip size for the current instrument.
Returns: Pip size adjusted for Forex instruments or 1 for others.
f_table_get_position(value)
Maps a string to a table position constant.
Parameters:
value (string) : String representing the desired position (e.g., "Top Right").
Returns: The corresponding position constant or `na` for invalid values.






















