AlgebraGeometryLabLibrary "AlgebraGeometryLab"
Algebra & 2D geometry utilities absent from Pine built-ins.
Rigorous, no-repaint, export-ready: vectors, robust roots, linear solvers, 2x2/3x3 det/inverse,
symmetric 2x2 eigensystem, orthogonal regression (TLS), affine transforms, intersections,
distances, projections, polygon metrics, point-in-polygon, convex hull (monotone chain),
Bezier/Catmull-Rom/Barycentric tools.
clamp(x, lo, hi)
clamp to
Parameters:
x (float)
lo (float)
hi (float)
near(a, b, atol, rtol)
approximately equal with relative+absolute tolerance
Parameters:
a (float)
b (float)
atol (float)
rtol (float)
sgn(x)
sign as {-1,0,1}
Parameters:
x (float)
hypot(x, y)
stable hypot (sqrt(x^2+y^2))
Parameters:
x (float)
y (float)
method length(v)
Namespace types: Vec2
Parameters:
v (Vec2)
method length2(v)
Namespace types: Vec2
Parameters:
v (Vec2)
method normalized(v)
Namespace types: Vec2
Parameters:
v (Vec2)
method add(a, b)
Namespace types: Vec2
Parameters:
a (Vec2)
b (Vec2)
method sub(a, b)
Namespace types: Vec2
Parameters:
a (Vec2)
b (Vec2)
method muls(v, s)
Namespace types: Vec2
Parameters:
v (Vec2)
s (float)
method dot(a, b)
Namespace types: Vec2
Parameters:
a (Vec2)
b (Vec2)
method crossz(a, b)
Namespace types: Vec2
Parameters:
a (Vec2)
b (Vec2)
method rotate(v, ang)
Namespace types: Vec2
Parameters:
v (Vec2)
ang (float)
method apply(v, T)
Namespace types: Vec2
Parameters:
v (Vec2)
T (Affine2)
affine_identity()
identity transform
affine_translate(tx, ty)
translation
Parameters:
tx (float)
ty (float)
affine_rotate(ang)
rotation about origin
Parameters:
ang (float)
affine_scale(sx, sy)
scaling about origin
Parameters:
sx (float)
sy (float)
affine_rotate_about(ang, px, py)
rotation about pivot (px,py)
Parameters:
ang (float)
px (float)
py (float)
affine_compose(T2, T1)
compose T2∘T1 (apply T1 then T2)
Parameters:
T2 (Affine2)
T1 (Affine2)
quadratic_roots(a, b, c)
Real roots of ax^2 + bx + c = 0 (numerically stable)
Parameters:
a (float)
b (float)
c (float)
Returns: with n∈{0,1,2}; r1<=r2 when n=2.
cubic_roots(a, b, c, d)
Real roots of ax^3+bx^2+cx+d=0 (Cardano; returns up to 3 real roots)
Parameters:
a (float)
b (float)
c (float)
d (float)
Returns: (valid r2/r3 only if n>=2/n>=3)
det2(a, b, c, d)
det2 of
Parameters:
a (float)
b (float)
c (float)
d (float)
inv2(a, b, c, d)
inverse of 2x2; returns
Parameters:
a (float)
b (float)
c (float)
d (float)
solve2(a, b, c, d, e, f)
solve 2x2 * = via Cramer
Parameters:
a (float)
b (float)
c (float)
d (float)
e (float)
f (float)
det3(a11, a12, a13, a21, a22, a23, a31, a32, a33)
det3 of 3x3
Parameters:
a11 (float)
a12 (float)
a13 (float)
a21 (float)
a22 (float)
a23 (float)
a31 (float)
a32 (float)
a33 (float)
inv3(a11, a12, a13, a21, a22, a23, a31, a32, a33)
inverse 3x3; returns
Parameters:
a11 (float)
a12 (float)
a13 (float)
a21 (float)
a22 (float)
a23 (float)
a31 (float)
a32 (float)
a33 (float)
eig2_symmetric(a, b, d)
symmetric 2x2 eigensystem: [ , ]
Parameters:
a (float)
b (float)
d (float)
Returns: with unit eigenvectors
tls_line(xs, ys)
Orthogonal (total least squares) regression line through point cloud
Input arrays must be same length N>=2. Returns line in normal form n•x + c = 0
Parameters:
xs (array)
ys (array)
Returns: where (nx,ny) unit normal; (cx,cy) centroid.
orient(a, b, c)
orientation (signed area*2): >0 CCW, <0 CW, 0 collinear
Parameters:
a (Vec2)
b (Vec2)
c (Vec2)
project_point_line(p, a, d)
project point p onto infinite line through a with direction d
Parameters:
p (Vec2)
a (Vec2)
d (Vec2)
Returns: where proj = a + t*d
closest_point_segment(p, a, b)
closest point on segment to p
Parameters:
p (Vec2)
a (Vec2)
b (Vec2)
Returns: where t∈ on segment
dist_point_line(p, a, d)
distance from point to line (infinite)
Parameters:
p (Vec2)
a (Vec2)
d (Vec2)
dist_point_segment(p, a, b)
distance from point to segment
Parameters:
p (Vec2)
a (Vec2)
b (Vec2)
intersect_lines(p1, d1, p2, d2)
line-line intersection: L1: p1+d1*t, L2: p2+d2*u
Parameters:
p1 (Vec2)
d1 (Vec2)
p2 (Vec2)
d2 (Vec2)
Returns:
intersect_segments(s1, s2)
segment-segment intersection (closed segments)
Parameters:
s1 (Segment2)
s2 (Segment2)
Returns: where kind: 0=no, 1=proper point, 2=overlap (ix/iy=na)
circumcircle(a, b, c)
circle through 3 non-collinear points
Parameters:
a (Vec2)
b (Vec2)
c (Vec2)
intersect_circle_line(C, p, d)
intersections of circle and line (param p + d t)
Parameters:
C (Circle2)
p (Vec2)
d (Vec2)
Returns: with n∈{0,1,2}
intersect_circles(A, B)
circle-circle intersection
Parameters:
A (Circle2)
B (Circle2)
Returns: with n∈{0,1,2}
polygon_area(xs, ys)
signed area (shoelace). Positive if CCW.
Parameters:
xs (array)
ys (array)
polygon_centroid(xs, ys)
polygon centroid (for non-self-intersecting). Fallback to vertex mean if area≈0.
Parameters:
xs (array)
ys (array)
point_in_polygon(px, py, xs, ys)
point-in-polygon test (ray casting). Returns true if inside; boundary counts as inside.
Parameters:
px (float)
py (float)
xs (array)
ys (array)
convex_hull(xs, ys)
convex hull (monotone chain). Returns array of hull vertex indices in CCW order.
Uses array.sort_indices(xs) (ascending by x). Ties on x are handled; result is deterministic.
Parameters:
xs (array)
ys (array)
lerp(a, b, t)
linear interpolate between a and b
Parameters:
a (float)
b (float)
t (float)
bezier2(p0, p1, p2, t)
quadratic Bezier B(t) for points p0,p1,p2
Parameters:
p0 (Vec2)
p1 (Vec2)
p2 (Vec2)
t (float)
bezier3(p0, p1, p2, p3, t)
cubic Bezier B(t) for p0,p1,p2,p3
Parameters:
p0 (Vec2)
p1 (Vec2)
p2 (Vec2)
p3 (Vec2)
t (float)
catmull_rom(p0, p1, p2, p3, t, alpha)
Catmull-Rom interpolation (centripetal form when alpha=0.5)
t∈ , returns point between p1 and p2
Parameters:
p0 (Vec2)
p1 (Vec2)
p2 (Vec2)
p3 (Vec2)
t (float)
alpha (float)
barycentric(A, B, C, P)
barycentric coordinates of P wrt triangle ABC
Parameters:
A (Vec2)
B (Vec2)
C (Vec2)
P (Vec2)
Returns:
point_in_triangle(A, B, C, P)
point-in-triangle using barycentric (boundary included)
Parameters:
A (Vec2)
B (Vec2)
C (Vec2)
P (Vec2)
Vec2
Fields:
x (series float)
y (series float)
Line2
Fields:
p (Vec2)
d (Vec2)
Segment2
Fields:
a (Vec2)
b (Vec2)
Circle2
Fields:
c (Vec2)
r (series float)
Affine2
Fields:
a (series float)
b (series float)
c (series float)
d (series float)
tx (series float)
ty (series float)
Indicators and strategies
RTACoreLibrary "RTACore"
Advanced multi-timeframe technical analysis framework for Pine Script
@author WavesUnchained
@build 2025-10-14 22:41:47
newFloatResult(value, context)
Create a successful Result with float value
Parameters:
value (float)
context (string)
newStringResult(value, context)
Create a successful Result with string value
Parameters:
value (string)
context (string)
newBoolResult(value, context)
Create a successful Result with boolean value
Parameters:
value (bool)
context (string)
newErrorResult(errorCode, errorMessage, floatFallback, stringFallback, boolFallback, context)
Create an error Result with fallback values
Parameters:
errorCode (string)
errorMessage (string)
floatFallback (float)
stringFallback (string)
boolFallback (bool)
context (string)
addResultTag(result, tag)
Add a tag to Result
Parameters:
result (Result)
tag (string)
newSignalResult(signalStrength, signalType)
Create a signal Result with trading-specific tags
Parameters:
signalStrength (float)
signalType (string)
newIndicatorResult(value, indicatorName)
Create an indicator calculation Result with indicator tag
Parameters:
value (float)
indicatorName (string)
newTimeframeResult(value, timeframe, context)
Create a timeframe-specific Result
Parameters:
value (float)
timeframe (string)
context (string)
newConfluenceResult(confluenceScore, confidenceLevel)
Create a confluence Result with confidence level
Parameters:
confluenceScore (float)
confidenceLevel (string)
newValidationResult(context)
Create a new validation result (starts as valid)
Parameters:
context (string)
newValidationSuccess(context)
Create a successful validation result
Parameters:
context (string)
newValidationFailure(errors, context)
Create a failed validation result with errors
Parameters:
errors (array)
context (string)
addValidationError(result, field, error)
Add an error to validation result
Parameters:
result (ValidationResult)
field (string)
error (string)
addValidationWarning(result, field, warning)
Add a warning to validation result
Parameters:
result (ValidationResult)
field (string)
warning (string)
addValidationCorrection(result, correction)
Add a correction to validation result
Parameters:
result (ValidationResult)
correction (string)
setValidationMode(result, mode)
Set validation mode
Parameters:
result (ValidationResult)
mode (string)
getValidationMode(result)
Get validation mode
Parameters:
result (ValidationResult)
incrementValidatedFields(result)
Increment validated fields counter
Parameters:
result (ValidationResult)
setValidationTotalFields(result, total)
Set total fields for validation
Parameters:
result (ValidationResult)
total (int)
calculateValidationScore(result)
Calculate and update validation score based on errors/warnings
Parameters:
result (ValidationResult)
newPerformanceProfile(functionName)
Create a new performance profile
Parameters:
functionName (string)
startTiming(profile)
Start timing a performance profile (simple)
Parameters:
profile (PerformanceProfile)
endTiming(profile, hadError)
End timing and update performance profile
Parameters:
profile (PerformanceProfile)
hadError (bool)
updateMemoryEstimate(profile, arrayElements)
Set estimated memory usage (array elements)
Parameters:
profile (PerformanceProfile)
arrayElements (int)
newHealthyStatus()
Create a new healthy status
setComponentHealth(status, component, isOK, message)
Set component health status
Parameters:
status (HealthStatus)
component (string)
isOK (bool)
message (string)
isHealthyOverall(status)
Quick health check - are all components OK?
Parameters:
status (HealthStatus)
getHealthSummary(status)
Get simple health summary
Parameters:
status (HealthStatus)
hasValidFloat(result)
Check if Result contains a valid float value
Parameters:
result (Result)
hasValidString(result)
Check if Result contains a valid string value
Parameters:
result (Result)
getFloat(result, fallback)
Get float value from Result with fallback
Parameters:
result (Result)
fallback (float)
getString(result, fallback)
Get string value from Result with fallback
Parameters:
result (Result)
fallback (string)
getBool(result, fallback)
Get boolean value from Result with fallback
Parameters:
result (Result)
fallback (bool)
hasResultTag(result, tag)
Check if Result has specific tag
Parameters:
result (Result)
tag (string)
getResultTags(result)
Get all tags from Result
Parameters:
result (Result)
setResultContext(result, context)
Set operation context for Result
Parameters:
result (Result)
context (string)
filterResultsByTag(results, tag)
Filter Results by tag (utility for arrays of Results)
Parameters:
results (array)
tag (string)
getAllResultTags(results)
Get all unique tags from array of Results
Parameters:
results (array)
newDefaultAnalysisConfig()
Create default analysis configuration
newAggressiveAnalysisConfig()
Create aggressive trading configuration
newConservativeAnalysisConfig()
Create conservative trading configuration
newDefaultTimeframeConfig()
Create default timeframe configuration
newIntradayTimeframeConfig()
Create intraday timeframe configuration
newSwingTimeframeConfig()
Create swing trading timeframe configuration
getConfigSummary(config)
Get configuration summary string
Parameters:
config (AnalysisConfig)
cloneAnalysisConfig(source)
Clone analysis configuration
Parameters:
source (AnalysisConfig)
newGenericAnalysis(analysisType, timeframe)
Create a new generic analysis result
Parameters:
analysisType (string)
timeframe (string)
newConsensusData()
Create empty consensus data
newNeutralSignal(reason)
Create a neutral signal result
Parameters:
reason (string)
newBuySignal(score, confidence, reason)
Create a buy signal result
Parameters:
score (float)
confidence (float)
reason (string)
newSellSignal(score, confidence, reason)
Create a sell signal result
Parameters:
score (float)
confidence (float)
reason (string)
newMultiTimeframeResult(config, tfConfig)
Create new multi-timeframe result
Parameters:
config (AnalysisConfig)
tfConfig (TimeframeConfig)
getAnalysisAction(analysis)
Get analysis action string
Parameters:
analysis (GenericAnalysis)
isBullish(analysis)
Check if analysis is bullish
Parameters:
analysis (GenericAnalysis)
isBearish(analysis)
Check if analysis is bearish
Parameters:
analysis (GenericAnalysis)
getSignalSummary(signal)
Get signal summary string
Parameters:
signal (SignalResult)
hasStrongConsensus(consensus)
Check if consensus is strong
Parameters:
consensus (ConsensusData)
getConsensusSummary(consensus)
Get consensus summary
Parameters:
consensus (ConsensusData)
isActionableSignal(signal)
Check if signal is actionable
Parameters:
signal (SignalResult)
getSignalColor(signal)
Get signal color for UI display
Parameters:
signal (SignalResult)
validateAnalysisConfig(config)
Validate analysis configuration
Parameters:
config (AnalysisConfig)
validateTimeframeConfig(config)
Validate timeframe configuration
Parameters:
config (TimeframeConfig)
validatePriceData(prices)
Validate price data array
Parameters:
prices (array)
sanitizeFloat(value, minVal, maxVal, defaultVal)
Sanitize numeric input
Parameters:
value (float)
minVal (float)
maxVal (float)
defaultVal (float)
sanitizeInt(value, minVal, maxVal, defaultVal)
Sanitize integer input
Parameters:
value (int)
minVal (int)
maxVal (int)
defaultVal (int)
sanitizeFloatArray(arr)
Sanitize array by removing invalid values
Parameters:
arr (array)
logError(message)
Log error message
Parameters:
message (string)
logWarning(message)
Log warning message
Parameters:
message (string)
safeExecute(operationName, condition)
Safe execute wrapper
Parameters:
operationName (string)
condition (bool)
shouldAllowOperation(errorCount, maxErrors)
Circuit breaker pattern
Parameters:
errorCount (int)
maxErrors (int)
retryOperation(maxRetries)
Retry mechanism
Parameters:
maxRetries (int)
atrDistance(value1, value2, atr)
Calculate ATR-normalized distance between two values
Parameters:
value1 (float)
value2 (float)
atr (float)
atrDistance(value, reference, atrLength)
Calculate ATR-normalized distance between values
Parameters:
value (float)
reference (float)
atrLength (simple int)
percentDistance(value1, value2)
Calculate percentage-based distance between two values
Parameters:
value1 (float)
value2 (float)
withinATRTolerance(value, reference, atr, multiplier)
Check if value is within ATR-based tolerance of reference
Parameters:
value (float)
reference (float)
atr (float)
multiplier (float)
withinATRTolerance(value, reference, multiplier)
Check if value is within ATR-based tolerance of reference
Parameters:
value (float)
reference (float)
multiplier (float)
withinPercentTolerance(value, reference, percentTolerance)
Check if value is within percentage tolerance of reference
Parameters:
value (float)
reference (float)
percentTolerance (float)
proximityScore(value, reference, maxDistance)
Get proximity score (0-1, where 1 = very close)
Parameters:
value (float)
reference (float)
maxDistance (float)
sortArrayByValue(values, sortOrder)
Efficient array sorting using Pine Script native sort
Note: Replaces inefficient bubble sort implementations found in modules
Parameters:
values (array)
sortOrder (string)
safeArrayAverage(values)
Safe array average with null handling
Parameters:
values (array)
formatTableHeader(title, width)
Create formatted header for display tables
Parameters:
title (string)
width (int)
formatTableRow(key, value, width)
Format table row with key-value pair
Parameters:
key (string)
value (string)
width (int)
formatTableFooter(width)
Close table formatting
Parameters:
width (int)
truncateText(txt, maxLength, suffix)
Truncate text to specified length
Parameters:
txt (string)
maxLength (int)
suffix (string)
padText(txt, width, padChar, align)
Pad text to specified width
Parameters:
txt (string)
width (int)
padChar (string)
align (string)
titleCase(txt)
Convert text to title case
Parameters:
txt (string)
joinStrings(strings, separator)
Join array of strings with separator
Parameters:
strings (array)
separator (string)
formatTimestamp(timestamp, format)
Format timestamp to readable date/time
Parameters:
timestamp (int)
format (string)
evictLRU(cache)
Evict least recently used entry
Parameters:
cache (CacheManager)
newRiskAssessment()
Create a default risk assessment
calculateRiskAssessment(signal, volatility, volumeLevel)
Calculate comprehensive risk assessment
Parameters:
signal (SignalResult)
volatility (float)
volumeLevel (float)
newPositionData()
Create new empty position data
getConservativeStrategy()
Create conservative strategy template
getAggressiveStrategy()
Create aggressive strategy template
newDefaultStrategy()
Create default balanced strategy template
getStandardATR()
Get standard ATR(14) - cached per bar
getATR(length)
Get custom ATR with specified length
Parameters:
length (simple int)
getATRTolerance(multiplier)
Get ATR-based tolerance for distance calculations
Parameters:
multiplier (float)
getStandardVolumeAverage()
Get standard volume average SMA(20) - cached per bar
getVolumeAverage(length)
Get custom volume average
Parameters:
length (int)
getVolumeRatio()
Get volume ratio (current vs average)
getVolumeConfirmation(threshold)
Get volume confirmation (above threshold)
Parameters:
threshold (float)
getStandardEMAs()
Get standard EMAs (21, 50, 200) - cached per bar
getEMA21()
Get individual standard EMAs
getEMA50()
getEMA200()
getEMATrendAlignment()
Get EMA trend alignment score
getStandardRSI()
Get standard RSI(14) - cached per bar
getRSILevels(overbought, oversold)
Get RSI with overbought/oversold levels
Parameters:
overbought (float)
oversold (float)
getStandardMACD()
Get standard MACD (12, 26, 9) - cached per bar
getMACDSignal()
Get MACD trend signal
getMomentumScore()
Get comprehensive momentum score
getTrendStrength()
Get trend strength (0-100)
getIndicatorSummary()
Get indicator calculation summary (for debugging)
newZoneDetectionConfig()
Create default zone configuration
newZoneDetection(upperBoundary, lowerBoundary, creationBar, zoneType)
Create new zone
Parameters:
upperBoundary (float)
lowerBoundary (float)
creationBar (int)
zoneType (string)
calculateZoneOverlap(zone1Upper, zone1Lower, zone2Upper, zone2Lower)
Calculate zone overlap ratio
Parameters:
zone1Upper (float)
zone1Lower (float)
zone2Upper (float)
zone2Lower (float)
isPriceTouchingZone(zone, currentPrice, touchTolerance)
Check if price is touching zone
Parameters:
zone (ZoneDetection)
currentPrice (float)
touchTolerance (float)
getZonesInRange(zones, minPrice, maxPrice)
Get zones within price range
Parameters:
zones (array)
minPrice (float)
maxPrice (float)
getNearestZones(zones, currentPrice)
Get nearest support and resistance zones
Parameters:
zones (array)
currentPrice (float)
processZoneDetection(zones, config)
Complete zone detection and management system
Parameters:
zones (array)
config (ZoneDetectionConfig)
processZoneDetectionEngine(zones, config)
Parameters:
zones (array)
config (ZoneDetectionConfig)
newChannelConfig()
calcKeltnerChannel(config)
Parameters:
config (ChannelConfig)
checkKeltnerTouch(upper, lower)
Parameters:
upper (float)
lower (float)
getKeltnerDepth(basis, upper, lower)
Parameters:
basis (float)
upper (float)
lower (float)
checkKeltnerBreakout(upper, lower)
Parameters:
upper (float)
lower (float)
calcDonchianChannel(config)
Parameters:
config (ChannelConfig)
checkDonchianTouch(upper, lower)
Parameters:
upper (float)
lower (float)
checkDonchianReentry(upper, lower)
Parameters:
upper (float)
lower (float)
getDonchianWidth(upper, lower)
Parameters:
upper (float)
lower (float)
calcBollingerBands(config)
Parameters:
config (ChannelConfig)
calcSqueezeRatio(bbStdev, kcMultiplier, kcAtr)
Parameters:
bbStdev (float)
kcMultiplier (float)
kcAtr (float)
detectSqueezeState(squeezeRatio)
Parameters:
squeezeRatio (float)
detectSqueezeBreak(squeezeRatio, kcUpper, kcLower)
Parameters:
squeezeRatio (float)
kcUpper (float)
kcLower (float)
getSqueezeIntensity(squeezeRatio)
Parameters:
squeezeRatio (float)
processChannelDetection(config)
Parameters:
config (ChannelConfig)
detectChannelSignals(state)
Parameters:
state (ChannelState)
detectQualityZones(state)
Parameters:
state (ChannelState)
getChannelSignalText(state)
Parameters:
state (ChannelState)
analyzeChannelTrend(state)
Parameters:
state (ChannelState)
getChannelConfluence(state)
Parameters:
state (ChannelState)
newVwapConfig()
newVwapAnchors()
calcSessionVwap()
getPreviousSessionVwap(sessionVwap)
Parameters:
sessionVwap (float)
updateVwapAnchors(anchors, config)
Parameters:
anchors (VwapAnchors)
config (VwapConfig)
calcAnchoredVwap(anchors, isHigh)
Parameters:
anchors (VwapAnchors)
isHigh (bool)
detectPriceCrosses(sessionVwap)
Parameters:
sessionVwap (float)
detectStructureCrosses(sessionVwap, anchoredHigh, anchoredLow)
Parameters:
sessionVwap (float)
anchoredHigh (float)
anchoredLow (float)
detectVwapCluster(sessionVwap, anchoredHigh, anchoredLow, config)
Parameters:
sessionVwap (float)
anchoredHigh (float)
anchoredLow (float)
config (VwapConfig)
canShowSignal(anchors, config, signalType)
Parameters:
anchors (VwapAnchors)
config (VwapConfig)
signalType (string)
updateSignalThrottle(anchors, signalType)
Parameters:
anchors (VwapAnchors)
signalType (string)
calcCrossStrength(sessionVwap, isPriceCross)
Parameters:
sessionVwap (float)
isPriceCross (bool)
calcClusterStrength(vwapsInCluster, priceInCluster, tolerance)
Parameters:
vwapsInCluster (bool)
priceInCluster (bool)
tolerance (float)
calcStructureStrength(sessionVwap, anchoredHigh, anchoredLow)
Parameters:
sessionVwap (float)
anchoredHigh (float)
anchoredLow (float)
analyzeVwapTrend(sessionVwap)
Parameters:
sessionVwap (float)
processVwapDetection(anchors, config)
Parameters:
anchors (VwapAnchors)
config (VwapConfig)
generateVwapSignals(state)
Parameters:
state (VwapState)
getVwapBias(state)
Parameters:
state (VwapState)
getVwapConfluence(state)
Parameters:
state (VwapState)
newZoneConfig()
newZoneState()
stringToFloats(s)
Parameters:
s (string)
calculateBias(config)
Parameters:
config (ZoneConfig)
createZone(top, bottom, isBull, isHTF)
Parameters:
top (float)
bottom (float)
isBull (bool)
isHTF (bool)
updateZoneStatus(zone)
Parameters:
zone (Zone)
detectFVGOverlap(zone)
Parameters:
zone (Zone)
scoreZone(zone, config)
Parameters:
zone (Zone)
config (ZoneConfig)
sortAndTrimZones(zones, config)
Parameters:
zones (array)
config (ZoneConfig)
adjustZoneVisibility(zones, config)
Parameters:
zones (array)
config (ZoneConfig)
calculateTargetsATR(base, stepsString, atrLength)
Parameters:
base (float)
stepsString (string)
atrLength (simple int)
calculateTargetsSigma(base, stepsString, sigmaLength)
Parameters:
base (float)
stepsString (string)
sigmaLength (int)
calculateTargetsLiquidity(isLong, config)
Parameters:
isLong (bool)
config (ZoneConfig)
detectZoneSignals(zones, bias, config)
Parameters:
zones (array)
bias (int)
config (ZoneConfig)
processZoneManagement(state, config)
Parameters:
state (ZoneState)
config (ZoneConfig)
findNearestZones(state)
Parameters:
state (ZoneState)
newVolumeConfig()
newVolumeState()
getPriceSource(config)
Parameters:
config (VolumeConfig)
isInSession(config)
Parameters:
config (VolumeConfig)
isNewSession(config)
Parameters:
config (VolumeConfig)
calculateWindow(config)
Parameters:
config (VolumeConfig)
calculateProfile(config, windowStart, windowLength)
Parameters:
config (VolumeConfig)
windowStart (int)
windowLength (int)
detectVolumeNodes(binVolumes, binPrices, totalVolume)
Parameters:
binVolumes (array)
binPrices (array)
totalVolume (float)
calculateVolumeChoppiness(config)
Calculate choppiness index for volume profile
Parameters:
config (VolumeConfig)
detectMarketRegime(state, config)
Detect market regime based on multiple factors
Parameters:
state (VolumeState)
config (VolumeConfig)
calculateAdaptiveParameters(state, config)
Calculate adaptive volume profile parameters
Parameters:
state (VolumeState)
config (VolumeConfig)
updateMarketConditions(state, config)
Update volume state with market conditions
Parameters:
state (VolumeState)
config (VolumeConfig)
applyAdaptiveConfig(config, state)
Apply adaptive parameters to profile calculation
Parameters:
config (VolumeConfig)
state (VolumeState)
getHTFPivots(config)
Parameters:
config (VolumeConfig)
checkPivotConfluence(price, config, pivotHigh1, pivotLow1, pivotHigh2, pivotLow2)
Parameters:
price (float)
config (VolumeConfig)
pivotHigh1 (float)
pivotLow1 (float)
pivotHigh2 (float)
pivotLow2 (float)
calculateMOST()
Calculate MOST (Moving Stop) indicator
calculateTrendFilters(config)
Parameters:
config (VolumeConfig)
findNearestNodes(hvnNodes, lvnNodes)
Parameters:
hvnNodes (array)
lvnNodes (array)
detectVolumeSignals(config, profile, trendBullish, htfConfluence)
Parameters:
config (VolumeConfig)
profile (VolumeProfile)
trendBullish (bool)
htfConfluence (bool)
calculateVolumeScore(profile, trendBullish)
Parameters:
profile (VolumeProfile)
trendBullish (bool)
processVolumeProfile(state, config)
Parameters:
state (VolumeState)
config (VolumeConfig)
newHTFConfig()
newHTFStackState()
getOptimalTimeframes(chartTF)
Parameters:
chartTF (string)
calculateChoppiness(length)
Parameters:
length (int)
detectTrendEMA(length, threshold)
Parameters:
length (simple int)
threshold (float)
detectTrendSupertrend(atrLength, multiplier)
Parameters:
atrLength (simple int)
multiplier (float)
detectTrendMOST(length, multiplier)
Parameters:
length (simple int)
multiplier (float)
analyzeTrendForTF(tf, config)
Parameters:
tf (string)
config (HTFConfig)
calculateStackConfluence(tfData, config)
Parameters:
tfData (array)
config (HTFConfig)
calculateAutoTuningParams(choppiness, stackStrength, config)
Parameters:
choppiness (float)
stackStrength (float)
config (HTFConfig)
detectStackSignals(state, prevState, config)
Parameters:
state (HTFStackState)
prevState (HTFStackState)
config (HTFConfig)
createStackPanel(state, config)
Parameters:
state (HTFStackState)
config (HTFConfig)
processHTFStack(state, config)
Parameters:
state (HTFStackState)
config (HTFConfig)
processHTFStackSignals(state, prevState, config)
Parameters:
state (HTFStackState)
prevState (HTFStackState)
config (HTFConfig)
newRedefiningTechnicalAnalysisCore(analysisConfig, timeframeConfig, strategy)
Initialize RedefiningTechnicalAnalysis Core Library
Note: This function requires valid config objects to be passed in
The configuration module must be used directly to create default configs
Parameters:
analysisConfig (AnalysisConfig)
timeframeConfig (TimeframeConfig)
strategy (StrategyTemplate)
performAnalysis(core, prices, volumes, timestamps)
Perform complete multi-timeframe analysis
Parameters:
core (RedefiningTechnicalAnalysisCore)
prices (array)
volumes (array)
timestamps (array)
generateSignal(core, analysisResult)
Generate trading signal from analysis results
Parameters:
core (RedefiningTechnicalAnalysisCore)
analysisResult (MultiTimeframeResult)
assessRisk(core, signal)
Assess risk for trading decision
Parameters:
core (RedefiningTechnicalAnalysisCore)
signal (SignalResult)
executeFullWorkflow(core)
Execute complete analysis workflow
Parameters:
core (RedefiningTechnicalAnalysisCore)
updateAnalysisConfig(core, newConfig)
Update analysis configuration
Parameters:
core (RedefiningTechnicalAnalysisCore)
newConfig (AnalysisConfig)
updateStrategy(core, newStrategy)
Update strategy template
Parameters:
core (RedefiningTechnicalAnalysisCore)
newStrategy (StrategyTemplate)
checkSystemHealth(core)
Perform system health check
Parameters:
core (RedefiningTechnicalAnalysisCore)
generateStatusReport(core)
Generate comprehensive status report
Parameters:
core (RedefiningTechnicalAnalysisCore)
enableDebugMode(core, enabled)
Enable debug mode
Parameters:
core (RedefiningTechnicalAnalysisCore)
enabled (bool)
setFeatureFlag(core, flag, enabled)
Set feature flag
Parameters:
core (RedefiningTechnicalAnalysisCore)
flag (string)
enabled (bool)
getFeatureFlag(core, flag, defaultValue)
Get feature flag
Parameters:
core (RedefiningTechnicalAnalysisCore)
flag (string)
defaultValue (bool)
resetLibraryState(core)
Reset library state
Parameters:
core (RedefiningTechnicalAnalysisCore)
getLibraryInfo()
Get library version information
quickAnalysis(config, tfConfig, strategy)
Quick analysis - simplified entry point
Parameters:
config (AnalysisConfig)
tfConfig (TimeframeConfig)
strategy (StrategyTemplate)
getQuickStatus(core)
Get quick status string
Parameters:
core (RedefiningTechnicalAnalysisCore)
Result
Generic Result type for safe operations with error handling and fallbacks
Fields:
floatValue (series float)
stringValue (series string)
boolValue (series bool)
intValue (series int)
isSuccess (series bool)
errorCode (series string)
errorMessage (series string)
floatFallback (series float)
stringFallback (series string)
boolFallback (series bool)
intFallback (series int)
operationContext (series string)
timestamp (series int)
tags (array)
ValidationResult
Comprehensive validation result with errors, warnings, and corrections
Fields:
isValid (series bool)
errors (array)
warnings (array)
corrections (array)
suggestions (array)
validationScore (series float)
validationMode (series string)
validatedFields (series int)
totalFields (series int)
validationContext (series string)
validationTime (series int)
PerformanceProfile
Simplified performance profiling for Pine Script limitations
Fields:
executionTimeMs (series float)
averageExecutionMs (series float)
executionCount (series int)
errorCount (series int)
cacheHits (series int)
cacheMisses (series int)
cacheHitRatio (series float)
estimatedArrayElements (series int)
hasHeavyCalculation (series bool)
lastOptimizationHint (series string)
performanceGrade (series string)
performanceScore (series float)
functionName (series string)
profileStartTime (series int)
HealthStatus
Simplified health status for Pine Script limitations
Fields:
isHealthy (series bool)
healthScore (series float)
healthGrade (series string)
issues (array)
warnings (array)
recommendations (array)
dataValidationOK (series bool)
calculationsOK (series bool)
memoryUsageOK (series bool)
errorCountSession (series int)
warningCountSession (series int)
lastHealthCheck (series int)
healthCheckVersion (series string)
AnalysisConfig
Comprehensive analysis configuration with factor weights, thresholds, and extensible options
Fields:
activeFactors (array)
factorWeights (map)
thresholds (map)
features (map)
tradingMode (series string)
consensusMode (series string)
riskProfile (series string)
minConfidence (series float)
signalStrength (series float)
requireConsensus (series bool)
minConsensusCount (series int)
parameters (map)
options (map)
flags (map)
configName (series string)
version (series string)
description (series string)
createdTime (series int)
lastModified (series int)
validation (ValidationResult)
TimeframeConfig
Multi-timeframe configuration with weights and adjustments
Fields:
timeframes (array)
weights (array)
autoDetectChartTF (series bool)
includeHigherTFs (series bool)
tfAdjustments (map)
tfSensitivity (map)
tfFeatures (map)
minTimeframes (series int)
consensusThreshold (series float)
consensusMethod (series string)
normalizeWeights (series bool)
adaptiveBias (series bool)
higherTFBias (series float)
tfConfigName (series string)
configTimestamp (series int)
validation (ValidationResult)
GenericAnalysis
Generic analysis result that all specific analysis types extend
Fields:
totalScore (series float)
confidence (series float)
action (series string)
strength (series string)
riskLevel (series string)
factorScores (map)
factorWeights (map)
factorSignals (map)
factorReasons (map)
analysisType (series string)
timeframeAnalyzed (series string)
analysisTimestamp (series int)
marketCondition (series string)
dataQuality (series float)
performance (PerformanceProfile)
validation (ValidationResult)
numericData (map)
textData (map)
flags (map)
ConsensusData
Multi-timeframe consensus analysis data
Fields:
agreementCount (series int)
totalTimeframes (series int)
agreementPercentage (series float)
hasStrongConsensus (series bool)
hasMajorityConsensus (series bool)
agreeingTimeframes (array)
disagreeingTimeframes (array)
tfScores (map)
tfActions (map)
consensusMode (series string)
consensusScore (series float)
consensusAction (series string)
consensusStrength (series string)
tfWeights (map)
weightedConsensus (series bool)
weightedScore (series float)
consensusQuality (series float)
consensusReliability (series string)
consensusWarnings (array)
SignalResult
Comprehensive trading signal result
Fields:
strongBuy (series bool)
buy (series bool)
neutral (series bool)
sell (series bool)
strongSell (series bool)
overallScore (series float)
confidence (series float)
primaryAction (series string)
signalStrength (series string)
signalReason (series string)
contributingFactors (array)
factorContributions (map)
triggerCondition (series string)
consensus (ConsensusData)
consensusLevel (series string)
hasConsensus (series bool)
riskLevel (series string)
riskRewardRatio (series float)
successProbability (series float)
signalTimestamp (series int)
urgency (series string)
validityPeriod (series int)
marketPhase (series string)
warningFlags (array)
metadata (map)
MultiTimeframeResult
Multi-timeframe analysis result container
Fields:
primaryAnalysis (GenericAnalysis)
tfResults (map)
consensus (ConsensusData)
aggregatedScore (series float)
confidenceScore (series float)
dominantAction (series string)
consensusStrength (series string)
analyzedTimeframes (array)
failedTimeframes (array)
failureReasons (map)
performance (PerformanceProfile)
validation (ValidationResult)
dataQualityScore (series float)
config (AnalysisConfig)
tfConfig (TimeframeConfig)
analysisTimestamp (series int)
DebugLogEntry
Debug log entry
Fields:
timestamp (series int)
level (series string)
module (series string)
function (series string)
message (series string)
context (series string)
data (map)
barIndex (series int)
timeframe (series string)
DebugLogger
Debug logger with configurable levels
Fields:
entries (array)
maxEntries (series int)
currentLevel (series string)
enabled (series bool)
enabledModules (array)
showTimestamp (series bool)
showBarIndex (series bool)
outputFormat (series string)
PerformanceMeasurement
Performance measurement
Fields:
name (series string)
startTime (series int)
endTime (series int)
duration (series float)
iterations (series int)
avgDuration (series float)
status (series string)
context (series string)
TraceEntry
Execution trace entry
Fields:
function (series string)
module (series string)
entryTime (series int)
exitTime (series int)
isEntry (series bool)
parameters (series string)
returnValue (series string)
depth (series int)
ExecutionTracer
Execution tracer
Fields:
traces (array)
currentDepth (series int)
maxDepth (series int)
enabled (series bool)
maxTraces (series int)
CacheEntry
Cache entry
Fields:
key (series string)
data (series string)
timestamp (series int)
ttl (series int)
accessCount (series int)
lastAccess (series int)
CacheManager
Cache manager
Fields:
name (series string)
entries (map)
maxEntries (series int)
defaultTTL (series int)
enabled (series bool)
hits (series int)
misses (series int)
evictions (series int)
RiskAssessment
Core risk assessment result
Fields:
riskLevel (series string)
riskScore (series float)
riskRewardRatio (series float)
successProbability (series float)
maxDrawdownExpected (series float)
positionRisk (series float)
portfolioExposure (series float)
correlationRisk (series float)
concentrationRisk (series float)
volatilityRisk (series float)
liquidityRisk (series float)
timeframeRisk (series float)
newsEventRisk (series float)
supportResistanceRisk (series float)
trendRisk (series float)
momentumRisk (series float)
volumeRisk (series float)
hasHighRisk (series bool)
hasExtremeRisk (series bool)
riskWarnings (array)
riskFactors (array)
recommendedPositionSize (series float)
stopLossDistance (series float)
takeProfitDistance (series float)
shouldAvoidTrade (series bool)
riskMitigationStrategy (series string)
assessmentTimestamp (series int)
assessmentMethod (series string)
performance (PerformanceProfile)
PositionData
Comprehensive position data
Fields:
hasPosition (series bool)
positionSide (series string)
positionSize (series float)
entryPrice (series float)
entryTimestamp (series int)
entryReason (series string)
unrealizedPnL (series float)
realizedPnL (series float)
maxUnrealizedGain (series float)
maxUnrealizedLoss (series float)
totalReturn (series float)
stopLossPrice (series float)
takeProfitPrice (series float)
riskAmount (series float)
riskRewardRatio (series float)
currentRisk (RiskAssessment)
barsInPosition (series int)
maxBarsAllowed (series int)
isTimedOut (series bool)
timeframe (series string)
hasExitSignal (series bool)
exitReason (series string)
exitScore (series float)
shouldExit (series bool)
exitUrgency (series string)
actionHistory (array)
timestampHistory (array)
reasonHistory (array)
sharpeRatio (series float)
maxDrawdown (series float)
winRate (series float)
avgHoldTime (series float)
StrategyTemplate
Base strategy template
Fields:
name (series string)
description (series string)
category (series string)
timeframes (array)
entryThreshold (series float)
entryConfidenceMin (series float)
requiredSignals (array)
excludeConditions (array)
exitThreshold (series float)
stopLossPercent (series float)
takeProfitPercent (series float)
maxBarsInTrade (series int)
maxPositionSize (series float)
basePositionSize (series float)
useVolatilityAdjustment (series bool)
useConfidenceAdjustment (series bool)
maxRiskPerTrade (series float)
maxDailyRisk (series float)
maxDrawdownLimit (series float)
useAdaptiveRisk (series bool)
requireConsensus (series bool)
minConsensusPercent (series float)
avoidNewsEvents (series bool)
requireVolume (series bool)
targetSharpeRatio (series float)
targetWinRate (series float)
targetRiskReward (series float)
parameters (map)
flags (map)
settings (map)
MetricDataPoint
Performance metric data point
Fields:
timestamp (series int)
value (series float)
name (series string)
unit (series string)
labels (map)
source (series string)
MetricStats
Metric statistics
Fields:
min (series float)
max (series float)
avg (series float)
sum (series float)
count (series int)
p50 (series float)
p95 (series float)
p99 (series float)
stdDev (series float)
firstTimestamp (series int)
lastTimestamp (series int)
MetricDataPointArray
Wrapper for array of metric data points (to avoid nested collections)
Fields:
dataPoints (array)
MetricsCollector
Metrics collector
Fields:
metrics (map)
stats (map)
maxDataPoints (series int)
retentionPeriod (series int)
autoCleanup (series bool)
enabled (series bool)
enabledMetrics (array)
lastCleanupTime (series int)
ComponentHealth
Component health status
Fields:
name (series string)
status (series string)
healthScore (series float)
lastCheckTime (series int)
warnings (array)
errors (array)
metrics (map)
lastError (series string)
errorCount (series int)
warningCount (series int)
isOperational (series bool)
SystemHealth
System health overview
Fields:
overallStatus (series string)
overallScore (series float)
healthyComponents (series int)
degradedComponents (series int)
unhealthyComponents (series int)
components (array)
systemWarnings (array)
systemErrors (array)
lastFullCheckTime (series int)
autoHealing (series bool)
healingAttempts (series int)
HealthAlert
Health alert
Fields:
level (series string)
component (series string)
message (series string)
timestamp (series int)
acknowledged (series bool)
category (series string)
ZoneDetection
Advanced zone data structure
Fields:
upper (series float)
lower (series float)
mid (series float)
height (series float)
score (series float)
quality (series string)
touchCount (series int)
lastTouchBar (series int)
creationBar (series int)
role (series int)
zoneType (series string)
isActive (series bool)
isBroken (series bool)
flipBar (series int)
flipRetestCount (series int)
flipBestQuality (series float)
flipScore (series float)
hasFlipped (series bool)
htfOverlap (series bool)
htfTimeframe (series string)
htfConfidence (series float)
retestQuality (series float)
volumeProfile (series float)
volatilityProfile (series float)
freshnessScore (series float)
successfulBounces (series int)
failedBreakouts (series int)
successRate (series float)
avgHoldTime (series float)
zoneBox (series box)
midLine (series line)
zoneLabel (series label)
flipLabel (series label)
ZoneDetectionConfig
Zone analysis configuration
Fields:
pivotPeriod (series int)
atrMultiplier (series float)
atrLength (series int)
maxZones (series int)
mergeThreshold (series float)
minTouchesForSignificance (series int)
weightTouches (series float)
weightFreshness (series float)
weightVolume (series float)
weightHTF (series float)
minWickPercent (series float)
maxBodyPercent (series float)
freshnessHalfLife (series int)
useHTFProjection (series bool)
htfTimeframe (series string)
htfPivotCount (series int)
htfProjectionMultiplier (series float)
ChannelConfig
Fields:
kcEmaLength (series int)
kcAtrLength (series int)
kcMultiplier (series float)
dcLength (series int)
bbLength (series int)
bbMultiplier (series float)
pivotLength (series int)
atrThreshold (series float)
minBarsPerLeg (series int)
minTouchCount (series int)
mergeThreshold (series float)
ChannelState
Fields:
kcUpper (series float)
kcLower (series float)
kcBasis (series float)
kcAtr (series float)
dcUpper (series float)
dcLower (series float)
dcMid (series float)
bbUpper (series float)
bbLower (series float)
bbBasis (series float)
bbStdev (series float)
squeezeRatio (series float)
isSqueezeActive (series bool)
isExpanding (series bool)
touchKcUpper (series bool)
touchKcLower (series bool)
touchDcUpper (series bool)
touchDcLower (series bool)
kcBreakoutUp (series bool)
kcBreakoutDown (series bool)
dcReentryUp (series bool)
dcReentryDown (series bool)
squeezeBreakUp (series bool)
squeezeBreakDown (series bool)
kcDepth (series float)
dcWidth (series float)
squeezeIntensity (series float)
ChannelSignal
Fields:
signalType (series string)
direction (series int)
strength (series float)
description (series string)
isQualitySignal (series bool)
VwapConfig
Fields:
pivotLeftBars (series int)
pivotRightBars (series int)
clusterTolerancePercent (series float)
minBarsBetweenSignals (series int)
crossThreshold (series float)
enableThrottling (series bool)
detectClusters (series bool)
VwapState
Fields:
sessionVwap (series float)
sessionVwapPrev (series float)
anchoredVwapHigh (series float)
anchoredVwapLow (series float)
hasAnchoredHigh (series bool)
hasAnchoredLow (series bool)
priceCrossUp (series bool)
priceCrossDown (series bool)
canShowPriceCross (series bool)
structureCrossUp (series bool)
structureCrossDown (series bool)
canShowStructureCross (series bool)
isClusterActive (series bool)
canShowCluster (series bool)
clusterTolerance (series float)
vwapsInCluster (series bool)
priceInCluster (series bool)
priceVwapPosition (series int)
priceVwapDistance (series float)
priceVwapDistancePercent (series float)
crossStrength (series float)
clusterStrength (series float)
structureStrength (series float)
VwapSignal
Fields:
signalType (series string)
direction (series int)
strength (series float)
description (series string)
isHighConfidence (series bool)
barIndex (series int)
VwapAnchors
Fields:
cumulativePV (series float)
cumulativeV (series float)
anchorPV_High (series float)
anchorV_High (series float)
hasHighAnchor (series bool)
anchorPV_Low (series float)
anchorV_Low (series float)
hasLowAnchor (series bool)
lastPriceCrossBar (series int)
lastStructureCrossBar (series int)
lastClusterBar (series int)
ZoneConfig
Fields:
htfTimeframe (series string)
useHTF (series bool)
maxZonesPerSide (series int)
rankFavorHTF (series bool)
rankFavorFVG (series bool)
rankFavorFresh (series bool)
showOnlyTopRank (series bool)
alphaTop (series int)
alphaRest (series int)
biasLength (series int)
biasBandMultiplier (series float)
targetMode (series string)
atrLength (series int)
atrSteps (series string)
sigmaLength (series int)
sigmaSteps (series string)
useSSL (series bool)
useFVGFills (series bool)
confirmMidline (series bool)
confirmBreak (series bool)
requireBias (series bool)
lazyTargets (series bool)
nearPercent (series float)
Zone
Fields:
top (series float)
bottom (series float)
mid (series float)
bornTime (series int)
isBull (series bool)
isHTF (series bool)
touched (series bool)
violated (series bool)
hasFVG (series bool)
score (series float)
rank (series int)
zoneBox (series box)
midLine (series line)
isActive (series bool)
ZoneState
Fields:
zonesTF (array)
zonesHTF (array)
bias (series int)
biasScore (series float)
biasRegime (series string)
vwapLevel (series float)
bandUpper (series float)
bandLower (series float)
targetLevels (array)
targetLines (array)
activeBullZones (series int)
activeBearZones (series int)
totalZones (series int)
avgZoneScore (series float)
longSignal (series bool)
shortSignal (series bool)
nearestBullZone (Zone)
nearestBearZone (Zone)
ZoneSignal
Fields:
signalType (series string)
sourceZone (Zone)
strength (series float)
description (series string)
confirmed (series bool)
barIndex (series int)
VolumeConfig
Fields:
profileMode (series string)
fixedLength (series int)
rollingLength (series int)
sessionString (series string)
binCount (series int)
valueAreaPercent (series float)
useHLC3 (series bool)
useHTF1 (series bool)
htfTimeframe1 (series string)
useHTF2 (series bool)
htfTimeframe2 (series string)
pivotLookback (series int)
pivotToleranceATR (series float)
enableAutoTuning (series bool)
vaPct_eff (series float)
epsATR_eff (series float)
adaptiveAlpha (series float)
choppinessLength (series int)
choppyThreshold (series float)
trendingThreshold (series float)
useMarketRegime (series bool)
enableLVNSignals (series bool)
enableVASignals (series bool)
maxRetestDistanceATR (series float)
useEMAFilter (series bool)
useSupertrendFilter (series bool)
useMOSTFilter (series bool)
showPOC (series bool)
showValueArea (series bool)
showNodes (series bool)
showSilhouette (series bool)
silhouetteOffset (series int)
silhouetteWidth (series int)
zoneOpacity (series int)
enableSessionSplits (series bool)
maxSessionCount (series int)
VolumeNode
Fields:
price (series float)
volume (series float)
nodeType (series string)
prominence (series float)
isSignificant (series bool)
VolumeProfile
Fields:
pocPrice (series float)
pocVolume (series float)
valueAreaHigh (series float)
valueAreaLow (series float)
totalVolume (series float)
windowStart (series int)
windowLength (series int)
windowHigh (series float)
windowLow (series float)
binVolumes (array)
binPrices (array)
hvnNodes (array)
lvnNodes (array)
nearestLVN (series float)
nearestHVN (series float)
htfConfluence (series bool)
pocLine (series line)
valueAreaBox (series box)
nodeBoxes (array)
silhouette (series polyline)
VolumeState
Fields:
currentProfile (VolumeProfile)
sessionProfiles (array)
trendBullish (series bool)
emaConfluence (series float)
supertrendBull (series bool)
mostBull (series bool)
choppiness (series float)
isChoppy (series bool)
isTrending (series bool)
marketRegime (series string)
vaPct_current (series float)
epsATR_current (series float)
smoothingFactor (series float)
longLVNSignal (series bool)
shortLVNSignal (series bool)
longVASignal (series bool)
shortVASignal (series bool)
volumeScore (series float)
passFilter (series bool)
inValueArea (series bool)
abovePOC (series bool)
pocRising (series bool)
nearLVN (series bool)
VolumeSignal
Fields:
signalType (series string)
direction (series int)
strength (series float)
description (series string)
triggerPrice (series float)
hasConfluence (series bool)
barIndex (series int)
HTFConfig
Fields:
timeframes (array)
tfWeights (array)
autoSelectTFs (series bool)
maxTimeframes (series int)
trendLength (series int)
trendThreshold (series float)
trendMethod (series string)
stackThreshold (series float)
requireAllTFs (series bool)
confluenceBonus (series float)
enableAutoTuning (series bool)
choppinessLength (series int)
choppyThreshold (series float)
trendingThreshold (series float)
showStackPanel (series bool)
panelPosition (series string)
panelRows (series int)
panelCols (series int)
showTooltips (series bool)
HTFTrendData
Fields:
timeframe (series string)
trendStrength (series float)
trendDirection (series string)
confidence (series float)
isValid (series bool)
weight (series float)
trendColor (series color)
HTFStackState
Fields:
tfData (array)
bullConfluence (series float)
bearConfluence (series float)
stackStrength (series float)
stackBias (series string)
choppiness (series float)
isChoppy (series bool)
isTrending (series bool)
marketRegime (series string)
vaPct_eff (series float)
epsATR_eff (series float)
adaptiveAlpha (series float)
bullStackSignal (series bool)
bearStackSignal (series bool)
stackBreakSignal (series bool)
stackTable (series table)
tfLabels (array)
strengthBars (array)
RedefiningTechnicalAnalysisCore
Main library state container
Fields:
analysisConfig (AnalysisConfig)
timeframeConfig (TimeframeConfig)
activeStrategy (StrategyTemplate)
lastAnalysis (MultiTimeframeResult)
lastSignal (SignalResult)
lastRisk (RiskAssessment)
currentPosition (PositionData)
isInitialized (series bool)
lastUpdateTime (series int)
currentTimeframe (series string)
globalPerformance (PerformanceProfile)
systemHealth (SystemHealth)
metricsCollector (MetricsCollector)
analysisCache (CacheManager)
calculationCache (CacheManager)
recentErrors (array)
recentWarnings (array)
errorCount (series int)
warningCount (series int)
debugLogger (DebugLogger)
debugMode (series bool)
extensionData (map)
featureFlags (map)
DynLenLibLibrary "DynLenLib"
sum_dyn(src, len)
Parameters:
src (float)
len (int)
lag_dyn(src, len)
Parameters:
src (float)
len (int)
highest_dyn(src, len)
Parameters:
src (float)
len (int)
lowest_dyn(src, len)
Parameters:
src (float)
len (int)
var_dyn(src, len)
Parameters:
src (float)
len (int)
stdev_dyn(src, len)
Parameters:
src (float)
len (int)
hl2()
hlc3()
ohlc4()
sma_dyn(src, len)
Parameters:
src (float)
len (int)
ema_dyn(src, len)
Parameters:
src (float)
len (int)
rma_dyn(src, len)
Parameters:
src (float)
len (int)
smma_dyn(src, len)
Parameters:
src (float)
len (int)
wma_dyn(src, len)
Parameters:
src (float)
len (int)
vwma_dyn(price, vol, len)
Parameters:
price (float)
vol (float)
len (int)
hma_dyn(src, len)
Parameters:
src (float)
len (int)
dema_dyn(src, len)
Parameters:
src (float)
len (int)
tema_dyn(src, len)
Parameters:
src (float)
len (int)
kama_dyn(src, erLen, fastLen, slowLen)
Parameters:
src (float)
erLen (int)
fastLen (int)
slowLen (int)
mcginley_dyn(src, len)
Parameters:
src (float)
len (int)
median_price()
true_range()
atr_dyn(len)
Parameters:
len (int)
bbands_dyn(src, len, mult)
Parameters:
src (float)
len (int)
mult (float)
bb_percent_b(src, len, mult)
Parameters:
src (float)
len (int)
mult (float)
bb_bandwidth(src, len, mult)
Parameters:
src (float)
len (int)
mult (float)
keltner_dyn(src, lenEMA, lenATR, multATR)
Parameters:
src (float)
lenEMA (int)
lenATR (int)
multATR (float)
donchian_dyn(len)
Parameters:
len (int)
choppiness_index(len)
Parameters:
len (int)
vol_stop(lenATR, mult)
Parameters:
lenATR (int)
mult (float)
roc_dyn(src, len)
Parameters:
src (float)
len (int)
rsi_dyn(src, len)
Parameters:
src (float)
len (int)
stoch_dyn(kLen, dLen, smoothK)
Parameters:
kLen (int)
dLen (int)
smoothK (int)
stoch_rsi_dyn(rsiLen, stochLen, kSmooth, dLen)
Parameters:
rsiLen (int)
stochLen (int)
kSmooth (int)
dLen (int)
cci_dyn(src, len)
Parameters:
src (float)
len (int)
cmo_dyn(src, len)
Parameters:
src (float)
len (int)
trix_dyn(len)
Parameters:
len (int)
tsi_dyn(shortLen, longLen)
Parameters:
shortLen (int)
longLen (int)
ultimate_osc(len1, len2, len3)
Parameters:
len1 (int)
len2 (int)
len3 (int)
dpo_dyn(src, len)
Parameters:
src (float)
len (int)
willr_dyn(len)
Parameters:
len (int)
macd_dyn(src, fastLen, slowLen, sigLen)
Parameters:
src (float)
fastLen (int)
slowLen (int)
sigLen (int)
ppo_dyn(src, fastLen, slowLen, sigLen)
Parameters:
src (float)
fastLen (int)
slowLen (int)
sigLen (int)
aroon_dyn(len)
Parameters:
len (int)
dmi_adx_dyn(diLen, adxLen)
Parameters:
diLen (int)
adxLen (int)
vortex_dyn(len)
Parameters:
len (int)
coppock_dyn(rocLen1, rocLen2, wmaLen)
Parameters:
rocLen1 (int)
rocLen2 (int)
wmaLen (int)
rvi_dyn(len)
Parameters:
len (int)
price_osc_dyn(src, fastLen, slowLen)
Parameters:
src (float)
fastLen (int)
slowLen (int)
rci_dyn(src, len)
Parameters:
src (float)
len (int)
obv()
pvt()
cmf_dyn(len)
Parameters:
len (int)
adl()
chaikin_osc_dyn(fastLen, slowLen)
Parameters:
fastLen (int)
slowLen (int)
mfi_dyn(len)
Parameters:
len (int)
volume_osc_dyn(fastLen, slowLen)
Parameters:
fastLen (int)
slowLen (int)
up_down_volume()
cvd()
supertrend_dyn(atrLen, mult)
Parameters:
atrLen (int)
mult (float)
envelopes_dyn(src, len, pct)
Parameters:
src (float)
len (int)
pct (float)
linreg_line_slope(src, len)
Parameters:
src (float)
len (int)
lsma_dyn(src, len)
Parameters:
src (float)
len (int)
corrcoef_dyn(a, b, len)
Parameters:
a (float)
b (float)
len (int)
psar(step, maxStep)
Parameters:
step (float)
maxStep (float)
pivots_standard()
williams_alligator(src, jawLen, teethLen, lipsLen)
Parameters:
src (float)
jawLen (int)
teethLen (int)
lipsLen (int)
twap_dyn(src, len)
Parameters:
src (float)
len (int)
vwap_anchored(price, volume, reset)
Parameters:
price (float)
volume (float)
reset (bool)
performance_pct(len)
Parameters:
len (int)
ema 狀態機Library "ema_flow_lib"
ema_flow_state(e10, e20, e100, entanglePct, farPct, e10_prev, e20_prev)
Parameters:
e10 (float)
e20 (float)
e100 (float)
entanglePct (float)
farPct (float)
e10_prev (float)
e20_prev (float)
state_name(s)
Parameters:
s (int)
phx_liq_tlLibrary "phx_liq_tl"
new_state()
update(st, len, cup, cdn, space, proximity_pct, shs)
Parameters:
st (LTState)
len (int)
cup (color)
cdn (color)
space (float)
proximity_pct (float)
shs (bool)
LTState
Fields:
upln (array)
dnln (array)
upBroken (series bool)
dnBroken (series bool)
phx_kroLibrary "phx_kro"
compute(src, bandwidth, bbwidth, sdLook, sdMult, obos_mult)
Parameters:
src (float)
bandwidth (int)
bbwidth (float)
sdLook (int)
sdMult (float)
obos_mult (float)
start_flags(src, bandwidth, bbwidth)
Parameters:
src (float)
bandwidth (int)
bbwidth (float)
KROFeed
Fields:
Wave (series float)
is_green (series bool)
is_red (series bool)
band_width (series float)
band_width_sma (series float)
band_width_std (series float)
is_hyper_wide (series bool)
wave_sma (series float)
wave_std (series float)
wave_ob_threshold (series float)
wave_os_threshold (series float)
is_overbought (series bool)
is_oversold (series bool)
is_oversold_confirmed (series bool)
is_overbought_confirmed (series bool)
enhanced_os_confirmed (series bool)
enhanced_ob_confirmed (series bool)
triple_green_transition (series bool)
triple_red_transition (series bool)
startwave_bull (series bool)
startwave_bear (series bool)
phx_fvgfvg generator 4h and current time frame
library to import fvg from 4h with midle line and proximity support and resistance
JK_Traders_Reality_LibLibrary "JK_Traders_Reality_Lib"
This library contains common elements used in Traders Reality scripts
calcPvsra(pvsraVolume, pvsraHigh, pvsraLow, pvsraClose, pvsraOpen, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, darkGreyCandleColor, lightGrayCandleColor)
calculate the pvsra candle color and return the color as well as an alert if a vector candle has apperared.
Situation "Climax"
Bars with volume >= 200% of the average volume of the 10 previous chart TFs, or bars
where the product of candle spread x candle volume is >= the highest for the 10 previous
chart time TFs.
Default Colors: Bull bars are green and bear bars are red.
Situation "Volume Rising Above Average"
Bars with volume >= 150% of the average volume of the 10 previous chart TFs.
Default Colors: Bull bars are blue and bear are violet.
Parameters:
pvsraVolume (float) : the instrument volume series (obtained from request.sequrity)
pvsraHigh (float) : the instrument high series (obtained from request.sequrity)
pvsraLow (float) : the instrument low series (obtained from request.sequrity)
pvsraClose (float) : the instrument close series (obtained from request.sequrity)
pvsraOpen (float) : the instrument open series (obtained from request.sequrity)
redVectorColor (simple color) : red vector candle color
greenVectorColor (simple color) : green vector candle color
violetVectorColor (simple color) : violet/pink vector candle color
blueVectorColor (simple color) : blue vector candle color
darkGreyCandleColor (simple color) : regular volume candle down candle color - not a vector
lightGrayCandleColor (simple color) : regular volume candle up candle color - not a vector
@return
adr(length, barsBack)
Parameters:
length (simple int) : how many elements of the series to calculate on
barsBack (simple int) : starting possition for the length calculation - current bar or some other value eg last bar
@return adr the adr for the specified lenght
adrHigh(adr, fromDo)
Calculate the ADR high given an ADR
Parameters:
adr (float) : the adr
fromDo (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrHigh the position of the adr high in price
adrLow(adr, fromDo)
Parameters:
adr (float) : the adr
fromDo (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrLow the position of the adr low in price
splitSessionString(sessXTime)
given a session in the format 0000-0100:23456 split out the hours and minutes
Parameters:
sessXTime (simple string) : the session time string usually in the format 0000-0100:23456
@return
calcSessionStartEnd(sessXTime, gmt)
calculate the start and end timestamps of the session
Parameters:
sessXTime (simple string) : the session time string usually in the format 0000-0100:23456
gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return
drawOpenRange(sessXTime, sessXcol, showOrX, gmt)
draw open range for a session
Parameters:
sessXTime (simple string) : session string in the format 0000-0100:23456
sessXcol (simple color) : the color to be used for the opening range box shading
showOrX (simple bool) : boolean flag to toggle displaying the opening range
gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return void
drawSessionHiLo(sessXTime, showRectangleX, showLabelX, sessXcolLabel, sessXLabel, gmt, sessionLineStyle)
Parameters:
sessXTime (simple string) : session string in the format 0000-0100:23456
showRectangleX (simple bool)
showLabelX (simple bool)
sessXcolLabel (simple color) : the color to be used for the hi/low lines and label
sessXLabel (simple string) : the session label text
gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
sessionLineStyle (simple string) : the line stile for the session high low lines
@return void
calcDst()
calculate market session dst on/off flags
@return indicating if DST is on or off for a particular region
timestampPreviousDayOfWeek(previousDayOfWeek, hourOfDay, gmtOffset, oneWeekMillis)
Timestamp any of the 6 previous days in the week (such as last Wednesday at 21 hours GMT)
Parameters:
previousDayOfWeek (simple string) : Monday or Satruday
hourOfDay (simple int) : the hour of the day when psy calc is to start
gmtOffset (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
oneWeekMillis (simple int) : the amount if time for a week in milliseconds
@return the timestamp of the psy level calculation start time
getdayOpen()
get the daily open - basically exchange midnight
@return the daily open value which is float price
newBar(res)
new_bar: check if we're on a new bar within the session in a given resolution
Parameters:
res (simple string) : the desired resolution
@return true/false is a new bar for the session has started
toPips(val)
to_pips Convert value to pips
Parameters:
val (float) : the value to convert to pips
@return the value in pips
rLabel(ry, rtext, rstyle, rcolor, valid, labelXOffset)
a function that draws a right aligned lable for a series during the current bar
Parameters:
ry (float) : series float the y coordinate of the lable
rtext (simple string) : the text of the label
rstyle (simple string) : the style for the lable
rcolor (simple color) : the color for the label
valid (simple bool) : a boolean flag that allows for turning on or off a lable
labelXOffset (int) : how much to offset the label from the current position
rLabelOffset(ry, rtext, rstyle, rcolor, valid, labelOffset)
a function that draws a right aligned lable for a series during the current bar
Parameters:
ry (float) : series float the y coordinate of the lable
rtext (string) : the text of the label
rstyle (simple string) : the style for the lable
rcolor (simple color) : the color for the label
valid (simple bool) : a boolean flag that allows for turning on or off a lable
labelOffset (int)
rLabelLastBar(ry, rtext, rstyle, rcolor, valid, labelXOffset)
a function that draws a right aligned lable for a series only on the last bar
Parameters:
ry (float) : series float the y coordinate of the lable
rtext (string) : the text of the label
rstyle (simple string) : the style for the lable
rcolor (simple color) : the color for the label
valid (simple bool) : a boolean flag that allows for turning on or off a lable
labelXOffset (int) : how much to offset the label from the current position
drawLine(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset, validTimeFrame)
a function that draws a line and a label for a series
Parameters:
xSeries (float) : series float the y coordinate of the line/label
res (simple string) : the desired resolution controlling when a new line will start
tag (simple string) : the text for the lable
xColor (simple color) : the color for the label
xStyle (simple string) : the style for the line
xWidth (simple int) : the width of the line
xExtend (simple string) : extend the line
isLabelValid (simple bool) : a boolean flag that allows for turning on or off a label
xLabelOffset (int)
validTimeFrame (simple bool) : a boolean flag that allows for turning on or off a line drawn
drawLineDO(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset, validTimeFrame)
a function that draws a line and a label for the daily open series
Parameters:
xSeries (float) : series float the y coordinate of the line/label
res (simple string) : the desired resolution controlling when a new line will start
tag (simple string) : the text for the lable
xColor (simple color) : the color for the label
xStyle (simple string) : the style for the line
xWidth (simple int) : the width of the line
xExtend (simple string) : extend the line
isLabelValid (simple bool) : a boolean flag that allows for turning on or off a label
xLabelOffset (int)
validTimeFrame (simple bool) : a boolean flag that allows for turning on or off a line drawn
drawPivot(pivotLevel, res, tag, pivotColor, pivotLabelColor, pivotStyle, pivotWidth, pivotExtend, isLabelValid, validTimeFrame, levelStart, pivotLabelXOffset)
draw a pivot line - the line starts one day into the past
Parameters:
pivotLevel (float) : series of the pivot point
res (simple string) : the desired resolution
tag (simple string) : the text to appear
pivotColor (simple color) : the color of the line
pivotLabelColor (simple color) : the color of the label
pivotStyle (simple string) : the line style
pivotWidth (simple int) : the line width
pivotExtend (simple string) : extend the line
isLabelValid (simple bool) : boolean param allows to turn label on and off
validTimeFrame (simple bool) : only draw the line and label at a valid timeframe
levelStart (int) : basically when to start drawing the levels
pivotLabelXOffset (int) : how much to offset the label from its current postion
@return the pivot line series
getPvsraFlagByColor(pvsraColor, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, lightGrayCandleColor)
convert the pvsra color to an internal code
Parameters:
pvsraColor (color) : the calculated pvsra color
redVectorColor (simple color) : the user defined red vector color
greenVectorColor (simple color) : the user defined green vector color
violetVectorColor (simple color) : the user defined violet vector color
blueVectorColor (simple color) : the user defined blue vector color
lightGrayCandleColor (simple color) : the user defined regular up candle color
@return pvsra internal code
updateZones(pvsra, direction, boxArr, maxlevels, pvsraHigh, pvsraLow, pvsraOpen, pvsraClose, transperancy, zoneupdatetype, zonecolor, zonetype, borderwidth, coloroverride, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor)
a function that draws the unrecovered vector candle zones
Parameters:
pvsra (int) : internal code
direction (simple int) : above or below the current pa
boxArr (array) : the array containing the boxes that need to be updated
maxlevels (simple int) : the maximum number of boxes to draw
pvsraHigh (float) : the pvsra high value series
pvsraLow (float) : the pvsra low value series
pvsraOpen (float) : the pvsra open value series
pvsraClose (float) : the pvsra close value series
transperancy (simple int) : the transparencfy of the vecor candle zones
zoneupdatetype (simple string) : the zone update type
zonecolor (simple color) : the zone color if overriden
zonetype (simple string) : the zone type
borderwidth (simple int) : the width of the border
coloroverride (simple bool) : if the color overriden
redVectorColor (simple color) : the user defined red vector color
greenVectorColor (simple color) : the user defined green vector color
violetVectorColor (simple color) : the user defined violet vector color
blueVectorColor (simple color) : the user defined blue vector color
cleanarr(arr)
clean an array from na values
Parameters:
arr (array) : the array to clean
@return if the array was cleaned
calcPsyLevels(oneWeekMillis, showPsylevels, psyType, sydDST)
calculate the psy levels
4 hour res based on how mt4 does it
mt4 code
int Li_4 = iBarShift(NULL, PERIOD_H4, iTime(NULL, PERIOD_W1, Li_0)) - 2 - Offset;
ObjectCreate("PsychHi", OBJ_TREND, 0, Time , iHigh(NULL, PERIOD_H4, iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)), iTime(NULL, PERIOD_W1, 0), iHigh(NULL, PERIOD_H4,
iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)));
so basically because the session is 8 hours and we are looking at a 4 hour resolution we only need to take the highest high an lowest low of 2 bars
we use the gmt offset to adjust the 0000-0800 session to Sydney open which is at 2100 during dst and at 2200 otherwize. (dst - spring foward, fall back)
keep in mind sydney is in the souther hemisphere so dst is oposite of when london and new york go into dst
Parameters:
oneWeekMillis (simple int) : a constant value
showPsylevels (simple bool) : should psy levels be calculated
psyType (simple string) : the type of Psylevels - crypto or forex
sydDST (bool) : is Sydney in DST
@return
adrHiLo(length, barsBack, fromDO)
Parameters:
length (simple int) : how many elements of the series to calculate on
barsBack (simple int) : starting possition for the length calculation - current bar or some other value eg last bar
fromDO (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adr, adrLow and adrHigh - the adr, the position of the adr High and adr Low with respect to price
drawSessionHiloLite(sessXTime, showRectangleX, showLabelX, sessXcolLabel, sessXLabel, gmt, sessionLineStyle, sessXcol)
Parameters:
sessXTime (simple string) : session string in the format 0000-0100:23456
showRectangleX (simple bool)
showLabelX (simple bool)
sessXcolLabel (simple color) : the color to be used for the hi/low lines and label
sessXLabel (simple string) : the session label text
gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
sessionLineStyle (simple string) : the line stile for the session high low lines
sessXcol (simple color) : - the color for the box color that will color the session
@return void
msToHmsString(ms)
converts milliseconds into an hh:mm string. For example, 61000 ms to '0:01:01'
Parameters:
ms (int) : - the milliseconds to convert to hh:mm
@return string - the converted hh:mm string
countdownString(openToday, closeToday, showMarketsWeekends, oneDay)
that calculates how much time is left until the next session taking the session start and end times into account. Note this function does not work on intraday sessions.
Parameters:
openToday (int) : - timestamps of when the session opens in general - note its a series because the timestamp was created using the dst flag which is a series itself thus producing a timestamp series
closeToday (int) : - timestamp of when the session closes in general - note its a series because the timestamp was created using the dst flag which is a series itself thus producing a timestamp series
@return a countdown of when next the session opens or 'Open' if the session is open now
showMarketsWeekends (simple bool)
oneDay (simple int)
countdownStringSyd(sydOpenToday, sydCloseToday, showMarketsWeekends, oneDay)
that calculates how much time is left until the next session taking the session start and end times into account. special case of intraday sessions like sydney
Parameters:
sydOpenToday (int)
sydCloseToday (int)
showMarketsWeekends (simple bool)
oneDay (simple int)
Market Structure Report Library [TradingFinder]🔵 Introduction
Market Structure is one of the most fundamental concepts in Price Action and Smart Money theory. In simple terms, it represents how price moves between highs and lows and reveals which phase of the market cycle we are currently in uptrend, downtrend, or transition.
Each structure in the market is formed by a combination of Breaks of Structure (BoS) and Changes of Character (CHoCH) :
BoS occurs when the market breaks a previous high or low, confirming the continuation of the current trend.
CHoCH occurs when price breaks in the opposite direction for the first time, signaling a potential trend reversal.
Since price movement is inherently fractal, market structure can be analyzed on two distinct levels :
Major / External Structure: represents the dominant macro trend.
Minor / Internal Structure: represents corrective or smaller-scale movements within the larger trend.
🔵 Library Purpose
The “Market Structure Report Library” is designed to automatically detect the current market structure type in real time.
Without drawing or displaying any visuals, it analyzes raw price data and returns a series of logical and textual outputs (Return Values) that describe the current structural state of the market.
It provides the following information :
Trend Type :
External Trend (Major): Up Trend, Down Trend, No Trend
Internal Trend (Minor): Up Trend, Down Trend, No Trend
Structure Type :
BoS : Confirms trend continuation
CHoCH : Indicates a potential trend reversal
Consecutive BoS Counter : Measures trend strength on both Major and Minor levels.
Candle Type : Returns the current candle’s condition(Bullish, Bearish, Doji)
This library is specifically designed for use in Smart Money–based screeners, indicators, and algorithmic strategies.
It can analyze multiple symbols and timeframes simultaneously and return the exact structure type (BoS or CHoCH) and trend direction for each.
🔵 Function Outputs
The function MS() processes the price data and returns seven key outputs,
each representing a distinct structural state of the market. These values can be used in indicators, strategies, or multi-symbol screeners.
🟣 ExternalTrend
Type : string
Description : Represents the direction of the Major (External) market structure.
Possible values :
Up Trend
Down Trend
No Trend
This is determined based on the behavior of Major Pivots (swing highs/lows).
🟣 InternalTrend
Type : string
Description : Represents the direction of the Minor (Internal) market structure.
Possible values :
Up Trend
Down Trend
No Trend
🟣 M_State
Type : string
Description : Specifies the type of the latest Major Structure event.
Possible values :
BoS
CHoCH
🟣 m_State
Type : string
Description : Specifies the type of the latest Minor Structure event.
Possible values :
BoS
CHoCH
🟣 MBoS_Counter
Type : integer
Description : Counts the number of consecutive structural breaks (BoS) in the Major structure.
Useful for evaluating trend strength :
Increasing count: indicates trend continuation.
Reset to zero: typically occurs after a CHoCH.
🟣 mBoS_Counter
Type : integer
Description : Counts the number of consecutive structural breaks in the Minor structure.
Helps analyze the micro structure of the market on lower timeframes.
Higher value : strong internal trend.
Reset : indicates a minor pullback or reversal.
🟣 Candle_Type
Type : string
Description : Represents the type of the current candle.
Possible values :
Bullish
Bearish
Doji
import TFlab/Market_Structure_Report_Library_TradingFinder/1 as MSS
PP = input.int (5 , 'Market Structure Pivot Period' , group = 'Symbol 1' )
= MSS.MS(PP)
SequencerLibraryLibrary "SequencerLibrary"
SequencerLibrary v1 is a Pine Script™ library for identifying, tracking, and visualizing
sequential bullish and bearish patterns on price charts.
It provides a complete framework for building sequence-based trading systems, including:
• Automatic detection and counting of setup and countdown phases.
• Real-time tracking of completion states, perfected setups, and exhaustion signals.
• Dynamic support and resistance thresholds derived from recent price structure.
• Customizable visual highlighting for both setup and countdown sequences.
method doSequence(s, src, config, condition)
Updates the sequence state based on the source value, and user configuration.
Namespace types: Sequence
Parameters:
s (Sequence) : The sequence object containing bullish and bearish setups.
src (float) : The source value (e.g., close price) used for evaluating sequence conditions.
config (SequenceInputs) : The user-defined settings for sequence analysis.
condition (bool) : When true, executes the sequence logic.
Returns:
highlight(s, css, condition)
Highlights the bullish and bearish sequence setups and countdowns on the chart.
Parameters:
s (Sequence) : The sequence object containing bullish and bearish sequence states.
css (SequenceCSS) : The styling configuration for customizing label appearances.
condition (bool) : When true, the function creates and displays labels for setups and countdowns.
Returns:
SequenceState
A type representing the configuration and state of a sequence setup.
Fields:
setup (series int) : Current count of the setup phase (e.g., how many bars have met the setup criteria).
countdown (series int) : Current count of the countdown phase (e.g., bars meeting countdown criteria).
threshold (series float) : The price threshold level used as support/resistance for the sequence.
priceWhenCompleted (series float) : The closing price when the setup or countdown phase is completed.
indicatorWhenCompleted (series float) : The indicator value when the setup or countdown phase is completed.
setupCompleted (series bool) : Indicates if the setup phase has been completed (i.e., reached the required count).
countdownCompleted (series bool) : Indicates if the countdown phase has been completed (i.e., reached exhaustion).
perfected (series bool) : Indicates if the setup meets the "perfected" condition (e.g., aligns with strict criteria).
highlightSetup (series bool) : Determines whether the setup phase should be visually highlighted on the chart.
highlightCountdown (series bool) : Determines whether the countdown phase should be visually highlighted on the chart.
Sequence
A type containing bullish and bearish sequence setups.
Fields:
bullish (SequenceState) : Configuration and state for bullish sequences.
bearish (SequenceState) : Configuration and state for bearish sequences.
SequenceInputs
A type for user-configurable input settings for sequence-based analysis.
Fields:
showSetup (series bool) : Enables or disables the display of setup sequences.
showCountdown (series bool) : Enables or disables the display of countdown sequences.
setupFilter (series string) : A comma‐separated string containing setup sequence counts to be highlighted (e.g., "1,2,3,4,5,6,7,8,9").
countdownFilter (series string) : A comma‐separated string containing countdown sequence counts to be highlighted (e.g., "1,2,3,4,5,6,7,8,9,10,11,12,13").
lookbackSetup (series int) : Defines the lookback period for evaluating setup conditions (default: 4 bars).
lookbackCountdown (series int) : Defines the lookback period for evaluating countdown conditions (default: 2 bars).
lookbackSetupPerfected (series int) : Defines the lookback period to determine a perfected setup condition (default: 6 bars).
maxSetup (series int) : The maximum count required to complete a setup phase (default: 9).
maxCountdown (series int) : The maximum count required to complete a countdown phase (default: 13).
SequenceCSS
A type defining the visual styling options for sequence labels.
Fields:
bullish (series color) : Color used for bullish sequence labels.
bearish (series color) : Color used for bearish sequence labels.
imperfect (series color) : Color used for labels representing imperfect sequences.
GBB_lib_utilsLibrary "GBB_lib_utils"
gbb_moving_average_source(_source, _length, _ma_type)
gbb_moving_average_source
@description Calculates the moving average of a source series.
Parameters:
_source (float) : (series float)
_length (simple int) : (int)
_ma_type (string) : (string)
Returns: (series) Moving average series
gbb_tf_to_display(tf_minutes, tf_string)
gbb_tf_to_display
@description Converts minutes and TF string into a short standard label.
Parameters:
tf_minutes (float) : (float)
tf_string (string) : (string)
Returns: (string) Timeframe label (M1,H1,D1,...)
gbb_convert_bars(_bars)
gbb_convert_bars
@description Formats a number of bars into a duration (days, hours, minutes + bar count).
Parameters:
_bars (int) : (int)
Returns: (string)
gbb_goldorak_init(_tf5Levels_input)
gbb_goldorak_init
@description Builds a contextual message about the current timeframe and optional 5-level TF.
Parameters:
_tf5Levels_input (string) : (string) Alternative timeframe ("" = current timeframe).
Returns: (string, string, float)
CarolTradeLibLibrary "CarolTradeLib"
f_generateSignalID(strategyName)
Parameters:
strategyName (string)
f_buildJSON(orderType, action, symbol, price, strategyName, apiKey, additionalFields, indicatorJSON)
Parameters:
orderType (string)
action (string)
symbol (string)
price (float)
strategyName (string)
apiKey (string)
additionalFields (string)
indicatorJSON (string)
sendSignal(action, symbol, price, strategyName, apiKey, indicatorJSON)
Parameters:
action (string)
symbol (string)
price (float)
strategyName (string)
apiKey (string)
indicatorJSON (string)
marketOrder(action, symbol, price, strategyName, apiKey, stopLoss, takeProfit, rrRatio, size, indicatorJSON)
Parameters:
action (string)
symbol (string)
price (float)
strategyName (string)
apiKey (string)
stopLoss (float)
takeProfit (float)
rrRatio (float)
size (float)
indicatorJSON (string)
limitOrder(action, symbol, price, strategyName, apiKey, limitPrice, size, indicatorJSON)
Parameters:
action (string)
symbol (string)
price (float)
strategyName (string)
apiKey (string)
limitPrice (float)
size (float)
indicatorJSON (string)
stopLimitOrder(action, symbol, price, strategyName, apiKey, stopPrice, limitPrice, size, indicatorJSON)
Parameters:
action (string)
symbol (string)
price (float)
strategyName (string)
apiKey (string)
stopPrice (float)
limitPrice (float)
size (float)
indicatorJSON (string)
TrailingStopLossLibrary "TrailingStopLoss"
简易追踪止损; 未充分测试,欢迎提交issue
drawdown_percent(entry_bar_index, direction_long)
drawdown_percent: 回撤百分比
Parameters:
entry_bar_index (int)
direction_long (bool)
Returns: percentage: 回撤百分比 > 0
closure_needed(entry_bar_index, initial_sl_price, percentage_ts, num_bars_tolerance, extra_drawdown_distance)
closure_needed: 是否满足平仓条件
Parameters:
entry_bar_index (int)
initial_sl_price (float)
percentage_ts (float)
num_bars_tolerance (int)
extra_drawdown_distance (float)
Returns: do_closure: bool 是否平仓
PubLibPivotLibrary "PubLibPivot"
Pivot detection library for harmonic pattern analysis - Fractal and ZigZag methods with validation and utility functions
fractalPivotHigh(depth)
Fractal pivot high condition
Parameters:
depth (int)
Returns: bool
fractalPivotLow(depth)
Fractal pivot low condition
Parameters:
depth (int)
Returns: bool
fractalPivotHighPrice(depth, occurrence)
Get fractal pivot high price
Parameters:
depth (int)
occurrence (simple int)
Returns: float
fractalPivotLowPrice(depth, occurrence)
Get fractal pivot low price
Parameters:
depth (int)
occurrence (simple int)
Returns: float
fractalPivotHighBarIndex(depth, occurrence)
Get fractal pivot high bar index
Parameters:
depth (int)
occurrence (simple int)
Returns: int
fractalPivotLowBarIndex(depth, occurrence)
Get fractal pivot low bar index
Parameters:
depth (int)
occurrence (simple int)
Returns: int
zigzagPivotHigh(deviation, backstep, useATR, atrLength)
ZigZag pivot high condition
Parameters:
deviation (float)
backstep (int)
useATR (bool)
atrLength (simple int)
Returns: bool
zigzagPivotLow(deviation, backstep, useATR, atrLength)
ZigZag pivot low condition
Parameters:
deviation (float)
backstep (int)
useATR (bool)
atrLength (simple int)
Returns: bool
zigzagPivotHighPrice(deviation, backstep, useATR, atrLength, occurrence)
Get ZigZag pivot high price
Parameters:
deviation (float)
backstep (int)
useATR (bool)
atrLength (simple int)
occurrence (simple int)
Returns: float
zigzagPivotLowPrice(deviation, backstep, useATR, atrLength, occurrence)
Get ZigZag pivot low price
Parameters:
deviation (float)
backstep (int)
useATR (bool)
atrLength (simple int)
occurrence (simple int)
Returns: float
zigzagPivotHighBarIndex(deviation, backstep, useATR, atrLength, occurrence)
Get ZigZag pivot high bar index
Parameters:
deviation (float)
backstep (int)
useATR (bool)
atrLength (simple int)
occurrence (simple int)
Returns: int
zigzagPivotLowBarIndex(deviation, backstep, useATR, atrLength, occurrence)
Get ZigZag pivot low bar index
Parameters:
deviation (float)
backstep (int)
useATR (bool)
atrLength (simple int)
occurrence (simple int)
Returns: int
isValidPivotVolume(pivotPrice, pivotBarIndex, minVolumeRatio, volumeLength)
Validate pivot quality based on volume
Parameters:
pivotPrice (float)
pivotBarIndex (int)
minVolumeRatio (float)
volumeLength (int)
Returns: bool
isValidPivotATR(pivotPrice, lastPivotPrice, minATRMultiplier, atrLength)
Validate pivot based on minimum ATR movement
Parameters:
pivotPrice (float)
lastPivotPrice (float)
minATRMultiplier (float)
atrLength (simple int)
Returns: bool
isValidPivotTime(pivotBarIndex, lastPivotBarIndex, minBars)
Validate pivot based on minimum time between pivots
Parameters:
pivotBarIndex (int)
lastPivotBarIndex (int)
minBars (int)
Returns: bool
isPivotConfirmed(pivotBarIndex, depth)
Check if pivot is not repainting (confirmed)
Parameters:
pivotBarIndex (int)
depth (int)
Returns: bool
addPivotToArray(pivotArray, barArray, pivotPrice, pivotBarIndex, maxSize)
Add pivot to array with validation
Parameters:
pivotArray (array)
barArray (array)
pivotPrice (float)
pivotBarIndex (int)
maxSize (int)
Returns: array - updated pivot array
getPivotFromArray(pivotArray, barArray, index)
Get pivot from array by index
Parameters:
pivotArray (array)
barArray (array)
index (int)
Returns: tuple - (price, bar_index)
getPivotsInRange(pivotArray, barArray, startIndex, count)
Get all pivots in range
Parameters:
pivotArray (array)
barArray (array)
startIndex (int)
count (int)
Returns: tuple, array> - (prices, bar_indices)
pivotDistance(barIndex1, barIndex2)
Calculate distance between two pivots in bars
Parameters:
barIndex1 (int)
barIndex2 (int)
Returns: int - distance in bars
pivotPriceRatio(price1, price2)
Calculate price ratio between two pivots
Parameters:
price1 (float)
price2 (float)
Returns: float - price ratio
pivotRetracementRatio(startPrice, endPrice, currentPrice)
Calculate retracement ratio
Parameters:
startPrice (float)
endPrice (float)
currentPrice (float)
Returns: float - retracement ratio (0-1)
pivotExtensionRatio(startPrice, endPrice, currentPrice)
Calculate extension ratio
Parameters:
startPrice (float)
endPrice (float)
currentPrice (float)
Returns: float - extension ratio (>1 for extension)
isInFibZone(startPrice, endPrice, currentPrice, fibLevel, tolerance)
Check if price is in Fibonacci retracement zone
Parameters:
startPrice (float)
endPrice (float)
currentPrice (float)
fibLevel (float)
tolerance (float)
Returns: bool - true if in zone
getPivotType(pivotPrice, pivotBarIndex, lookback)
Get pivot type (high/low) based on surrounding prices
Parameters:
pivotPrice (float)
pivotBarIndex (int)
lookback (int)
Returns: string - "high", "low", or "unknown"
calculatePivotStrength(pivotPrice, pivotBarIndex, lookback)
Calculate pivot strength based on volume and price action
Parameters:
pivotPrice (float)
pivotBarIndex (int)
lookback (int)
Returns: float - strength score (0-100)
AlertSenderLibrary_TradingFinderLibrary "AlertSenderLibrary_TradingFinder"
TODO: add library description here
AlertSender(Condition, Alert, AlertName, AlertType, DetectionType, SetupData, Frequncy, UTC, MoreInfo, Message, o, h, l, c, Entry, TP, SL, Distal, Proximal)
Parameters:
Condition (bool)
Alert (string)
AlertName (string)
AlertType (string)
DetectionType (string)
SetupData (string)
Frequncy (string)
UTC (string)
MoreInfo (string)
Message (string)
o (float)
h (float)
l (float)
c (float)
Entry (float)
TP (float)
SL (float)
Distal (float)
Proximal (float)
TA█ TA Library
📊 OVERVIEW
TA is a Pine Script technical analysis library. This library provides 25+ moving averages and smoothing filters , from classic SMA/EMA to Kalman Filters and adaptive algorithms, implemented based on academic research.
🎯 Core Features
Academic Based - Algorithms follow original papers and formulas
Performance Optimized - Pre-calculated constants for faster response
Unified Interface - Consistent function design
Research Based - Integrates technical analysis research
🎯 CONCEPTS
Library Design Philosophy
This technical analysis library focuses on providing:
Academic Foundation
Algorithms based on published research papers and academic standards
Implementations that follow original mathematical formulations
Clear documentation with research references
Developer Experience
Unified interface design for consistent usage patterns
Pre-calculated constants for optimal performance
Comprehensive function collection to reduce development time
Single import statement for immediate access to all functions
Each indicator encapsulated as a simple function call - one line of code simplifies complexity
Technical Excellence
25+ carefully implemented moving averages and filters
Support for advanced algorithms like Kalman Filter and MAMA/FAMA
Optimized code structure for maintainability and reliability
Regular updates incorporating latest research developments
🚀 USING THIS LIBRARY
Import Library
//@version=6
import DCAUT/TA/1 as dta
indicator("Advanced Technical Analysis", overlay=true)
Basic Usage Example
// Classic moving average combination
ema20 = ta.ema(close, 20)
kama20 = dta.kama(close, 20)
plot(ema20, "EMA20", color.red, 2)
plot(kama20, "KAMA20", color.green, 2)
Advanced Trading System
// Adaptive moving average system
kama = dta.kama(close, 20, 2, 30)
= dta.mamaFama(close, 0.5, 0.05)
// Trend confirmation and entry signals
bullTrend = kama > kama and mamaValue > famaValue
bearTrend = kama < kama and mamaValue < famaValue
longSignal = ta.crossover(close, kama) and bullTrend
shortSignal = ta.crossunder(close, kama) and bearTrend
plot(kama, "KAMA", color.blue, 3)
plot(mamaValue, "MAMA", color.orange, 2)
plot(famaValue, "FAMA", color.purple, 2)
plotshape(longSignal, "Buy", shape.triangleup, location.belowbar, color.green)
plotshape(shortSignal, "Sell", shape.triangledown, location.abovebar, color.red)
📋 FUNCTIONS REFERENCE
ewma(source, alpha)
Calculates the Exponentially Weighted Moving Average with dynamic alpha parameter.
Parameters:
source (series float) : Series of values to process.
alpha (series float) : The smoothing parameter of the filter.
Returns: (float) The exponentially weighted moving average value.
dema(source, length)
Calculates the Double Exponential Moving Average (DEMA) of a given data series.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: (float) The calculated Double Exponential Moving Average value.
tema(source, length)
Calculates the Triple Exponential Moving Average (TEMA) of a given data series.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: (float) The calculated Triple Exponential Moving Average value.
zlema(source, length)
Calculates the Zero-Lag Exponential Moving Average (ZLEMA) of a given data series. This indicator attempts to eliminate the lag inherent in all moving averages.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: (float) The calculated Zero-Lag Exponential Moving Average value.
tma(source, length)
Calculates the Triangular Moving Average (TMA) of a given data series. TMA is a double-smoothed simple moving average that reduces noise.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: (float) The calculated Triangular Moving Average value.
frama(source, length)
Calculates the Fractal Adaptive Moving Average (FRAMA) of a given data series. FRAMA adapts its smoothing factor based on fractal geometry to reduce lag. Developed by John Ehlers.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: (float) The calculated Fractal Adaptive Moving Average value.
kama(source, length, fastLength, slowLength)
Calculates Kaufman's Adaptive Moving Average (KAMA) of a given data series. KAMA adjusts its smoothing based on market efficiency ratio. Developed by Perry J. Kaufman.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the efficiency calculation.
fastLength (simple int) : Fast EMA length for smoothing calculation. Optional. Default is 2.
slowLength (simple int) : Slow EMA length for smoothing calculation. Optional. Default is 30.
Returns: (float) The calculated Kaufman's Adaptive Moving Average value.
t3(source, length, volumeFactor)
Calculates the Tilson Moving Average (T3) of a given data series. T3 is a triple-smoothed exponential moving average with improved lag characteristics. Developed by Tim Tillson.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
volumeFactor (simple float) : Volume factor affecting responsiveness. Optional. Default is 0.7.
Returns: (float) The calculated Tilson Moving Average value.
ultimateSmoother(source, length)
Calculates the Ultimate Smoother of a given data series. Uses advanced filtering techniques to reduce noise while maintaining responsiveness. Based on digital signal processing principles by John Ehlers.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the smoothing calculation.
Returns: (float) The calculated Ultimate Smoother value.
kalmanFilter(source, processNoise, measurementNoise)
Calculates the Kalman Filter of a given data series. Optimal estimation algorithm that estimates true value from noisy observations. Based on the Kalman Filter algorithm developed by Rudolf Kalman (1960).
Parameters:
source (series float) : Series of values to process.
processNoise (simple float) : Process noise variance (Q). Controls adaptation speed. Optional. Default is 0.05.
measurementNoise (simple float) : Measurement noise variance (R). Controls smoothing. Optional. Default is 1.0.
Returns: (float) The calculated Kalman Filter value.
mcginleyDynamic(source, length)
Calculates the McGinley Dynamic of a given data series. McGinley Dynamic is an adaptive moving average that adjusts to market speed changes. Developed by John R. McGinley Jr.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the dynamic calculation.
Returns: (float) The calculated McGinley Dynamic value.
mama(source, fastLimit, slowLimit)
Calculates the Mesa Adaptive Moving Average (MAMA) of a given data series. MAMA uses Hilbert Transform Discriminator to adapt to market cycles dynamically. Developed by John F. Ehlers.
Parameters:
source (series float) : Series of values to process.
fastLimit (simple float) : Maximum alpha (responsiveness). Optional. Default is 0.5.
slowLimit (simple float) : Minimum alpha (smoothing). Optional. Default is 0.05.
Returns: (float) The calculated Mesa Adaptive Moving Average value.
fama(source, fastLimit, slowLimit)
Calculates the Following Adaptive Moving Average (FAMA) of a given data series. FAMA follows MAMA with reduced responsiveness for crossover signals. Developed by John F. Ehlers.
Parameters:
source (series float) : Series of values to process.
fastLimit (simple float) : Maximum alpha (responsiveness). Optional. Default is 0.5.
slowLimit (simple float) : Minimum alpha (smoothing). Optional. Default is 0.05.
Returns: (float) The calculated Following Adaptive Moving Average value.
mamaFama(source, fastLimit, slowLimit)
Calculates Mesa Adaptive Moving Average (MAMA) and Following Adaptive Moving Average (FAMA).
Parameters:
source (series float) : Series of values to process.
fastLimit (simple float) : Maximum alpha (responsiveness). Optional. Default is 0.5.
slowLimit (simple float) : Minimum alpha (smoothing). Optional. Default is 0.05.
Returns: ( ) Tuple containing values.
laguerreFilter(source, length, gamma, order)
Calculates the standard N-order Laguerre Filter of a given data series. Standard Laguerre Filter uses uniform weighting across all polynomial terms. Developed by John F. Ehlers.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Length for UltimateSmoother preprocessing.
gamma (simple float) : Feedback coefficient (0-1). Lower values reduce lag. Optional. Default is 0.8.
order (simple int) : The order of the Laguerre filter (1-10). Higher order increases lag. Optional. Default is 8.
Returns: (float) The calculated standard Laguerre Filter value.
laguerreBinomialFilter(source, length, gamma)
Calculates the Laguerre Binomial Filter of a given data series. Uses 6-pole feedback with binomial weighting coefficients. Developed by John F. Ehlers.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Length for UltimateSmoother preprocessing.
gamma (simple float) : Feedback coefficient (0-1). Lower values reduce lag. Optional. Default is 0.5.
Returns: (float) The calculated Laguerre Binomial Filter value.
superSmoother(source, length)
Calculates the Super Smoother of a given data series. SuperSmoother is a second-order Butterworth filter from aerospace technology. Developed by John F. Ehlers.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Period for the filter calculation.
Returns: (float) The calculated Super Smoother value.
rangeFilter(source, length, multiplier)
Calculates the Range Filter of a given data series. Range Filter reduces noise by filtering price movements within a dynamic range.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the average range calculation.
multiplier (simple float) : Multiplier for the smooth range. Higher values increase filtering. Optional. Default is 2.618.
Returns: ( ) Tuple containing filtered value, trend direction, upper band, and lower band.
qqe(source, rsiLength, rsiSmooth, qqeFactor)
Calculates the Quantitative Qualitative Estimation (QQE) of a given data series. QQE is an improved RSI that reduces noise and provides smoother signals. Developed by Igor Livshin.
Parameters:
source (series float) : Series of values to process.
rsiLength (simple int) : Number of bars for the RSI calculation. Optional. Default is 14.
rsiSmooth (simple int) : Number of bars for smoothing the RSI. Optional. Default is 5.
qqeFactor (simple float) : QQE factor for volatility band width. Optional. Default is 4.236.
Returns: ( ) Tuple containing smoothed RSI and QQE trend line.
sslChannel(source, length)
Calculates the Semaphore Signal Level (SSL) Channel of a given data series. SSL Channel provides clear trend signals using moving averages of high and low prices.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: ( ) Tuple containing SSL Up and SSL Down lines.
ma(source, length, maType)
Calculates a Moving Average based on the specified type. Universal interface supporting all moving average algorithms.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
maType (simple MaType) : Type of moving average to calculate. Optional. Default is SMA.
Returns: (float) The calculated moving average value based on the specified type.
atr(length, maType)
Calculates the Average True Range (ATR) using the specified moving average type. Developed by J. Welles Wilder Jr.
Parameters:
length (simple int) : Number of bars for the ATR calculation.
maType (simple MaType) : Type of moving average to use for smoothing. Optional. Default is RMA.
Returns: (float) The calculated Average True Range value.
macd(source, fastLength, slowLength, signalLength, maType, signalMaType)
Calculates the Moving Average Convergence Divergence (MACD) with customizable MA types. Developed by Gerald Appel.
Parameters:
source (series float) : Series of values to process.
fastLength (simple int) : Period for the fast moving average.
slowLength (simple int) : Period for the slow moving average.
signalLength (simple int) : Period for the signal line moving average.
maType (simple MaType) : Type of moving average for main MACD calculation. Optional. Default is EMA.
signalMaType (simple MaType) : Type of moving average for signal line calculation. Optional. Default is EMA.
Returns: ( ) Tuple containing MACD line, signal line, and histogram values.
dmao(source, fastLength, slowLength, maType)
Calculates the Dual Moving Average Oscillator (DMAO) of a given data series. Uses the same algorithm as the Percentage Price Oscillator (PPO), but can be applied to any data series.
Parameters:
source (series float) : Series of values to process.
fastLength (simple int) : Period for the fast moving average.
slowLength (simple int) : Period for the slow moving average.
maType (simple MaType) : Type of moving average to use for both calculations. Optional. Default is EMA.
Returns: (float) The calculated Dual Moving Average Oscillator value as a percentage.
continuationIndex(source, length, gamma, order)
Calculates the Continuation Index of a given data series. The index represents the Inverse Fisher Transform of the normalized difference between an UltimateSmoother and an N-order Laguerre filter. Developed by John F. Ehlers, published in TASC 2025.09.
Parameters:
source (series float) : Series of values to process.
length (simple int) : The calculation length.
gamma (simple float) : Controls the phase response of the Laguerre filter. Optional. Default is 0.8.
order (simple int) : The order of the Laguerre filter (1-10). Optional. Default is 8.
Returns: (float) The calculated Continuation Index value.
📚 RELEASE NOTES
v1.0 (2025.09.24)
✅ 25+ technical analysis functions
✅ Complete adaptive moving average series (KAMA, FRAMA, MAMA/FAMA)
✅ Advanced signal processing filters (Kalman, Laguerre, SuperSmoother, UltimateSmoother)
✅ Performance optimized with pre-calculated constants and efficient algorithms
✅ Unified function interface design following TradingView best practices
✅ Comprehensive moving average collection (DEMA, TEMA, ZLEMA, T3, etc.)
✅ Volatility and trend detection tools (QQE, SSL Channel, Range Filter)
✅ Continuation Index - Latest research from TASC 2025.09
✅ MACD and ATR calculations supporting multiple moving average types
✅ Dual Moving Average Oscillator (DMAO) for arbitrary data series analysis
tclibLibrary "tclib"
super_smoother(data, smoothing_period)
Parameters:
data (float)
smoothing_period (int)
FiniteStateMachine🟩 OVERVIEW
A flexible framework for creating, testing and implementing a Finite State Machine (FSM) in your script. FSMs use rules to control how states change in response to events.
This is the first Finite State Machine library on TradingView and it's quite a different way to think about your script's logic. Advantages of using this vs hardcoding all your logic include:
• Explicit logic : You can see all rules easily side-by-side.
• Validation : Tables show your rules and validation results right on the chart.
• Dual approach : Simple matrix for straightforward transitions; map implementation for concurrent scenarios. You can combine them for complex needs.
• Type safety : Shows how to use enums for robustness while maintaining string compatibility.
• Real-world examples : Includes both conceptual (traffic lights) and practical (trading strategy) demonstrations.
• Priority control : Explicit control over which rules take precedence when multiple conditions are met.
• Wildcard system : Flexible pattern matching for states and events.
The library seems complex, but it's not really. Your conditions, events, and their potential interactions are complex. The FSM makes them all explicit, which is some work. However, like all "good" pain in life, this is front-loaded, and *saves* pain later, in the form of unintended interactions and bugs that are very hard to find and fix.
🟩 SIMPLE FSM (MATRIX-BASED)
The simple FSM uses a matrix to define transition rules with the structure: state > event > state. We look up the current state, check if the event in that row matches, and if it does, output the resulting state.
Each row in the matrix defines one rule, and the first matching row, counting from the top down, is applied.
A limitation of this method is that you can supply only ONE event.
You can design layered rules using widlcards. Use an empty string "" or the special string "ANY" for any state or event wildcard.
The matrix FSM is foruse where you have clear, sequential state transitions triggered by single events. Think traffic lights, or any logic where only one thing can happen at a time.
The demo for this FSM is of traffic lights.
🟩 CONCURRENT FSM (MAP-BASED)
The map FSM uses a more complex structure where each state is a key in the map, and its value is an array of event rules. Each rule maps a named condition to an output (event or next state).
This FSM can handle multiple conditions simultaneously. Rules added first have higher priority.
Adding more rules to existing states combines the entries in the map (if you use the supplied helper function) rather than overwriting them.
This FSM is for more complex scenarios where multiple conditions can be true simultaneously, and you need to control which takes precedence. Like trading strategies, or any system with concurrent conditions.
The demo for this FSM is a trading strategy.
🟩 HOW TO USE
Pine Script libraries contain reusable code for importing into indicators. You do not need to copy any code out of here. Just import the library and call the function you want.
For example, for version 1 of this library, import it like this:
import SimpleCryptoLife/FiniteStateMachine/1
See the EXAMPLE USAGE sections within the library for examples of calling the functions.
For more information on libraries and incorporating them into your scripts, see the Libraries section of the Pine Script User Manual.
🟩 TECHNICAL IMPLEMENTATION
Both FSM implementations support wildcards using blank strings "" or the special string "ANY". Wildcards match in this priority order:
• Exact state + exact event match
• Exact state + empty event (event wildcard)
• Empty state + exact event (state wildcard)
• Empty state + empty event (full wildcard)
When multiple rules match the same state + event combination, the FIRST rule encountered takes priority. In the matrix FSM, this means row order determines priority. In the map FSM, it's the order you add rules to each state.
The library uses user-defined types for the map FSM:
• o_eventRule : Maps a condition name to an output
• o_eventRuleWrapper : Wraps an array of rules (since maps can't contain arrays directly)
Everything uses strings for maximum library compatibility, though the examples show how to use enums for type safety by converting them to strings.
Unlike normal maps where adding a duplicate key overwrites the value, this library's `m_addRuleToEventMap()` method *combines* rules, making it intuitive to build rule sets without breaking them.
🟩 VALIDATION & ERROR HANDLING
The library includes comprehensive validation functions that catch common FSM design errors:
Error detection:
• Empty next states
• Invalid states not in the states array
• Duplicate rules
• Conflicting transitions
• Unreachable states (no entry/exit rules)
Warning detection:
• Redundant wildcards
• Empty states/events (potential unintended wildcards)
• Duplicate conditions within states
You can display validation results in tables on the chart, with tooltips providing detailed explanations. The helper functions to display the tables are exported so you can call them from your own script.
🟩 PRACTICAL EXAMPLES
The library includes four comprehensive demos:
Traffic Light Demo (Simple FSM) : Uses the matrix FSM to cycle through traffic light states (red → red+amber → green → amber → red) with timer events. Includes pseudo-random "break" events and repair logic to demonstrate wildcards and priority handling.
Trading Strategy Demo (Concurrent FSM) : Implements a realistic long-only trading strategy using BOTH FSM types:
• Map FSM converts multiple technical conditions (EMA crosses, gaps, fractals, RSI) into prioritised events
• Matrix FSM handles state transitions (idle → setup → entry → position → exit → re-entry)
• Includes position management, stop losses, and re-entry logic
Error Demonstrations : Both FSM types include error demos with intentionally malformed rules to showcase the validation system's capabilities.
🟩 BRING ON THE FUNCTIONS
f_printFSMMatrix(_mat_rules, _a_states, _tablePosition)
Prints a table of states and rules to the specified position on the chart. Works only with the matrix-based FSM.
Parameters:
_mat_rules (matrix)
_a_states (array)
_tablePosition (simple string)
Returns: The table of states and rules.
method m_loadMatrixRulesFromText(_mat_rules, _rulesText)
Loads rules into a rules matrix from a multiline string where each line is of the form "current state | event | next state" (ignores empty lines and trims whitespace).
This is the most human-readable way to define rules because it's a visually aligned, table-like format.
Namespace types: matrix
Parameters:
_mat_rules (matrix)
_rulesText (string)
Returns: No explicit return. The matrix is modified as a side-effect.
method m_addRuleToMatrix(_mat_rules, _currentState, _event, _nextState)
Adds a single rule to the rules matrix. This can also be quite readble if you use short variable names and careful spacing.
Namespace types: matrix
Parameters:
_mat_rules (matrix)
_currentState (string)
_event (string)
_nextState (string)
Returns: No explicit return. The matrix is modified as a side-effect.
method m_validateRulesMatrix(_mat_rules, _a_states, _showTable, _tablePosition)
Validates a rules matrix and a states array to check that they are well formed. Works only with the matrix-based FSM.
Checks: matrix has exactly 3 columns; no empty next states; all states defined in array; no duplicate states; no duplicate rules; all states have entry/exit rules; no conflicting transitions; no redundant wildcards. To avoid slowing down the script unnecessarily, call this method once (perhaps using `barstate.isfirst`), when the rules and states are ready.
Namespace types: matrix
Parameters:
_mat_rules (matrix)
_a_states (array)
_showTable (bool)
_tablePosition (simple string)
Returns: `true` if the rules and states are valid; `false` if errors or warnings exist.
method m_getStateFromMatrix(_mat_rules, _currentState, _event, _strictInput, _strictTransitions)
Returns the next state based on the current state and event, or `na` if no matching transition is found. Empty (not na) entries are treated as wildcards if `strictInput` is false.
Priority: exact match > event wildcard > state wildcard > full wildcard.
Namespace types: matrix
Parameters:
_mat_rules (matrix)
_currentState (string)
_event (string)
_strictInput (bool)
_strictTransitions (bool)
Returns: The next state or `na`.
method m_addRuleToEventMap(_map_eventRules, _state, _condName, _output)
Adds a single event rule to the event rules map. If the state key already exists, appends the new rule to the existing array (if different). If the state key doesn't exist, creates a new entry.
Namespace types: map
Parameters:
_map_eventRules (map)
_state (string)
_condName (string)
_output (string)
Returns: No explicit return. The map is modified as a side-effect.
method m_addEventRulesToMapFromText(_map_eventRules, _configText)
Loads event rules from a multiline text string into a map structure.
Format: "state | condName > output | condName > output | ..." . Pairs are ordered by priority. You can have multiple rules on the same line for one state.
Supports wildcards: Use an empty string ("") or the special string "ANY" for state or condName to create wildcard rules.
Examples: " | condName > output" (state wildcard), "state | > output" (condition wildcard), " | > output" (full wildcard).
Splits lines by , extracts state as key, creates/appends to array with new o_eventRule(condName, output).
Call once, e.g., on barstate.isfirst for best performance.
Namespace types: map
Parameters:
_map_eventRules (map)
_configText (string)
Returns: No explicit return. The map is modified as a side-effect.
f_printFSMMap(_map_eventRules, _a_states, _tablePosition)
Prints a table of map-based event rules to the specified position on the chart.
Parameters:
_map_eventRules (map)
_a_states (array)
_tablePosition (simple string)
Returns: The table of map-based event rules.
method m_validateEventRulesMap(_map_eventRules, _a_states, _a_validEvents, _showTable, _tablePosition)
Validates an event rules map to check that it's well formed.
Checks: map is not empty; wrappers contain non-empty arrays; no duplicate condition names per state; no empty fields in o_eventRule objects; optionally validates outputs against matrix events.
NOTE: Both "" and "ANY" are treated identically as wildcards for both states and conditions.
To avoid slowing down the script unnecessarily, call this method once (perhaps using `barstate.isfirst`), when the map is ready.
Namespace types: map
Parameters:
_map_eventRules (map)
_a_states (array)
_a_validEvents (array)
_showTable (bool)
_tablePosition (simple string)
Returns: `true` if the event rules map is valid; `false` if errors or warnings exist.
method m_getEventFromConditionsMap(_currentState, _a_activeConditions, _map_eventRules)
Returns a single event or state string based on the current state and active conditions.
Uses a map of event rules where rules are pre-sorted by implicit priority via load order.
Supports wildcards using empty string ("") or "ANY" for flexible rule matching.
Priority: exact match > condition wildcard > state wildcard > full wildcard.
Namespace types: series string, simple string, input string, const string
Parameters:
_currentState (string)
_a_activeConditions (array)
_map_eventRules (map)
Returns: The output string (event or state) for the first matching condition, or na if no match found.
o_eventRule
o_eventRule defines a condition-to-output mapping for the concurrent FSM.
Fields:
condName (series string) : The name of the condition to check.
output (series string) : The output (event or state) when the condition is true.
o_eventRuleWrapper
o_eventRuleWrapper wraps an array of o_eventRule for use as map values (maps cannot contain collections directly).
Fields:
a_rules (array) : Array of o_eventRule objects for a specific state.
ApicodeLibrary "Apicode"
percentToTicks(percent, from)
Converts a percentage of the average entry price or a specified price to ticks when the
strategy has an open position.
Parameters:
percent (float) : (series int/float) The percentage of the `from` price to express in ticks, e.g.,
a value of 50 represents 50% (half) of the price.
from (float) : (series int/float) Optional. The price from which to calculate a percentage and convert
to ticks. The default is `strategy.position_avg_price`.
Returns: (float) The number of ticks within the specified percentage of the `from` price if
the strategy has an open position. Otherwise, it returns `na`.
percentToPrice(percent, from)
Calculates the price value that is a specific percentage distance away from the average
entry price or a specified price when the strategy has an open position.
Parameters:
percent (float) : (series int/float) The percentage of the `from` price to use as the distance. If the value
is positive, the calculated price is above the `from` price. If negative, the result is
below the `from` price. For example, a value of 10 calculates the price 10% higher than
the `from` price.
from (float) : (series int/float) Optional. The price from which to calculate a percentage distance.
The default is `strategy.position_avg_price`.
Returns: (float) The price value at the specified `percentage` distance away from the `from` price
if the strategy has an open position. Otherwise, it returns `na`.
percentToCurrency(price, percent)
Parameters:
price (float) : (series int/float) The price from which to calculate the percentage.
percent (float) : (series int/float) The percentage of the `price` to calculate.
Returns: (float) The amount of the symbol's currency represented by the percentage of the specified
`price`.
percentProfit(exitPrice)
Calculates the expected profit/loss of the open position if it were to close at the
specified `exitPrice`, expressed as a percentage of the average entry price.
NOTE: This function may not return precise values for positions with multiple open trades
because it only uses the average entry price.
Parameters:
exitPrice (float) : (series int/float) The position's hypothetical closing price.
Returns: (float) The expected profit percentage from exiting the position at the `exitPrice`. If
there is no open position, it returns `na`.
priceToTicks(price)
Converts a price value to ticks.
Parameters:
price (float) : (series int/float) The price to convert.
Returns: (float) The value of the `price`, expressed in ticks.
ticksToPrice(ticks, from)
Calculates the price value at the specified number of ticks away from the average entry
price or a specified price when the strategy has an open position.
Parameters:
ticks (float) : (series int/float) The number of ticks away from the `from` price. If the value is positive,
the calculated price is above the `from` price. If negative, the result is below the `from`
price.
from (float) : (series int/float) Optional. The price to evaluate the tick distance from. The default is
`strategy.position_avg_price`.
Returns: (float) The price value at the specified number of ticks away from the `from` price if
the strategy has an open position. Otherwise, it returns `na`.
ticksToCurrency(ticks)
Converts a specified number of ticks to an amount of the symbol's currency.
Parameters:
ticks (float) : (series int/float) The number of ticks to convert.
Returns: (float) The amount of the symbol's currency represented by the tick distance.
ticksToStopLevel(ticks)
Calculates a stop-loss level using a specified tick distance from the position's average
entry price. A script can plot the returned value and use it as the `stop` argument in a
`strategy.exit()` call.
Parameters:
ticks (float) : (series int/float) The number of ticks from the position's average entry price to the
stop-loss level. If the position is long, the value represents the number of ticks *below*
the average entry price. If short, it represents the number of ticks *above* the price.
Returns: (float) The calculated stop-loss value for the open position. If there is no open position,
it returns `na`.
ticksToTpLevel(ticks)
Calculates a take-profit level using a specified tick distance from the position's average
entry price. A script can plot the returned value and use it as the `limit` argument in a
`strategy.exit()` call.
Parameters:
ticks (float) : (series int/float) The number of ticks from the position's average entry price to the
take-profit level. If the position is long, the value represents the number of ticks *above*
the average entry price. If short, it represents the number of ticks *below* the price.
Returns: (float) The calculated take-profit value for the open position. If there is no open
position, it returns `na`.
calcPositionSizeByStopLossTicks(stopLossTicks, riskPercent)
Calculates the entry quantity required to risk a specified percentage of the strategy's
current equity at a tick-based stop-loss level.
Parameters:
stopLossTicks (float) : (series int/float) The number of ticks in the stop-loss distance.
riskPercent (float) : (series int/float) The percentage of the strategy's equity to risk if a trade moves
`stopLossTicks` away from the entry price in the unfavorable direction.
Returns: (int) The number of contracts/shares/lots/units to use as the entry quantity to risk the
specified percentage of equity at the stop-loss level.
calcPositionSizeByStopLossPercent(stopLossPercent, riskPercent, entryPrice)
Calculates the entry quantity required to risk a specified percentage of the strategy's
current equity at a percent-based stop-loss level.
Parameters:
stopLossPercent (float) : (series int/float) The percentage of the `entryPrice` to use as the stop-loss distance.
riskPercent (float) : (series int/float) The percentage of the strategy's equity to risk if a trade moves
`stopLossPercent` of the `entryPrice` in the unfavorable direction.
entryPrice (float) : (series int/float) Optional. The entry price to use in the calculation. The default is
`close`.
Returns: (int) The number of contracts/shares/lots/units to use as the entry quantity to risk the
specified percentage of equity at the stop-loss level.
exitPercent(id, lossPercent, profitPercent, qty, qtyPercent, comment, alertMessage)
A wrapper for the `strategy.exit()` function designed for creating stop-loss and
take-profit orders at percentage distances away from the position's average entry price.
NOTE: This function calls `strategy.exit()` without a `from_entry` ID, so it creates exit
orders for *every* entry in an open position until the position closes. Therefore, using
this function when the strategy has a pyramiding value greater than 1 can lead to
unexpected results. See the "Exits for multiple entries" section of our User Manual's
"Strategies" page to learn more about this behavior.
Parameters:
id (string) : (series string) Optional. The identifier of the stop-loss/take-profit orders, which
corresponds to an exit ID in the strategy's trades after an order fills. The default is
`"Exit"`.
lossPercent (float) : (series int/float) The percentage of the position's average entry price to use as the
stop-loss distance. The function does not create a stop-loss order if the value is `na`.
profitPercent (float) : (series int/float) The percentage of the position's average entry price to use as the
take-profit distance. The function does not create a take-profit order if the value is `na`.
qty (float) : (series int/float) Optional. The number of contracts/lots/shares/units to close when an
exit order fills. If specified, the call uses this value instead of `qtyPercent` to
determine the order size. The exit orders reserve this quantity from the position, meaning
other orders from `strategy.exit()` cannot close this portion until the strategy fills or
cancels those orders. The default is `na`, which means the order size depends on the
`qtyPercent` value.
qtyPercent (float) : (series int/float) Optional. A value between 0 and 100 representing the percentage of the
open trade quantity to close when an exit order fills. The exit orders reserve this
percentage from the open trades, meaning other calls to this command cannot close this
portion until the strategy fills or cancels those orders. The percentage calculation
depends on the total size of the applicable open trades without considering the reserved
amount from other `strategy.exit()` calls. The call ignores this parameter if the `qty`
value is not `na`. The default is 100.
comment (string) : (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the specified `id`. The default is `na`.
alertMessage (string) : (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
closeAllAtEndOfSession(comment, alertMessage)
A wrapper for the `strategy.close_all()` function designed to close all open trades with a
market order when the last bar in the current day's session closes. It uses the command's
`immediately` parameter to exit all trades at the last bar's `close` instead of the `open`
of the next session's first bar.
Parameters:
comment (string) : (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the automatically generated exit identifier. The default is `na`.
alertMessage (string) : (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
closeAtEndOfSession(entryId, comment, alertMessage)
A wrapper for the `strategy.close()` function designed to close specific open trades with a
market order when the last bar in the current day's session closes. It uses the command's
`immediately` parameter to exit the trades at the last bar's `close` instead of the `open`
of the next session's first bar.
Parameters:
entryId (string)
comment (string) : (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the automatically generated exit identifier. The default is `na`.
alertMessage (string) : (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
sortinoRatio(interestRate, forceCalc)
Calculates the Sortino ratio of the strategy based on realized monthly returns.
Parameters:
interestRate (simple float) : (simple int/float) Optional. The *annual* "risk-free" return percentage to compare against
strategy returns. The default is 2, meaning it uses an annual benchmark of 2%.
forceCalc (bool) : (series bool) Optional. A value of `true` forces the function to calculate the ratio on the
current bar. If the value is `false`, the function calculates the ratio only on the latest
available bar for efficiency. The default is `false`.
Returns: (float) The Sortino ratio, which estimates the strategy's excess return per unit of
downside volatility.
sharpeRatio(interestRate, forceCalc)
Calculates the Sharpe ratio of the strategy based on realized monthly returns.
Parameters:
interestRate (simple float) : (simple int/float) Optional. The *annual* "risk-free" return percentage to compare against
strategy returns. The default is 2, meaning it uses an annual benchmark of 2%.
forceCalc (bool) : (series bool) Optional. A value of `true` forces the function to calculate the ratio on the
current bar. If the value is `false`, the function calculates the ratio only on the latest
available bar for efficiency. The default is `false`.
Returns: (float) The Sortino ratio, which estimates the strategy's excess return per unit of
total volatility.
GBB_lib_fiboLibrary "GBB_lib_fibo"
draw_fibo(high_point, low_point)
draw_fibo
/ @description Draws Fibonacci retracement lines between a high point and a low point.
/ @param high_point (float) Highest point of the move.
/ @param low_point (float) Lowest point of the move.
/ @returns (void) Draws lines on the chart.
Parameters:
high_point (float)
low_point (float)
GBB_lib_utilsLibrary "GBB_lib_utils"
gbb_tf_to_display(tf_minutes, tf_string)
gbb_tf_to_display
/ @description Converts minutes and TF string into a short standard label.
/ @param tf_minutes (float)
/ @param tf_string (string)
/ @returns (string) Timeframe label (M1,H1,D1,...)
Parameters:
tf_minutes (float)
tf_string (string)
gbb_convert_bars(_bars)
gbb_convert_bars
/ @description Formats a number of bars into a duration (days, hours, minutes + bar count).
/ @param _bars (int)
/ @returns (string)
Parameters:
_bars (int)
gbb_goldorak_init(_tf5Levels_input)
gbb_goldorak_init
/ @description Builds a contextual message about the current timeframe and optional 5-level TF.
/ @param _tf5Levels_input (string) Alternative timeframe ("" = current timeframe).
/ @returns (string, string, float)
Parameters:
_tf5Levels_input (string)
GGB_lib_fiboLibrary "GGB_lib_fibo"
draw_fibo(high_point, low_point)
draw_fibo
/ @description Draws Fibonacci retracement lines between a high point and a low point.
/ @param high_point (float) Highest point of the move.
/ @param low_point (float) Lowest point of the move.
/ @returns (void) Draws lines on the chart.
Parameters:
high_point (float)
low_point (float)