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
Göstergeler ve stratejiler
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
OHLCVRangeLibrary "OHLCVRange"
validateOHLCVRange(ohlcvRange)
Parameters:
ohlcvRange (OHLCVRangeType)
toString(ohlcvRange)
Parameters:
ohlcvRange (OHLCVRangeType)
buildFixedRange(size, isStart, currentCandle, activeOHLCVRange, activeCandles, isRangeActive)
Parameters:
size (int)
isStart (bool)
currentCandle (OHLCV type from viorel8/OHLCVData/13)
activeOHLCVRange (OHLCVRangeType)
activeCandles (array type from viorel8/OHLCVData/13)
isRangeActive (bool)
buildSessionRange(sessionStart, sessionEnd, currentCandle, activeOHLCVRange, activeCandles, isRangeActive)
Parameters:
sessionStart (int)
sessionEnd (int)
currentCandle (OHLCV type from viorel8/OHLCVData/13)
activeOHLCVRange (OHLCVRangeType)
activeCandles (array type from viorel8/OHLCVData/13)
isRangeActive (bool)
buildConsolidationRange(threshold, currentCandle, activeOHLCVRange, activeCandles, isRangeActive)
Parameters:
threshold (float)
currentCandle (OHLCV type from viorel8/OHLCVData/13)
activeOHLCVRange (OHLCVRangeType)
activeCandles (array type from viorel8/OHLCVData/13)
isRangeActive (bool)
buildPriceTriggerRange(triggerPrice, direction, maxBars, currentCandle, activeOHLCVRange, activeCandles, isRangeActive)
Parameters:
triggerPrice (float)
direction (string)
maxBars (int)
currentCandle (OHLCV type from viorel8/OHLCVData/13)
activeOHLCVRange (OHLCVRangeType)
activeCandles (array type from viorel8/OHLCVData/13)
isRangeActive (bool)
buildHTFAlignedRange(timeframe, currentCandle, activeOHLCVRange, activeCandles, isRangeActive, htfCandle)
Parameters:
timeframe (string)
currentCandle (OHLCV type from viorel8/OHLCVData/13)
activeOHLCVRange (OHLCVRangeType)
activeCandles (array type from viorel8/OHLCVData/13)
isRangeActive (bool)
htfCandle (OHLCV type from viorel8/OHLCVData/13)
OHLCVRangeType
Fields:
id (series string)
start_bar_index (series int)
end_bar_index (series int)
start_time (series int)
end_time (series int)
candles (array type from viorel8/OHLCVData/13)
duration (series int)
isValid (series bool)
RejectionPatternsLibrary "RejectionPatterns"
handleError(reason)
Parameters:
reason (string)
analyzeRejection(candles, model, levelLower, levelUpper, lookbackVolatility, volatilityThreshold, volumeThreshold)
Parameters:
candles (array type from viorel8/OHLCVData/13)
model (string)
levelLower (float)
levelUpper (float)
lookbackVolatility (int)
volatilityThreshold (float)
volumeThreshold (float)
testLabel(result)
Parameters:
result (PatternResult)
PatternResult
Fields:
isValid (series bool)
confidence (series float)
description (series string)
high (series float)
low (series float)
volume (series float)
atr (series float)
wickStrength (series float)
score (series float)
ADXZigZagLibrary "ADXZigZag"
method lastPivot(this)
Returns the last Pivot of `this` ZigZag if there is at least one Pivot to return, and `na` otherwise.
Can be used as a function or method.
Namespace types: ZigZag
Parameters:
this (ZigZag) : (series ZigZag) A ZigZag object.
Returns: (Pivot) The last Pivot in the ZigZag.
update(this)
Updates `this` ZigZag object with new pivots, volume, lines, labels. NOTE: The function must be called on every bar for accurate calculations.
Can be used as a function or method.
Parameters:
this (ZigZag) : (series ZigZag) a ZigZag object.
Returns: (bool) true if a new Zig Zag line is found or the last Zig Zag line has changed.
newInstance(settings)
Instantiates a new ZigZag object with `settings`. If no settings are provided, a default ZigZag object is created.
Parameters:
settings (Settings) : (series Settings) A Settings object.
Returns: (ZigZag) A new ZigZag instance.
Settings
Provides calculation and display attributes to ZigZag objects.
Fields:
devThreshold (series float) : The minimum percentage deviation from a point before the ZigZag will change direction.
depth (series int) : The number of bars required for pivot detection.
lineColor (series color) : Line color.
extendLast (series bool) : Condition allowing a line to connect the most recent pivot with the current close.
displayReversalPrice (series bool) : Condition to display the pivot price in the pivot label.
displayCumulativeVolume (series bool) : Condition to display the cumulative volume for the pivot segment in the pivot label.
displayReversalPriceChange (series bool) : Condition to display the change in price or percent from the previous pivot in the pivot label.
differencePriceMode (series string) : Reversal change display mode. Options are "Absolute" or "Percent".
draw (series bool) : Condition to display lines and labels.
allowZigZagOnOneBar (series bool) : Condition to allow double pivots to occur ie. when a large bar makes both a pivot high and a pivot low.
Point
A coordinate containing bar, price, and time information.
Fields:
tm (series int) : A value in UNIX time.
price (series float) : A value on the Y axis (price).
barIndex (series int) : A `bar_index`.
Pivot
A level of significance used to determine directional movement or potential support and resistance.
Fields:
ln (series line) : A line object connecting the `start` and `end` Point objects.
lb (series label) : A label object to display pivot values.
isHigh (series bool) : A condition to determine if the pivot is a pivot high.
vol (series float) : Volume for the pivot segment.
start (Point) : The coordinate of the previous Point.
end (Point) : The coordinate of the current Point.
ZigZag
An object to maintain Zig Zag settings, pivots, and volume.
Fields:
settings (Settings) : Settings object to provide calculation and display attributes.
pivots (array) : An array of Pivot objects.
sumVol (series float) : The volume sum for the pivot segment.
extend (Pivot) : Pivot object used to project a line from the last pivot to the last bar.
ADXZigZagLibrary "ADXZigZag"
method lastPivot(this)
Returns the last Pivot of `this` ZigZag if there is at least one Pivot to return, and `na` otherwise.
Can be used as a function or method.
Namespace types: ZigZag
Parameters:
this (ZigZag) : (series ZigZag) A ZigZag object.
Returns: (Pivot) The last Pivot in the ZigZag.
update(this)
Updates `this` ZigZag object with new pivots, volume, lines, labels. NOTE: The function must be called on every bar for accurate calculations.
Can be used as a function or method.
Parameters:
this (ZigZag) : (series ZigZag) a ZigZag object.
Returns: (bool) true if a new Zig Zag line is found or the last Zig Zag line has changed.
newInstance(settings)
Instantiates a new ZigZag object with `settings`. If no settings are provided, a default ZigZag object is created.
Parameters:
settings (Settings) : (series Settings) A Settings object.
Returns: (ZigZag) A new ZigZag instance.
Settings
Provides calculation and display attributes to ZigZag objects.
Fields:
devThreshold (series float) : The minimum percentage deviation from a point before the ZigZag will change direction.
depth (series int) : The number of bars required for pivot detection.
lineColor (series color) : Line color.
extendLast (series bool) : Condition allowing a line to connect the most recent pivot with the current close.
displayReversalPrice (series bool) : Condition to display the pivot price in the pivot label.
displayCumulativeVolume (series bool) : Condition to display the cumulative volume for the pivot segment in the pivot label.
displayReversalPriceChange (series bool) : Condition to display the change in price or percent from the previous pivot in the pivot label.
differencePriceMode (series string) : Reversal change display mode. Options are "Absolute" or "Percent".
draw (series bool) : Condition to display lines and labels.
allowZigZagOnOneBar (series bool) : Condition to allow double pivots to occur ie. when a large bar makes both a pivot high and a pivot low.
Point
A coordinate containing bar, price, and time information.
Fields:
tm (series int) : A value in UNIX time.
price (series float) : A value on the Y axis (price).
barIndex (series int) : A `bar_index`.
Pivot
A level of significance used to determine directional movement or potential support and resistance.
Fields:
ln (series line) : A line object connecting the `start` and `end` Point objects.
lb (series label) : A label object to display pivot values.
isHigh (series bool) : A condition to determine if the pivot is a pivot high.
vol (series float) : Volume for the pivot segment.
start (Point) : The coordinate of the previous Point.
end (Point) : The coordinate of the current Point.
ZigZag
An object to maintain Zig Zag settings, pivots, and volume.
Fields:
settings (Settings) : Settings object to provide calculation and display attributes.
pivots (array) : An array of Pivot objects.
sumVol (series float) : The volume sum for the pivot segment.
extend (Pivot) : Pivot object used to project a line from the last pivot to the last bar.
ProbabilityContextLibrary "ProbabilityContext"
initContext(sessionTime, timeframe, instrumentType, timezone, maxBufferSize, useLIFO)
Parameters:
sessionTime (string)
timeframe (string)
instrumentType (string)
timezone (int)
maxBufferSize (int)
useLIFO (bool)
addCondition(ctx, name, value, patternName, priority, confidence)
Parameters:
ctx (Context)
name (string)
value (bool)
patternName (string)
priority (float)
confidence (float)
removeCondition(ctx, name, patternName)
Parameters:
ctx (Context)
name (string)
patternName (string)
clearConditions(ctx, patternName)
Parameters:
ctx (Context)
patternName (string)
isPatternValid(ctx, patternName, minConfidence)
Parameters:
ctx (Context)
patternName (string)
minConfidence (float)
Condition
Fields:
name (series string)
value (series bool)
patternName (series string)
timestamp (series int)
priority (series float)
confidence (series float)
ConditionGroup
Fields:
conditions (array)
Context
Fields:
sessionTime (series string)
timeframe (series string)
instrumentType (series string)
conditionGroups (map)
timezone (series int)
maxBufferSize (series int)
useLIFO (series bool)
MathLibrary "Math"
clamp(value, minVal, maxVal)
Parameters:
value (float)
minVal (float)
maxVal (float)
LibMirPapaICTLibrary "LibMirPapaICT"
isConsecutiveBullish(_len, _count)
Parameters:
_len (int) : int
/ @param _count int
/ @return bool
_count (int)
isConsecutiveBearish(_len, _count)
Parameters:
_len (int) : int
/ @param _count int
/ @return bool
_count (int)
createBoxOrderBlock(_isState, _leftBar, _rightBar, _priceTop, _priceBot, _useMidline, _xloc, _color, _offset)
Parameters:
_isState (bool)
_leftBar (int)
_rightBar (int)
_priceTop (float)
_priceBot (float)
_useMidline (bool)
_xloc (string)
_color (color)
_offset (int)
processBoxLevels(_levels, _useLineMid, _useTouch, _closeCount)
Parameters:
_levels (array) : BoxLevel
/ @param _useMidline bool
/ @param _useOBtouch bool
/ @param _closeCount int
_useLineMid (bool)
_useTouch (bool)
_closeCount (int)
BoxLevel
Fields:
isState (series bool)
boxInfos (series box)
lineMid (series line)
offset (series int)
priceTop (series float)
priceBot (series float)
volBuy (series float)
volSell (series float)
breakStage (series int)
breakTop (series float)
breakBot (series float)
result (series string)
MirPapaTrendConditionsLibrary "MirPapaTrendConditions"
getMaColor(level)
Parameters:
level (int) : : 1= lowest, 2= low, 3= mid, 4= high, 5= highest, 6= Base
getMA(mode, src, len)
Parameters:
mode (string) : MA 종류
/ @param src 소스
/ @param len 기간
/ @returns 선택된 MA
src (float)
len (simple int)
getMA(maName, src, intLow, intMid, intHigh)
Parameters:
maName (string) : 이동평균 종류
/ @param src 기준 소스
/ @param intLow 단기
/ @param intMid 중기
/ @param intHigh 장기
/ @returns 배열
src (float)
intLow (simple int)
intMid (simple int)
intHigh (simple int)
getMA(maName, src, intLowest, intLow, intMid, intHigh, intHighest, intBase)
Parameters:
maName (string) : 이동평균 종류
/ @param src 기준 소스
/ @param intLowest 초단기
/ @param intLow 단기
/ @param intMid 중기
/ @param intHigh 장기
/ @param intHighest 초장기
/ @param intBase 기준선
/ @returns 배열
src (float)
intLowest (simple int)
intLow (simple int)
intMid (simple int)
intHigh (simple int)
intHighest (simple int)
intBase (simple int)
getStochastic(src, intLen)
Parameters:
src (float) : 기준 소스
/ @param Len 기간
/ @returns 선택된 스토캐스틱
intLen (int)
getStochastic(src, intLow, intMid, intHigh)
Parameters:
src (float) : 기준 소스
/ @param intLow 단기 기간
/ @param intMid 중기 기간
/ @param intHigh 장기 기간
/ @returns
intLow (int)
intMid (int)
intHigh (int)
getStochastic(src, intLowest, intLow, intMid, intHigh, intHighest, intBase)
Parameters:
src (float) : 기준 소스
/ @param intLowest 초단기 기간
/ @param intLow 단기 기간
/ @param intMid 중기 기간
/ @param intHigh 장기 기간
/ @param intHighest 최장기 기간
/ @param intBase 기준선 기간
/ @returns
intLowest (int)
intLow (int)
intMid (int)
intHigh (int)
intHighest (int)
intBase (int)
getRSX(src, intLen)
Parameters:
src (float) : 기준 소스
/ @param intLen 기간
/ @returns 선택된 rsx
intLen (int)
getRSX(src, intLow, intMid, intHigh)
Parameters:
src (float) : 기준 소스
/ @param intLow 중단기
/ @param intMid 중기
/ @param intHigh 장기
/ @returns
intLow (int)
intMid (int)
intHigh (int)
getRSX(src, intLowest, intLow, intMid, intHigh, intHighest, intBase)
Parameters:
src (float) : 기준 소스
/ @param intTiny 초단기
/ @param intLowest 단기
/ @param intLow 중단기
/ @param intMid 중기
/ @param intHigh 장기
/ @param intHighest 초장기
/ @returns
intLowest (int)
intLow (int)
intMid (int)
intHigh (int)
intHighest (int)
intBase (int)
getMACD(src, fastLen, slowLen, signalLen)
Parameters:
src (float) : 기준 소스
/ @param fastLen 빠른 EMA 기간
/ @param slowLen 느린 EMA 기간
/ @param signalLen 시그널 기간
/ @returns
fastLen (simple int)
slowLen (simple int)
signalLen (simple int)
getBollingerBand(src, len, mult)
Parameters:
src (float) : 기준 소스
/ @param len 기준 기간
/ @param mult 표준편차 배수
/ @returns
len (int)
mult (float)
getATR(intLen)
Parameters:
intLen (simple int) : ATR 기간
/ @returns 선택된 ATR
getATR(intLow, intMid, intHigh)
Parameters:
intLow (simple int) : 단기 ATR 기간
/ @param intMid 중기 ATR 기간
/ @param intHigh 장기 ATR 기간
/ @returns 배열
intMid (simple int)
intHigh (simple int)
getATR(intLowest, intLow, intMid, intHigh, intHighest, intBase)
Parameters:
intLowest (simple int)
intLow (simple int)
intMid (simple int)
intHigh (simple int)
intHighest (simple int)
intBase (simple int)
isCross(fastLine, baseLine)
Parameters:
fastLine (float) : 빠른선
/ @param baseLine 기준선
/ @returns 상태
baseLine (float)
isMAtrend(maLow, maMid, maHigh)
Parameters:
maLow (float) : 가장 빠른 MA
/ @param maMid 중간 MA
/ @param maHigh 느린 MA
/ @returns 상태
maMid (float)
maHigh (float)
isMAline(val, valPrev, intBaseLine)
Parameters:
val (float) : 현재 값
/ @param valPrev 이전 값
/ @param intBaseLine 기준값
/ @returns 상태
valPrev (float)
intBaseLine (int)
getStage(v1, v2, v3)
Parameters:
v1 (float) : 첫 번째 값
/ @param v2 두 번째 값
/ @param v3 세 번째 값
/ @returns 1~6
v2 (float)
v3 (float)
getBgColor(stage)
Parameters:
stage (int) : 스테이지 값
/ @returns 색상
getBgColor(stage, transp)
Parameters:
stage (int) : 스테이지 값
/ @param transp 투명도
/ @returns 색상
transp (int)
getBGColor(v1, v2, v3)
Parameters:
v1 (float) : 첫 번째 값
/ @param v2 두 번째 값
/ @param v3 세 번째 값
/ @param transp 투명도
/ @param customColor 사용자 지정 색 (옵션)
/ @returns 색상
v2 (float)
v3 (float)
getBGColor(v1, v2, v3, transp)
Parameters:
v1 (float) : 첫 번째 값
/ @param v2 두 번째 값
/ @param v3 세 번째 값
/ @param transp 투명도
/ @param customColor 사용자 지정 색 (옵션)
/ @returns 색상
v2 (float)
v3 (float)
transp (int)
createStackedLabel(labelText, isUp, maLowest, maLow, maMid, maHigh, maHighest, maBase)
Parameters:
labelText (string) : 라벨 텍스트
/ @param isUp 위/아래 여부
/ @param maTiny~maHighest MA 값들
/ @returns 생성된 라벨
isUp (bool)
maLowest (float)
maLow (float)
maMid (float)
maHigh (float)
maHighest (float)
maBase (float)
isDoubleBottom(src, left, right)
Parameters:
src (float) : 기준 시리즈 (예: 중간 MA 값, low 등)
/ @param left PivotLow 검색 시 좌측 봉 개수
/ @param right PivotLow 검색 시 우측 봉 개수
/ @returns true: 이번 봉에 쌍바닥(이전 PivotLow < 현재 PivotLow) 발생
left (int)
right (int)
isDoubleTop(src, left, right)
Parameters:
src (float) : 기준 시리즈 (예: 중간 MA 값, high 등)
/ @param left PivotHigh 검색 시 좌측 봉 개수
/ @param right PivotHigh 검색 시 우측 봉 개수
/ @returns true: 이번 봉에 쌍봉(이전 PivotHigh > 현재 PivotHigh) 발생
left (int)
right (int)
isFractalHigh(src, left, right)
Parameters:
src (float) : 고가 시리즈 (예: high, 중간 MA 값 등)
/ @param left 좌측 확인 봉 개수
/ @param right 우측 확인 봉 개수
/ @returns true: 프랙탈 하이 발생
left (int)
right (int)
isFractalLow(src, left, right)
Parameters:
src (float) : 저가 시리즈 (예: low, 중간 MA 값 등)
/ @param left 좌측 확인 봉 개수
/ @param right 우측 확인 봉 개수
/ @returns true: 프랙탈 로우 발생
left (int)
right (int)
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
DispersionLibLibrary "DispersionLib"
dispersionCore(ma5, use5, ma20, use20, ma50, use50, ma200, use200, weightMethod, w5, w20, w50, w200, normMethod, srcClose, srcATR, avgMA)
Parameters:
ma5 (float)
use5 (bool)
ma20 (float)
use20 (bool)
ma50 (float)
use50 (bool)
ma200 (float)
use200 (bool)
weightMethod (string)
w5 (float)
w20 (float)
w50 (float)
w200 (float)
normMethod (string)
srcClose (float)
srcATR (float)
avgMA (float)
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