Library

fsl_helpersLibrary "fsl_helpers"
A library with function helpers for FSL script family, including functions for plotting, formatting, etc.
@version=6
plot_width_get()
Returns the internal panel width used by the helper library.
Returns: int Width of the custom plot panel.
plot_x_axis(x, inc, theme)
Draws a vertical tick and label on the custom X-axis of the panel.
Parameters:
x (int) : X-axis coordinate in panel space.
inc (float) : Label value displayed below the tick.
theme (Theme type from QuantNomad/fsl_theme/3) : Theme used for the chart
plot_y_axis(yy, min, max, theme, plot_mult)
Draws a horizontal Y-axis guide line and corresponding price label.
Converts the normalized panel coordinate to the actual price level.
Parameters:
yy (float) : Normalized Y coordinate in panel space.
min (float) : Minimum value of the plotted price range.
max (float) : Maximum value of the plotted price range.
theme (Theme type from QuantNomad/fsl_theme/3) : Theme used for the chart
plot_mult (int) : Horizontal spacing multiplier used by the panel.
Returns: void
plot_scale(y, min, max)
Converts a price value into the normalized panel scale used
by the forward-curve plotting area.
Parameters:
y (float) : Price value to scale.
min (float) : Minimum value of the plotted price range.
max (float) : Maximum value of the plotted price range.
Returns: float Normalized Y coordinate for plotting.
plot_scatter(x, y, max, min, col, s, tiptool, theme, plot_mult)
Draws a scatter-point marker in the forward-curve panel.
Optionally attaches a tooltip containing symbol, time, and price.
Parameters:
x (int) : X index position within the curve.
y (float) : Price value of the point.
max (float) : Maximum value of the plotted price range.
min (float) : Minimum value of the plotted price range.
col (color) : Marker color.
s (string) : Marker size.
tiptool (string) : Text shown in the tooltip.
theme (Theme type from QuantNomad/fsl_theme/3) : Theme used for the chart
plot_mult (int) : Horizontal spacing multiplier used by the panel.
Returns: void
plot_line(x, y, max, min, x1, y1, col, w, sty, plot_mult)
Draws a line segment between two curve points in the panel.
Used to connect consecutive futures contracts in the forward curve.
Parameters:
x (int) : X position of the ending point.
y (float) : Price value of the ending point.
max (float) : Maximum value of the plotted price range.
min (float) : Minimum value of the plotted price range.
x1 (int) : X position of the starting point.
y1 (float) : Price value of the starting point.
col (color) : Line color.
w (int) : Line width.
sty (string) : Line style.
plot_mult (int) : Horizontal spacing multiplier used by the panel.
Returns: void
plot_legend(y, col, sty, txt, theme, plot_mult)
Draws a legend entry composed of a marker, line sample, and label.
Parameters:
y (float) : Y position of the legend row.
col (color) : Legend color.
sty (string) : Line style used for the sample segment.
txt (string) : Legend label text.
theme (Theme type from QuantNomad/fsl_theme/3) : Theme used for the chart
plot_mult (int) : Horizontal spacing multiplier used by the panel.
Returns: void
plot_remove_all_boxes()
Deletes all boxes currently drawn by the script.
Useful before redrawing the custom panel.
Returns: void
plot_remove_all_labels()
Deletes all labels currently drawn by the script.
Useful before redrawing the custom panel.
Returns: void
plot_remove_all_lines()
Deletes all lines currently drawn by the script.
Useful before redrawing the custom panel.
Returns: void
plot_main_boxes(main_title, theme, plot_mult)
Draws the main panel boxes for the forward-curve display, including
frame, title area, legend area, and timeframe header.
Parameters:
main_title (string) : Main title for the plot
theme (Theme type from QuantNomad/fsl_theme/3) : Theme used for the chart
plot_mult (int) : Horizontal spacing multiplier used by the panel.
Returns: void Library

Library

Library

Library

Library

Library

Library

ScaleScale Library v1 - The Ultimate UI Framework for Pine Script™
Construct. Visualize. Deploy.
📢 ABOUT
Scale is a comprehensive, open-source UI framework meticulously designed to simplify the creation of advanced visual scales, interactive progress bars, and complex dashboards in Pine Script™. It abstracts away the cumbersome and error-prone complexity of manual drawing (such as managing lines, labels, boxes, and calculations) into a clean, chainable, and highly intuitive method suite.
Whether you're building a simple RSI indicator, a dynamic MACD histogram, or a complex multi-metric trading dashboard, Scale handles the heavy lifting of:
• Auto-scaling : Intelligently calculates positions relative to bars or time, ensuring your UI elements are perfectly aligned regardless of chart zoom or resolution.
• Real-time updates : Flawlessly handles intra-bar price changes, providing smooth and accurate visualizations on every tick without flickering.
• Theming : Offers robust support for aesthetic customization, including smooth gradients, auto-coloring based on conditions, and custom branding.
• Responsive layout : Features granular padding, offset, and alignment controls so your visual components flexibly adapt to any chart environment.
✨ WHAT'S NEW IN v1
📛 Method Badges
Quickly identify method capabilities and execution context with visual badges:
• 🔵 method-primary — The core function required to initialize a specific feature or element.
• 🟣 chainable — Indicates the method returns the setup object itself, allowing for elegant, single-line method chaining (e.g., `scale.build().addMarker().show()`).
• 🟡 realtime — Specialized methods that update fluidly on every tick (realtime data), ideal for timers and loaders.
• 🔷 since-v6 — Leverages the latest Pine Script™ v6 features for maximum performance.
📊 Icon Reference Tables
No more guessing icon indices! Comprehensive tables are integrated directly into this documentation, showing every available icon for Markers, Rulers, Trends, and more.
🎯 Inline Examples
Every core module is accompanied by copy-paste ready examples, getting you from an empty script to a functioning UI in seconds.
🚀 QUICK START
1. Import the library
Bring the Scale framework into your script:
import cryptolinx/Scale/1 as s
2. Create a Theme (optional but recommended)
Define your aesthetic preferences early on:
// Example theme for a classic blue look
var theme = s.theme.new(
color_bar_filled = color.blue,
color_bar_unfilled = color.new(color.blue, 80)
)
3. Build and Deploy
Create your scale, feed it data, and add components:
// Simple RSI Scale with a marker and a background ruler
var myScale = s.setup.new()
myScale.build(theme, bar_index, high + 10, ta.rsi(close, 14), 14, 0, 100)
.addMarker(_icon = 0) // Pinpoints current value
.addRuler() // Adds a structural background
🔧 CORE METHODS
build() 🔵 primary 🟣 chainable
The foundational engine that initializes your scale's model, view, and controller. It explicitly defines *what* data is visualized, *where* it is anchored on the chart, and the dimensional constraints.
scale.build(__theme, _xOffset, _y, _src, _length, _minValue, _maxValue, ...)
• `__theme` (theme) — Required : Theme object encapsulating your colors/styling.
• `_xOffset` (int) — Required : Horizontal offset relative to `bar_index` (can be historical or future bars).
• `_y` (float) — Required : Vertical y-coordinate anchor (price/value level).
• `_src` (float) — Required : The incoming source value to visualize (e.g., RSI, Stochastic, custom oscillator).
• `_length` (int) — Required : Mathematical lookback length for internal calculations and dynamic ranges.
• `_minValue` (float) — Required : Minimum baseline value of the scale (representing 0%).
• `_maxValue` (float) — Required : Maximum ceiling value of the scale (representing 100%).
• `_numBars` (int) — Default: 10: Total number of discrete segments or 'ticks' comprising the bar.
• `_barWidth` (int) — Default: 2: Visual width of each individual segment in chart bars.
• `_barHeight` (int) — Default: 5: Visual vertical thickness of the bar in pixels.
• `_prefill` (bool) — Default: true: Determines fill behavior (Left-to-Right progression vs Center-out Range).
• `_dynamic` (bool) — Default: false: If explicitly set to true, minimum and maximum values will auto-adapt to the source data's historical extremes.
show() / hide() 🟣 chainable
Conditionally control visibility. Highly effective for decluttering the chart based on specific market conditions, timeframes, or user toggles.
// Only display the scale on the very last active bar
scale.show(barstate.islast)
// Automatically hide the scale during bearish price action
scale.hide(close < open)
🎨 ELEMENT METHODS
Modular add-ons that enhance the visual clarity and depth of your scale.
addLabel() 🔵 primary 🟣 chainable
Attaches a clean, customizable text label at specific anchor points relative to the scale geometry.
scale.addLabel(position.top_center, _text="RSI", _textColor=color.white)
addMarker() 🔵 primary 🟣 chainable
Places a precise symbol or shape exactly at the current value's interpolated position along the scale.
scale.addMarker(_icon=0, _color=color.yellow, _location=location.bottom)
📊 Marker Icon Table (_icon)
• 0 : ▼ : ▲ | 5 : ↧ : ↥ | 10 : ⁝
• 1 : ▽ : △ | 6 : ⇟ : ⇞ | 11 : ⋎ : ⋏
• 2 : ▾ : ▴ | 7 : ↓ : ↑ | 12 : ⋁ : ⋀
• 3 : ▿ : ▵ | 8 : |
• 4 : ⇣ : ⇡ | 9 : ⁞
addMark() 🔵 primary 🟣 chainable
Injects a static structural mark at a specific numerical offset. Highly useful for visualizing thresholds, midlines, or historic support/resistance levels.
// Places a '┼' symbol at the 2nd offset position
scale.addMark(_xOffset=2, _mark=2)
📊 Mark Icon Table (_mark)
• 0 : | | 4 : ⁞
• 1 : ¦ | 5 : ⁝
• 2 : ┼ | 6 : ▼ : ▲
• 3 : ≎ | 7 : ▽ : △
addBadge() 🔵 primary 🟣 chainable
Generates a prominent text badge with a dedicated background block. Perfect for communicating state, establishing titles, or flagging status alerts.
scale.addBadge("STRONG BUY", _position=position.top_left, _color=color.green)
📈 INDICATOR METHODS
Sophisticated overlays for visualizing statistical data, volatility, and market structure directly alongside your scale.
addRuler() 🔵 primary 🟣 chainable
Deploys a structural background ruler complete with distinct start, center, and end markers, defining the scale's boundaries for better readability.
// Injects a classic ├ -┼- ┤ style ruler framework
scale.addRuler(_icon=0)
📊 Ruler Icon Table (_icon)
• 0 : ├ -┼- ┤ | 6 : ╟ -╥- ╢
• 1 : ├ -┴- ┤ | 7 : ⥢ -≎- ⥤
• 2 : ├ -┬- ┤ | 8 : ⥏ -≏- ⥑
• 3 : ╞ -╧- ╡ | 9 : | - | - |
• 4 : ╞ -╤- ╡ | 10 : | - ¦ - |
• 5 : ╟ -╨- ╢ | 11 : ⁅ - ¦ - ⁆
addAvg() 🔵 primary 🟣 chainable
Computes and visually embeds a Simple Moving Average (SMA) of the incoming source data, allowing you to compare the current value to its historical mean.
scale.addAvg(_length=14, _markerIcon=3)
📊 Average Icon Table
*Text Icons (_textIcon)*: ⌀, Ø, ∅
*Marker Icons (_markerIcon)*: Utilizes the Standard Marker Set (0-12, refer to addMarker)
addRange() 🔵 primary 🟣 chainable
Tracks and plots the Highest High and Lowest Low over a specified period, visually expressing volatility and market extremities relative to the scale limits.
scale.addRange(_length=50, _showBg=true)
📊 Range Icon Table (_textIcon)
• 0 : L - H | 5 : ▼ : ▲
• 1 : ⇊ - ⇈ | 6 : ▽ : △
• 2 : ↓ - ↑ | 7 : ▾ : ▴
• 3 : ⇣ - ⇡ | 8 : ▿ : ▵
• 4 : ↧ - ↥
addTrend() 🔵 primary 🟣 chainable
Calculates and projects a directional trend indicator (rising, falling, or neutral) derived from the source data's momentum profile.
scale.addTrend(_length=14, _colored=true)
📊 Trend Icon Table (_icon)
• 0 : ◀-|-▶ | 6 : ⟪-|-⟫
• 1 : ◁-|-▷ | 7 : ↓-=-↑
• 2 : <-±-> | 8 : ⇊-=-⇈
• 3 : ‹-±-› | 9 : ↧-±-↥
• 4 : «-±-» | 10 : ⇣-±-⇡
• 5 : ⟨-|-⟩
addAlert() 🔵 primary 🟣 chainable
Flags the exact position where a crossover or crossunder event occurs relative to a critical target level.
Note: This acts as an on-chart visual companion; you must still configure a backend PulseWire alert system for notifications.
scale.addAlert(_target=70, _type="cross", _icon=0)
⚡ ANIMATION & DECORATION
addTimer() 🟡 realtime 🟣 chainable
Embeds an active countdown timer tied to the current bar's close, updating continuously tick-by-tick.
scale.addTimer(_position=position.bottom_left)
addLoader() 🟡 realtime 🟣 chainable
Attaches a kinetic spinning or loading animation that forces visual updates on every incoming tick, conveying active data processing to the user.
// Implements an active circular progression loader
scale.addLoader(_loaderIcon=1)
📊 Loader Icon Table (_loaderIcon)
• 0 : ◜-◝-◞-◟ | 4 : ⨫-⨬
• 1 : ◎-◉ | 5 : ▰▱▱...
• 2 : ⋮-⋰-⋯-⋱ | 6 : ⊶⊷⊶⊷...
• 3 : ≓-≒-≑
addDecoration() 🔵 primary 🟣 chainable
Caps your scale with polished decorative brackets or enclosing corners, framing the data and finalizing the professional aesthetic.
scale.addDecoration(_decor=0)
📊 Decoration Icon Table (_decor)
• 0 : ◤-◥ : ◣-◢ | 5 : ⊢-⊣
• 1 : ⌜-⌝ : ⌞-⌟ | 6 : ◖-◗
• 2 : ⌏-⌎ : ⌍-⌌ | 7 : ⟦-⟧
• 3 : ◜-◝ : ◟-◞ | 8 : ⟪-⟫
• 4 : ⊞-⊟ | 9 : ⟨-⟩
📋 CHANGELOG
✅ Initial release of the Scale UI framework
✅ Implemented multi-element coordinate management
✅ Added dynamic scaling and formatting options
✅ Included comprehensive visual decorators
🙏 RELATED LIBRARIES
Check out ScaleValidator for robust input validation that can be used alongside this framework.
Also check out Motion for animating labels and colors dynamically!
Happy coding! 🚀
Made with ☕ by @cryptolinx Library

tp_sl_drawing_lib_v2TP/SL Drawing Library V2
A professional-grade library for creating highly customizable trade management visualizations with extensive styling options and multiple display versions. Perfect for indicators and strategies that require consistent, professional-looking trade level drawings.
Key Features - Extensive Styling Options
Multiple Visual Styles
Version 1 : Traditional multi-label style with left/center/right positioning
Version 2 : Modern streamlined style with single-side labels and tooltips
Version 3 : Advanced style with directional arrows and bar-level indicators
Version 4 : Compact with prices, R:R ratio display, and direction-based label positioning
Comprehensive Customization
Line Styles : Solid, Dashed, Dotted for all levels
Line Thickness : Individual thickness control for each level
Color Schemes : Separate colors for TP1, TP2, TP3, SL, Entry, Buy/Sell signals
Label Positioning : Flexible left/center/right positioning for all information
Information Display : Configurable display of prices, R:R ratios, percentages, and position sizes
Professional Features
Memory Management : Proper cleanup functions prevent memory leaks
Dynamic Line Management : Lines can grow in real-time while trades are open (extend_lines) and shrink to actual trade duration on close (shrink_lines)
Tooltip Integration : Hover information for all trade levels
Bad R/R Detection : Special visualization for poor risk/reward scenarios
Direction-Aware Labels (V4) : Labels automatically position away from the entry line
What's New in V4
Version 4 builds on the compact V2 style and adds:
Price Display : Shows actual price levels on SL, TP, and Entry labels
R:R Ratio on Entry : Entry label displays direction arrow and risk/reward ratio (e.g., "▼ (2R): 78.60")
Label Format : Clean "SL: price" and "TP: price" format with colon separator
Zoom-Stable Labels : All labels use style_none with text.align_left so text stays anchored at the line end regardless of zoom level
Configurable Visibility : Respects the tp_sl_price_pos and tp_sl_rrr_pos parameters — set to "Off" to hide prices or R:R ratio
Real-Time Line Extension : extend_lines() grows all trade lines with each new bar while a trade is active
Usage Example
//@version=6
indicator("My Strategy", overlay = true)
import KlausPeterchen/tp_sl_drawing_lib_v2/1 as tpsl
// Create trade drawings with V4 (compact + prices + direction-aware)
var drawings = tpsl.tradeDrawingsUnion.new()
if entrySignal
tpsl.remove_trade_drawings(4, drawings)
drawings := tpsl.draw_trade_tp_sl(
version = 4,
direction = 1,
ep = entry_price,
tp1 = take_profit,
tp2 = 0.0,
tp3 = 0.0,
sl = stop_loss,
rrr = risk_reward_ratio,
tp1_perc = 0.0,
tp2_perc = 0.0,
tp3_perc = 0.0,
sizeInfo = "",
patternStartBarIdx = bar_index,
tp_sl_line_length = 10,
show_tp1 = true,
show_tp2 = false,
show_tp3 = false,
show_sl = true,
show_ep = true,
show_size_info = false,
tp_sl_label_pos = "Left",
tp_sl_price_pos = "Right",
tp_sl_rrr_pos = "Center",
tp_sl_perc_pos = "Off",
tp_sl_qty_pos = "Off",
tp1_style = "Dashed",
tp2_style = "Dotted",
tp3_style = "Dotted",
sl_style = "Solid",
ep_style = "Solid",
tp1_thickness = 1,
tp2_thickness = 1,
tp3_thickness = 1,
sl_thickness = 1,
ep_thickness = 1,
tp1_color = color.green,
tp2_color = color.green,
tp3_color = color.green,
sl_color = color.red,
ep_color = color.gray,
buy_color = color.rgb(27, 94, 32),
sell_color = color.rgb(128, 25, 34)
)
Main Functions
Core Drawing Functions
draw_trade_tp_sl() - Create complete trade visualization with all styling options
draw_bad_rrr() - Special visualization for poor risk/reward scenarios
remove_trade_drawings() - Clean up all drawings to prevent memory issues
remove_trade_drawings_labels() - Remove only labels while keeping lines
shrink_lines() - Adjust line lengths to match elapsed trade duration on close
extend_lines() - Extend all trade lines and labels to the current bar (call each bar while a trade is open)
Data Types
tradeDrawingsV1 - Traditional multi-label style (20 drawing objects)
tradeDrawingsV2 - Modern streamlined style (10 drawing objects)
tradeDrawingsV3 - Advanced style with directional indicators
tradeDrawingsV4 - Compact with prices and direction-aware positioning (10 drawing objects)
tradeDrawingsUnion - Unified interface for all versions
Version Comparison
Label Positions:
V1 (Traditional) : Left/Center/Right positioning available
V2 (Modern) : Right-side positioning only
V3 (Advanced) : Right-side + Bar-level positioning
V4 (Compact+) : Right-side with direction-aware above/below placement
Price Display:
V1 (Traditional) : Configurable via position parameters
V2 (Modern) : Not shown (tooltip only)
V3 (Advanced) : Not shown (tooltip only)
V4 (Compact+) : Configurable via tp_sl_price_pos ("Off" to hide)
R:R Ratio Display:
V1 (Traditional) : Configurable via position parameters
V2 (Modern) : Always shown on entry
V3 (Advanced) : Always shown on entry
V4 (Compact+) : Configurable via tp_sl_rrr_pos ("Off" to hide)
Direction-Aware Labels:
V1 (Traditional) : No
V2 (Modern) : No
V3 (Advanced) : No
V4 (Compact+) : Yes — labels positioned away from entry
Tooltips:
V1 (Traditional) : No
V2 (Modern) : Yes
V3 (Advanced) : Yes
V4 (Compact+) : Yes
Memory Efficiency (drawing objects per trade):
V1 (Traditional) : 20 objects
V2 (Modern) : 10 objects
V3 (Advanced) : 12 objects
V4 (Compact+) : 10 objects
Note : This library is designed for professional use and provides extensive customization options. Choose the version that best fits your visual style and requirements.
Library

ScaleValidator🛡️ ScaleValidator Library - Input Validation for PineScript
📢 ABOUT
ScaleValidator is a lightweight utility library that provides robust input validation for PineScript. It ensures your scripts receive valid arguments and throws helpful runtime errors when they don't.
✨ FEATURES
🛡️ Validation Methods
Validate inputs and throw descriptive runtime errors if invalid:
• isValidLocation() — Validate location strings
• isValidPosition() — Validate position strings
• isValidFormat() — Validate format strings
• isValidPOV() — Validate point-of-view (extend) strings
🔍 Helper Methods
Quick boolean checks without throwing errors:
• isLocationAbove() / isLocationBelow() — Check vertical location
• isPositionAbove() / isPositionCenter() / isPositionBelow() — Check position row
• isPositionLeft() / isPositionRight() — Check position column
💡 USAGE EXAMPLE
//@version=6
indicator("Validator Demo", overlay = true)
import cryptolinx/ScaleValidator/1 as v
// Validate inputs before using them
userPosition = input.string(position.top_center, "Position")
if v.isValidPosition(userPosition)
// Safe to use the position
label.new(bar_index, high, "Valid!",
xloc = xloc.bar_index,
style = label.style_label_down,
textcolor = color.white)
// Quick checks without throwing errors
if v.isPositionAbove(userPosition)
// Position is in top row
plotchar(close, char = "▲", location = location.abovebar)
📊 VALID CONSTANTS REFERENCE
Locations
• location.top — Top of pane
• location.bottom — Bottom of pane
• location.abovebar — Above price bar
• location.belowbar — Below price bar
• location.absolute — Absolute position
Positions (3x3 Grid)
• Top Row: top_left, top_center, top_right
• Middle Row: middle_left, middle_center, middle_right
• Bottom Row: bottom_left, bottom_center, bottom_right
Formats
• format.inherit — Inherit from parent
• format.percent — Percentage format
Point of View (Extend)
• extend.both — Extend in both directions
• extend.left — Extend to the left
• extend.right — Extend to the right
🔧 METHOD REFERENCE
Validators (throw runtime error if invalid)
• isValidLocation(string) → bool
• isValidPosition(string) → bool
• isValidFormat(string) → bool
• isValidPOV(string) → bool
Helpers (return bool, no errors)
• isLocationAbove(string) → bool
• isLocationBelow(string) → bool
• isPositionAbove(string) → bool
• isPositionCenter(string) → bool
• isPositionBelow(string) → bool
• isPositionLeft(string) → bool
• isPositionRight(string) → bool
🚀 WHY USE THIS?
• 🛡️ Defensive Programming — Catch invalid inputs early
• 📖 Helpful Errors — Descriptive messages show valid options
• ⚡ Lightweight — No dependencies, minimal overhead
• 🔗 Companion to ScalesDEV — Used internally by the Scale library
📋 CHANGELOG
✅ Added method badges (helper/validator)
✅ Created reference tables for valid constants
✅ Improved parameter descriptions
✅ Formatted return types
🙏 RELATED LIBRARIES
Check out Scales for building beautiful scale visualizations that use this validator!
Battries included! 🔋Happy coding! 🚀 @cryptolinx for the PulseWire community
Library

DafeVisLibDafeVisLib: The Intelligent Visualization & UI Engine
This is not a library of colors and drawing functions. This is an AI-powered artist and data scientist that lives in your code. It automates the complex, time-consuming process of data analysis and visualization, allowing you to focus on what truly matters: your trading ideas.
█ CHAPTER 1: THE PHILOSOPHY - BEYOND PLOTTING, INTO PERCEPTION
For too long, the world of technical indicator development has been bifurcated. On one side, you have the quantitative analyst, obsessed with mathematical purity but often displaying their work in a crude, unintuitive manner. On the other, you have the visual designer, creating beautiful indicators that often lack analytical depth. The result for the end-user is a compromise: either a tool that is powerful but ugly and hard to interpret, or one that is beautiful but analytically shallow.
The DafeVisLib was created to shatter this compromise. Its core philosophy is that great analysis and great visualization are not separate disciplines; they are two sides of the same coin . An indicator should not just present data; it should communicate intelligence. It should automatically understand the nature of the data it is given and render it in the most effective, intuitive, and aesthetically pleasing way possible.
This library is an "Architect." You provide it with the raw materials—a simple data series like an RSI or a moving average—and it handles the entire complex process of analysis, configuration, and rendering. It is the ultimate accelerator for developers, saving hundreds of hours of boilerplate code, and the ultimate upgrade for traders, providing a level of clarity and visual intelligence previously unseen on this platform.
█ CHAPTER 2: THE CORE INNOVATION - THE "ANALYZE, THEN RENDER" PARADIGM
The DafeVisualsLib operates on a revolutionary two-stage pipeline that sets it apart from any other tool. This is not a passive collection of functions; it is an active, intelligent system.
STAGE 1: The analyze() Function (The Data Scientist)
This is the brain. Before a single line is drawn, this function performs a sophisticated statistical analysis on your raw data series to understand its fundamental character. It asks the critical questions that a human analyst would:
What is the Data Type? It automatically detects if your data is a bounded "oscillator" like an RSI, a zero-centric "momentum" indicator like MACD, a "price"-based line like a moving average, or a "volume"-based metric. This is crucial, as an oscillator should be visualized differently than a volume histogram.
What is the Market Regime? It analyzes the data's volatility (using the coefficient of variation) to classify the current environment as a low-volatility "squeeze," a moderate-volatility "trend," or a high-volatility "volatile" state.
Where is the Data in its Cycle? It normalizes the data to a 0-100 scale and calculates its Z-Score to determine if it is currently at a statistical "extreme."
The output of this stage is a MetricAnalysis object—a complete analytical report on the DNA of your data.
STAGE 2: The auto_config() Function (The Artist & Physicist)
This is where the magic happens. This function takes the analytical report from analyze() and uses it to make a series of intelligent, context-aware decisions about how the data should be visualized.
Intelligent Color Logic: It doesn't just use one color. For an "oscillator," it will create a beautiful heatmap gradient. For a "momentum" indicator, it will use a binary bull/bear color scheme.
Neon Physics: It separates the color into a solid c_core and a transparent c_glow. The opacity of the glow is not static; it is dynamically controlled by the detected market regime. In a "volatile" regime, the glow becomes bright and intense. In a "squeeze," it becomes dim and subtle.
Adaptive Style & Width: It automatically adjusts the plot style and line width. A "momentum" indicator will be rendered as an area chart by default. A "volume" series will become columns. A "price" line will be thick and bold in a volatile market and thin and clean in a calm market.
Smart Zones: If it detects that the data is an "oscillator," it will automatically recommend showing overbought/oversold zones and provide the standard 70/30 levels.
The output of this stage is a PlotConfig object—a complete, ready-to-use set of plotting instructions, intelligently tailored to your specific data and the current market conditions.
█ CHAPTER 3: A DEEP DIVE INTO THE DEVELOPER'S TOOLKIT
This library is a gift to Pine Script developers. It is a suite of powerful, high-level functions designed to dramatically simplify your workflow and elevate the final product.
The Theme Engine
Forget hard-coding colors. The get_theme() function provides access to a library of professionally designed, high-contrast color themes ( Neon, Cyber, Matrix, Gold, Ice, Blood, DAFE Signature ). Each Theme object contains a complete, consistent palette for primary, secondary, accent, bull, bear, and neutral colors. This allows you to build indicators that are not only functional but also have a polished, professional aesthetic that is consistent across all your DAFE-powered creations.
The Color Engine
Go beyond simple colors with a powerful suite of advanced color functions. gradient_color() allows for smooth linear interpolation between any two colors. gradient_3() creates a three-point gradient, perfect for heatmaps. adaptive_alpha() calculates the optimal transparency for an element based on a confidence or strength score, making your visuals dynamically react to the data.
Candle Diagnostics
The diagnose_candle() function is a complete microstructure analysis tool in a single call. It returns a detailed breakdown of any candle, including its body vs. wick percentages, and flags for common patterns like Dojis, Hammers, Shooting Stars, and Marubozus. The companion candle_color() function uses this analysis to provide intelligent, health-based candle coloring.
The UI & HUD Toolkit
Building user interfaces with tables can be tedious and complex. This library provides a comprehensive suite of helper functions to make it effortless and beautiful.
ASCII Art Generators: Functions like draw_bar(), draw_gauge(), draw_stars(), and the incredible draw_sparkline() allow you to create rich, data-dense, text-based visualizations directly within your dashboards.
Dashboard Builders: A modular toolkit for creating professional dashboards. create_pane() initializes the table. fill_header(), fill_metric(), fill_status(), and fill_separator() provide a simple, high-level API for populating your dashboard with consistently styled and beautifully formatted information.
Smart Formatting: Utilities like smart_text() (which auto-selects black or white text for optimal contrast) and format_compact() (which abbreviates large numbers to "1.23M" or "456K") handle the small details that create a polished user experience.
█ CHAPTER 4: DEVELOPMENT PHILOSOPHY
The DafeVisLib was born from a desire to democratize elite-level indicator design. For too long, the ability to create beautiful, context-aware, and intuitively designed indicators has been the domain of a select few developers with deep knowledge of both programming and graphic design. This library changes that. It is an open-source tool that encapsulates thousands of hours of research and development into a simple, powerful API.
Our philosophy is that a developer's most valuable asset is their idea. They should be free to focus on inventing new, powerful analytical concepts, without getting bogged down in the tedious, repetitive work of building robust visualization and configuration systems from scratch. This library is our contribution to the Pine Script community—a tool for builders, designed to accelerate innovation and elevate the quality of indicators for everyone.
This library embraces that philosophy. It handles immense complexity on the backend to deliver absolute simplicity and elegance on the frontend, both for the developer who uses it and the trader who benefits from it.
█ DISCLAIMER & IMPORTANT NOTES
THIS IS A LIBRARY FOR DEVELOPERS: This script does nothing on its own. It is a powerful engine that must be imported and used by other indicator developers in their own scripts. It is a tool for building, not a ready-made indicator.
THE ANALYSIS IS A GUIDE: The analyze() function's classification of data and regimes is based on a robust set of heuristics, but it is a statistical interpretation. It provides a powerful baseline for visualization but is not a substitute for a trader's own judgment.
"Simplicity is the ultimate sophistication."
— Leonardo da Vinci
Taking you to school. — Dskyz, Trade with insight. Trade with anticipation. Library

ToolsNotificationLibrary "ToolsNotification"
notify(value, pos, width, height, textColor, alignV, alignH, textSize, backgroundColor, tooltip, fontFamily)
Parameters:
value (string)
pos (string)
width (int)
height (int)
textColor (color)
alignV (string)
alignH (string)
textSize (string)
backgroundColor (color)
tooltip (string)
fontFamily (string) Library

LECAPS_BONCAP_DUALES_LibraryLECAPS BONCAP DUALES Library - Argentine Fixed Income Data
===========================================================
Library containing instrument data for Argentine Treasury fixed-rate securities (LECAPs, BONCAPs, and DUALES) and Dólar Futures contracts.
📊 CONTENTS
-----------
• LECAP (9 instruments): Zero-coupon treasury notes with "S" prefix
• BONCAP (6 instruments): Fixed-rate treasury bonds with "T" prefix
• DUALES (2 instruments): Dual-rate TAMAR-linked bonds with "M" prefix
• Dólar Futures (11 contracts): ROFEX USD/ARS futures (Feb-Dec 2026)
📈 DATA PROVIDED
----------------
For each instrument:
• Ticker symbol (full and short versions)
• Maturity price (precio de vencimiento)
• Maturity date/timestamp
🔧 EXPORTED FUNCTIONS
---------------------
// Counts
getLecapCount() → int
getBoncapCount() → int
getDualesCount() → int
getDolarFuturesCount() → int
// LECAP data
getLecapTicker(index) → string // e.g., "BCBA:S27F6"
getLecapTickerShort(index) → string // e.g., "S27F6"
getLecapMaturityPrice(index) → float // e.g., 125.84
getLecapMaturityTimestamp(index) → int
// BONCAP data
getBoncapTicker(index) → string
getBoncapTickerShort(index) → string
getBoncapMaturityPrice(index) → float
getBoncapMaturityTimestamp(index) → int
// DUALES data
getDualesTicker(index) → string
getDualesTickerShort(index) → string
getDualesMaturityPrice(index) → float
getDualesMaturityTimestamp(index) → int
// Dólar Futures data
getDolarFuturesTicker(index) → string // e.g., "ROFEX:DLRG2026"
getDolarFuturesShort(index) → string // e.g., "DLR Feb26"
getDolarFuturesExpiry(index) → int
// Helpers
isExpired(maturityTs) → bool
getDaysToMaturity(maturityTs) → int
💡 USAGE EXAMPLE
----------------
import YourUsername/LECAPS_BONCAP_DUALES_Library/1 as lib
// Get LECAP count and iterate
for i = 0 to lib.getLecapCount() - 1
ticker = lib.getLecapTickerShort(i)
maturityPrice = lib.getLecapMaturityPrice(i)
maturityTs = lib.getLecapMaturityTimestamp(i)
if not lib.isExpired(maturityTs)
// Process active instrument
daysLeft = lib.getDaysToMaturity(maturityTs)
📅 INSTRUMENTS (as of 2026-02-11)
---------------------------------
LECAP:
S27F6 (27-Feb-26), S16M6 (16-Mar-26), S17A6 (17-Apr-26),
S30A6 (30-Apr-26), S29Y6 (29-May-26), S31L6 (31-Jul-26),
S31G6 (31-Aug-26), S30O6 (30-Oct-26), S30N6 (30-Nov-26)
BONCAP:
T13F6 (13-Feb-26), T30J6 (30-Jun-26), T15E7 (15-Jan-27),
T30A7 (30-Apr-27), T31Y7 (31-May-27), T30J7 (30-Jun-27)
DUALES:
M27F6 (27-Feb-26), M30A6 (30-Apr-26)
DÓLAR FUTURES:
DLRG2026 (Feb), DLRH2026 (Mar), DLRJ2026 (Apr), DLRK2026 (May),
DLRM2026 (Jun), DLRN2026 (Jul), DLRQ2026 (Aug), DLRU2026 (Sep),
DLRV2026 (Oct), DLRX2026 (Nov), DLRZ2026 (Dec)
⚠️ NOTES
--------
• Data is updated periodically as new instruments are issued
• Expired instruments are automatically filtered via isExpired()
• Maturity prices are set at public auction (licitación)
• Use with the companion indicator "Breakeven LECAPs BONCAPs DUALES"
🏷️ TAGS
-------
argentina, lecap, boncap, duales, treasury, fixed-income, bonds,
letras, bonos, dolar, futures, rofex, bcba, breakeven
Library

Library

Library

MovingAveragesLibrary "MovingAverages"
A collection of O(1) numerically stable moving averages that support anchors and fractional lengths up to 100k bars.
Pine Script has a robust set of moving averages suitable for a majority of cases, making these alternatives useful only if you need anchoring, fractional lengths, or more than 5k bars. Included are the classic SMA , EMA , RMA , WMA , VWMA , VWAP , HMA , SWMA , Linear Regression , and ATR . The common parameters are:
source (float) : Series of values to process.
length (simple float) : Number of bars. Optional.
anchor (bool) : The condition that triggers a calculation reset. Optional.
parity (simple bool) : Sets if built-in function should be used. Optional.
Other DSP filter adaptations include One Euro , Laguerre , Super Smoother , and Holt , as well as rate limiting functions such as Smooth Damp and Slew Rate Limiter .
ANCHORING
This is the libraries first and primary benefit. Akin to the built-in VWAP, anchoring is managed by passing a series bool into the function. For sessional anchoring, the included new_session() returns true on the first bar of intraday sessions, and stabilize_anchor() helps reduce near-anchor volatility. When no length is provided, the series continues indefinitely until a new anchor is set. Values during the warmup period are returned.
source = close
length = 9.5
anchor = ma.new_session() // Assumes library is imported as "ma"
swma = ma.swma(source, length, anchor).stabilize_anchor(source, length, anchor)
STREAMING UPDATES
Rather than naively using loops to recalculate the whole series on each bar, linear interpolation (aka. "lerping") is used to incrementally update and translate between values. The canonical formula being: a + (b - a) * t. This formula is effectively an EMA, but it's applicable to nearly all averaging equations. Coupling this technique with a circular buffer captures 3 of the 5 benefits this library offers: O(1) computation, fractional lengths, and 100k bars.
NUMERIC STABILITY
The last benefit is how the library minimizes floating point errors. When possible, Pine Script functions are used for mathematical parity. Otherwise Kahan summation error compensation is used when calculating an average. Not only does this keep custom implementations stable throughout the series, it also helps keep them within 1.0e-10 of the built-in functions. Automatically defaulting to the built-in functions can be disabled by setting parity to false . Library

Library

RSMPatternLibLibrary "RSMPatternLib"
RSM Pattern Library - All chart patterns from PATTERNS.md
Implements: Candlestick patterns, Support/Resistance, Gaps, Triangles, Volume Divergence, and more
ALL PATTERNS ARE OWN IMPLEMENTATION - No external dependencies
EDGE CASES HANDLED:
- Zero/tiny candle bodies
- Missing volume data
- Low bar count scenarios
- Integer division issues
- Price normalization for different instruments
bullishEngulfing(minBodyRatio, minPrevBodyRatio)
Detects Bullish Engulfing pattern
Parameters:
minBodyRatio (float) : Minimum body size as ratio of total range (default 0.3)
minPrevBodyRatio (float) : Minimum previous candle body ratio to filter dojis (default 0.1)
Returns: bool True when bullish engulfing detected
EDGE CASES: Handles doji previous candle, zero range, tiny bodies
bearishEngulfing(minBodyRatio, minPrevBodyRatio)
Detects Bearish Engulfing pattern
Parameters:
minBodyRatio (float) : Minimum body size as ratio of total range (default 0.3)
minPrevBodyRatio (float) : Minimum previous candle body ratio to filter dojis (default 0.1)
Returns: bool True when bearish engulfing detected
EDGE CASES: Handles doji previous candle, zero range, tiny bodies
doji(maxBodyRatio, minRangeAtr)
Detects Doji candle (indecision)
Parameters:
maxBodyRatio (float) : Maximum body size as ratio of total range (default 0.1)
minRangeAtr (float) : Minimum range as multiple of ATR to filter flat candles (default 0.3)
Returns: bool True when doji detected
EDGE CASES: Filters out no-movement bars, handles zero range
shootingStar(wickMultiplier, maxLowerWickRatio, minBodyAtrRatio)
Detects Shooting Star (bearish reversal)
Parameters:
wickMultiplier (float) : Upper wick must be at least this times the body (default 2.0)
maxLowerWickRatio (float) : Lower wick max as ratio of body (default 0.5)
minBodyAtrRatio (float) : Minimum body size as ratio of ATR (default 0.1)
Returns: bool True when shooting star detected
EDGE CASES: Handles zero body (uses range-based check), tiny bodies
hammer(wickMultiplier, maxUpperWickRatio, minBodyAtrRatio)
Detects Hammer (bullish reversal)
Parameters:
wickMultiplier (float) : Lower wick must be at least this times the body (default 2.0)
maxUpperWickRatio (float) : Upper wick max as ratio of body (default 0.5)
minBodyAtrRatio (float) : Minimum body size as ratio of ATR (default 0.1)
Returns: bool True when hammer detected
EDGE CASES: Handles zero body (uses range-based check), tiny bodies
invertedHammer(wickMultiplier, maxLowerWickRatio)
Detects Inverted Hammer (bullish reversal after downtrend)
Parameters:
wickMultiplier (float) : Upper wick must be at least this times the body (default 2.0)
maxLowerWickRatio (float) : Lower wick max as ratio of body (default 0.5)
Returns: bool True when inverted hammer detected
EDGE CASES: Same as shootingStar but requires bullish close
hangingMan(wickMultiplier, maxUpperWickRatio)
Detects Hanging Man (bearish reversal after uptrend)
Parameters:
wickMultiplier (float) : Lower wick must be at least this times the body (default 2.0)
maxUpperWickRatio (float) : Upper wick max as ratio of body (default 0.5)
Returns: bool True when hanging man detected
NOTE: Identical to hammer - context (uptrend) determines meaning
morningStar(requireGap, minAvgBars)
Detects Morning Star (3-candle bullish reversal)
Parameters:
requireGap (bool) : Whether to require gap between candles (default false for crypto/forex)
minAvgBars (int) : Minimum bars for average body calculation (default 14)
Returns: bool True when morning star pattern detected
EDGE CASES: Gap is optional, handles low bar count, uses shifted average
eveningStar(requireGap, minAvgBars)
Detects Evening Star (3-candle bearish reversal)
Parameters:
requireGap (bool) : Whether to require gap between candles (default false for crypto/forex)
minAvgBars (int) : Minimum bars for average body calculation (default 14)
Returns: bool True when evening star pattern detected
EDGE CASES: Gap is optional, handles low bar count
gapUp()
Detects Gap Up
Returns: bool True when current bar opens above previous bar's high
gapDown()
Detects Gap Down
Returns: bool True when current bar opens below previous bar's low
gapSize()
Returns gap size in price
Returns: float Gap size (positive for gap up, negative for gap down, 0 for no gap)
gapPercent()
Returns gap size as percentage
Returns: float Gap size as percentage of previous close
gapType(volAvgLen, breakawayMinPct, highVolMult)
Classifies gap type based on volume
Parameters:
volAvgLen (int) : Length for volume average (default 20)
breakawayMinPct (float) : Minimum gap % for breakaway (default 1.0)
highVolMult (float) : Volume multiplier for high volume (default 1.5)
Returns: string Gap type: "Breakaway", "Common", "Continuation", or "None"
EDGE CASES: Handles missing volume data, low bar count
swingHigh(leftBars, rightBars)
Detects swing high using pivot
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
Returns: float Swing high price or na
swingLow(leftBars, rightBars)
Detects swing low using pivot
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
Returns: float Swing low price or na
higherHigh(leftBars, rightBars, lookback)
Checks if current swing high is higher than previous swing high
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : How many bars back to search for previous pivot (default 50)
Returns: bool True when higher high pattern detected
EDGE CASES: Searches backwards for pivots instead of using var (library-safe)
higherLow(leftBars, rightBars, lookback)
Checks if current swing low is higher than previous swing low
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : How many bars back to search for previous pivot (default 50)
Returns: bool True when higher low pattern detected
lowerHigh(leftBars, rightBars, lookback)
Checks if current swing high is lower than previous swing high
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : How many bars back to search for previous pivot (default 50)
Returns: bool True when lower high pattern detected
lowerLow(leftBars, rightBars, lookback)
Checks if current swing low is lower than previous swing low
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : How many bars back to search for previous pivot (default 50)
Returns: bool True when lower low pattern detected
bullishTrend(leftBars, rightBars, lookback)
Detects Bullish Trend (HH + HL within lookback)
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : Lookback period (default 50)
Returns: bool True when making higher highs AND higher lows
bearishTrend(leftBars, rightBars, lookback)
Detects Bearish Trend (LH + LL within lookback)
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : Lookback period (default 50)
Returns: bool True when making lower highs AND lower lows
nearestResistance(lookback, leftBars, rightBars)
Finds nearest resistance level above current price
Parameters:
lookback (int) : Number of bars to look back (default 50)
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
Returns: float Nearest resistance level or na
EDGE CASES: Pre-computes pivots, handles bounds properly
nearestSupport(lookback, leftBars, rightBars)
Finds nearest support level below current price
Parameters:
lookback (int) : Number of bars to look back (default 50)
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
Returns: float Nearest support level or na
resistanceBreakout(lookback, leftBars, rightBars)
Detects resistance breakout
Parameters:
lookback (int) : Number of bars to look back (default 50)
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
Returns: bool True when price breaks above resistance
EDGE CASES: Uses previous bar's resistance to avoid lookahead
supportBreakdown(lookback, leftBars, rightBars)
Detects support breakdown
Parameters:
lookback (int) : Number of bars to look back (default 50)
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
Returns: bool True when price breaks below support
bullishVolumeDivergence(leftBars, rightBars, lookback)
Detects Bullish Volume Divergence (price makes lower low, volume decreases)
Parameters:
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
lookback (int) : Bars to search for previous pivot (default 50)
Returns: bool True when bullish volume divergence detected
EDGE CASES: Library-safe (no var), searches for previous pivot
bearishVolumeDivergence(leftBars, rightBars, lookback)
Detects Bearish Volume Divergence (price makes higher high, volume decreases)
Parameters:
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
lookback (int) : Bars to search for previous pivot (default 50)
Returns: bool True when bearish volume divergence detected
rangeContracting(lookback)
Detects if price is in a contracting range (triangle formation)
Parameters:
lookback (int) : Bars to analyze (default 20)
Returns: bool True when range is contracting
EDGE CASES: Uses safe integer division, checks minimum lookback
ascendingTriangle(lookback, flatTolerance)
Detects Ascending Triangle (flat top, rising bottom)
Parameters:
lookback (int) : Bars to analyze (default 20)
flatTolerance (float) : Max normalized slope for "flat" line (default 0.002)
Returns: bool True when ascending triangle detected
EDGE CASES: Safe division, normalized slope, minimum lookback
descendingTriangle(lookback, flatTolerance)
Detects Descending Triangle (falling top, flat bottom)
Parameters:
lookback (int) : Bars to analyze (default 20)
flatTolerance (float) : Max normalized slope for "flat" line (default 0.002)
Returns: bool True when descending triangle detected
symmetricalTriangle(lookback, minSlope)
Detects Symmetrical Triangle (converging trend lines)
Parameters:
lookback (int) : Bars to analyze (default 20)
minSlope (float) : Minimum normalized slope magnitude (default 0.0005)
Returns: bool True when symmetrical triangle detected
doubleBottom(tolerance, minSpanBars, lookback)
Detects Double Bottom (W pattern) - OWN IMPLEMENTATION
Two swing lows at similar price levels with a swing high between them
Parameters:
tolerance (float) : Max price difference between lows as % (default 3)
minSpanBars (int) : Minimum bars between the two lows (default 5)
lookback (int) : Max bars to search for pattern (default 100)
Returns: bool True when double bottom detected
doubleTop(tolerance, minSpanBars, lookback)
Detects Double Top (M pattern) - OWN IMPLEMENTATION
Two swing highs at similar price levels with a swing low between them
Parameters:
tolerance (float) : Max price difference between highs as % (default 3)
minSpanBars (int) : Minimum bars between the two highs (default 5)
lookback (int) : Max bars to search for pattern (default 100)
Returns: bool True when double top detected
tripleBottom(tolerance, minSpanBars, lookback)
Detects Triple Bottom - OWN IMPLEMENTATION
Three swing lows at similar price levels
Parameters:
tolerance (float) : Max price difference between lows as % (default 3)
minSpanBars (int) : Minimum total bars for pattern (default 10)
lookback (int) : Max bars to search for pattern (default 150)
Returns: bool True when triple bottom detected
tripleTop(tolerance, minSpanBars, lookback)
Detects Triple Top - OWN IMPLEMENTATION
Three swing highs at similar price levels
Parameters:
tolerance (float) : Max price difference between highs as % (default 3)
minSpanBars (int) : Minimum total bars for pattern (default 10)
lookback (int) : Max bars to search for pattern (default 150)
Returns: bool True when triple top detected
bearHeadShoulders()
Detects Bearish Head and Shoulders (OWN IMPLEMENTATION)
Head is higher than both shoulders, shoulders roughly equal, with valid neckline
STRICT VERSION - requires proper structure, neckline, and minimum span
Returns: bool True when bearish H&S detected
bullHeadShoulders()
Detects Bullish (Inverse) Head and Shoulders (OWN IMPLEMENTATION)
Head is lower than both shoulders, shoulders roughly equal, with valid neckline
STRICT VERSION - requires proper structure, neckline, and minimum span
Returns: bool True when bullish H&S detected
bearAscHeadShoulders()
Detects Bearish Ascending Head and Shoulders (variant)
Returns: bool True when pattern detected
bullAscHeadShoulders()
Detects Bullish Ascending Head and Shoulders (variant)
Returns: bool True when pattern detected
bearDescHeadShoulders()
Detects Bearish Descending Head and Shoulders (variant)
Returns: bool True when pattern detected
bullDescHeadShoulders()
Detects Bullish Descending Head and Shoulders (variant)
Returns: bool True when pattern detected
isSwingLow()
Re-export: Detects swing low
Returns: bool True when swing low detected
isSwingHigh()
Re-export: Detects swing high
Returns: bool True when swing high detected
swingHighPrice(idx)
Re-export: Gets swing high price at index
Parameters:
idx (int) : Index (0 = most recent)
Returns: float Swing high price
swingLowPrice(idx)
Re-export: Gets swing low price at index
Parameters:
idx (int) : Index (0 = most recent)
Returns: float Swing low price
swingHighBarIndex(idx)
Re-export: Gets swing high bar index
Parameters:
idx (int) : Index (0 = most recent)
Returns: int Bar index of swing high
swingLowBarIndex(idx)
Re-export: Gets swing low bar index
Parameters:
idx (int) : Index (0 = most recent)
Returns: int Bar index of swing low
cupBottom(smoothLen, minDepthAtr, maxDepthAtr)
Detects Cup and Handle pattern formation
Uses price acceleration and depth analysis
Parameters:
smoothLen (int) : Smoothing length for price (default 10)
minDepthAtr (float) : Minimum cup depth as ATR multiple (default 1.0)
maxDepthAtr (float) : Maximum cup depth as ATR multiple (default 5.0)
Returns: bool True when potential cup bottom detected
EDGE CASES: Added depth filter, ATR validation
cupHandle(lookback, maxHandleRetraceRatio)
Detects potential handle formation after cup
Parameters:
lookback (int) : Bars to look back for cup (default 30)
maxHandleRetraceRatio (float) : Maximum handle retracement of cup depth (default 0.5)
Returns: bool True when handle pattern detected
bullishPatternCount()
Returns count of bullish patterns detected
Returns: int Number of bullish patterns currently active
bearishPatternCount()
Returns count of bearish patterns detected
Returns: int Number of bearish patterns currently active
detectedPatterns()
Returns string description of detected patterns
Returns: string Comma-separated list of detected patterns Library

SimpleTableA library for when you just want to get a table up with the least hassle.
The function `f_drawTableFromColumns()`, is intended to be the simplest possible way to draw a table with the least code in the calling script. Just pass in between one and ten arrays that contain the strings you want to show. Each string array represents one column. That's it. You get a table back.
If you want to style the table you can optionally pass colours, size, and whether the table has a header row that should be displayed differently.
An example usage section demonstrates creating a three-column table.
The function automatically sizes the table based on the number of non-na arrays and the maximum column length.
Optional styling parameters cover table position, text size, text alignment, text colour, cell background, header background, header text, and border width. If you don't supply any of these arguments, the table uses some sensible default values.
The table is created and updated on the last bar only, with caching to avoid unnecessary redraws.
Column shrink detection clears the table only when required, preventing stale cell content.
This is not a full-fledged table management library; there are already lots of those published. It is (I believe and hope) the easiest library to use. For example, you don't need to supply a matrix, or a user-defined type full of settings. The library wraps the input arrays into a map, and uses a user-defined type, but internally, so you don't need to worry about it. Just supply one or more arrays with some text.
f_drawTableFromColumnArrays(_a_col1, _a_col2, _a_col3, _a_col4, _a_col5, _a_col6, _a_col7, _a_col8, _a_col9, _a_col10, _position, _textSize, _textAlign, _textColor, _cellBgColor, _headerBgColor, _headerTextColor, _hasHeaderRow, _borderWidth)
Renders a table using up to ten string arrays. The table size is derived from the number of non-na arrays and the maximum length across the supplied arrays.
Parameters:
_a_col1 (array) : (array) Column 1 values. Supply na to omit.
_a_col2 (array) : (array) Column 2 values. Supply na to omit.
_a_col3 (array) : (array) Column 3 values. Supply na to omit.
_a_col4 (array) : (array) Column 4 values. Supply na to omit.
_a_col5 (array) : (array) Column 5 values. Supply na to omit.
_a_col6 (array) : (array) Column 6 values. Supply na to omit.
_a_col7 (array) : (array) Column 7 values. Supply na to omit.
_a_col8 (array) : (array) Column 8 values. Supply na to omit.
_a_col9 (array) : (array) Column 9 values. Supply na to omit.
_a_col10 (array) : (array) Column 10 values. Supply na to omit.
_position (string) : (TablePosition) Table position on the chart. Default is top right.
_textSize (string) : (TableTextSize) Text size for all cells. Default is normal.
_textAlign (string) : (TableTextAlign) Horizontal alignment for all cells. Default is left.
_textColor (color) : (color) Text colour for all cells. Default is chart foreground color.
_cellBgColor (color) : (color) Background colour for all cells. Uses a default if na. Default is gray 90%.
_headerBgColor (color) : (color) Background colour for the header row. Uses a default if na. Default is gray 75%.
_headerTextColor (color) : (color) Text colour for the header row. Uses a default if na.
_hasHeaderRow (bool) : (bool) If true, row 0 is treated as a header. Default is true.
_borderWidth (int) : (int) Table border width. Must be non-negative. Default is 1.
Returns: The table object, so the caller can store the table ID if required. Library

historicalEngine by N&M🇬🇧 English Introduction
historicalEngine is a Pine Script library designed for advanced state-based backtesting.
It does not test a single strategy, but evaluates full market configurations (trend, structure, momentum, multi-TF context).
Each trade is linked to a unique state hash, revealing which conditions truly perform over time.
The engine computes professional metrics: PnL, win rate, expectancy, Sharpe, drawdown, reliability.
It includes dynamic TP/SL, liquidation logic, early exits, realistic fees and slippage.
Built to be modular, extensible, and efficient, it plugs into any indicator.
Goal: turn historical data into a statistical trading edge.
V1 – a solid foundation for adaptive and data-driven trading systems.
Library

tradeEngineLibrary "tradeEngine"
calculateLiquidationPrice(entryPrice, isLong, leverage, buffer)
Parameters:
entryPrice (float)
isLong (bool)
leverage (int)
buffer (float)
calculateTPLevels(entryPrice, atr, isLong, risk)
Parameters:
entryPrice (float)
atr (float)
isLong (bool)
risk (RiskConfig)
calculateSL(entryLow, entryHigh, isLong, risk)
Parameters:
entryLow (float)
entryHigh (float)
isLong (bool)
risk (RiskConfig)
simulateTrade(highs, lows, closes, entryIdx, entryPrice, entryLow, entryHigh, entryATR, isLong, risk, maxBars)
Parameters:
highs (array)
lows (array)
closes (array)
entryIdx (int)
entryPrice (float)
entryLow (float)
entryHigh (float)
entryATR (float)
isLong (bool)
risk (RiskConfig)
maxBars (int)
createRiskConfig(leverage, liqBuffer, useTP1, tp1ATR, useTP2, tp2ATR, useSL, slBuffer, maker, taker, slip)
Parameters:
leverage (int)
liqBuffer (float)
useTP1 (bool)
tp1ATR (float)
useTP2 (bool)
tp2ATR (float)
useSL (bool)
slBuffer (float)
maker (float)
taker (float)
slip (float)
TradeResult
Fields:
exitType (series string)
exitBarIdx (series int)
exitPrice (series float)
finalPnL (series float)
maxPnL (series float)
tp1Hit (series bool)
tp2Hit (series bool)
slHit (series bool)
liquidated (series bool)
barsInTrade (series int)
tp1Level (series float)
tp2Level (series float)
slLevel (series float)
liqLevel (series float)
RiskConfig
Fields:
leverage (series int)
liquidationBuffer (series float)
useTP1 (series bool)
tp1ATR (series float)
useTP2 (series bool)
tp2ATR (series float)
useFixedSL (series bool)
slBuffer (series float)
makerFee (series float)
takerFee (series float)
slippage (series float) Library

matrixCoreLibrary "matrixCore"
analyzeCandleStructure(o, h, l, c, atr, smallBodyThreshold, longWickRatio)
Parameters:
o (float)
h (float)
l (float)
c (float)
atr (float)
smallBodyThreshold (float)
longWickRatio (float)
isRedRejectionCandle(o, l, c, redRejectionWickMin)
Parameters:
o (float)
l (float)
c (float)
redRejectionWickMin (float)
isEqual(a, b, tol)
Parameters:
a (float)
b (float)
tol (float)
detectPattern(kf, km, ks, tol)
Parameters:
kf (float)
km (float)
ks (float)
tol (float)
calculateStateHash(kp, ep, pp, comp, cType, slope, tfH, tfL, redRej)
Parameters:
kp (int)
ep (int)
pp (int)
comp (int)
cType (int)
slope (int)
tfH (bool)
tfL (bool)
redRej (bool)
createStateConfig(kp, ep, pp, comp, cType, slope, tfH, tfL, redRej, hash)
Parameters:
kp (int)
ep (int)
pp (int)
comp (int)
cType (int)
slope (int)
tfH (bool)
tfL (bool)
redRej (bool)
hash (int)
createBarSnapshot(barIdx, o, h, l, c, atr, ema, stateHash, kp, ep, pp, comp, cType, slope, tfH, tfL, redRej)
Parameters:
barIdx (int)
o (float)
h (float)
l (float)
c (float)
atr (float)
ema (float)
stateHash (int)
kp (int)
ep (int)
pp (int)
comp (int)
cType (int)
slope (int)
tfH (bool)
tfL (bool)
redRej (bool)
stateToString(cfg)
Parameters:
cfg (StateConfig)
getTablePosition(pos)
Parameters:
pos (string)
getGradientColor(value, minVal, maxVal)
Parameters:
value (float)
minVal (float)
maxVal (float)
StateConfig
Fields:
kijunPattern (series int)
emaPattern (series int)
pricePos (series int)
compression (series int)
candleType (series int)
emaSlope (series int)
tfHigherBullish (series bool)
tfLowerBullish (series bool)
redRejection (series bool)
hash (series int)
BarSnapshot
Fields:
barIndex (series int)
openPrice (series float)
highPrice (series float)
lowPrice (series float)
closePrice (series float)
atr (series float)
emaFast (series float)
stateHash (series int)
kijunPattern (series int)
emaPattern (series int)
pricePos (series int)
compression (series int)
candleType (series int)
emaSlope (series int)
tfHigherBullish (series bool)
tfLowerBullish (series bool)
redRejection (series bool) Library
