candle_utilsLibrary "candle_utils"
isRejectionCandle(candleHigh, candleLow, candleOpen, candleClose)
Parameters:
candleHigh (float)
candleLow (float)
candleOpen (float)
candleClose (float)
mergeCandlesForRejection(_numCandles, direction)
Parameters:
_numCandles (int)
direction (int)
hasRejection(direction)
Parameters:
direction (int)
isBullish(open, close)
Parameters:
open (float)
close (float)
isBearish(open, close)
Parameters:
open (float)
close (float)
bodySize(open, close)
Parameters:
open (float)
close (float)
upperWickSize(high, open, close)
Parameters:
high (float)
open (float)
close (float)
lowerWickSize(low, open, close)
Parameters:
low (float)
open (float)
close (float)
Indicators and strategies
array_utilsLibrary "array_utils"
get(arr, index)
Parameters:
arr (array)
index (int)
last(arr)
Parameters:
arr (array)
secondLast(arr)
Parameters:
arr (array)
thirdLast(arr)
Parameters:
arr (array)
fourthLast(arr)
Parameters:
arr (array)
sum(arr)
Parameters:
arr (array)
average(arr)
Parameters:
arr (array)
max(arr)
Parameters:
arr (array)
min(arr)
Parameters:
arr (array)
reverse(arr)
Parameters:
arr (array)
clear(arr)
Parameters:
arr (array)
clone(arr)
Parameters:
arr (array)
base_utilsLibrary "base_utils"
percentOf(num, outOf)
Parameters:
num (float)
outOf (float)
xPercentOf(x, num)
Parameters:
x (float)
num (float)
arrayGet(arr, index)
Parameters:
arr (array)
index (int)
arrayLast(arr)
Parameters:
arr (array)
arraySecondLast(arr)
Parameters:
arr (array)
arrayThirdLast(arr)
Parameters:
arr (array)
arrayFourthLast(arr)
Parameters:
arr (array)
isRejectionCandle(candleHigh, candleLow, candleOpen, candleClose)
Parameters:
candleHigh (float)
candleLow (float)
candleOpen (float)
candleClose (float)
mergeCandlesForRejection(_numCandles, direction)
Parameters:
_numCandles (int)
direction (int)
hasRejection(direction)
Parameters:
direction (int)
QTA_LeGo_LibraryLibrary "QTA_LeGo_Library"
detectFVG(useStrongBody, useWeakSides, useDirectional, bodyStrengthRatio, weakBodyRatio)
Parameters:
useStrongBody (bool)
useWeakSides (bool)
useDirectional (bool)
bodyStrengthRatio (float)
weakBodyRatio (float)
Crypto_in_details_MAlibCrypto_in_details_MaLib — Advanced Moving Average Library for Pine Script
Overview:
Crypto_in_details_MaLib is a comprehensive, performance-optimized Moving Average (MA) library designed specifically for Pine Script v6 users seeking advanced technical analysis tools. Developed by Crypto_in_details, this library consolidates the most popular and sophisticated MA calculation methods — including classical, weighted, exponential, and Hull variants — into one seamless package.
Key Features:
Implements a wide range of Moving Averages: SMA, EMA, WMA, RMA, VWMA, HMA, TEMA, EHMA, THMA.
Designed for precision and flexibility — suitable for diverse trading strategies and indicator development.
Fully typed functions compatible with Pine Script v6 standards.
Simplifies your scripting workflow by providing ready-to-use MA functions via clean and easy-to-import methods.
Well-documented and maintained by an experienced Pine Script developer.
Why Use Crypto_in_details_MaLib?
Gain access to advanced MA calculations that enhance trend analysis, smoothing, and signal accuracy.
Save time on coding complex moving averages from scratch.
Easily extend or combine with your own strategies or indicators for improved performance.
Rely on a tested and community-driven solution backed by a prolific Pine Script author.
Ideal for:
Traders and developers building custom indicators or strategies requiring versatile MA techniques.
Anyone looking to improve their Pine Script efficiency and code maintainability.
Pine Script enthusiasts wanting a professional-grade MA toolkit.
HexworksSharedUtilitiesLibrary "HexworksSharedUtilities"
Shared global utilities that can be used for
- creating bounded queues from primitives
- checking visibility of objects having Bounds on both (x, y) axes
- checking if a line is too long
method offer(history, value)
Namespace types: FloatHistory
Parameters:
history (FloatHistory)
value (simple float)
method offer(history, value)
Namespace types: IntHistory
Parameters:
history (IntHistory)
value (simple int)
method offer(history, value)
Namespace types: StringHistory
Parameters:
history (StringHistory)
value (simple string)
method offer(history, value)
Namespace types: BoolHistory
Parameters:
history (BoolHistory)
value (simple bool)
method toString(point)
Namespace types: chart.point
Parameters:
point (chart.point)
method toString(num)
Namespace types: simple float, input float, const float
Parameters:
num (simple float)
method toString(num)
Namespace types: simple int, input int, const int
Parameters:
num (simple int)
method toString(value)
Namespace types: simple bool, input bool, const bool
Parameters:
value (simple bool)
method toString(l)
Namespace types: series line
Parameters:
l (line)
method isLineTooLong(fromPoint, toPoint)
Namespace types: chart.point
Parameters:
fromPoint (chart.point)
toPoint (chart.point)
method isTooLong(l)
Namespace types: series line
Parameters:
l (line)
createVisibilityChecker()
method update(v)
Namespace types: VisibilityChecker
Parameters:
v (VisibilityChecker)
method canDraw(v)
Namespace types: VisibilityChecker
Parameters:
v (VisibilityChecker)
method isVisible(v, b)
Namespace types: VisibilityChecker
Parameters:
v (VisibilityChecker)
b (Bounds)
FloatHistory
Fields:
history (array)
maxLength (series int)
IntHistory
Fields:
history (array)
maxLength (series int)
StringHistory
Fields:
history (array)
maxLength (series int)
BoolHistory
Fields:
history (array)
maxLength (series int)
Bounds
Fields:
startIdx (series int)
endIdx (series int)
highValue (series float)
lowValue (series float)
VisibilityChecker
Fields:
leftVisibleBarIdx (series int)
rightVisibleBarIdx (series int)
maxDrawDistance (series int)
updatedAt (series int)
visibleHighest (series float)
visibleLowest (series float)
VolumeFlowOscillatorLibVolume Flow Oscillator Library
Overview
The Volume Flow Oscillator library provides a comprehensive framework for analyzing directional volume flow in financial markets. It creates a multi-band oscillator system that transforms price and volume data into a spectrum of sensitivity bands, revealing the underlying buying and selling pressure.
Technical Approach
The library combines price direction with trading volume to generate an oscillator that fluctuates around a zero line, with positive values indicating buying pressure and negative values showing selling pressure. Using sophisticated ALMA (Arnaud Legoux Moving Average) smoothing techniques with asymmetric sensitivity, the library creates seven distinct bands that help identify various intensity levels of volume flow.
Key Features
Multi-band oscillator system with seven sensitivity levels
Directional volume flow analysis combining price movement and volume
Zero-line oscillation showing the balance between buying and selling pressure
Asymmetric ALMA smoothing for different sensitivity on positive/negative bands
Customizable lookback periods and multipliers for fine-tuning
Color-coded visualization for intuitive chart reading
Applications
This library offers developers a versatile foundation for creating volume-based indicators that go beyond simple volume measurement to reveal the directional force behind market movements. Ideal for confirming price trends, detecting divergences, identifying volume climaxes, and assessing overall market strength.
STA_Core_Library_2Library "STA_Core_Library_2"
sta_detect_mss_basic(srcHigh, srcLow, length)
Parameters:
srcHigh (float)
srcLow (float)
length (int)
sta_detect_fvg_box_ict()
sta_detect_ote_box_basic()
sta_detect_order_block_basic()
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
PnL_Visual_LibraryLibrary "PnL_Visual_Library"
f_getFastMA()
f_getSlowMA()
f_getConditions()
f_getEquityGradient()
f_getMaxProfitLoss()
MyLibraryLibrary "MyLibrary"
isPriceAbove(threshold)
Parameters:
threshold (float) :
isBullishCandle()
KTUtilsLibrary "KTUtils"
Utility functions for technical analysis indicators, trend detection, and volatility confirmation.
MGz(close, length)
MGz
@description Moving average smoother used for signal processing
Parameters:
close (float) : float Price input (typically close)
length (int) : int Length of smoothing period
Returns: float Smoothed value
atrConf(length)
atrConf
@description Calculates Average True Range (ATR) for volatility confirmation
Parameters:
length (simple int) : int Length for ATR calculation
Returns: float ATR value
f(input)
f
@description Simple Moving Average with fixed length
Parameters:
input (float) : float Input value
Returns: float Smoothed average
bcwSMA(s, l, m)
bcwSMA
@description Custom smoothing function with weight multiplier
Parameters:
s (float) : float Signal value
l (int) : int Length of smoothing
m (int) : int Weighting multiplier
Returns: float Smoothed output
MGxx(close, length)
MGxx
@description Custom Weighted Moving Average (WMA) variant
Parameters:
close (float) : float Price input
length (int) : int Period length
Returns: float MGxx smoothed output
_PerChange(lengthTime)
_PerChange
@description Measures percentage price change over a period and range deviation
Parameters:
lengthTime (int) : int Period for change measurement
Returns: tuple Measured change, high deviation, low deviation
dirmov(len)
dirmov
@description Calculates directional movement components
Parameters:
len (simple int) : int Lookback period
Returns: tuple Plus and Minus DI values
adx(dilen, adxlen)
adx
@description Calculates Average Directional Index (ADX)
Parameters:
dilen (simple int) : int Length for DI calculation
adxlen (simple int) : int Length for ADX smoothing
Returns: float ADX value
trChopAnalysis()
trChopAnalysis
@description Identifies chop and trend phases based on True Range Bollinger Bands
Returns: tuple TR SMA, chop state, trending state
wtiAnalysis(haclose, close, filterValue)
wtiAnalysis
@description Wave Trend Indicator (WTI) with signal crossover logic
Parameters:
haclose (float) : float Heikin-Ashi close
close (float) : float Standard close
filterValue (simple int) : int Smoothing length
Returns: tuple WTI lines and direction states
basicTrend(hahigh, halow, close, open, filterValue)
basicTrend
@description Determines trend direction based on HA high/low and close
Parameters:
hahigh (float) : float Heikin-Ashi high
halow (float) : float Heikin-Ashi low
close (float) : float Standard close
open (float) : float Standard open
filterValue (simple int) : int Smoothing period
Returns: tuple Uptrend, downtrend flags
metrics(close, filterValue)
metrics
@description Common market metrics
Parameters:
close (float) : float Price input
filterValue (int) : int RSI smoothing length
Returns: tuple VWMA, SMA10, RSI, smoothed RSI
piff(close, trend_change)
piff
@description Price-Informed Forward Forecasting (PIFF) model for trend strength
Parameters:
close (float) : float Price input
trend_change (float) : float Change in trend
Returns: tuple Percent change, flags for trend direction
getMACD()
getMACD
@description Returns MACD, signal line, and histogram
Returns: tuple MACD line, Signal line, Histogram
getStoch()
getStoch
@description Returns K and D lines of Stochastic Oscillator
Returns: tuple K and D lines
getKDJ()
getKDJ
@description KDJ momentum oscillator
Returns: tuple K, D, J, Average
getBBRatio()
getBBRatio
@description Bollinger Band Ratio (BBR) and signal flags
Returns: tuple Basis, Upper, Lower, BBR, BBR Up, BBR Down
getSupertrend()
getSupertrend
@description Supertrend values and direction flags
Returns: tuple Supertrend, Direction, Up, Down
remaLibrary " REMA "
Custom Regional Exponential Moving Average with enhanced sensitivity to recent price action
Description: What Makes REMA Unique?
REMA introduces a dual-region weighting system that intelligently balances short-term responsiveness with long-term trend context, solving the fundamental limitation of standard EMAs where longer periods necessarily sacrifice recent price sensitivity.
Key Differences from Standard EMA:
Adaptive Regional Weighting: Applies stronger exponential decay to recent price data while maintaining appropriate weighting for historical context.
Maintains Responsiveness at Any Length: Unlike standard EMAs where longer periods become progressively less responsive, REMA preserves significant sensitivity to recent price action even at 100+ period lengths.
Mathematically Sound Enhancement: Preserves the core mathematical integrity of exponential averaging while introducing region-specific weighting that better reflects how traders actually interpret price action.
Value to TradingView Community:
Improved Signal Timing: Detects reversals 1-3 bars earlier than traditional EMAs without increasing false signals.
Better Multi-Timeframe Analysis: Provides more consistent behavior across different period settings, reducing conflicting signals between timeframes.
Ideal for Modern Markets: Better handles today's high-volatility, algorithm-driven markets where traditional indicators often lag too much to be effective.
Optimized for Both Trend and Reversal Trading: Simultaneously provides strong trend-following capabilities while remaining sensitive to legitimate reversal signals.
Computation Efficiency: The fast implementation offers enhanced capabilities with minimal computational overhead, making it practical for real-time analysis.
REMA fills a critical gap between lagging long-period EMAs and noisy short-period EMAs, giving traders a single, versatile tool that adapts to market conditions more effectively than standard technical indicators.
Implementation:
rema(src, length, recency_bias, transition_point)
Regional Exponential Moving Average that maintains recent price sensitivity even with long lookback periods
Parameters:
src (float) : Input source series
length (int) : Overall EMA period length
recency_bias (float) : Weighting factor to increase sensitivity to recent prices (1.0-3.0 recommended)
transition_point (float) : Percentage point (0.0-1.0) in the lookback period where weighting shifts from recent to historical
Returns: Custom exponentially weighted moving average with regional bias
rema_fast(src, length, recency_bias)
Simplified Regional EMA that uses a recursive calculation method
Parameters:
src (float) : Input source series
length (int) : Overall EMA period
recency_bias (float) : Factor to increase sensitivity to recent price (1.0-3.0 recommended)
Returns: Computationally efficient regional EMA
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.
UTSConvenienceToolsLibrary "UTSConvenienceTools"
Convenience tool library containing helper functions for drawing and charting.
isDarkColor(color)
Determines on base of the luminance of the given color if the color can be considered a 'dark' color. Usefull for determining the readable font color for arbitrary colored backgrounds. Credits out to:
Parameters:
color (color) : (color): The actual color value.
Returns: (bool): A boolean value.
smallLabelLowerRight(txt, yPos, bgColor)
Displays the specified `txt` in a small label at the `yPos` of the current bar. The label points to the lower right.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
smallLabelUpperRight(txt, yPos, bgColor)
Displays the specified `txt` in a small label at the `yPos` of the current bar. The label points to the upper right.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned below the candle pass 'low'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
smallLabelCenter(txt, yPos, bgColor)
Displays the specified `txt` in a small label at the `yPos` of the current bar. The label points to the center.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'. To have it positioned below the candle pass 'low'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
smallLabelDown(txt, yPos, bgColor)
Displays the specified `txt` in a small label at the `yPos` of the current bar. The label points down.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
smallLabelUp(txt, yPos, bgColor)
Displays the specified `txt` in a small label at the `yPos` of the current bar. The label points down.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned below the candle pass 'low'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
normalLabelLowerRight(txt, yPos, bgColor)
Displays the specified `txt` in a normal label at the `yPos` of the current bar. The label points to the lower right.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
normalLabelUpperRight(txt, yPos, bgColor)
Displays the specified `txt` in a normal label at the `yPos` of the current bar. The label points to the upper right.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned below the candle pass 'low'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
normalLabelCenter(txt, yPos, bgColor)
Displays the specified `txt` in a normal label at the `yPos` of the current bar. The label points to the center.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'. To have it positioned below the candle pass 'low'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
normalLabelDown(txt, yPos, bgColor)
Displays the specified `txt` in a normal label at the `yPos` of the current bar. The label points down.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
normalLabelUp(txt, yPos, bgColor)
Displays the specified `txt` in a normal label at the `yPos` of the current bar. The label points down.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned below the candle pass 'low'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
largeLabelLowerRight(txt, yPos, bgColor)
Displays the specified `txt` in a large label at the `yPos` of the current bar. The label points to the lower right.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
largeLabelUpperRight(txt, yPos, bgColor)
Displays the specified `txt` in a large label at the `yPos` of the current bar. The label points to the upper right.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned below the candle pass 'low'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
largeLabelCenter(txt, yPos, bgColor)
Displays the specified `txt` in a large label at the `yPos` of the current bar. The label points to the center.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'. To have it positioned below the candle pass 'low'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
largeLabelDown(txt, yPos, bgColor)
Displays the specified `txt` in a large label at the `yPos` of the current bar. The label points down.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
largeLabelUp(txt, yPos, bgColor)
Displays the specified `txt` in a large label at the `yPos` of the current bar. The label points down.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned below the candle pass 'low'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
autoLabelLowerRight(txt, yPos, bgColor)
Displays the specified `txt` in a auto label at the `yPos` of the current bar. The label points to the lower right.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
autoLabelUpperRight(txt, yPos, bgColor)
Displays the specified `txt` in a auto label at the `yPos` of the current bar. The label points to the upper right.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned below the candle pass 'low'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
autoLabelCenter(txt, yPos, bgColor)
Displays the specified `txt` in a auto label at the `yPos` of the current bar. The label points to the center.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'. To have it positioned below the candle pass 'low'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
autoLabelDown(txt, yPos, bgColor)
Displays the specified `txt` in a auto label at the `yPos` of the current bar. The label points down.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned above the candle pass 'high'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
autoLabelUp(txt, yPos, bgColor)
Displays the specified `txt` in a auto label at the `yPos` of the current bar. The label points down.
Parameters:
txt (string)
yPos (float) : (float): The y-position value. To have it positioned below the candle pass 'low'.
bgColor (color) : (color): The background color value.
Returns: (bool): A boolean value.
visualizationLibrary "visualization"
method tagLine(message, priceLevel, showCondition, labelPosition, labelSize, offsetX, textColor, bgColor, lineWidth, lineStyle)
Creates a textLabel with line at specified price level
Namespace types: series string, simple string, input string, const string
Parameters:
message (string) : Text to display in the textLabel. If starts with '$', price included. Empty = no textLabel
priceLevel (float) : Price level for textLabel and line positioning
showCondition (bool) : Condition to display the textLabel and line
labelPosition (string) : Label position ("above", "below")
labelSize (string) : Label size
offsetX (int) : X-axis offset for textLabel and line
textColor (color) : Text color
bgColor (color) : Background color
lineWidth (int) : Line width
lineStyle (string) : Line style
Returns: void
textLabel(message, showCondition, position, textColor)
Creates dynamic labels with optional arrows
Parameters:
message (string) : Message to show (prefix with "!" to hide arrow)
showCondition (bool) : Display condition
position (string) : Label position ("above", "below")
textColor (color) : Text color
Returns: void
box(showCondition, topValue, bottomValue, barsBack, borderColor, bgColor)
Creates a box around price range
Parameters:
showCondition (bool) : Condition to draw the box
topValue (float) : Optional custom top value
bottomValue (float) : Optional custom bottom value
barsBack (int) : Number of bars to look back
borderColor (color) : Box border color
bgColor (color) : Box background color
Returns: box Box object
pymath█ OVERVIEW
This library ➕ enhances Pine Script's built-in types (`float`, `int`, `array`, `array`) with mathematical methods, mirroring 🪞 many functions from Python's `math` module. Import this library to overload or add to built-in capabilities, enabling calls like `myFloat.sin()` or `myIntArray.gcd()`.
█ CONCEPTS
This library wraps Pine's built-in `math.*` functions and implements others where necessary, expanding the mathematical toolkit available within Pine Script. It provides a more object-oriented approach to mathematical operations on core data types.
█ HOW TO USE
• Import the library: i mport kaigouthro/pymath/1
• Call methods directly on variables: myFloat.sin() , myIntArray.gcd()
• For raw integer literals, you MUST use parentheses: `(1234).factorial()`.
█ FEATURES
• **Infinity Handling:** Includes `isinf()` and `isfinite()` for robust checks. Uses `POS_INF_PROXY` to represent infinity.
• **Comprehensive Math Functions:** Implements a wide range of methods, including trigonometric, logarithmic, hyperbolic, and array operations.
• **Object-Oriented Approach:** Allows direct method calls on `int`, `float`, and arrays for cleaner code.
• **Improved Accuracy:** Some functions (e.g., `remainder()`) offer improved accuracy compared to default Pine behavior.
• **Helper Functions:** Internal helper functions optimize calculations and handle edge cases.
█ NOTES
This library improves upon Pine Script's built-in `math` functions by adding new ones and refining existing implementations. It handles edge cases such as infinity, NaN, and zero values, enhancing the reliability of your Pine scripts. For Speed, it wraps and uses built-ins, as thy are fastest.
█ EXAMPLES
//@version=6
indicator("My Indicator")
// Import the library
import kaigouthro/pymath/1
// Create some Vars
float myFloat = 3.14159
int myInt = 10
array myIntArray = array.from(1, 2, 3, 4, 5)
// Now you can...
plot( myFloat.sin() ) // Use sin() method on a float, using built in wrapper
plot( (myInt).factorial() ) // Factorial of an integer (note parentheses)
plot( myIntArray.gcd() ) // GCD of an integer array
method isinf(self)
isinf: Checks if this float is positive or negative infinity using a proxy value.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) value to check.
Returns: (bool) `true` if the absolute value of `self` is greater than or equal to the infinity proxy, `false` otherwise.
method isfinite(self)
isfinite: Checks if this float is finite (not NaN and not infinity).
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The value to check.
Returns: (bool) `true` if `self` is not `na` and not infinity (as defined by `isinf()`), `false` otherwise.
method fmod(self, divisor)
fmod: Returns the C-library style floating-point remainder of `self / divisor` (result has the sign of `self`).
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) Dividend `x`.
divisor (float) : (float) Divisor `y`. Cannot be zero or `na`.
Returns: (float) The remainder `x - n*y` where n is `trunc(x/y)`, or `na` if divisor is 0, `na`, or inputs are infinite in a way that prevents calculation.
method factorial(self)
factorial: Calculates the factorial of this non-negative integer.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : (int) The integer `n`. Must be non-negative.
Returns: (float) `n!` as a float, or `na` if `n` is negative or overflow occurs (based on `isinf`).
method isqrt(self)
isqrt: Calculates the integer square root of this non-negative integer (floor of the exact square root).
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : (int) The non-negative integer `n`.
Returns: (int) The greatest integer `a` such that a² <= n, or `na` if `n` is negative.
method comb(self, k)
comb: Calculates the number of ways to choose `k` items from `self` items without repetition and without order (Binomial Coefficient).
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : (int) Total number of items `n`. Must be non-negative.
k (int) : (int) Number of items to choose. Must be non-negative.
Returns: (float) The binomial coefficient nCk, or `na` if inputs are invalid (n<0 or k<0), `k > n`, or overflow occurs.
method perm(self, k)
perm: Calculates the number of ways to choose `k` items from `self` items without repetition and with order (Permutations).
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : (int) Total number of items `n`. Must be non-negative.
k (simple int) : (simple int = na) Number of items to choose. Must be non-negative. Defaults to `n` if `na`.
Returns: (float) The number of permutations nPk, or `na` if inputs are invalid (n<0 or k<0), `k > n`, or overflow occurs.
method log2(self)
log2: Returns the base-2 logarithm of this float. Input must be positive. Wraps `math.log(self) / math.log(2.0)`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number. Must be positive.
Returns: (float) The base-2 logarithm, or `na` if input <= 0.
method trunc(self)
trunc: Returns this float with the fractional part removed (truncates towards zero).
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number.
Returns: (int) The integer part, or `na` if input is `na` or infinite.
method abs(self)
abs: Returns the absolute value of this float. Wraps `math.abs()`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number.
Returns: (float) The absolute value, or `na` if input is `na`.
method acos(self)
acos: Returns the arccosine of this float, in radians. Wraps `math.acos()`. Input must be between -1 and 1.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number. Must be between -1 and 1.
Returns: (float) Angle in radians , or `na` if input is outside or `na`.
method asin(self)
asin: Returns the arcsine of this float, in radians. Wraps `math.asin()`. Input must be between -1 and 1.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number. Must be between -1 and 1.
Returns: (float) Angle in radians , or `na` if input is outside or `na`.
method atan(self)
atan: Returns the arctangent of this float, in radians. Wraps `math.atan()`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number.
Returns: (float) Angle in radians , or `na` if input is `na`.
method ceil(self)
ceil: Returns the ceiling of this float (smallest integer >= self). Wraps `math.ceil()`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number.
Returns: (int) The ceiling value, or `na` if input is `na` or infinite.
method cos(self)
cos: Returns the cosine of this float (angle in radians). Wraps `math.cos()`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The angle in radians.
Returns: (float) The cosine, or `na` if input is `na`.
method degrees(self)
degrees: Converts this float from radians to degrees. Wraps `math.todegrees()`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The angle in radians.
Returns: (float) The angle in degrees, or `na` if input is `na`.
method exp(self)
exp: Returns e raised to the power of this float. Wraps `math.exp()`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The exponent.
Returns: (float) `e**self`, or `na` if input is `na`.
method floor(self)
floor: Returns the floor of this float (largest integer <= self). Wraps `math.floor()`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number.
Returns: (int) The floor value, or `na` if input is `na` or infinite.
method log(self)
log: Returns the natural logarithm (base e) of this float. Wraps `math.log()`. Input must be positive.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number. Must be positive.
Returns: (float) The natural logarithm, or `na` if input <= 0 or `na`.
method log10(self)
log10: Returns the base-10 logarithm of this float. Wraps `math.log10()`. Input must be positive.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number. Must be positive.
Returns: (float) The base-10 logarithm, or `na` if input <= 0 or `na`.
method pow(self, exponent)
pow: Returns this float raised to the power of `exponent`. Wraps `math.pow()`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The base.
exponent (float) : (float) The exponent.
Returns: (float) `self**exponent`, or `na` if inputs are `na` or lead to undefined results.
method radians(self)
radians: Converts this float from degrees to radians. Wraps `math.toradians()`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The angle in degrees.
Returns: (float) The angle in radians, or `na` if input is `na`.
method round(self)
round: Returns the nearest integer to this float. Wraps `math.round()`. Ties are rounded away from zero.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number.
Returns: (int) The rounded integer, or `na` if input is `na` or infinite.
method sign(self)
sign: Returns the sign of this float (-1, 0, or 1). Wraps `math.sign()`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number.
Returns: (int) -1 if negative, 0 if zero, 1 if positive, `na` if input is `na`.
method sin(self)
sin: Returns the sine of this float (angle in radians). Wraps `math.sin()`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The angle in radians.
Returns: (float) The sine, or `na` if input is `na`.
method sqrt(self)
sqrt: Returns the square root of this float. Wraps `math.sqrt()`. Input must be non-negative.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number. Must be non-negative.
Returns: (float) The square root, or `na` if input < 0 or `na`.
method tan(self)
tan: Returns the tangent of this float (angle in radians). Wraps `math.tan()`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The angle in radians.
Returns: (float) The tangent, or `na` if input is `na`.
method acosh(self)
acosh: Returns the inverse hyperbolic cosine of this float. Input must be >= 1.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number. Must be >= 1.
Returns: (float) The inverse hyperbolic cosine, or `na` if input < 1 or `na`.
method asinh(self)
asinh: Returns the inverse hyperbolic sine of this float.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number.
Returns: (float) The inverse hyperbolic sine, or `na` if input is `na`.
method atanh(self)
atanh: Returns the inverse hyperbolic tangent of this float. Input must be between -1 and 1 (exclusive).
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number. Must be between -1 and 1 (exclusive).
Returns: (float) The inverse hyperbolic tangent, or `na` if input is outside (-1, 1) or `na`.
method cosh(self)
cosh: Returns the hyperbolic cosine of this float.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number.
Returns: (float) The hyperbolic cosine, or `na` if input is `na`.
method sinh(self)
sinh: Returns the hyperbolic sine of this float.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number.
Returns: (float) The hyperbolic sine, or `na` if input is `na`.
method tanh(self)
tanh: Returns the hyperbolic tangent of this float.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The input number.
Returns: (float) The hyperbolic tangent, or `na` if input is `na`.
method atan2(self, dx)
atan2: Returns the angle in radians between the positive x-axis and the point (dx, self). Wraps `math.atan2()`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The y-coordinate `y`.
dx (float) : (float) The x-coordinate `x`.
Returns: (float) The angle in radians , result of `math.atan2(self, dx)`. Returns `na` if inputs are `na`. Note: `math.atan2(0, 0)` returns 0 in Pine.
Optimization: Use built-in math.atan2()
method cbrt(self)
cbrt: Returns the cube root of this float.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The value to find the cube root of.
Returns: (float) The real cube root. Handles negative inputs correctly, or `na` if input is `na`.
method exp2(self)
exp2: Returns 2 raised to the power of this float. Calculated as `2.0.pow(self)`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The exponent.
Returns: (float) `2**self`, or `na` if input is `na` or results in non-finite value.
method expm1(self)
expm1: Returns `e**self - 1`. Calculated as `self.exp() - 1.0`. May offer better precision for small `self` in some environments, but Pine provides no guarantee over `self.exp() - 1.0`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The exponent.
Returns: (float) `e**self - 1`, or `na` if input is `na` or `self.exp()` is `na`.
method log1p(self)
log1p: Returns the natural logarithm of (1 + self). Calculated as `(1.0 + self).log()`. Pine provides no specific precision guarantee for self near zero.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) Value to add to 1. `1 + self` must be positive.
Returns: (float) Natural log of `1 + self`, or `na` if input is `na` or `1 + self <= 0`.
method modf(self)
modf: Returns the fractional and integer parts of this float as a tuple ` `. Both parts have the sign of `self`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The number `x` to split.
Returns: ( ) A tuple containing ` `, or ` ` if `x` is `na` or non-finite.
method remainder(self, divisor)
remainder: Returns the IEEE 754 style remainder of `self` with respect to `divisor`. Result `r` satisfies `abs(r) <= 0.5 * abs(divisor)`. Uses round-half-to-even.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) Dividend `x`.
divisor (float) : (float) Divisor `y`. Cannot be zero or `na`.
Returns: (float) The IEEE 754 remainder, or `na` if divisor is 0, `na`, or inputs are non-finite in a way that prevents calculation.
method copysign(self, signSource)
copysign: Returns a float with the magnitude (absolute value) of `self` but the sign of `signSource`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) Value providing the magnitude `x`.
signSource (float) : (float) Value providing the sign `y`.
Returns: (float) `abs(x)` with the sign of `y`, or `na` if either input is `na`.
method frexp(self)
frexp: Returns the mantissa (m) and exponent (e) of this float `x` as ` `, such that `x = m * 2^e` and `0.5 <= abs(m) < 1` (unless `x` is 0).
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) The number `x` to decompose.
Returns: ( ) A tuple ` `, or ` ` if `x` is 0, or ` ` if `x` is non-finite or `na`.
method isclose(self, other, rel_tol, abs_tol)
isclose: Checks if this float `a` and `other` float `b` are close within relative and absolute tolerances.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) First value `a`.
other (float) : (float) Second value `b`.
rel_tol (simple float) : (simple float = 1e-9) Relative tolerance. Must be non-negative and less than 1.0.
abs_tol (simple float) : (simple float = 0.0) Absolute tolerance. Must be non-negative.
Returns: (bool) `true` if `abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)`. Handles `na`/`inf` appropriately. Returns `na` if tolerances are invalid.
method ldexp(self, exponent)
ldexp: Returns `self * (2**exponent)`. Inverse of `frexp`.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : (float) Mantissa part `x`.
exponent (int) : (int) Exponent part `i`.
Returns: (float) The result of `x * pow(2, i)`, or `na` if inputs are `na` or result is non-finite.
method gcd(self)
gcd: Calculates the Greatest Common Divisor (GCD) of all integers in this array.
Namespace types: array
Parameters:
self (array) : (array) An array of integers.
Returns: (int) The largest positive integer that divides all non-zero elements, 0 if all elements are 0 or array is empty. Returns `na` if any element is `na`.
method lcm(self)
lcm: Calculates the Least Common Multiple (LCM) of all integers in this array.
Namespace types: array
Parameters:
self (array) : (array) An array of integers.
Returns: (int) The smallest positive integer that is a multiple of all non-zero elements, 0 if any element is 0, 1 if array is empty. Returns `na` on potential overflow or if any element is `na`.
method dist(self, other)
dist: Returns the Euclidean distance between this point `p` and another point `q` (given as arrays of coordinates).
Namespace types: array
Parameters:
self (array) : (array) Coordinates of the first point `p`.
other (array) : (array) Coordinates of the second point `q`. Must have the same size as `p`.
Returns: (float) The Euclidean distance, or `na` if arrays have different sizes, are empty, or contain `na`/non-finite values.
method fsum(self)
fsum: Returns an accurate floating-point sum of values in this array. Uses built-in `array.sum()`. Note: Pine Script does not guarantee the same level of precision tracking as Python's `math.fsum`.
Namespace types: array
Parameters:
self (array) : (array) The array of floats to sum.
Returns: (float) The sum of the array elements. Returns 0.0 for an empty array. Returns `na` if any element is `na`.
method hypot(self)
hypot: Returns the Euclidean norm (distance from origin) for this point given by coordinates in the array. `sqrt(sum(x*x for x in coordinates))`.
Namespace types: array
Parameters:
self (array) : (array) Array of coordinates defining the point.
Returns: (float) The Euclidean norm, or 0.0 if the array is empty. Returns `na` if any element is `na` or non-finite.
method prod(self, start)
prod: Calculates the product of all elements in this array.
Namespace types: array
Parameters:
self (array) : (array) The array of values to multiply.
start (simple float) : (simple float = 1.0) The starting value for the product (returned if the array is empty).
Returns: (float) The product of array elements * start. Returns `na` if any element is `na`.
method sumprod(self, other)
sumprod: Returns the sum of products of values from this array `p` and another array `q` (dot product).
Namespace types: array
Parameters:
self (array) : (array) First array of values `p`.
other (array) : (array) Second array of values `q`. Must have the same size as `p`.
Returns: (float) The sum of `p * q ` for all i, or `na` if arrays have different sizes or contain `na`/non-finite values. Returns 0.0 for empty arrays.
SMCDrawingLibrary "SMCDrawing"
drawSwingPointLabel(bar_index, price, swing_type, text_color, size)
Parameters:
bar_index (int)
price (float)
swing_type (string)
text_color (color)
size (string)
drawBOSLabel(start_bar, price, end_bar, bos_text, line_color, line_style, line_width, text_color, size)
Parameters:
start_bar (int)
price (float)
end_bar (int)
bos_text (string)
line_color (color)
line_style (string)
line_width (int)
text_color (color)
size (string)
drawRetracementLine(start_bar, price, end_bar, line_color, line_style, line_width)
Parameters:
start_bar (int)
price (float)
end_bar (int)
line_color (color)
line_style (string)
line_width (int)
drawFVG(high_time, low_time, high_price, low_price, is_bullish, line_color, line_width, bar_time)
Parameters:
high_time (int)
low_time (int)
high_price (float)
low_price (float)
is_bullish (bool)
line_color (color)
line_width (int)
bar_time (int)
drawBPRLabel(bar_time, price, is_bullish, text_color)
Parameters:
bar_time (int)
price (float)
is_bullish (bool)
text_color (color)
drawVolumeSpike(bar_time, price, percent_oi, normalized_volume, spike_color)
Parameters:
bar_time (int)
price (float)
percent_oi (float)
normalized_volume (float)
spike_color (color)
drawCandle(bar_index, open, high, low, close, up_color, down_color, wick_color, up_border_color, down_border_color)
Parameters:
bar_index (int)
open (float)
high (float)
low (float)
close (float)
up_color (color)
down_color (color)
wick_color (color)
up_border_color (color)
down_border_color (color)
SMCFunctionsLibrary "SMCFunctions"
findSwingPoints(high, low, swing_size)
Parameters:
high (float)
low (float)
swing_size (int)
detectBOS(close, high, low, prevHigh, prevLow, highActive, lowActive, bos_conf_type)
Parameters:
close (float)
high (float)
low (float)
prevHigh (float)
prevLow (float)
highActive (bool)
lowActive (bool)
bos_conf_type (string)
getBOSDetails(highBroken, lowBroken, prevHigh, prevLow, prevSwing, prevHighIndex, prevLowIndex, input_show_choch)
Parameters:
highBroken (bool)
lowBroken (bool)
prevHigh (float)
prevLow (float)
prevSwing (int)
prevHighIndex (int)
prevLowIndex (int)
input_show_choch (bool)
calculateRetracementLevels(start_price, end_price)
Parameters:
start_price (float)
end_price (float)
MLExtensions_CoreLibrary "MLExtensions_Core"
A set of extension methods for a novel implementation of a Approximate Nearest Neighbors (ANN) algorithm in Lorentzian space, focused on computation.
normalizeDeriv(src, quadraticMeanLength)
Returns the smoothed hyperbolic tangent of the input series.
Parameters:
src (float) : The input series (i.e., the first-order derivative for price).
quadraticMeanLength (int) : The length of the quadratic mean (RMS).
Returns: nDeriv The normalized derivative of the input series.
normalize(src, min, max)
Rescales a source value with an unbounded range to a target range.
Parameters:
src (float) : The input series
min (float) : The minimum value of the unbounded range
max (float) : The maximum value of the unbounded range
Returns: The normalized series
rescale(src, oldMin, oldMax, newMin, newMax)
Rescales a source value with a bounded range to anther bounded range
Parameters:
src (float) : The input series
oldMin (float) : The minimum value of the range to rescale from
oldMax (float) : The maximum value of the range to rescale from
newMin (float) : The minimum value of the range to rescale to
newMax (float) : The maximum value of the range to rescale to
Returns: The rescaled series
getColorShades(color)
Creates an array of colors with varying shades of the input color
Parameters:
color (color) : The color to create shades of
Returns: An array of colors with varying shades of the input color
getPredictionColor(prediction, neighborsCount, shadesArr)
Determines the color shade based on prediction percentile
Parameters:
prediction (float) : Value of the prediction
neighborsCount (int) : The number of neighbors used in a nearest neighbors classification
shadesArr (array) : An array of colors with varying shades of the input color
Returns: shade Color shade based on prediction percentile
color_green(prediction)
Assigns varying shades of the color green based on the KNN classification
Parameters:
prediction (float) : Value (int|float) of the prediction
Returns: color
color_red(prediction)
Assigns varying shades of the color red based on the KNN classification
Parameters:
prediction (float) : Value of the prediction
Returns: color
tanh(src)
Returns the the hyperbolic tangent of the input series. The sigmoid-like hyperbolic tangent function is used to compress the input to a value between -1 and 1.
Parameters:
src (float) : The input series (i.e., the normalized derivative).
Returns: tanh The hyperbolic tangent of the input series.
dualPoleFilter(src, lookback)
Returns the smoothed hyperbolic tangent of the input series.
Parameters:
src (float) : The input series (i.e., the hyperbolic tangent).
lookback (int) : The lookback window for the smoothing.
Returns: filter The smoothed hyperbolic tangent of the input series.
tanhTransform(src, smoothingFrequency, quadraticMeanLength)
Returns the tanh transform of the input series.
Parameters:
src (float) : The input series (i.e., the result of the tanh calculation).
smoothingFrequency (int)
quadraticMeanLength (int)
Returns: signal The smoothed hyperbolic tangent transform of the input series.
n_rsi(src, n1, n2)
Returns the normalized RSI ideal for use in ML algorithms.
Parameters:
src (float) : The input series (i.e., the result of the RSI calculation).
n1 (simple int) : The length of the RSI.
n2 (simple int) : The smoothing length of the RSI.
Returns: signal The normalized RSI.
n_cci(src, n1, n2)
Returns the normalized CCI ideal for use in ML algorithms.
Parameters:
src (float) : The input series (i.e., the result of the CCI calculation).
n1 (simple int) : The length of the CCI.
n2 (simple int) : The smoothing length of the CCI.
Returns: signal The normalized CCI.
n_wt(src, n1, n2)
Returns the normalized WaveTrend Classic series ideal for use in ML algorithms.
Parameters:
src (float) : The input series (i.e., the result of the WaveTrend Classic calculation).
n1 (simple int)
n2 (simple int)
Returns: signal The normalized WaveTrend Classic series.
n_adx(highSrc, lowSrc, closeSrc, n1)
Returns the normalized ADX ideal for use in ML algorithms.
Parameters:
highSrc (float) : The input series for the high price.
lowSrc (float) : The input series for the low price.
closeSrc (float) : The input series for the close price.
n1 (simple int) : The length of the ADX.
regime_filter(src, threshold, useRegimeFilter)
Parameters:
src (float)
threshold (float)
useRegimeFilter (bool)
filter_adx(src, length, adxThreshold, useAdxFilter)
filter_adx
Parameters:
src (float) : The source series.
length (simple int) : The length of the ADX.
adxThreshold (int) : The ADX threshold.
useAdxFilter (bool) : Whether to use the ADX filter.
Returns: The ADX.
filter_volatility(minLength, maxLength, sensitivityMultiplier, useVolatilityFilter)
filter_volatility
Parameters:
minLength (simple int) : The minimum length of the ATR.
maxLength (simple int) : The maximum length of the ATR.
sensitivityMultiplier (float) : Multiplier for the historical ATR to control sensitivity.
useVolatilityFilter (bool) : Whether to use the volatility filter.
Returns: Boolean indicating whether or not to let the signal pass through the filter.
WebhookGeneratorLibrary "WebhookGenerator"
Generates Json objects for webhook messages.
GenerateOT(license_id, symbol, action, order_type, trade_type, size, price, tp, sl, risk, trailPrice, trailOffset)
CreateOrderTicket: Establishes a order ticket.
Parameters:
license_id (string) : Provide your license index
symbol (string) : Symbol on which to execute the trade
action (string) : Execution method of the trade : "MRKT" or "PENDING"
order_type (string) : Direction type of the order: "BUY" or "SELL"
trade_type (string) : Is it a "SPREAD" trade or a "SINGLE" symbol execution?
size (float) : Size of the trade, in units
price (float) : If the order is pending you must specify the execution price
tp (float) : (Optional) Take profit of the order
sl (float) : (Optional) Stop loss of the order
risk (float) : Percent to risk for the trade, if size not specified
trailPrice (float) : (Optional) Price at which trailing stop is starting
trailOffset (float) : (Optional) Amount to trail by
Returns: Return Order string
VolumaticDataLibraryLibrary "VolumaticDataLibrary"
norm(src)
Normalizes a value if mean is 0
This function does not access global variables.
Parameters:
src (float)
addVolumeNodeIfSignificant(level, line_amount, node_prices, node_volumes, node_colors, color_up, color_dn, src_open, src_high, src_low, src_close, src_volume)
Processes the current bar's data to see if it represents a significant volume node,
and if so, updates the provided arrays with the node data.
This function should be called on every bar from the consuming indicator/strategy.
Parameters:
level (float) : The sensitivity level for detecting nodes.
line_amount (int) : The maximum number of nodes to store.
node_prices (array) : Array to store node prices (passed by reference).
node_volumes (array) : Array to store node absolute volumes (passed by reference).
node_colors (array) : Array to store node colors (passed by reference).
color_up (color) : The color to use for upward significant volume.
color_dn (color) : The color to use for downward significant volume.
src_open (float) : The open price series from the calling script.
src_high (float) : The high price series from the calling script.
src_low (float) : The low price series from the calling script.
src_close (float) : The close price series from the calling script.
src_volume (float) : The volume series from the calling script.
createVolumeNodeArray(node_prices, node_volumes, node_colors)
Creates an array of VolumeNode objects from the provided separate arrays.
This function can be called on the last bar from the consuming indicator/strategy
to get the current list of significant volume nodes.
Parameters:
node_prices (array) : Array containing the prices of the nodes.
node_volumes (array) : Array containing the absolute volumes of the nodes.
node_colors (array) : Array containing the colors of the nodes.
Returns: An array of VolumeNode objects representing the stored volume nodes.
VolumeNode
Fields:
price (series float)
volume (series float)
node_color (series color)
AllCandlestickPatternsLibraryAll Candlestick Patterns Library
The Candlestick Patterns Library is a Pine Script (version 6) library extracted from the All Candlestick Patterns indicator. It provides a comprehensive set of functions to calculate candlestick properties, detect market trends, and identify various candlestick patterns (bullish, bearish, and neutral). The library is designed for reusability, enabling TradingView users to incorporate pattern detection into their own scripts, such as indicators or strategies.
The library is organized into three main sections:
Trend Detection: Functions to determine market trends (uptrend or downtrend) based on user-defined rules.
Candlestick Property Calculations: A function to compute core properties of a candlestick, such as body size, shadow lengths, and doji characteristics.
Candlestick Pattern Detection: Functions to detect specific candlestick patterns, each returning a tuple with detection status, pattern name, type, and description.
Library Structure
1. Trend Detection
This section includes the detectTrend function, which identifies whether the market is in an uptrend or downtrend based on user-specified rules, such as the relationship between the closing price and Simple Moving Averages (SMAs).
Function: detectTrend
Parameters:
downTrend (bool): Initial downtrend condition.
upTrend (bool): Initial uptrend condition.
trendRule (string): The rule for trend detection ("SMA50" or "SMA50, SMA200").
p_close (float): Current closing price.
sma50 (float): Simple Moving Average over 50 periods.
sma200 (float): Simple Moving Average over 200 periods.
Returns: A tuple indicating the detected trend.
Logic:
If trendRule is "SMA50", a downtrend is detected when p_close < sma50, and an uptrend when p_close > sma50.
If trendRule is "SMA50, SMA200", a downtrend is detected when p_close < sma50 and sma50 < sma200, and an uptrend when p_close > sma50 and sma50 > sma200.
2. Candlestick Property Calculations
This section includes the calculateCandleProperties function, which computes essential properties of a candlestick based on OHLC (Open, High, Low, Close) data and configuration parameters.
Function: calculateCandleProperties
Parameters:
p_open (float): Candlestick open price.
p_close (float): Candlestick close price.
p_high (float): Candlestick high price.
p_low (float): Candlestick low price.
bodyAvg (float): Average body size (e.g., from EMA of body sizes).
shadowPercent (float): Minimum shadow size as a percentage of body size.
shadowEqualsPercent (float): Tolerance for equal shadows in doji detection.
dojiBodyPercent (float): Maximum body size as a percentage of range for doji detection.
Returns: A tuple containing 17 properties:
C_BodyHi (float): Higher of open or close price.
C_BodyLo (float): Lower of open or close price.
C_Body (float): Body size (difference between C_BodyHi and C_BodyLo).
C_SmallBody (bool): True if body size is below bodyAvg.
C_LongBody (bool): True if body size is above bodyAvg.
C_UpShadow (float): Upper shadow length (p_high - C_BodyHi).
C_DnShadow (float): Lower shadow length (C_BodyLo - p_low).
C_HasUpShadow (bool): True if upper shadow exceeds shadowPercent of body.
C_HasDnShadow (bool): True if lower shadow exceeds shadowPercent of body.
C_WhiteBody (bool): True if candle is bullish (p_open < p_close).
C_BlackBody (bool): True if candle is bearish (p_open > p_close).
C_Range (float): Candlestick range (p_high - p_low).
C_IsInsideBar (bool): True if current candle body is inside the previous candle's body.
C_BodyMiddle (float): Midpoint of the candle body.
C_ShadowEquals (bool): True if upper and lower shadows are equal within shadowEqualsPercent.
C_IsDojiBody (bool): True if body size is small relative to range (C_Body <= C_Range * dojiBodyPercent / 100).
C_Doji (bool): True if the candle is a doji (C_IsDojiBody and C_ShadowEquals).
Purpose: These properties are used by pattern detection functions to evaluate candlestick formations.
3. Candlestick Pattern Detection
This section contains functions to detect specific candlestick patterns, each returning a tuple . The patterns are categorized as bullish, bearish, or neutral, and include detailed descriptions for use in tooltips or alerts.
Supported Patterns
The library supports the following candlestick patterns, grouped by type:
Bullish Patterns:
Rising Window: A two-candle continuation pattern in an uptrend with a price gap between the first candle's high and the second candle's low.
Rising Three Methods: A five-candle continuation pattern with a long green candle, three short red candles, and another long green candle.
Tweezer Bottom: A two-candle reversal pattern in a downtrend with nearly identical lows.
Upside Tasuki Gap: A three-candle continuation pattern in an uptrend with a gap between the first two green candles and a red candle closing partially into the gap.
Doji Star (Bullish): A two-candle reversal pattern in a downtrend with a long red candle followed by a doji gapping down.
Morning Doji Star: A three-candle reversal pattern with a long red candle, a doji gapping down, and a long green candle.
Piercing: A two-candle reversal pattern in a downtrend with a red candle followed by a green candle closing above the midpoint of the first.
Hammer: A single-candle reversal pattern in a downtrend with a small body and a long lower shadow.
Inverted Hammer: A single-candle reversal pattern in a downtrend with a small body and a long upper shadow.
Morning Star: A three-candle reversal pattern with a long red candle, a short candle gapping down, and a long green candle.
Marubozu White: A single-candle pattern with a long green body and minimal shadows.
Dragonfly Doji: A single-candle reversal pattern in a downtrend with a doji where open and close are at the high.
Harami Cross (Bullish): A two-candle reversal pattern in a downtrend with a long red candle followed by a doji inside its body.
Harami (Bullish): A two-candle reversal pattern in a downtrend with a long red candle followed by a small green candle inside its body.
Long Lower Shadow: A single-candle pattern with a long lower shadow indicating buyer strength.
Three White Soldiers: A three-candle reversal pattern with three long green candles in a downtrend.
Engulfing (Bullish): A two-candle reversal pattern in a downtrend with a small red candle followed by a larger green candle engulfing it.
Abandoned Baby (Bullish): A three-candle reversal pattern with a long red candle, a doji gapping down, and a green candle gapping up.
Tri-Star (Bullish): A three-candle reversal pattern with three doji candles in a downtrend, with gaps between them.
Kicking (Bullish): A two-candle reversal pattern with a bearish marubozu followed by a bullish marubozu gapping up.
Bearish Patterns:
On Neck: A two-candle continuation pattern in a downtrend with a long red candle followed by a short green candle closing near the first candle's low.
Falling Window: A two-candle continuation pattern in a downtrend with a price gap between the first candle's low and the second candle's high.
Falling Three Methods: A five-candle continuation pattern with a long red candle, three short green candles, and another long red candle.
Tweezer Top: A two-candle reversal pattern in an uptrend with nearly identical highs.
Dark Cloud Cover: A two-candle reversal pattern in an uptrend with a green candle followed by a red candle opening above the high and closing below the midpoint.
Downside Tasuki Gap: A three-candle continuation pattern in a downtrend with a gap between the first two red candles and a green candle closing partially into the gap.
Evening Doji Star: A three-candle reversal pattern with a long green candle, a doji gapping up, and a long red candle.
Doji Star (Bearish): A two-candle reversal pattern in an uptrend with a long green candle followed by a doji gapping up.
Hanging Man: A single-candle reversal pattern in an uptrend with a small body and a long lower shadow.
Shooting Star: A single-candle reversal pattern in an uptrend with a small body and a long upper shadow.
Evening Star: A three-candle reversal pattern with a long green candle, a short candle gapping up, and a long red candle.
Marubozu Black: A single-candle pattern with a long red body and minimal shadows.
Gravestone Doji: A single-candle reversal pattern in an uptrend with a doji where open and close are at the low.
Harami Cross (Bearish): A two-candle reversal pattern in an uptrend with a long green candle followed by a doji inside its body.
Harami (Bearish): A two-candle reversal pattern in an uptrend with a long green candle followed by a small red candle inside its body.
Long Upper Shadow: A single-candle pattern with a long upper shadow indicating seller strength.
Three Black Crows: A three-candle reversal pattern with three long red candles in an uptrend.
Engulfing (Bearish): A two-candle reversal pattern in an uptrend with a small green candle followed by a larger red candle engulfing it.
Abandoned Baby (Bearish): A three-candle reversal pattern with a long green candle, a doji gapping up, and a red candle gapping down.
Tri-Star (Bearish): A three-candle reversal pattern with three doji candles in an uptrend, with gaps between them.
Kicking (Bearish): A two-candle reversal pattern with a bullish marubozu followed by a bearish marubozu gapping down.
Neutral Patterns:
Doji: A single-candle pattern with a very small body, indicating indecision.
Spinning Top White: A single-candle pattern with a small green body and long upper and lower shadows, indicating indecision.
Spinning Top Black: A single-candle pattern with a small red body and long upper and lower shadows, indicating indecision.
Pattern Detection Functions
Each pattern detection function evaluates specific conditions based on candlestick properties (from calculateCandleProperties) and trend conditions (from detectTrend). The functions return:
detected (bool): True if the pattern is detected.
name (string): The name of the pattern (e.g., "On Neck").
type (string): The pattern type ("Bullish", "Bearish", or "Neutral").
description (string): A detailed description of the pattern for use in tooltips or alerts.
For example, the detectOnNeckBearish function checks for a bearish On Neck pattern by verifying a downtrend, a long red candle followed by a short green candle, and specific price relationships.
Usage Example
To use the library in a TradingView indicator, you can import it and call its functions as shown below:
//@version=6
indicator("Candlestick Pattern Detector", overlay=true)
import CandlestickPatternsLibrary as cp
// Calculate SMA for trend detection
sma50 = ta.sma(close, 50)
sma200 = ta.sma(close, 200)
= cp.detectTrend(true, true, "SMA50", close, sma50, sma200)
// Calculate candlestick properties
bodyAvg = ta.ema(math.max(close, open) - math.min(close, open), 14)
= cp.calculateCandleProperties(open, close, high, low, bodyAvg, 5.0, 100.0, 5.0)
// Detect a pattern (e.g., On Neck Bearish)
= cp.detectOnNeckBearish(downTrend, blackBody, longBody, whiteBody, open, close, low, bodyAvg, smallBody, candleRange)
if onNeckDetected
label.new(bar_index, low, onNeckName, style=label.style_label_up, color=color.red, textcolor=color.white, tooltip=onNeckDesc)
// Detect another pattern (e.g., Piercing Bullish)
= cp.detectPiercingBullish(downTrend, blackBody, longBody, whiteBody, open, low, close, bodyMiddle)
if piercingDetected
label.new(bar_index, low, piercingName, style=label.style_label_up, color=color.blue, textcolor=color.white, tooltip=piercingDesc)
Steps in the Example
Import the Library: Use import CandlestickPatternsLibrary as cp to access the library's functions.
Calculate Trend: Use detectTrend to determine the market trend based on SMA50 or SMA50/SMA200 rules.
Calculate Candlestick Properties: Use calculateCandleProperties to compute properties like body size, shadow lengths, and doji status.
Detect Patterns: Call specific pattern detection functions (e.g., detectOnNeckBearish, detectPiercingBullish) and use the returned values to display labels or alerts.
Visualize Patterns: Use label.new to display detected patterns on the chart with their names, types, and descriptions.
Key Features
Modularity: The library is designed as a standalone module, making it easy to integrate into other Pine Script projects.
Comprehensive Pattern Coverage: Supports over 40 candlestick patterns, covering bullish, bearish, and neutral formations.
Detailed Documentation: Each function includes comments with @param and @returns annotations for clarity.
Reusability: Can be used in indicators, strategies, or alerts by importing the library and calling its functions.
Extracted from All Candlestick Patterns: The library is derived from the All Candlestick Patterns indicator, ensuring it inherits a well-tested foundation for pattern detection.
Notes for Developers
Pine Script Version: The library uses Pine Script version 6, as specified by //@version=6.
Parameter Naming: Parameters use prefixes like p_ (e.g., p_open, p_close) to avoid conflicts with built-in variables.
Error Handling: The library has been fixed to address issues like undeclared identifiers (C_SmallBody, C_Range), unused arguments (factor), and improper comment formatting.
Testing: Developers should test the library in TradingView to ensure patterns are detected correctly under various market conditions.
Customization: Users can adjust parameters like bodyAvg, shadowPercent, shadowEqualsPercent, and dojiBodyPercent in calculateCandleProperties to fine-tune pattern detection sensitivity.
Conclusion
The Candlestick Patterns Library, extracted from the All Candlestick Patterns indicator, is a powerful tool for traders and developers looking to implement candlestick pattern detection in TradingView. Its modular design, comprehensive pattern support, and detailed documentation make it an ideal choice for building custom indicators or strategies. By leveraging the library's functions, users can analyze market trends, compute candlestick properties, and detect a wide range of patterns to inform their trading decisions.