AIUnifiedCoreLibrary "AIUnifiedCore"
Core signal engine for the AI Learning Trader Bot unified system.
This library contains reusable logic only. Inputs, plots, labels, strategy orders,
and alerts belong in the wrapper scripts that import this library.
clampFloat(value, minValue, maxValue)
Clamps a number between a minimum and maximum.
Parameters:
value (float) : Number to clamp.
minValue (float) : Minimum allowed value.
maxValue (float) : Maximum allowed value.
Returns: Clamped value.
trendEngine(source, fastLen, midLen, slowLen)
Calculates the EMA/VWAP trend engine.
Parameters:
source (float) : Source price.
fastLen (simple int) : Fast EMA length.
midLen (simple int) : Middle EMA length.
slowLen (simple int) : Slow EMA length.
Returns: Fast EMA, middle EMA, slow EMA, VWAP, bullish trend, bearish trend.
momentumEngine(source, rsiLen)
Calculates RSI/MACD momentum engine.
Parameters:
source (float) : Source price.
rsiLen (simple int) : RSI length.
Returns: RSI, MACD line, MACD signal, MACD histogram, bullish momentum, bearish momentum.
volumeEngine(volumeLen)
Calculates volume confirmation.
Parameters:
volumeLen (simple int) : Volume average length.
Returns: Volume average, high volume, bullish volume, bearish volume.
priceActionEngine(swingLen)
Calculates price action breakout and candle direction.
Parameters:
swingLen (simple int) : Swing lookback length.
Returns: Swing high, swing low, bullish break, bearish break, bullish candle, bearish candle.
chopEngine(diLen, adxSmooth, minAdx, atrLen, minAtrPercent, minEmaSpreadPercent, votesNeeded, emaFast, emaSlow)
Calculates the chop/no-trade filter.
Parameters:
diLen (simple int) : DMI DI length.
adxSmooth (simple int) : ADX smoothing.
minAdx (float) : Minimum ADX trend strength.
atrLen (simple int) : ATR length.
minAtrPercent (float) : Minimum ATR percent.
minEmaSpreadPercent (float) : Minimum EMA spread percent.
votesNeeded (simple int) : Number of chop votes needed.
emaFast (float) : Fast EMA.
emaSlow (float) : Slow EMA.
Returns: DI+, DI-, ADX, ATR, ATR percent, EMA spread percent, chop votes, chop market.
probabilityEngine(bullTrend, bearTrend, bullMomentum, bearMomentum, bullVolume, bearVolume, bullBreak, bearBreak, bullCandle, bearCandle, mtfLongOk, mtfShortOk)
Calculates long/short probability scores.
Parameters:
bullTrend (bool) : Bullish trend.
bearTrend (bool) : Bearish trend.
bullMomentum (bool) : Bullish momentum.
bearMomentum (bool) : Bearish momentum.
bullVolume (bool) : Bullish volume.
bearVolume (bool) : Bearish volume.
bullBreak (bool) : Bullish breakout.
bearBreak (bool) : Bearish breakout.
bullCandle (bool) : Bullish candle.
bearCandle (bool) : Bearish candle.
mtfLongOk (bool) : Higher-timeframe long confirmation.
mtfShortOk (bool) : Higher-timeframe short confirmation.
Returns: Long probability and short probability.
superEngine(emaFast, emaMid, rsiValue, macdHist)
Calculates premium super-aggressive pressure scores.
Parameters:
emaFast (float) : Fast EMA.
emaMid (float) : Middle EMA.
rsiValue (float) : RSI value.
macdHist (float) : MACD histogram.
Returns: Super long probability, super short probability.
likelyRevEngine(showSignals, aggression, minVotes, realtimeOnly, chopOk, cooldownUpOk, cooldownDownOk, longProbability, shortProbability, superLongProbability, superShortProbability, bullTrend, bearTrend, emaFast, rsiValue, macdHist, superSensitivity, minEntryProbability)
Calculates early likely reversal votes/signals.
Parameters:
showSignals (bool) : Master toggle.
aggression (simple string) : Aggression text: Balanced, Aggressive, or Hyper.
minVotes (simple int) : Minimum votes.
realtimeOnly (bool) : Only allow before candle closes.
chopOk (bool) : Whether chop filter allows signal.
cooldownUpOk (bool)
cooldownDownOk (bool)
longProbability (float) : Long probability.
shortProbability (float) : Short probability.
superLongProbability (float) : Super long probability.
superShortProbability (float) : Super short probability.
bullTrend (bool) : Bull trend.
bearTrend (bool) : Bear trend.
emaFast (float) : Fast EMA.
rsiValue (float) : RSI value.
macdHist (float) : MACD histogram.
superSensitivity (simple int) : Super aggressive threshold.
minEntryProbability (simple int) : Minimum entry probability.
Returns: Up votes, down votes, votes needed, likely rev up, likely rev down.
easyQuality(trendOk, momentumOk, mtfOk, volumeOk, breakOk, chopMarket, oppositeLikelyRev, probability)
Calculates Easy Mode trade quality score.
Parameters:
trendOk (bool) : Trend agreement.
momentumOk (bool) : Momentum agreement.
mtfOk (bool) : Higher-timeframe agreement.
volumeOk (bool) : Volume agreement.
breakOk (bool) : Breakout agreement.
chopMarket (bool) : No-trade/chop state.
oppositeLikelyRev (bool) : Opposite likely reversal warning.
probability (float) : Direction probability.
Returns: Easy Mode quality score.
actionCode(chopMarket, masterLong, masterShort, exitLong, exitShort, flipLong, flipShort, likelyRevUp, likelyRevDown)
Final unified action code.
Parameters:
chopMarket (bool) : No-trade market.
masterLong (bool) : Master long.
masterShort (bool) : Master short.
exitLong (bool) : Exit long.
exitShort (bool) : Exit short.
flipLong (bool) : Flip to long.
flipShort (bool) : Flip to short.
likelyRevUp (bool) : Likely reversal up.
likelyRevDown (bool) : Likely reversal down.
Returns: Integer action code.
actionText(action)
Converts an action code into text.
Parameters:
action (int) : Action code.
Returns: Action text.
trendText(bullTrend, bearTrend)
Converts trend states into text.
Parameters:
bullTrend (bool) : Bull trend.
bearTrend (bool) : Bear trend.
Returns: Trend text.
topStackPrice(highValue, atrValue, gapAtr, slot)
Returns stacked label price above the candle.
Parameters:
highValue (float) : Candle high.
atrValue (float) : ATR.
gapAtr (float) : Gap in ATR multiples.
slot (int) : Stack slot, starting at 1.
Returns: Label price.
bottomStackPrice(lowValue, atrValue, gapAtr, slot)
Returns stacked label price below the candle.
Parameters:
lowValue (float) : Candle low.
atrValue (float) : ATR.
gapAtr (float) : Gap in ATR multiples.
slot (int) : Stack slot, starting at 1.
Returns: Label price. Library

AmendLogic CSS - Brand and Semantic Color LibraryOverview
AmendLogic_CSS is a centralized style and theme utility library for Pine Script v6. It provides a standardized color palette designed to maintain visual consistency across indicators, strategies, and UI components. By shifting color management to a library, scripts stay clean, modular, and easy to maintain.
Key Features
Unified Brand Identity: Access core AmendLogic brand colors ("blue", "cyan", "purple", etc.) instantly via a single wrapper function.
Semantic Trade Layering: Includes a pre-graded 5-tier Take-Profit color matrix ("tp1" to "tp5") to design clean, incremental scaling visuals on your charts.
Adaptive Theme Detection ("colorVar"): Features a built-in environment check. It analyzes the user's current chart background on the fly, dynamically switching text/line elements between light and dark modes to guarantee perfect contrast and readability.
Inline Alpha Control: The getColor() function supports a native transparency parameter ($0$ to $100$), removing the need to wrap color outputs in separate color.new() calls manually.
How to Use (Quick Start)
To implement this design framework into your own indicators or strategies, simply import the library at the top of your script and query your desired color string:
//@version=6
indicator("My Custom Indicator", overlay=true)
// 1. Import the library
import Kevinroku/AmendLogic_css_SEC/1 as css
// 2. Fetch semantic or adaptive colors with custom transparency
brandBlue = css.getColor("blue")
stopLossRed = css.getColor("red", t = 50)
uiText = css.getColor("colorVar") // Automatically flips based on dark/light mode
// 3. Apply to your plots, lines, or boxes
plot(close, color=brandBlue)
Available Color IDs:
Brand: "blue", "cyan", "purple", "gray", "black"
UI Semantics: "green", "red", "yellow"
Targets: "tp1", "tp2", "tp3", "tp4", "tp5"
Adaptive: "colorVar" (Dynamic contrast toggle)
Library

CyberVisLib# CyberVisLib v5
CyberVisLib provides rendering and visualization utilities for multi-oscillator indicators: color blending, sub-pane management, diagnostic tables, and tooltip formatting. Pure visualization layer—no market logic.
## What it does
Delivers four capabilities: color utilities (RGB blending, diverging/sequential gradients, confidence-to-transparency), sub-pane management (vertical space allocation for multiple oscillators), diagnostic tables (key-value pairs, dynamic coloring), and tooltip formatting. Stack RSI, MACD, Stochastic in non-overlapping vertical bands.
Outputs color values, MiniSubPane structs (band coordinates), table objects, formatted strings. All stateless, rendering-focused.
## How it works
Color blending: `RGB_out = (1-t)×RGB_a + t×RGB_b`. Diverging gradients split at zero (negative→red-yellow, positive→yellow-green). Transparency: `90 - 60×confidence`.
Sub-pane management:
1. Register oscillators (MiniOscMeta)
2. Finalize layout (STACK_TOP/BOTTOM/EQUAL_SPLIT policies)
3. Map values: `pane.band_y(unit_val)` converts to vertical coordinate
Diagnostic tables: key-value pairs, multi-column grids, conditional formatting.
## Why this is original
Only PulseWire library with complete rendering toolkit. Existing libraries mix rendering with market logic.
Unique features:
- Sub-pane vertical allocation (automatic band calculation)
- Lightweight UDT variants (co-import with OscLib)
- Diverging gradients with zero-centering
- Confidence-to-transparency mapping
- Regime color enum (consistent color mapping)
Separation of concerns: VisLib (rendering), NumLib (math), SignalLib (signals).
## How to use it
```pine
//@version=6
indicator("CyberVisLib Demo", overlay=false)
import cybermediaboy/CyberVisLib/5 as VL
// Diverging gradient
rsi = ta.rsi(close, 14)
z_rsi = (rsi - 50.0) / 25.0
color rsi_color = VL.f_diverging_rgyg(z_rsi)
plot(rsi, "RSI", color=rsi_color)
// Sub-pane management
var spm = VL.f_subpane_manager_new(VL.SubPanePolicy.EQUAL_SPLIT, 5.0)
if barstate.isfirst
spm.register(VL.f_meta_unipolar0100("rsi", "RSI", color.blue))
spm.register(VL.f_meta_bipolar("macd", "MACD", color.orange))
spm.finalize()
var pane_rsi = array.get(spm.panes, 0)
rsi_y = pane_rsi.band_y(pane_rsi.meta.to_unit(rsi))
plot(rsi_y, "RSI Pane", color.blue)
// Confidence transparency
conf = math.abs(rsi - 50.0) / 50.0
bgcolor(color.new(color.green, VL.f_transp(conf)))
```
## Key functions
- `f_blend()` - RGB color blending
- `f_diverging_rgyg()` - Diverging gradient (zero-centered)
- `f_transp()` - Confidence-to-transparency mapping
- `f_subpane_manager_new()` - Sub-pane allocation
- `f_regime_color()` - Regime color enum
- `f_kv_tooltip()` - Tooltip formatting
## Limitations
- Sub-pane allocation static after finalize
- RGB-only blending (no HSL/HSV)
- No automatic label/line cleanup
- Tables require manual cell updates
- Assumes `overlay=false` (separate pane indicators only)
Library

ChopEngineLibrary "ChopEngine"
chopBase(_high, _low, _len)
Parameters:
_high (float)
_low (float)
_len (simple int)
gaugeFromCi(_ci, _tl, _cl)
Parameters:
_ci (float)
_tl (simple float)
_cl (simple float)
chopGauge(_high, _low, _tl, _cl, _len)
Parameters:
_high (float)
_low (float)
_tl (simple float)
_cl (simple float)
_len (simple int)
getChopBase(_sym, _tf)
Parameters:
_sym (simple string)
_tf (simple string)
getChop(_ciPrev, _ci, _tl, _cl)
Parameters:
_ciPrev (simple float)
_ci (simple float)
_tl (simple float)
_cl (simple float)
chgStateLabel(_g)
Parameters:
_g (float)
chgColor(_chg)
Parameters:
_chg (float)
chgCell(_chg, _prefix)
Parameters:
_chg (float)
_prefix (string)
method init(this, _ciPrev, _ci, _tl, _cl)
Namespace types: Chop
Parameters:
this (Chop)
_ciPrev (float)
_ci (float)
_tl (simple float)
_cl (simple float)
method update(this, _ciPrev, _ci, _tl, _cl)
Namespace types: Chop
Parameters:
this (Chop)
_ciPrev (float)
_ci (float)
_tl (simple float)
_cl (simple float)
method chgVsPrev(this)
Namespace types: Chop
Parameters:
this (Chop)
method chgVsEod(this)
Namespace types: Chop
Parameters:
this (Chop)
method state(this)
Namespace types: Chop
Parameters:
this (Chop)
method isTrending(this)
Namespace types: Chop
Parameters:
this (Chop)
method isChoppy(this)
Namespace types: Chop
Parameters:
this (Chop)
method isImproving(this)
Namespace types: Chop
Parameters:
this (Chop)
method isDeteriorating(this)
Namespace types: Chop
Parameters:
this (Chop)
Chop
Fields:
now (series float)
prev (series float)
eod (series float) Library

Library

PriceActionLibrary "PriceAction"
Will draw out the market structure for the disired pivot length.
SetBarIndices(pivotHigh, pivotLow)
Sets the 'BarIndex' value of the 'Pivot' object. Useful if the pivot is from an other timeframe.
Parameters:
pivotHigh (Pivot) : The 'Pivot' object for the high pivot.
pivotLow (Pivot) : The 'Pivot' object for the low pivot.
Alert(turtleSoupsContext, settings)
Will fire off an alert if there is one. To be used lastly in the calling script.
Parameters:
turtleSoupsContext (TurtleSoups) : The context of all turtle soups.
settings (TurtleSoupSettings) : The settings for turtle soups.
VisualizeTurtleSoups(pivots, turtleSoups, turtleSoupsContext, settings)
Will visulize found turtle soups and add alert messages for it.
Parameters:
pivots (array) : All current pivots (high or low).
turtleSoups (array) : All bullish or bearish turtle soups.
turtleSoupsContext (TurtleSoups) : The context of all turtle soups.
settings (TurtleSoupSettings) : The settings for turtle soups.
GetPivots(settings)
Will get available pivots. Can be called from another timeframe.
Parameters:
settings (TurtleSoupSettings) : The settings for turtle soups.
Returns: A tuple of high and then low pivots.
SetPivots(turtleSoupsContext, settings, pivotHigh, pivotLow)
Will set the new pivots in turtleSoupsContext.
Parameters:
turtleSoupsContext (TurtleSoups) : The context of all turtle soups.
settings (TurtleSoupSettings) : The settings for turtle soups.
pivotHigh (Pivot) : The 'Pivot' object for the high pivot.
pivotLow (Pivot) : The 'Pivot' object for the low pivot.
Confirm(turtleSoups, turtleSoupsContext, settings, previousStructureBreakBarIndex, screener)
Will visualize turtle soups. To be called if 'TurtleSoupSettings.Confirmation' is true.
Parameters:
turtleSoups (array) : All bullish or bearish turtle soups.
turtleSoupsContext (TurtleSoups) : The context of all turtle soups.
settings (TurtleSoupSettings) : The settings for turtle soups.
previousStructureBreakBarIndex (int) : The bar index of the previous structure break (BOS/CHoCH/CHoCH+).
screener (Screener) : The 'Screener' object to be used for Pine Screening by Tradingview. The function will set 'TurtleSoupUntilBarIndex' if there's a confirmed turtle soup.
Liqudity(liquidity)
Will draw liquidity.
Parameters:
liquidity (Liquidity) : The 'PriceAction.Liquidity' object.
Pivot(structure)
Sets the pivots in the structure.
Parameters:
structure (Structure)
PivotLabels(structure)
Draws labels for the pivots found.
Parameters:
structure (Structure)
EqualHighOrLow(structure)
Draws the boxes for equal highs/lows. Also creates labels for the pivots included.
Parameters:
structure (Structure)
BreakOfStructure(structure)
Will create lines when a break of strycture occures.
Parameters:
structure (Structure)
Returns: The 'Pivot' that caused the break of structure, na otherwise.
ChangeOfCharacter(structure)
Will create lines when a change of character occures. This line will have a label with "CHoCH" or "CHoCH+".
Parameters:
structure (Structure)
Returns: The 'Pivot' that caused the change of character, na otherwise.
VisualizeCurrent(structure)
Will create a box with a background for between the latest high and low pivots. This can be used as the current trading range (if the pivots broke strucure somehow).
Parameters:
structure (Structure)
StructureBreak
Holds drawings for a structure break.
Fields:
Line (series line) : The line object.
Label (series label) : The label object.
Pivot
Holds all the values for a found pivot.
Fields:
Price (series float) : The price of the pivot.
BarIndex (series int) : The bar_index where the pivot occured.
Type (series int) : The type of the pivot (-1 = low, 1 = high).
Time (series int) : The time where the pivot occured.
BreakOfStructureBroken (series bool) : Sets to true if a break of structure has happened.
LiquidityBroken (series bool) : Sets to true if a liquidity of the price level has happened.
ChangeOfCharacterBroken (series bool) : Sets to true if a change of character has happened.
Structure
Holds all the values for the market structure.
Fields:
LeftLength (series int) : Define the left length of the pivots used.
RightLength (series int) : Define the right length of the pivots used.
Type (series Type) : Set the type of the market structure. Two types can be used, 'internal' and 'swing' (0 = internal, 1 = swing).
Trend (series int) : This will be set internally and can be -1 = downtrend, 1 = uptrend.
EqualPivotsFactor (series float) : Set how the limits are for an equal pivot. This is a factor of the Average True Length (ATR) of length 14. If a low pivot is considered to be equal if it doesn't break the low pivot (is at a lower value) and is inside the previous low pivot + this limit.
ExtendEqualPivotsZones (series bool) : Set to true if you want the equal pivots zones to be extended.
ExtendEqualPivotsStyle (series string) : Set the style of equal pivot zones.
ExtendEqualPivotsColor (series color) : Set the color of equal pivot zones.
EqualHighs (array) : Holds the boxes for zones that contains equal highs.
EqualLows (array) : Holds the boxes for zones that contains equal lows.
BreakOfStructures (array) : Holds all the break of structures within the trend (before a change of character).
Pivots (array) : All the pivots in the current trend, added with the latest first, this is cleared when the trend changes.
FontSize (series int) : Holds the size of the font displayed.
AlertChangeOfCharacter (series bool) : Holds true or false if a change of character should be alerted or not.
AlertBreakOfStructure (series bool) : Holds true or false if a break of structure should be alerted or not.
AlerEqualPivots (series bool) : Holds true or false if equal highs/lows should be alerted or not.
Liquidity
Holds all the values for liquidity.
Fields:
LiquidityPivotsHigh (array) : All high pivots for liquidity.
LiquidityPivotsLow (array) : All low pivots for liquidity.
LiquidityConfirmationBars (series int) : The number of bars to confirm that a liquidity is valid.
LiquidityPivotsLookback (series int) : A number of pivots to look back for.
FontSize (series int) : Holds the size of the font displayed.
PriceAction
Holds all the values for the general price action and the market structures.
Fields:
Liquidity (Liquidity)
Swing (Structure) : Placeholder for all objects used for the swing market structure.
Internal (Structure) : Placeholder for all objects used for the internal market structure.
TurtleSoupSettings
Holds sll the values for the settings for turtle soups.
Fields:
PivotLeftLenght (series int) : Define the left length of the pivots used.
PivotRightLenght (series int) : Define the right length of the pivots used.
Lookback (series int) : Set how many pivots back that will be used.
Confirmation (series bool) : Set if you want confirmation to be needed for q turtle soup to be formed (e g. a CHoCH).
Color (series color) : The color of turtle soups.
ScreenerKeep (series int) : Set the number of bars that the plot 'Turtle soup' will have a value after a turtle soup is found.
AlertFrequency (series string) : Set the frequency of alerts, possible values are 'alert.freq_all', 'alert.freq_once_per_bar' or 'alert.freq_once_per_bar_close'.
TurtleSoup
To be used when a turtle soup is found and holds all values needed for it.
Fields:
Line (series line) : The line object between the pivot and the turtle soup.
Box (series box) : The bos for the turtle soup.
Start (series int) : The first bar of the turtle soup.
End (series int) : The last bar of the turtle soup.
Pivot (Pivot) : The pivot which liquidity was taken by the turtle soup.
Screener
Holds all values to be used in the Pine Screener by Tradingview.
Fields:
TurtleSoupUntilBarIndex (series int) : Pine Screener value for turtle soups.
TurtleSoups
TurtleSoups The entire context for all turtle soups.
Fields:
Highs (array) : The high pivots.
Lows (array) : The low pivots.
Bullish (array) : Bullish turtle soups.
Bearish (array) : Bearish turtle soups.
AlertMessages (array) : All messages for the current iteration. Library

Library

Library

Library

VisualStructureToolsLibrary "VisualStructureTools"
MTF-safe drawing library (Unix-Time). Designed for high visual discrimination and efficient debugging of complex logic without cluttering the main script.
Optimized for Pine Script® v6 to prevent runtime errors in multi-timeframe environments.
setLine(price, startTime, labelText, labelPos, is_extend, l_width, l_col, l_style)
Draws a horizontal level or a segment with an optional label.
Parameters:
price (float) : Price level for the line.
startTime (int) : UNIX timestamp (ms) for the starting point.
labelText (string) : Text to display on the label. Use "none" to hide.
labelPos (string) : Position of the label relative to the price ('above' or 'below', 'none').
is_extend (bool) : If true, the line extends infinitely (extend.both).
l_width (int) : Width of the line in pixels.
l_col (color) : Color for the line and label text.
l_style (string) : Style of the line ('solid', 'dashed', 'dotted').
setBox(top, bottom, startTime, endTime, boxText, b_col, b_width, b_style, b_transp)
Draws a filled box with an optional synchronized text label.
Parameters:
top (float) : Price of the upper boundary.
bottom (float) : Price of the lower boundary.
startTime (int) : UNIX timestamp (ms) for the left side of the box.
endTime (int) : UNIX timestamp (ms) for the right side (defaults to current 'time').
boxText (string) : Optional text label for the box. Use "" to hide.
b_col (color) : Border and fill color.
b_width (int) : Border width.
b_style (string) : Border style ('solid', 'dashed', 'dotted').
b_transp (int) : Transparency for the background fill (0-100). Library

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

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

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

colors_library# ColorsLibrary - PineScript v6
A comprehensive PineScript v6 library containing **10 color themes** and utility functions for PulseWire.
---
## 📦 Installation
```pinescript
import TheTradingSpiderMan/colors_library/1 as CLR
```
---
## 🎨 All Available Color Themes (10)
### Default Theme (Green/Red - Classic Trading)
| Function | Description |
| ------------------ | --------------- |
| `defaultBull()` | Green (#26A69A) |
| `defaultBear()` | Red (#EF5350) |
| `defaultNeutral()` | Grey (#787B86) |
### Monochrome Theme (White/Grey/Black)
| Function | Description |
| --------------- | -------------------- |
| `monoBull()` | White (#FFFFFF) |
| `monoBear()` | Black (#000000) |
| `monoNeutral()` | Grey (#808080) |
| `monoLight()` | Light Grey (#C0C0C0) |
| `monoDark()` | Dark Grey (#404040) |
### Vaporwave Theme (Purple/Pink, Blue/Cyan)
| Function | Description |
| ---------------- | ----------------------- |
| `vaporBull()` | Cyan (#00FFFF) |
| `vaporBear()` | Magenta (#FF00FF) |
| `vaporNeutral()` | Grey (#787B86) |
| `vaporPurple()` | Purple (#9B59B6) |
| `vaporPink()` | Hot Pink (#FF6EC7) |
| `vaporBlue()` | Electric Blue (#0080FF) |
### Neon Theme (Bright Fluorescent Colors)
| Function | Description |
| --------------- | --------------------- |
| `neonBull()` | Neon Green (#39FF14) |
| `neonBear()` | Neon Red (#FF073A) |
| `neonNeutral()` | Grey (#787B86) |
| `neonYellow()` | Neon Yellow (#FFFF00) |
| `neonOrange()` | Neon Orange (#FF6600) |
| `neonBlue()` | Neon Blue (#00BFFF) |
### Ocean Theme (Blues and Teals)
| Function | Description |
| ---------------- | ------------------- |
| `oceanBull()` | Teal (#20B2AA) |
| `oceanBear()` | Deep Blue (#1E3A5F) |
| `oceanNeutral()` | Grey (#787B86) |
| `oceanAqua()` | Aqua (#00CED1) |
| `oceanNavy()` | Navy (#000080) |
| `oceanSeafoam()` | Seafoam (#3EB489) |
### Sunset Theme (Oranges, Yellows, Reds)
| Function | Description |
| ----------------- | ----------------------- |
| `sunsetBull()` | Golden Yellow (#FFD700) |
| `sunsetBear()` | Crimson (#DC143C) |
| `sunsetNeutral()` | Grey (#787B86) |
| `sunsetOrange()` | Orange (#FF8C00) |
| `sunsetCoral()` | Coral (#FF7F50) |
| `sunsetPurple()` | Twilight (#8B008B) |
### Forest Theme (Greens and Browns)
| Function | Description |
| ----------------- | ---------------------- |
| `forestBull()` | Forest Green (#228B22) |
| `forestBear()` | Brown (#8B4513) |
| `forestNeutral()` | Grey (#787B86) |
| `forestLime()` | Lime Green (#32CD32) |
| `forestOlive()` | Olive (#6B8E23) |
| `forestEarth()` | Earth Brown (#704214) |
### Candy Theme (Pastel/Soft Colors)
| Function | Description |
| ----------------- | -------------------- |
| `candyBull()` | Mint Green (#98FB98) |
| `candyBear()` | Soft Pink (#FFB6C1) |
| `candyNeutral()` | Grey (#787B86) |
| `candyLavender()` | Lavender (#E6E6FA) |
| `candyPeach()` | Peach (#FFDAB9) |
| `candySky()` | Sky Blue (#87CEEB) |
### Fire Theme (Reds, Oranges, Yellows)
| Function | Description |
| --------------- | ---------------------- |
| `fireBull()` | Flame Orange (#FF5722) |
| `fireBear()` | Dark Red (#B71C1C) |
| `fireNeutral()` | Grey (#787B86) |
| `fireYellow()` | Flame Yellow (#FFC107) |
| `fireEmber()` | Ember (#FF6F00) |
| `fireAsh()` | Ash Grey (#424242) |
### Ice Theme (Cool Blues and Whites)
| Function | Description |
| -------------- | ---------------------- |
| `iceBull()` | Ice Blue (#B3E5FC) |
| `iceBear()` | Frost Blue (#0277BD) |
| `iceNeutral()` | Grey (#787B86) |
| `iceWhite()` | Snow White (#F5F5F5) |
| `iceCrystal()` | Crystal Blue (#81D4FA) |
| `iceFrost()` | Frost (#4FC3F7) |
---
## 🔧 Selector & Utility Functions
| Function | Description |
| -------------------- | --------------------------------------------------- |
| `bullColor()` | Get bullish color by theme name |
| `bearColor()` | Get bearish color by theme name |
| `trendColor()` | Returns bull/bear color based on boolean condition |
| `gradientColor()` | Creates gradient between bull/bear (0-100 value) |
| `rsiGradient()` | RSI-style coloring (oversold=bull, overbought=bear) |
| `candleColor()` | Returns color based on candle direction |
| `volumeColor()` | Returns color based on close vs previous close |
| `withTransparency()` | Applies transparency to any color |
| `getAllThemes()` | Returns comma-separated list of all theme names |
| `getThemeOptions()` | Returns array of theme names for input options |
---
## 🔧 Usage Examples
### Basic Usage
```pinescript
//@version=6
indicator("Color Example")
import quantablex/colors_library/1 as CLR
// Direct color usage
plot(close, "Close", CLR.defaultBull())
plot(open, "Open", CLR.defaultBear())
// With transparency
plot(high, "High", CLR.vaporPurple(50))
```
### Using Theme Selector
```pinescript
//@version=6
indicator("Theme Selector")
import quantablex/colors_library/1 as CLR
theme = input.string("DEFAULT", "Color Theme",
options= )
bullCol = CLR.bullColor(theme)
bearCol = CLR.bearColor(theme)
plot(close, "Close", close >= open ? bullCol : bearCol)
```
### Trend Coloring
```pinescript
//@version=6
indicator("Trend Colors")
import quantablex/colors_library/1 as CLR
theme = input.string("VAPOR", "Theme")
ma = ta.ema(close, 20)
// Auto trend color based on condition
trendCol = CLR.trendColor(close > ma, theme)
plot(ma, "EMA", trendCol, 2)
```
### Gradient & RSI Coloring
```pinescript
//@version=6
indicator("Gradient Example")
import quantablex/colors_library/1 as CLR
rsi = ta.rsi(close, 14)
// Gradient based on RSI value
gradCol = CLR.gradientColor(rsi, "NEON")
plot(rsi, "RSI", gradCol)
// Or use built-in RSI gradient
rsiCol = CLR.rsiGradient(rsi, "DEFAULT")
bgcolor(rsiCol, transp=90)
```
### Candle & Volume Coloring
```pinescript
//@version=6
indicator("Candle Colors", overlay=true)
import quantablex/colors_library/1 as CLR
theme = input.string("FIRE", "Theme")
// Auto candle coloring
barcolor(CLR.candleColor(theme))
// Volume bars colored by direction
plotshape(volume, style=shape.circle, color=CLR.volumeColor(theme, 30))
```
---
## 🎨 Theme Selection Guide
| Use Case | Recommended Themes |
| --------------------- | --------------------- |
| **Classic Trading** | DEFAULT, MONO |
| **Dark Mode Charts** | NEON, VAPOR, ICE |
| **Light Mode Charts** | CANDY, SUNSET, FOREST |
| **High Visibility** | NEON, FIRE |
| **Low Eye Strain** | OCEAN, CANDY, ICE |
| **Professional Look** | MONO, DEFAULT, OCEAN |
| **Aesthetic/Stylish** | VAPOR, SUNSET, CANDY |
---
## ⚙️ Parameters Reference
### Common Parameters
- `transparency` - Transparency level (0-100, where 0=opaque, 100=invisible)
### Selector Parameters
- `theme` - Theme name string: `DEFAULT`, `MONO`, `VAPOR`, `NEON`, `OCEAN`, `SUNSET`, `FOREST`, `CANDY`, `FIRE`, `ICE`
---
## 📝 Notes
- All functions accept optional `transparency` parameter (default 0)
- Theme selector functions default to `DEFAULT` theme if invalid name provided
- Use `getAllThemes()` to get comma-separated list of all theme names
- Use `getThemeOptions()` to get array for `input.string` options
- All 50+ color functions are exported for direct use
---
**Author:** thetradingspiderman
**Version:** 1.0
**PineScript Version:** 6
**Total Themes:** 10
**Total Color Functions:** 50+
Library

Table_UtilsLibrary "Table_Utils"
Enhanced Table Utilities for Professional Dashboards V2.0
get_position(posStr)
Convert string to position constant
Parameters:
posStr (string) : User-selected position string
Returns: Pine Script position constant
get_size(sizeStr)
Convert string to size constant
Parameters:
sizeStr (string) : User-selected size string
Returns: Pine Script size constant
get_theme_color(scheme, colorType)
Get color from predefined palette
Parameters:
scheme (string) : Palette name: "Cyberpunk", "Professional", "Pastel", "Dark"
colorType (string) : Color role: "bull", "bear", "neutral", "bg", "border"
Returns: Color value
create_dashboard(posStr, cols, rows, scheme)
Create standard dashboard table with preset styling
Parameters:
posStr (string) : Position string
cols (int) : Number of columns
rows (int) : Number of rows
scheme (string) : Color scheme name
Returns: Configured table object
add_header_cell(tbl, col, row, text_, scheme)
Add header cell with preset styling
Parameters:
tbl (table) : Table object
col (int) : Column index
row (int) : Row index
text_ (string)
scheme (string) : Color scheme
add_data_cell(tbl, col, row, text_, value, scheme)
Add data cell with conditional coloring
Parameters:
tbl (table) : Table object
col (int) : Column index
row (int) : Row index
text_ (string)
value (float) : Numeric value for color coding
scheme (string) : Color scheme
format_number(value, decimals)
Format number with appropriate suffix (K, M, B)
Parameters:
value (float) : Number to format
decimals (int) : Number of decimal places
Returns: Formatted string
format_percentage(value)
Format percentage with sign
Parameters:
value (float) : Percentage value (as decimal, e.g., 0.05 = 5%)
Returns: Formatted string with % symbol Library

Library
