DafeUltimateLibDAFE Ultimate Library: The Universal AI Dashboard & Analysis System
This is the operating system for your next generation of trading tools. Welcome to the future of on-chart intelligence.
█ PHILOSOPHY: BEYOND THE INDICATOR, INTO THE CONSCIOUSNESS
For decades, technical analysis has been a monologue. We load indicators onto our charts, and they give us static, one-dimensional answers: a line, a number, a crossover. They provide data, but they offer no wisdom, no context, no actionable intelligence. They are tools without a mind.
The DAFE Ultimate Library was created to fundamentally shatter this paradigm. It was not designed to be another indicator, but to be the very brain that powers all of your future indicators. This is a professional-grade, open-source library that allows any Pine Script developer to integrate a sophisticated, AI-powered analytical and visualization engine into their own scripts with just a few lines of code.
This library transforms your indicator from a simple data plotter into an intelligent trading assistant. It takes in raw metrics—RSI, MACD, Volume, Volatility—and synthesizes them into a rich, multi-dimensional analysis, complete with a primary bias, confidence score, market state assessment, and a set of dynamic, actionable recommendations. It doesn't just give you the "what"; it gives you the " so what? "
█ WHAT IS THIS LIBRARY? A REVOLUTION IN PINE SCRIPT
This is a foundational shift in what's possible within the TradingView ecosystem.
A Universal AI Brain: At its core is a powerful analysis engine. You feed it any number of metrics from your own custom script—each with its own type (bounded, zero-centric, trend, etc.) and weight—and the AI synthesizes them into a single, cohesive analysis. It's like having a quantitative analyst living inside your indicator.
The ASCII Art Visualization Core: This is the soul of the library. We have pushed the boundaries of what's possible with Pine Script's table and label objects to create a stunning, fully animated, and customizable ASCII art interface. This is not a gimmick; it is a high-information-density display that brings your data to life in a way that is both beautiful and intuitively understandable. Choose from multiple "genders" (Male, Female, Droid) and themes to create an AI assistant that fits your personal aesthetic.
Open & Extensible Framework: This is a library, not a closed black box. It is designed to be the foundation for a new generation of "smart" indicators. I provide a simple, powerful API (Application Programming Interface) that allows any developer to plug their own unique metrics into the DAFE AI brain and instantly gain access to its analytical and visualization power.
Human-Readable Intelligence: The output is not just numbers. The AI communicates in natural language. It provides you with its "Thoughts" ("Bullish momentum across 3 metrics," "Structural weakness developing") and a set of "Recommended Actions" ("ACCUMULATE on pullbacks," "TIGHTEN stops") that adapt in real-time to the changing market conditions.
█ HOW IT WORKS: THE ARCHITECTURE OF AN AI
The library operates on a simple but powerful three-stage pipeline.
Stage 1: Metric Ingestion (The Senses)
As a developer, you first define the "senses" of your AI. Using the library's simple create_metric functions, you tell the AI what to look at. This is a highly flexible system that can handle any type of data your indicator produces. You define the metric's name, its current value, its "mode" of operation, and its relative importance (weight). The available modes allow the AI to correctly interpret any data source:
metric_bounded: For oscillators like RSI or Stochastics that move between set levels (e.g., 0-100).
metric_zero: For indicators like MACD or a Momentum oscillator that fluctuate around a central zero line.
metric_trend: For moving averages or trend lines, analyzing their position relative to price.
metric_volume / metric_volatility: Specialized metrics for analyzing volume and volatility events against high/low thresholds.
Stage 2: The Analysis Engine (The Brain)
On every bar, the library takes the updated metric values and feeds them into its core analytical model. This is where the magic happens.
Normalization: Each metric is processed according to its "mode" and converted into a standardized signal score from -100 (extremely bearish) to +100 (extremely bullish). This allows the AI to compare apples and oranges—an RSI of 80 can now be directly compared to a MACD histogram of 0.5.
Synthesis: The AI calculates a composite score by taking a weighted average of all the individual metric signals. This gives a single, unified view of the market's state based on all available evidence.
State Assessment: It analyzes the distribution of signals (how many are bullish vs. bearish), the number of "extreme" readings (e.g., overbought, high volume), and the overall composite score to determine the current Market State (e.g., "STRONG TREND," "MIXED SIGNALS," "EXTREME CONDITIONS").
Confidence Calculation: The magnitude of the final composite score is translated into a Confidence percentage, representing the strength of the AI's conviction in its current bias.
Natural Language Generation: Based on the final analysis, the engine selects the most appropriate "Thoughts" and "Recommended Actions" from its pre-programmed library of strategic heuristics, providing you with context and a potential game plan.
Stage 3: The Rendering Engine (The Face)
The final analysis is passed to the visualization core, which renders the complete AI Terminal on your chart. This is a masterwork of Pine Script's drawing capabilities.
The Face: The stunning ASCII art face is dynamically generated on every bar. Its Mood (Confident, Focused, Cautious, etc.) is directly determined by the AI's confidence level. Its eyes will even animate with a subtle, customizable Blink cycle, bringing the character to life and creating an unparalleled user experience.
The Dashboard: The surrounding terminal is built, displaying the primary bias, market state, confidence, and the detailed thoughts, active metrics, and recommended actions in a clean, retro-futuristic interface.
Theming: The entire display is colored according to your chosen theme, from the cool greens of "Matrix" to the vibrant pinks of "Neon," allowing for deep personalization.
█ A GUIDE FOR DEVELOPERS: INTEGRATING THE DAFE AI
We have made it incredibly simple to bring your indicators to life with the DAFE AI. This is the true purpose of the library—to empower you.
Import the Library: Add the following line to the top of your script import DskyzInvestments/DafeUltimateLib/1 as dafe
Define Your Metrics: In the barstate.isfirst block of your script, create an array and populate it with the metrics your indicator uses. For example:
var array my_metrics = array.new()
if barstate.isfirst
array.push(my_metrics, dafe.metric_bounded("RSI", 50.0, 70.0, 30.0, 1.5))
array.push(my_metrics, dafe.metric_zero("MACD Hist", 0.0, 0.5, 1.0))
Update Your Metrics: On every bar, update the values of your metrics.
dafe.update_metric(array.get(my_metrics, 0), ta.rsi(close, 14))
dafe.update_metric(array.get(my_metrics, 1), macd_histogram_value)
Configure & Render: Create a configuration object from user inputs and call the main render function.
dafe.DafeConfig my_config = dafe.quick_config("Droid", "Cyber")
dafe.render(my_metrics, my_config)
That's it. With these few steps, you have integrated a complete AI dashboard and analysis engine directly into your own script, saving you hundreds of hours of development time and providing your users with a revolutionary interface.
█ DEVELOPMENT PHILOSOPHY
The DAFE Ultimate Library was born from a desire to push the boundaries of Pine Script and to empower the entire TradingView developer community. We believe that the future of technical analysis is not just in creating more complex algorithms, but in building more intelligent and intuitive ways to interact with the data those algorithms provide. This library is our contribution to that future. It is an open-source tool designed to elevate the work of every developer who uses it, fostering a new era of "smart" indicators on the platform.
This library is designed to help you and your users make the best trades by providing a layer of objective, synthesized intelligence that filters out noise, quantifies confidence, and promotes a disciplined, analytical approach to the market.
█ A NOTE TO USERS & DISCLAIMER
THIS IS A LIBRARY: This script does nothing on its own. It is a powerful engine that must be integrated by other indicator developers. It is a tool for builders.
THE AI IS A GUIDE, NOT A GURU: The analysis provided is based on the mathematical synthesis of the metrics it is fed. It is a powerful decision-support tool, but it is not a crystal ball. All trading involves substantial risk.
GARBAGE IN, GARBAGE OUT: The quality of the AI's analysis is directly dependent on the quality and logic of the metrics it is given by the host indicator.
"The goal of a successful trader is to make the best trades. Money is secondary."
— Alexander Elder
Taking you to school. - Dskyz, Trade with DAFE.
Indicators and strategies
StolenKernelFunctionsLibrary "StolenKernelFunctions"
This library provides non-repainting kernel functions for Nadaraya-Watson estimator implementations. This allows for easy substition/comparison of different kernel functions for one another in indicators. Furthermore, kernels can easily be combined with other kernels to create newer, more customized kernels.
rationalQuadratic(_src, _lookback, _relativeWeight, startAtBar)
Rational Quadratic Kernel - An infinite sum of Gaussian Kernels of different length scales.
Parameters:
_src (float) : The source series.
_lookback (simple int) : The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
_relativeWeight (simple float) : Relative weighting of time frames. Smaller values resut in a more stretched out curve and larger values will result in a more wiggly curve. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel.
startAtBar (simple int)
Returns: yhat The estimated values according to the Rational Quadratic Kernel.
gaussian(_src, _lookback, startAtBar)
Gaussian Kernel - A weighted average of the source series. The weights are determined by the Radial Basis Function (RBF).
Parameters:
_src (float) : The source series.
_lookback (simple int) : The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
startAtBar (simple int)
Returns: yhat The estimated values according to the Gaussian Kernel.
periodic(_src, _lookback, _period, startAtBar)
Periodic Kernel - The periodic kernel (derived by David Mackay) allows one to model functions which repeat themselves exactly.
Parameters:
_src (float) : The source series.
_lookback (simple int) : The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
_period (simple int) : The distance between repititions of the function.
startAtBar (simple int)
Returns: yhat The estimated values according to the Periodic Kernel.
locallyPeriodic(_src, _lookback, _period, startAtBar)
Locally Periodic Kernel - The locally periodic kernel is a periodic function that slowly varies with time. It is the product of the Periodic Kernel and the Gaussian Kernel.
Parameters:
_src (float) : The source series.
_lookback (simple int) : The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
_period (simple int) : The distance between repititions of the function.
startAtBar (simple int)
Returns: yhat The estimated values according to the Locally Periodic Kernel.
Better Contrast (NTSC Optimized)Library Better Contrast (NTSC Optimized)
This lightweight utility library automatically selects the optimal text color (black or white) for any given background color, ensuring maximum readability for labels, tables, and UI elements.
Unlike standard libraries that use the HSP model or simple averaging, this library utilizes the NTSC Perceived Brightness formula.
🟢 Why NTSC?
The human eye is significantly more sensitive to green light than red or blue. Standard formulas often miscalculate brightness for high‑energy colors like yellow (red + green) or cyan, resulting in white text on bright yellow backgrounds — which is hard to read.
The NTSC formula weights colors based on human perception:
Brightness = (Red * 0.299) + (Green * 0.587) + (Blue * 0.114)
By heavily weighting the green channel (58.7%), this method correctly identifies yellow and cyan as “bright” backgrounds, forcing the text to black for superior contrast.
🛠 Usage
Import the library:
import Robertsanktov/Better_Contrast/1 as contrast
Use the method directly on any color variable:
textColor = myBackgroundColor.contrast()
Parameters
- threshold : (optional) brightness cutoff (0.0–1.0 or 0–255). Default is 0.55 .
Higher values force more white text; lower values force more black text.
basechartpatternsLibrary "basechartpatterns"
Library having complete chart pattern implementation
getPatternNameById(id)
Returns pattern name by id
Parameters:
id (int) : pattern id
Returns: Pattern name
method find(points, properties, dProperties, ohlcArray)
Find patterns based on array of points
Namespace types: array
Parameters:
points (array) : array of chart.point objects
properties (ScanProperties type from SwSpace/abstractchartpatterns/1) : ScanProperties object
dProperties (DrawingProperties type from SwSpace/abstractchartpatterns/1) : DrawingProperties object
ohlcArray (array type from SwSpace/ohlc/1)
Returns: Flag indicating if the pattern is valid, Current Pattern object
method find(this, properties, dProperties, patterns, ohlcArray)
Find patterns based on the currect zigzag object but will not store them in the pattern array.
Namespace types: zg.Zigzag
Parameters:
this (Zigzag type from SwSpace/ZigzagLite/1) : Zigzag object containing pivots
properties (ScanProperties type from SwSpace/abstractchartpatterns/1) : ScanProperties object
dProperties (DrawingProperties type from SwSpace/abstractchartpatterns/1) : DrawingProperties object
patterns (array type from SwSpace/abstractchartpatterns/1) : Array of Pattern objects
ohlcArray (array type from SwSpace/ohlc/1)
Returns: Flag indicating if the pattern is valid, Current Pattern object
abstractchartpatternsLibrary "abstractchartpatterns"
Library having abstract types and methods for chart pattern implementations
method checkSize(filters, points)
checks if the series of pivots are within the size filter
Namespace types: SizeFilters
Parameters:
filters (SizeFilters) : SizeFilters object containing size criteria to be matched
points (array) : list of pivot points
Returns: true if matches the size filter, false otherwise
checkBarRatio(p1, p2, p3, properties)
checks if three zigzag pivot points are having uniform bar ratios
Parameters:
p1 (chart.point) : First pivot point
p2 (chart.point) : Second pivot point
p3 (chart.point) : Third pivot point
properties (ScanProperties)
Returns: true if points are having uniform bar ratio
getRatioDiff(p1, p2, p3)
gets ratio difference between 3 pivot combinations
Parameters:
p1 (chart.point)
p2 (chart.point)
p3 (chart.point)
Returns: returns the ratio difference between pivot2/pivot1 ratio and pivot3/pivot2 ratio
method inspect(points, stratingBar, endingBar, direction, ohlcArray)
Creates a trend line between 2 or 3 points and validates and selects best combination
Namespace types: array
Parameters:
points (array) : Array of chart.point objects used for drawing trend line
stratingBar (int) : starting bar of the trend line
endingBar (int) : ending bar of the trend line
direction (float) : direction of the last pivot. Tells whether the line is joining upper pivots or the lower pivots
ohlcArray (array type from SwSpace/ohlc/1) : Array of OHLC values
Returns: boolean flag indicating if the trend line is valid and the trend line object as tuple
method draw(this)
draws pattern on the chart
Namespace types: Pattern
Parameters:
this (Pattern) : Pattern object that needs to be drawn
Returns: Current Pattern object
method erase(this)
erase the given pattern on the chart
Namespace types: Pattern
Parameters:
this (Pattern) : Pattern object that needs to be erased
Returns: Current Pattern object
method pushWithLimit(this, p, maxItems)
push Pattern object to the array by keeping maxItems limit
Namespace types: array
Parameters:
this (array) : array of Pattern objects
p (Pattern) : Pattern object to be added to array
@oaram maxItems Max number of items the array can hold
maxItems (int)
Returns: Current Pattern array
method deepcopy(this)
Perform deep copy of a chart point array
Namespace types: array
Parameters:
this (array) : array of chart.point objects
Returns: deep copy array
DrawingProperties
Object containing properties for pattern drawing
Fields:
patternLineWidth (series int) : Line width of the pattern trend lines
showZigzag (series bool) : show zigzag associated with pattern
zigzagLineWidth (series int) : line width of the zigzag lines. Used only when showZigzag is set to true
zigzagLineColor (series color) : color of the zigzag lines. Used only when showZigzag is set to true
showPatternLabel (series bool) : display pattern label containing the name
patternLabelSize (series string) : size of the pattern label. Used only when showPatternLabel is set to true
showPivotLabels (series bool) : Display pivot labels of the patterns marking 1-6
pivotLabelSize (series string) : size of the pivot label. Used only when showPivotLabels is set to true
pivotLabelColor (series color) : color of the pivot label outline. chart.bg_color or chart.fg_color are the appropriate values.
deleteOnPop (series bool) : delete the pattern when popping out from the array of Patterns.
Pattern
Object containing Individual Pattern data
Fields:
dir (series int) : direction of the last pivot
points (array) : array of Zigzag Pivot points
trendLine1 (Line type from SwSpace/LineWrapper/1) : First trend line joining pivots 1, 3, 5
trendLine2 (Line type from SwSpace/LineWrapper/1) : Second trend line joining pivots 2, 4 (, 6)
properties (DrawingProperties) : DrawingProperties Object carrying common properties
patternColor (series color) : Individual pattern color. Lines and labels will be using this color.
ratioDiff (series float) : Difference between trendLine1 and trendLine2 ratios
zigzagLine (series polyline) : Internal zigzag line drawing Object
pivotLabels (array) : array containning Pivot labels
patternLabel (series label) : pattern label Object
patternType (series int) : integer representing the pattern type
patternName (series string) : Type of pattern in string
SizeFilters
Object containing properties for pattern size filters
Fields:
filterByBar (series bool) : If set filter the patterns by the bar range
minPatternBars (series int) : Used only when filterByBar is set to true. Minimum bars range for pattern size
maxPatternBars (series int) : Used only when filterByBar is set to true. Maximum bars range for pattern size
filterByPercent (series bool) : Filters patterns by percent of price if set
minPatternPercent (series int) : Used only when filterByPercent is set. Minimum pattern size in terms of percent of price
maxPatternPercent (series int) : Used only when filterByPercent is set. Maximum pattern size in terms of percent of price
ScanProperties
Object containing properties for pattern scanning
Fields:
offset (series int) : Zigzag pivot offset. Set it to 1 for non repainting scan.
numberOfPivots (series int) : Number of pivots to be used in pattern search. Can be either 5 or 6
errorRatio (series float) : Error Threshold to be considered for comparing the slope of lines
flatRatio (series float) : Retracement ratio threshold used to determine if the lines are flat
checkBarRatio (series bool) : Also check bar ratio are within the limits while scanning the patterns
barRatioLimit (series float) : Bar ratio limit used for checking the bars. Used only when checkBarRatio is set to true
avoidOverlap (series bool) : avoid overlapping patterns.
ignoreIfEntryCrossed (series bool) : Ignore the trade if close price does not fall within the price entry price range
allowedPatterns (array) : array of bool encoding the allowed pattern types.
allowedLastPivotDirections (array) : array of int representing allowed last pivot direction for each pattern types
themeColors (array) : color array of themes to be used.
filters (SizeFilters)
ZigzagLiteLibrary "ZigzagLite"
Lighter version of the Zigzag Library. Without indicators and sub-component divisions
method getPrices(pivots)
Gets the array of prices from array of Pivots
Namespace types: array
Parameters:
pivots (array) : array array of Pivot objects
Returns: array array of pivot prices
method getBars(pivots)
Gets the array of bars from array of Pivots
Namespace types: array
Parameters:
pivots (array) : array array of Pivot objects
Returns: array array of pivot bar indices
method getPoints(pivots)
Gets the array of chart.point from array of Pivots
Namespace types: array
Parameters:
pivots (array) : array array of Pivot objects
Returns: array array of pivot points
method getPoints(this)
Gets the array of chart.point from Zigzag Object
Namespace types: Zigzag
Parameters:
this (Zigzag) : Zigzag object
Returns: array array of pivot points
method calculate(this, ohlc, ltfHighTime, ltfLowTime)
Calculate zigzag based on input values and indicator values
Namespace types: Zigzag
Parameters:
this (Zigzag) : Zigzag object
ohlc (array) : Array containing OHLC values. Can also have custom values for which zigzag to be calculated
ltfHighTime (int) : Used for multi timeframe zigzags when called within request.security. Default value is current timeframe open time.
ltfLowTime (int) : Used for multi timeframe zigzags when called within request.security. Default value is current timeframe open time.
Returns: current Zigzag object
method calculate(this)
Calculate zigzag based on properties embedded within Zigzag object
Namespace types: Zigzag
Parameters:
this (Zigzag) : Zigzag object
Returns: current Zigzag object
method nextlevel(this)
Calculate Next Level Zigzag based on the current calculated zigzag object
Namespace types: Zigzag
Parameters:
this (Zigzag) : Zigzag object
Returns: Next Level Zigzag object
method clear(this)
Clears zigzag drawings array
Namespace types: array
Parameters:
this (array) : array
Returns: void
method clear(this)
Clears zigzag drawings array
Namespace types: array
Parameters:
this (array) : array
Returns: void
method drawplain(this)
draws fresh zigzag based on properties embedded in ZigzagDrawing object without trying to calculate
Namespace types: ZigzagDrawing
Parameters:
this (ZigzagDrawing) : ZigzagDrawing object
Returns: ZigzagDrawing object
method drawplain(this)
draws fresh zigzag based on properties embedded in ZigzagDrawingPL object without trying to calculate
Namespace types: ZigzagDrawingPL
Parameters:
this (ZigzagDrawingPL) : ZigzagDrawingPL object
Returns: ZigzagDrawingPL object
method drawfresh(this, ohlc)
draws fresh zigzag based on properties embedded in ZigzagDrawing object
Namespace types: ZigzagDrawing
Parameters:
this (ZigzagDrawing) : ZigzagDrawing object
ohlc (array) : values on which the zigzag needs to be calculated and drawn. If not set will use regular OHLC
Returns: ZigzagDrawing object
method drawcontinuous(this, ohlc)
draws zigzag based on the zigzagmatrix input
Namespace types: ZigzagDrawing
Parameters:
this (ZigzagDrawing) : ZigzagDrawing object
ohlc (array) : values on which the zigzag needs to be calculated and drawn. If not set will use regular OHLC
Returns:
PivotCandle
PivotCandle represents data of the candle which forms either pivot High or pivot low or both
Fields:
_high (series float) : High price of candle forming the pivot
_low (series float) : Low price of candle forming the pivot
length (series int) : Pivot length
pHighBar (series int) : represents number of bar back the pivot High occurred.
pLowBar (series int) : represents number of bar back the pivot Low occurred.
pHigh (series float) : Pivot High Price
pLow (series float) : Pivot Low Price
Pivot
Pivot refers to zigzag pivot. Each pivot can contain various data
Fields:
point (chart.point) : pivot point coordinates
dir (series int) : direction of the pivot. Valid values are 1, -1, 2, -2
level (series int) : is used for multi level zigzags. For single level, it will always be 0
ratio (series float) : Price Ratio based on previous two pivots
sizeRatio (series float) : ratio of current zigzag wave size in comparison to last zigzag wave in the same direction
barRatio (series float) : Bar Ratio based on previous two pivots
ZigzagFlags
Flags required for drawing zigzag. Only used internally in zigzag calculation. Should not set the values explicitly
Fields:
newPivot (series bool) : true if the calculation resulted in new pivot
doublePivot (series bool) : true if the calculation resulted in two pivots on same bar
updateLastPivot (series bool) : true if new pivot calculated replaces the old one.
Zigzag
Zigzag object which contains whole zigzag calculation parameters and pivots
Fields:
length (series int) : Zigzag length. Default value is 5
numberOfPivots (series int) : max number of pivots to hold in the calculation. Default value is 20
offset (series int) : Bar offset to be considered for calculation of zigzag. Default is 0 - which means calculation is done based on the latest bar.
level (series int) : Zigzag calculation level - used in multi level recursive zigzags
zigzagPivots (array) : array which holds the last n pivots calculated.
flags (ZigzagFlags) : ZigzagFlags object which is required for continuous drawing of zigzag lines.
ZigzagObject
Zigzag Drawing Object
Fields:
zigzagLine (series line) : Line joining two pivots
zigzagLabel (series label) : Label which can be used for drawing the values, ratios, directions etc.
ZigzagProperties
Object which holds properties of zigzag drawing. To be used along with ZigzagDrawing
Fields:
lineColor (series color) : Zigzag line color. Default is color.blue
lineWidth (series int) : Zigzag line width. Default is 1
lineStyle (series string) : Zigzag line style. Default is line.style_solid.
showLabel (series bool) : If set, the drawing will show labels on each pivot. Default is false
textColor (series color) : Text color of the labels. Only applicable if showLabel is set to true.
maxObjects (series int) : Max number of zigzag lines to display. Default is 300
xloc (series string) : Time/Bar reference to be used for zigzag drawing. Default is Time - xloc.bar_time.
curved (series bool) : Boolean field to print curved zigzag - used only with polyline implementation
force_overlay (series bool) : force drawing in price overlay
ZigzagDrawing
Object which holds complete zigzag drawing objects and properties.
Fields:
zigzag (Zigzag) : Zigzag object which holds the calculations.
properties (ZigzagProperties) : ZigzagProperties object which is used for setting the display styles of zigzag
drawings (array) : array which contains lines and labels of zigzag drawing.
ZigzagDrawingPL
Object which holds complete zigzag drawing objects and properties - polyline version
Fields:
zigzag (Zigzag) : Zigzag object which holds the calculations.
properties (ZigzagProperties) : ZigzagProperties object which is used for setting the display styles of zigzag
zigzagLabels (array)
zigzagLine (series polyline) : polyline object of zigzag lines
LineWrapperLibrary "LineWrapper"
Wrapper Type for Line. Useful when you want to store the line details without drawing them. Can also be used in scnearios where you collect lines to be drawn and draw together towards the end.
method draw(this)
draws line as per the wrapper object contents
Namespace types: Line
Parameters:
this (Line) : (series Line) Line object.
Returns: current Line object
method draw(this)
draws lines as per the wrapper object array
Namespace types: array
Parameters:
this (array) : (series array) Array of Line object.
Returns: current Array of Line objects
method update(this)
updates or redraws line as per the wrapper object contents
Namespace types: Line
Parameters:
this (Line) : (series Line) Line object.
Returns: current Line object
method update(this)
updates or redraws lines as per the wrapper object array
Namespace types: array
Parameters:
this (array) : (series array) Array of Line object.
Returns: current Array of Line objects
method delete(this)
Deletes the underlying line drawing object
Namespace types: Line
Parameters:
this (Line) : (series Line) Line object.
Returns: Current Line object
method get_price(this, bar)
get line price based on bar
Namespace types: Line
Parameters:
this (Line) : (series Line) Line object.
bar (int) : (series/int) bar at which line price need to be calculated
Returns: line price at given bar.
Line
Line Wrapper object
Fields:
p1 (chart.point)
p2 (chart.point)
xloc (series string) : (series string) See description of x1 argument. Possible values: xloc.bar_index and xloc.bar_time. Default is xloc.bar_index.
extend (series string) : (series string) If extend=extend.none, draws segment starting at point (x1, y1) and ending at point (x2, y2). If extend is equal to extend.right or extend.left, draws a ray starting at point (x1, y1) or (x2, y2), respectively. If extend=extend.both, draws a straight line that goes through these points. Default value is extend.none.
color (series color) : (series color) Line color.
style (series string) : (series string) Line style. Possible values: line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both.
width (series int) : (series int) Line width in pixels.
obj (series line) : line object
utilsLibrary "utils"
Few essentials captured together (subset of arrayutils)
timer(timeStart, timeEnd)
finds difference between two timestamps
Parameters:
timeStart (int) : start timestamp
timeEnd (int)
Returns:
check_overflow(pivots, barArray, dir)
finds difference between two timestamps
Parameters:
pivots (array) : pivots array
barArray (array) : pivot bar array
dir (int) : direction for which overflow need to be checked
Returns: bool overflow
get_trend_series(pivots, length, highLow, trend)
finds series of pivots in particular trend
Parameters:
pivots (array) : pivots array
length (int) : length for which trend series need to be checked
highLow (int) : filter pivot high or low
trend (int) : Uptrend or Downtrend
Returns: int trendIndexes
get_trend_series(pivots, firstIndex, lastIndex)
finds series of pivots in particular trend
Parameters:
pivots (array) : pivots array
firstIndex (int) : First index of the series
lastIndex (int) : Last index of the series
Returns: int trendIndexes
getConsolidatedLabel(include, labels, separator)
Consolidates labels into single string by concatenating it with given separator
Parameters:
include (array) : array of conditions to include label or not
labels (array) : string array of labels
separator (simple string) : Separator for concatenating labels
Returns: string labelText
getColors(theme)
gets array of colors based on theme
Parameters:
theme (simple string) : dark or light theme
Returns: color themeColors
ohlcLibrary "ohlc"
Library having OHLC and Indicator type and method implementations.
getOhlcArray(o, h, l, c, highBeforeLow, highAfterLow, lowBeforeHigh, lowAfterHigh, barindex, bartime, indicators)
get array of OHLC values when called on every bar
Parameters:
o (float) : Open price
h (float) : High Price
l (float) : Low Price
c (float) : Close Price
highBeforeLow (float) : to be calculated based on lower timeframe. high price attained within the candle before reaching the lowest point.
highAfterLow (float) : to be calculated based on lower timeframe. high price attained within the candle after reaching the lowest point.
lowBeforeHigh (float) : to be calculated based on lower timeframe. low price attained within the candle before reaching the highest point.
lowAfterHigh (float) : to be calculated based on lower timeframe. low price attained within the candle after reaching the highest point.
barindex (int) : bar_index of OHLC data
bartime (int) : time of OHLC cata
indicators (array) : array containing indicator
Returns: Array of OHLC objects
pushWithLimit(this, item, maxItems)
Push items to OHLC array with maxItems limit
Parameters:
this (array)
item (OHLC) : OHLC Item to be pushed to the array
maxItems (int) : max Items the array can hold at a time
Returns: current object
pushWithLimit(this, item, maxItems)
Push items to Indicator array with maxItems limit
Parameters:
this (array)
item (Indicator) : Indicator Item to be pushed to the array
maxItems (int) : max Items the array can hold at a time
Returns: current object
unshiftWithLimit(this, item, maxItems)
Unshift items to OHLC array with maxItems limit
Parameters:
this (array)
item (OHLC) : OHLC Item to be unshifted to the array
maxItems (int) : max Items the array can hold at a time
Returns: current object
unshiftWithLimit(this, item, maxItems)
Unshift items to Indicator array with maxItems limit
Parameters:
this (array)
item (Indicator) : Indicator Item to be unshifted to the array
maxItems (int) : max Items the array can hold at a time
Returns: current object
method getPoints(indicators)
get array of points based on array of indicator values
Namespace types: array
Parameters:
indicators (array) : Array containing indicator objects
Returns: array of indicator points
method plot(indicator, xloc, line_color, line_style, line_width)
plots an array of Indicator using polyline
Namespace types: array
Parameters:
indicator (array) : Array containing indicator objects
xloc (string) : can have values xloc.bar_index or xloc.bar_time. Used for drawing the line based on either bars or time.
line_color (color) : color in which the plots need to be printed on chart.
line_style (string) : line style line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_right, line.style_arrow_left, line.style_arrow_both
line_width (int) : width of the plot line
Returns: array of plot polyline
Indicator
Object containing Indicator name and value
Fields:
name (series string) : Indicator Name
value (chart.point) : Indicator Value as a chart point
OHLC
Object containing OHLC and indicator values
Fields:
o (series float) : Open price
h (series float) : High Price
l (series float) : Low Price
c (series float) : Close Price
highBeforeLow (series float) : to be calculated based on lower timeframe. high price attained within the candle before reaching the lowest point.
highAfterLow (series float) : to be calculated based on lower timeframe. high price attained within the candle after reaching the lowest point.
lowBeforeHigh (series float) : to be calculated based on lower timeframe. low price attained within the candle before reaching the highest point.
lowAfterHigh (series float) : to be calculated based on lower timeframe. low price attained within the candle after reaching the highest point.
barindex (series int) : bar_index of OHLC data
bartime (series int) : time of OHLC cata
indicators (array) : array containing indicator
ma_libraryTitle: Library: Advanced Moving Average Collection
Description:
This library provides a comprehensive set of Moving Average algorithms, ranging from standard filters (SMA, EMA) to adaptive trendlines (KAMA, FRAMA) and experimental smoothers (ALMA, JMA).
It has been fully optimized for Pine Script v6, ensuring efficient execution and strict robustness against na (missing) values. Unlike standard implementations that propagate na values, these functions dynamically recalculate weights to maintain continuity in disjointed datasets.
🧩 Library Features
Robustness: Non-recursive filters ignore na values within the lookback window. Recursive filters maintain state to prevent calculation breaks.
Optimization: Logic updated to v6 standards, utilizing efficient loops and var persistence.
Standardization: All functions utilize a consistent f_ prefix and standardized parameters for easy integration.
Scope: Contains over 35 different smoothing algorithms.
📊 Input Requirements
Source (src): The data series to smooth (usually close, hl2, etc.).
Length (length): The lookback period (must be a simple int).
Specifics: Some adaptive MAs (like f_evwma) require volume data, while others (like f_alma) require offset/sigma settings.
🛠️ Integration Example
You can import the library and call functions directly, or use the built-in f_selector to create dynamic inputs for your users.
code
Pine
download
content_copy
expand_less
//@version=6
indicator("MA Library Demo", overlay=true)
// Import the library
import YourUsername/ma_/1 as ma
// --- Example 1: Direct Function Call ---
// calculating Jurik Moving Average (JMA)
float jma_val = ma.f_jma(close, 14)
plot(jma_val, "JMA", color=color.yellow, linewidth=2)
// --- Example 2: User Selector ---
// Allowing the user to choose the MA type via settings
string selected_type = input.string("ALMA", "MA Type", options= )
int length = input.int(20, "Length")
// Using the generic selector function
float dynamic_ma = ma.f_selector(close, length, selected_type)
plot(dynamic_ma, "Dynamic MA", color=color.aqua)
📋 Included Algorithms
The following methods are available (prefixed with f_):
Standard: SMA, EMA, WMA, VWMA, RMA
Adaptive: KAMA (Kaufman), FRAMA (Fractal), VIDYA (Chande/VARMA), VAMA (Vol. Adjusted)
Low Lag: ZLEMA (Zero Lag), HMA (Hull), JMA (Jurik), DEMA, TEMA
Statistical/Math: LSMA (Least Squares), GMMA (Geometric Mean), FLSMA (Fisher Least Squares)
Advanced/Exotic:
ALMA (Arnaud Legoux)
EIT (Ehlers Instantaneous Trend)
ESD (Ehlers Simple Decycler)
AHMA (Ahrens)
BMF (Blackman Filter)
CMA (Corrective)
DSWF (Damped Sine Wave)
EVWMA (Elastic Vol. Weighted)
HCF (Hybrid Convolution)
LMA (Leo)
MD (McGinley Dynamic)
MF (Modular Filter)
MM (Moving Median)
QMA (Quick)
RPMA (Repulsion)
RSRMA (Right Sided Ricker)
SMMA (Smoothed)
SSMA (Shapeshifting)
SWMA (Sine Weighted)
TMA (Triangular)
TSF (True Strength Force)
VBMA (Variable Band)
KRXNameMapperLibrary "KRXNameMapper"
TODO: add library description here
getCompanyName(code)
TODO: add function description here
Parameters:
code (string)
Returns: TODO: add what function returns
Jags_LibLibrary "Jags_Lib"
TODO: add library description here
ComplexRejBear(_can)
Returns whether candle is a rejection based on complex rules within library
Parameters:
_can (int)
Returns: true/false
ComplexRejBull(_can)
Returns whether candle is a rejection based on complex rules within library
Parameters:
_can (int)
Returns: true/false
bullHCS(_can, _lookback)
Returns whether current candle is creating a bull HCS
Parameters:
_can (int)
_lookback (int)
Returns: integer value representing the first candle in the HCS. 0 = no HCS
bearHCS(_can, _lookback)
Returns whether current candle is creating a bear HCS
Parameters:
_can (int)
_lookback (int)
Returns: integer value representing the first candle in the HCS. 0 = no HCS
bullIBLQtake(_can, _lookback)
Returns whether current candle is is a BullRej which has taken IB liquidiy in the last _lookback candles
Parameters:
_can (int)
_lookback (int)
Returns: integer value representing the first candle in the HCS. 0 = no HCS
bearIBLQtake(_can, _lookback)
Returns whether current candle is is a BearRej which has taken IB liquidiy in the last _lookback candles
Parameters:
_can (int)
_lookback (int)
Returns: integer value representing the first candle in the HCS. 0 = no HCS
Vantage_NewsVantage News is a Pine Script library that provides pre-market economic event filtering defaults intended for strategies that trade on YM futures. It determines a default for whether trading should be blocked, delayed, or allowed on any given day.
Core Concept
News events are pre-compiled into Pine Script data libraries organized by half-year (LO1_News2025H1, LO1_News2025H2, etc.), updated weekly on Sundays. There are no API calls — events are baked into arrays of dates, times, type IDs, and severities.
Severity System
Can be configured to define or override three default severity tiers:
- Sev 3 (CPI, NFP, FOMC) — defaults to blocks the entire day or delays, depending on policy
- Sev 2 (ISM PMI, claims) — defaults to delay trading until the event time + a configurable post-delay window
- Sev 1 (secondary indicators) — defaults to no delays
Blocking vs Delaying
- Block: No trading for the full session. WillTradeToday() returns false.
- Delay: Trading allowed after eventTime + delayMinutes. IsDelayed(currentTimeMs) returns true until the release time passes.
Provides a per-event-type policy mechanism so overrides can force any event to block, delay, or be ignored regardless of its base severity.
Next Trading Window Calculation
FindNextTradingWindow() scans forward up to 14 days, skipping weekends and blocked days based on the provided configuration. If the next tradeable day has a delay, it returns the delayed start time — so an info panel can show e.g. "Mon 7:35 AM" to indicate the next trading opening
Exception Mappings
Each half-year library can ship per-event-type overrides (different severity, custom delay minutes, tags). When the applyLibExceptionMappings configuration is enabled, these override the base severity — allowing the data to carry date-specific adjustments.
Special Handling
CME early close days are encoded as a special event type. CheckCmeEarlyClose() returns a halt timestamp so a strategy can truncate the session.
Caching
Evaluation is lazy and memoized by date string — EvaluateForDate() only recomputes when the date changes. The event cache is built once at initialization via a day index for fast date lookups.
Vantage_NewsTypesLibrary "Vantage_NewsTypes"
News Type definitions and default severity ratings with respect to YM futures. Updated weekly as news changes.
Severity 1 - Watch but not considered very impactful
Severity 2 - Default to don't trade until after event
Severity 3 - Default to don't trade on a day with this event
HawkDoveScoreLibLibrary "HawkDoveScoreLib"
hds_score(sym2y, sym10y, symBE10, symBS, symFCI, tfMacro, lenTrend, lenNorm, smoothScore, useRatePath, useCurve, useRealYield, useBalanceSh, useStressFCI, wRatePath, wCurve, wRealYield, wBS, wStress)
Parameters:
sym2y (string)
sym10y (string)
symBE10 (string)
symBS (string)
symFCI (string)
tfMacro (string)
lenTrend (int)
lenNorm (int)
smoothScore (simple int)
useRatePath (bool)
useCurve (bool)
useRealYield (bool)
useBalanceSh (bool)
useStressFCI (bool)
wRatePath (float)
wCurve (float)
wRealYield (float)
wBS (float)
wStress (float)
hds_regime(score, thrDove, thrHawk)
Parameters:
score (float)
thrDove (int)
thrHawk (int)
hds_regime_label(score, thrDove, thrHawk)
Parameters:
score (float)
thrDove (int)
thrHawk (int)
pubLibCandlestickPatternsLibrary "pubLibCandlestickPatterns"
candlestick pattern conditions for indicator and strategy development
doji()
bull_marubozu()
bear_marubozu()
spinning_top()
bull_belt_hold_line()
bear_belt_hold_line()
bull_breakaway()
bear_breakaway()
concealing_baby_swallow()
bull_counterattack()
bear_counterattack()
dark_cloud_cover()
long_legged_doji()
southern_doji()
northern_doji()
dumpling_top()
bull_engulfing()
bear_engulfing()
frypan_bottom()
hammer()
hanging_man()
bull_harami()
bear_harami()
bull_harami_cross()
bear_harami_cross()
high_wave()
bull_hikkake()
bear_hikkake()
homing_pigeon()
in_neck()
bull_kicking()
bear_kicking()
matching_low()
on_neck()
piercing()
bull_separating_lines()
bear_separating_lines()
upgap_side_by_side_white_lines()
downgap_side_by_side_white_lines()
stalled()
bull_star()
bear_star()
bull_doji_star()
bear_doji_star()
morning_star()
evening_star()
morning_doji_star()
evening_doji_star()
abandoned_baby_bottom()
abandoned_baby_top()
inverted_hammer()
shooting_star()
dragonfly_doji()
gravestone_doji()
stick_sandwich()
upward_gapping_tasuki()
downward_gapping_tasuki()
three_black_crows()
advance_block()
three_advancing_white_soldiers()
bull_three_line_strike()
bear_three_line_strike()
rising_three_methods()
falling_three_methods()
three_stars_in_the_south()
thrusting()
tower_bottom()
tower_top()
tri_star_bottom()
tri_star_top()
tweezer_bottom()
tweezer_top()
upside_gap_two_crows()
NodialTreesLows2: ML Random Forest / Pivot Lows (Part 2 of 2)Title: `Library: ML Random Forest / Pivot Lows (Part 2 of 2)`
Description:
This library contains the second half (Trees 6-11) of the Random Forest Classifier designed to validate Pivot Lows (Long setups).
It is a direct extension of NodialTreesL1 and cannot be used alone. Due to Pine Script's compilation limits on complexity and file size, the 12-tree ensemble model has been split into two separate libraries.
### 🧩 Library Contents
This module exports the following methods representing the specific decision paths of the trained AI model:
- `tree_6(array f)`
- `tree_7(array f)`
- `tree_8(array f)`
- `tree_9(array f)`
- `tree_10(array f)`
- `tree_11(array f)`
### ⚠️ Implementation Guide
To use this library, you must combine it with Part 1.
Please refer to the NodialTreesLows1 library description for:
1. The full Integration Code Example (how to average the votes).
2. The exact Input Feature List (the 27 required metrics).
3. Detailed explanation of the Machine Learning logic.
How to finish the integration:
Import this library alongside Part 1 and add the results of `tree_6` through `tree_11` to your voting sum, as shown in the Part 1 documentation.
NodialTreesLows1: ML Random Forest / Pivot Lows (Part 1 of 2)Title: `Library: ML Random Forest / Pivot Lows (Part 1 of 2)`
Description:
This library contains the first half (Trees 0-5) of a Random Forest Classifier designed to validate Pivot Lows (Long setups).
Due to Pine Script size constraints, the model is split into two libraries. You must use this library in conjunction with NodialTreesL2 to run the full ensemble.
### 🧩 System Architecture
- Model: Random Forest (12 Trees total).
- This Library: Contains `tree_0` to `tree_5`.
- Logic: Each tree analyzes a feature array and outputs a probability score.
- Target: Validating Swing Lows / Support Bounces.
### 📊 Input Requirements
The methods expect an `array` of size 27 containing market features (Price Action, Momentum, Volatility, Volume, Structure). The exact order of features is critical for the model's accuracy.
### 🛠️ Integration Example
Since this is a modular library, you need to import both parts and average their results to get the final prediction.
### 📋 Feature Mapping (Array Indexing)
To get accurate predictions, the input array must contain exactly 27 floats in this specific order:
0. Timeframe (in seconds)
1. RSI (Raw Value)
2. MACD Histogram
3. Relative Volume
4. EMA Distance (%)
5. EMA Slope
6. ATR Ratio
7. ADX
8. Buying/Selling Pressure
9. Wick Ratio
10-16. Divergences & Pattern Flags (Boolean 0.0/1.0)
17-22. Proprietary Momentum Metrics ("Onion" Structure)
23-26. Derived Volatility/Volume Features
*Note: For the advanced proprietary metrics (Indices 17-26), users must implement their own calculations or use compatible indicators.*
//@version=6
indicator("My ML Long Strategy", overlay=true)
// Import BOTH libraries
import YourUsername/NodialTreesL1/1 as rf_part1
import YourUsername/NodialTreesL2/1 as rf_part2
// ... (Calculate your 27 features and fill the array) ...
// var features = array.from(timeframe, rsi, macd, ...)
// Calculate Ensemble Probability (Average of 12 Trees)
float vote_sum = 0.0
// Trees from Part 1
vote_sum += rf_part1.tree_0(features)
vote_sum += rf_part1.tree_1(features)
vote_sum += rf_part1.tree_2(features)
vote_sum += rf_part1.tree_3(features)
vote_sum += rf_part1.tree_4(features)
vote_sum += rf_part1.tree_5(features)
// Trees from Part 2 (Trees 6-11)
vote_sum += rf_part2.tree_6(features)
vote_sum += rf_part2.tree_7(features)
vote_sum += rf_part2.tree_8(features)
vote_sum += rf_part2.tree_9(features)
vote_sum += rf_part2.tree_10(features)
vote_sum += rf_part2.tree_11(features)
// Final Probability (0.0 to 1.0)
float final_prob = vote_sum / 12.0
if final_prob > 0.60
label.new(bar_index, low, "Valid Low", color=color.green)
NodialTreesHighs2: ML Random Forest / Pivot Highs (Part 2 of 2)Title: `Library: ML Random Forest / Pivot Highs (Part 2 of 2)`
Description:
This library contains the second half (Trees 6-11) of the Random Forest Classifier designed to validate Pivot Highs (Short setups).
It is a direct extension of NodialTreesH1 and cannot be used alone. Due to Pine Script's compilation limits on complexity and file size, the 12-tree ensemble model has been split into two separate libraries.
### 🧩 Library Contents
This module exports the following methods representing the specific decision paths of the trained AI model:
- `tree_6(array f)`
- `tree_7(array f)`
- `tree_8(array f)`
- `tree_9(array f)`
- `tree_10(array f)`
- `tree_11(array f)`
### ⚠️ Implementation Guide
To use this library, you must combine it with Part 1.
Please refer to the NodialTreesH1 library description for:
1. The full Integration Code Example (how to average the votes).
2. The exact Input Feature List (the 27 required metrics).
3. Detailed explanation of the Machine Learning logic.
How to finish the integration:
Import this library alongside Part 1 and add the results of `tree_6` through `tree_11` to your voting sum, as shown in the Part 1 documentation.
NodialTreesHighs1: ML Random Forest / Pivot Highs (Part 1 of 2)Title: `Library: ML Random Forest / Pivot Highs (Part 1 of 2)`
Description:
This library contains the first half (Trees 0-5) of a Random Forest Classifier designed to validate Pivot Highs (Short setups).
Due to Pine Script size constraints, the model is split into two libraries. You must use this library in conjunction with NodialTreesH2 to run the full ensemble.
### 🧩 System Architecture
- Model: Random Forest (12 Trees total).
- This Library: Contains `tree_0` to `tree_5`.
- Logic: Each tree analyzes a feature array and outputs a probability score.
- Target: Validating Swing Highs / Resistance Rejections.
### 📊 Input Requirements
The methods expect an `array` of size 27 containing market features (Price Action, Momentum, Volatility, Volume, Structure). The exact order of features is critical for the model's accuracy.
### 🛠️ Integration Example
Since this is a modular library, you need to import both parts and average their results to get the final prediction.
### 📋 Feature Mapping (Array Indexing)
To get accurate predictions, the input array must contain exactly 27 floats in this specific order:
0. Timeframe (in seconds)
1. RSI (Raw Value)
2. MACD Histogram
3. Relative Volume
4. EMA Distance (%)
5. EMA Slope
6. ATR Ratio
7. ADX
8. Buying/Selling Pressure
9. Wick Ratio
10-16. Divergences & Pattern Flags (Boolean 0.0/1.0)
17-22. Proprietary Momentum Metrics ("Onion" Structure)
23-26. Derived Volatility/Volume Features
*Note: For the advanced proprietary metrics (Indices 17-26), users must implement their own calculations or use compatible indicators.*
//@version=6
indicator("My ML Short Strategy", overlay=true)
// Import BOTH libraries
import YourUsername/NodialTreesH1/1 as rf_part1
import YourUsername/NodialTreesH2/1 as rf_part2
// ... (Calculate your 27 features and fill the array) ...
// var features = array.from(timeframe, rsi, macd, ...)
// Calculate Ensemble Probability (Average of 12 Trees)
float vote_sum = 0.0
// Trees from Part 1
vote_sum += rf_part1.tree_0(features)
vote_sum += rf_part1.tree_1(features)
vote_sum += rf_part1.tree_2(features)
vote_sum += rf_part1.tree_3(features)
vote_sum += rf_part1.tree_4(features)
vote_sum += rf_part1.tree_5(features)
// Trees from Part 2 (Trees 6-11)
vote_sum += rf_part2.tree_6(features)
vote_sum += rf_part2.tree_7(features)
vote_sum += rf_part2.tree_8(features)
vote_sum += rf_part2.tree_9(features)
vote_sum += rf_part2.tree_10(features)
vote_sum += rf_part2.tree_11(features)
// Final Probability (0.0 to 1.0)
float final_prob = vote_sum / 12.0
if final_prob > 0.60
label.new(bar_index, high, "Valid Short", color=color.red)
NormalizedVolume_HHHLNormalized volume + HH/HL/LH/LL structure logic for confirming moves and spotting traps. Library only—intended for use with indicators. Does not plot or draw anything by itself.






















